pngine 2.0.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/src/gpu.js CHANGED
@@ -11,6 +11,7 @@
11
11
 
12
12
  import { dispatchResourcePassCommand } from "./gpu-resource-pass-commands.js";
13
13
  import { dispatchQueueCommand } from "./gpu-queue-commands.js";
14
+ import { countCachedBindGroups, countLive } from "./gpu-stats.js";
14
15
  import { uniformToTypedArray } from "./uniform-convert.js";
15
16
  import { decodeTextureFormat } from "./enums.js";
16
17
  import {
@@ -53,6 +54,13 @@ export function requiredFeaturesFor(adapter) {
53
54
  return out;
54
55
  }
55
56
 
57
+ // One decoder for the process, not one per string read. A TextDecoder carries
58
+ // native decoding state and is stateless between decode() calls with no
59
+ // `stream: true`, so a fresh one per read bought nothing — and rs() is on the
60
+ // frame path (call_wasm_func reads its function name every frame), which made
61
+ // it the only per-frame allocation in the corpus that was not a few bytes.
62
+ const DECODER = new TextDecoder();
63
+
56
64
  // Build flag - esbuild replaces DEBUG with false in production (--define:DEBUG=false)
57
65
  // For dev: Vite provides DEBUG=true via define config
58
66
  // Fallback for Worker contexts where Vite's define doesn't reach
@@ -69,21 +77,24 @@ const PNGB_MAGIC = 0x42474e50; // "PNGB" little-endian
69
77
  // flags bit 2 — payload carries an authored device-limits table appended after
70
78
  // the animation table; its byte offset lives in the 3 reserved header bytes.
71
79
  const PNGB_FLAG_DEVICE_LIMITS = 0x04;
72
- // flags bit 3 — the author requested an OPAQUE canvas ((canvas :alpha-mode
73
- // opaque)); clear = the historical premultiplied configure. (spec/04)
74
- 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;
75
85
 
76
86
  /**
77
- * Canvas alphaMode the payload requests: "opaque" when header flag bit 3 is
78
- * 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.
79
90
  * @param {Uint8Array|null|undefined} bytecode
80
91
  * @returns {"opaque"|"premultiplied"}
81
92
  */
82
93
  export function canvasAlphaMode(bytecode) {
83
- if (!bytecode || bytecode.length < PNGB_HEADER_SIZE) return "premultiplied";
94
+ if (!bytecode || bytecode.length < PNGB_HEADER_SIZE) return "opaque";
84
95
  const view = new DataView(bytecode.buffer, bytecode.byteOffset, bytecode.byteLength);
85
- if (view.getUint32(0, true) !== PNGB_MAGIC) return "premultiplied";
86
- 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";
87
98
  }
88
99
 
89
100
  /**
@@ -280,17 +291,44 @@ export function createCommandDispatcher(device, ctx) {
280
291
  // which is the honest answer to "how far did the clock move".
281
292
  let tdelta = 0;
282
293
  let cw = 0, ch = 0; // canvas width/height
283
- let px = 0, py = 0, pcx = 0, pcy = 0, pdx = 0, pdy = 0, pb = 0, pp = 0; // pointer state
284
- let pm = 0, psx = 0, psy = 0; // modifiers, scrollX, scrollY
294
+ // Staging for the two built-in uniform writes, allocated once per dispatcher.
295
+ //
296
+ // Both used to build `new Float32Array([…])` per write — 60 allocations a
297
+ // second each, whose whole purpose was to be copied by writeBuffer and
298
+ // dropped, and multiplied by however many queue steps a frame runs (the step
299
+ // list is uncapped). mini already avoided this on one of the two arms (§310);
300
+ // this is the same move on both, one tier up.
301
+ //
302
+ // `.ptr` doubles as the pointer STATE — setPointer writes into it directly, so
303
+ // there is no per-frame copy either. Index 11 is the layout's padding float
304
+ // and stays 0 (pinned by tests/npm/helpers/pointer-layout.js).
305
+ //
306
+ // The byte views exist so the queue write can be BYTE-counted: writeBuffer's
307
+ // 5-argument form measures dataOffset/size in ELEMENTS of the array it is
308
+ // handed, and the sizes on the wire are byte counts.
309
+ const timeAB = new ArrayBuffer(16); // pngine-inputs: time, w, h, aspect
310
+ const ptrAB = new ArrayBuffer(48); // pointer-inputs: 11 floats + padding
311
+ const scratch = {
312
+ time: new Float32Array(timeAB), timeBytes: new Uint8Array(timeAB),
313
+ ptr: new Float32Array(ptrAB), ptrBytes: new Uint8Array(ptrAB),
314
+ };
285
315
  let enc = null; // command encoder
286
316
  let pass = null; // current pass
287
317
  let dbg = false; // debug flag
288
318
  let curPip = -1; // current pipeline ID (for bind group layout recreation)
319
+ // Cleared by destroy(). Read by the execute loop and by the two async create
320
+ // handlers, both of which can resume after this dispatcher was released.
321
+ let alive = true;
289
322
 
290
323
  // Resource tables - arrays indexed by ID (more minifiable than Maps)
291
324
  const buf = []; // buffers
292
325
  const tex = []; // textures
293
- const txv = []; // texture views
326
+ const txv = []; // texture views, explicit — (texture-view …), rt 4
327
+ const dfv = []; // texture views, default — createView(), cached per texture id
328
+ // What each explicit view was made from: {tid, desc}. Kept because a view
329
+ // outlives nothing — when resizeCanvasBound destroys and recreates its source
330
+ // texture, the only way to rebuild the view is to still know how it was made.
331
+ const txs = [];
294
332
  const smp = []; // samplers
295
333
  const shd = []; // shaders
296
334
  const pip = []; // pipelines
@@ -301,6 +339,9 @@ export function createCommandDispatcher(device, ctx) {
301
339
  const wm = []; // wasm modules
302
340
  const wcr = []; // wasm call results
303
341
  const bgd = []; // bind group descriptors (for recreation)
342
+ // create_bind_group's layout_id id-space tag; mirrors
343
+ // src/types/opcodes.zig BIND_GROUP_LAYOUT_TAG. Set ⇒ standalone bgl id.
344
+ const BGL_TAG = 0x8000;
304
345
  const txd = []; // texture descriptors
305
346
  const bun = []; // render bundles
306
347
  const qs = []; // query sets
@@ -319,7 +360,7 @@ export function createCommandDispatcher(device, ctx) {
319
360
  // Helper: read string from WASM memory
320
361
  function rs(ptr, len) {
321
362
  if (len === 0) return "";
322
- return new TextDecoder().decode(new Uint8Array(mem.buffer, ptr, len));
363
+ return DECODER.decode(new Uint8Array(mem.buffer, ptr, len));
323
364
  }
324
365
 
325
366
  // A create-resource command arrived with an empty descriptor payload — a
@@ -343,14 +384,21 @@ export function createCommandDispatcher(device, ctx) {
343
384
  // Skipped entirely when no host is listening, and that is correctness rather
344
385
  // than thrift: pushing a scope SUPPRESSES onuncapturederror for the enclosed
345
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.
346
392
  function scoped(kind, id, make) {
347
393
  if (!onError) return make();
348
394
  device.pushErrorScope("validation");
349
- const resource = make();
350
- device.popErrorScope().then((e) => {
351
- if (e) onError({ message: `${kind}(${id}) failed validation: ${e.message}`, source: "validation" });
352
- });
353
- 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
+ }
354
402
  }
355
403
 
356
404
  // Decode texture format enum - uses centralized lookup from enums.js
@@ -403,7 +451,12 @@ export function createCommandDispatcher(device, ctx) {
403
451
  layout: (desc.layoutId !== undefined && ppl[desc.layoutId]) ? ppl[desc.layoutId] : "auto",
404
452
  vertex: {
405
453
  module: shd[desc.vertex?.shader ?? 0],
406
- 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,
407
460
  buffers: desc.vertex?.buffers ?? [],
408
461
  },
409
462
  primitive: desc.primitive ?? { topology: "triangle-list" },
@@ -423,7 +476,7 @@ export function createCommandDispatcher(device, ctx) {
423
476
  DEBUG && dbg && console.log(`[GPU] targets:`, JSON.stringify(targets));
424
477
  pipeDesc.fragment = {
425
478
  module: shd[desc.fragment.shader ?? desc.vertex?.shader ?? 0],
426
- entryPoint: desc.fragment.entryPoint ?? "fs_main",
479
+ entryPoint: desc.fragment.entryPoint,
427
480
  targets,
428
481
  };
429
482
  } else {
@@ -441,7 +494,10 @@ export function createCommandDispatcher(device, ctx) {
441
494
  const v = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
442
495
  const shaderId = v.getUint16(1, true); // bytes 1-2, little endian
443
496
  const entryLen = bytes[3];
444
- 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));
445
501
  DEBUG && dbg && console.log(`[GPU] createComputePipeline(${id}) shader=${shaderId} entry=${entryPoint}`);
446
502
  // Check for optional layout ID after entry point bytes
447
503
  const layoutOff = 4 + entryLen;
@@ -467,7 +523,7 @@ export function createCommandDispatcher(device, ctx) {
467
523
  txd[id] = { format: desc.format, usage: desc.usage, canvasBound,
468
524
  dimension: desc.dimension, sampleCount: desc.sampleCount, depth: desc.size[2] };
469
525
  DEBUG && dbg && console.log(`[GPU] createTexture(${id}) ${desc.size[0]}x${desc.size[1]} ${desc.format} usage=0x${desc.usage.toString(16)}${canvasBound ? ' [canvas]' : ''}`);
470
- tex[id] = scoped("createTexture", id, () => device.createTexture(desc));
526
+ installTexture(id, scoped("createTexture", id, () => device.createTexture(desc)));
471
527
  }
472
528
 
473
529
  function createSampler(id, ptr, len) {
@@ -482,11 +538,66 @@ export function createCommandDispatcher(device, ctx) {
482
538
  if (bg[id]) return;
483
539
  if (len === 0) return emptyDescriptor("createBindGroup", id);
484
540
  const { gi, entries } = decodeBindGroupData(new Uint8Array(mem.buffer, ptr, len));
485
- bgd[id] = { layoutId, gi, entries };
486
- DEBUG && dbg && console.log(`[GPU] createBindGroup(${id}) layoutId=${layoutId} entries=[${entries.map(e => `{b=${e.binding} rt=${e.rt} rid=${e.rid}}`).join(',')}]`);
487
- const p = pip[layoutId];
488
- if (!p) return;
489
- bg[id] = scoped("createBindGroup", id, () => device.createBindGroup({ layout: p.getBindGroupLayout(gi), entries: buildBindGroupEntries(entries) }));
541
+ // `alt` caches the auto-layout rebuilds set_bind_group makes when this
542
+ // group is bound under a pipeline other than `layoutId`, keyed by pipeline
543
+ // id. Filled lazily there; invalidated by resizeCanvasBound below, whose
544
+ // rebuilt textures would otherwise leave every cached entry holding a view
545
+ // of a destroyed texture. An explicit-BGL group never rebuilds (see below),
546
+ // so its `alt` stays null.
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(',')}]`);
548
+ const layout = resolveBindGroupLayout(layoutId, gi);
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.
554
+ bg[id] = scoped("createBindGroup", id, () => device.createBindGroup({ layout, entries: buildBindGroupEntries(entries) }));
555
+ bgd[id] = { layoutId, gi, entries, alt: null };
556
+ }
557
+
558
+ // `layout_id` names one of two id spaces, discriminated by BGL_TAG: tagged is a
559
+ // standalone (bind-group-layout …) id, untagged is the id of the pipeline whose
560
+ // auto-derived layout the group targets. Both are numbered from 0, so the tag is
561
+ // the only thing separating them.
562
+ //
563
+ // The spaces do NOT fall back to each other. WebGPU makes an auto-derived layout
564
+ // exclusive to its own pipeline, and an explicitly created layout incompatible
565
+ // with any auto-layout pipeline — so resolving one as the other does not produce
566
+ // a merely different layout, it produces a bind group the driver rejects at draw
567
+ // time. Returning undefined (→ no bind group) is the honest outcome. §339.
568
+ function resolveBindGroupLayout(layoutId, gi) {
569
+ if (layoutId & BGL_TAG) return bgl[layoutId & ~BGL_TAG];
570
+ return pip[layoutId]?.getBindGroupLayout(gi);
571
+ }
572
+
573
+ function fmtLayoutId(layoutId) {
574
+ return (layoutId & BGL_TAG) ? `bgl:${layoutId & ~BGL_TAG}` : `pipeline:${layoutId}`;
575
+ }
576
+
577
+ // Install a texture and its default view together, so `dfv[id]` exists for
578
+ // exactly the ids `tex[id]` does. The two call sites are the only places a
579
+ // texture enters a table: createTexture and the resize rebuild.
580
+ //
581
+ // Why the view is cached at all: every attachment and every rt-1 bind-group
582
+ // entry used to mint a fresh `createView()` at the point of use, which for an
583
+ // attachment is once per pass per FRAME — 99 views per frame across the
584
+ // example corpus, none released (the wire protocol has no destroy for a view,
585
+ // and WebGPU offers none either; they go when the GC reaches the wrapper).
586
+ // Collectable, so not growth — but invisible to BOTH leak instruments, which
587
+ // is what made it worth fixing rather than documenting (LEAK-07-A, §351).
588
+ //
589
+ // Why eagerly rather than lazily: a lazy fill happens on the first pass that
590
+ // needs the view, i.e. inside frame 0, and a create inside a frame is exactly
591
+ // what the frame-purity gate exists to forbid. Creating it here keeps the
592
+ // gate's allowlist honest instead of carving out an exception for the fill.
593
+ //
594
+ // NOT used for the swap-chain texture: getCurrentTexture() returns a DIFFERENT
595
+ // GPUTexture each frame, so a cached view of it would point a pass at a stale
596
+ // image. That one createView stays per-frame, and is the only one the
597
+ // frame-purity allowlist admits.
598
+ function installTexture(id, texture) {
599
+ tex[id] = texture;
600
+ dfv[id] = texture.createView();
490
601
  }
491
602
 
492
603
  // Map decoded bind-group entries (rt 0=buffer, 1=texture default-view,
@@ -497,18 +608,21 @@ export function createCommandDispatcher(device, ctx) {
497
608
  return entries.map(e => {
498
609
  const entry = { binding: e.binding };
499
610
  if (e.rt === 0) { entry.resource = { buffer: buf[e.rid] }; if (e.offset) entry.resource.offset = e.offset; if (e.size) entry.resource.size = e.size; }
500
- else if (e.rt === 1) entry.resource = tex[e.rid]?.createView();
611
+ else if (e.rt === 1) entry.resource = dfv[e.rid];
501
612
  else if (e.rt === 2) entry.resource = smp[e.rid];
502
613
  else if (e.rt === 4) entry.resource = txv[e.rid]; // pre-created (texture-view …)
503
614
  return entry;
504
615
  });
505
616
  }
506
617
 
507
- // Build one color attachment. r/g/b/a are 0-255 bytes; load 1=clear else load,
508
- // 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.
509
623
  function colorAttachment(view, load, store, r, g, b, a) {
510
624
  return { view, loadOp: load === 1 ? "clear" : "load", storeOp: store === 0 ? "store" : "discard",
511
- 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 } };
512
626
  }
513
627
 
514
628
  // Apply pending pass-scoped state (depth-stencil attachment, occlusion query
@@ -517,7 +631,7 @@ export function createCommandDispatcher(device, ctx) {
517
631
  if (depthId !== 0xffff && tex[depthId]) {
518
632
  const pds = pendingDepthStencilOps;
519
633
  const pcv = pendingClearValues;
520
- const dsa = { view: tex[depthId].createView(), depthLoadOp: pds ? pds.dl : "clear", depthStoreOp: pds ? pds.ds : "store", depthClearValue: pcv ? pcv.depth : 1.0 };
634
+ const dsa = { view: dfv[depthId], depthLoadOp: pds ? pds.dl : "clear", depthStoreOp: pds ? pds.ds : "store", depthClearValue: pcv ? pcv.depth : 1.0 };
521
635
  if (txd[depthId]?.format?.includes("stencil")) { dsa.stencilLoadOp = pds ? pds.sl : "clear"; dsa.stencilStoreOp = pds ? pds.ss : "store"; dsa.stencilClearValue = pcv ? pcv.stencil : 0; }
522
636
  pd.depthStencilAttachment = dsa;
523
637
  pendingDepthStencilOps = null;
@@ -541,11 +655,11 @@ export function createCommandDispatcher(device, ctx) {
541
655
  const canvasTex = targetCtx.getCurrentTexture();
542
656
  cv = canvasTex.createView();
543
657
  } else {
544
- cv = tex[colorId]?.createView();
658
+ cv = dfv[colorId];
545
659
  }
546
660
  const att = colorAttachment(cv, loadOp, storeOp, cr, cg, cb, ca);
547
661
  if (resolveId !== undefined && resolveId !== 0xffff) {
548
- att.resolveTarget = (resolveId === CANVAS) ? targetCtx.getCurrentTexture().createView() : tex[resolveId]?.createView();
662
+ att.resolveTarget = (resolveId === CANVAS) ? targetCtx.getCurrentTexture().createView() : dfv[resolveId];
549
663
  }
550
664
  pd = { colorAttachments: [att] };
551
665
  }
@@ -557,7 +671,7 @@ export function createCommandDispatcher(device, ctx) {
557
671
  if (!enc) enc = device.createCommandEncoder();
558
672
  const CANVAS = 0xfffe;
559
673
  const colorAttachments = attachments.map(a => {
560
- const cv = (a.tid === CANVAS) ? targetCtx.getCurrentTexture().createView() : tex[a.tid]?.createView();
674
+ const cv = (a.tid === CANVAS) ? targetCtx.getCurrentTexture().createView() : dfv[a.tid];
561
675
  return colorAttachment(cv, a.load, a.store, a.r, a.g, a.b, a.a);
562
676
  });
563
677
  DEBUG && dbg && console.log(`[GPU] beginRenderPassMRT count=${attachments.length} depth=${depthId}`);
@@ -587,6 +701,7 @@ export function createCommandDispatcher(device, ctx) {
587
701
  createComputePipeline,
588
702
  createBindGroup,
589
703
  txv,
704
+ txs,
590
705
  tex,
591
706
  bgl,
592
707
  device,
@@ -639,11 +754,12 @@ export function createCommandDispatcher(device, ctx) {
639
754
  return e;
640
755
  },
641
756
  clock: () => ({ time, cw, ch }),
642
- pointer: () => [px, py, pcx, pcy, pdx, pdy, pb, pp, pm, psx, psy],
757
+ scratch,
643
758
  decodeWasmArgs: (ab) => decodeWasmArgs(ab, { cw, ch, time, tdelta }),
644
759
  getOnQueryResult: () => onQueryResult,
645
760
  debug: () => dbg,
646
761
  reportError: (e) => { onError && onError(e); },
762
+ alive: () => alive,
647
763
  };
648
764
 
649
765
  // Main dispatch - inline command constants for minification
@@ -664,8 +780,33 @@ export function createCommandDispatcher(device, ctx) {
664
780
  return UNKNOWN_CMD;
665
781
  }
666
782
 
783
+ // Command buffers executed since this dispatcher was built. The denominator
784
+ // for "resources per frame" in a soak — a live count that is flat over 10
785
+ // buffers and flat over 600 are very different statements.
786
+ let executed = 0;
787
+
788
+ /**
789
+ * Live GPU objects this dispatcher holds, by kind. See gpu-stats.js for why
790
+ * these are derived from the tables rather than counted at each create.
791
+ */
792
+ function getStats() {
793
+ const { live, total } = countLive({
794
+ // Two view tables, counted apart: `txv` is an authored resource
795
+ // ((texture-view …), bound as rt 4), `dfv` is the dispatcher's own
796
+ // per-texture default-view cache. Merging them would hide which side grew.
797
+ buffer: buf, texture: tex, textureView: txv, defaultView: dfv,
798
+ sampler: smp, shader: shd,
799
+ pipeline: pip, bindGroup: bg, bindGroupLayout: bgl, pipelineLayout: ppl,
800
+ imageBitmap: bmp, wasmModule: wm, renderBundle: bun, querySet: qs,
801
+ });
802
+ const cachedBindGroups = countCachedBindGroups(bgd);
803
+ live.bindGroup += cachedBindGroups;
804
+ return { live, total: total + cachedBindGroups, cachedBindGroups, executed };
805
+ }
806
+
667
807
  // Execute command buffer
668
808
  async function execute(ptr) {
809
+ executed++;
669
810
  let view = new DataView(mem.buffer);
670
811
  const totalLen = view.getUint32(ptr, true);
671
812
  const cmdCount = view.getUint16(ptr + 4, true);
@@ -684,6 +825,11 @@ export function createCommandDispatcher(device, ctx) {
684
825
  }
685
826
  if (result instanceof Promise) {
686
827
  pos = await result;
828
+ // destroy() is synchronous and can run during an async command (0x0B
829
+ // decode, 0x30 compile). Past this point the loop reads `mem`, which
830
+ // destroy() drops (a TypeError), and every create it reaches lands in a
831
+ // table already emptied (a leak).
832
+ if (!alive) break;
687
833
  view = new DataView(mem.buffer);
688
834
  } else {
689
835
  pos = result;
@@ -691,16 +837,44 @@ export function createCommandDispatcher(device, ctx) {
691
837
  }
692
838
  }
693
839
 
694
- // Destroy resources
840
+ // Release everything this dispatcher holds.
841
+ //
842
+ // Runs on every payload reload (worker-core.js loadBytecode) — in an editor,
843
+ // that is once per compile — and on teardown. The reload path then builds a
844
+ // FRESH dispatcher, so the tables below become garbage wholesale either way;
845
+ // what this function buys is DETERMINISTIC release, which for GPU-backed
846
+ // objects is the difference between freeing driver memory now and freeing it
847
+ // whenever the JS wrapper happens to be collected.
848
+ //
849
+ // Three kinds carry an explicit release and so must appear here: GPUBuffer
850
+ // and GPUTexture (destroy), GPUQuerySet (destroy), and ImageBitmap (close —
851
+ // a decoded bitmap is megabytes of pixel memory). GPURenderBundle, shader
852
+ // modules, pipelines and layouts have no release method; truncating their
853
+ // tables just drops the references.
695
854
  function destroy() {
855
+ alive = false;
696
856
  buf.forEach(b => b?.destroy?.());
697
857
  tex.forEach(t => t?.destroy?.());
698
- buf.length = tex.length = txv.length = smp.length = shd.length = pip.length = 0;
858
+ qs.forEach(q => q?.destroy?.());
859
+ bmp.forEach(b => b?.close?.());
860
+ buf.length = tex.length = txv.length = dfv.length = smp.length = shd.length = pip.length = 0;
699
861
  bg.length = bgl.length = ppl.length = bmp.length = wm.length = 0;
700
- wcr.length = bgd.length = txd.length = bufUsage.length = 0;
862
+ wcr.length = bgd.length = txd.length = txs.length = bufUsage.length = 0;
863
+ qs.length = bun.length = 0;
701
864
  curPip = -1;
702
865
  pendingReadbacks.length = 0;
703
- onQueryResult = null;
866
+ pendingOcclusionQS = pendingTimestampWrites = null;
867
+ pendingDepthStencilOps = pendingClearValues = null;
868
+ // The remaining closure state. Moot while a destroyed dispatcher is
869
+ // immediately replaced, but handleDestroy now keeps the worker alive
870
+ // between the device teardown and the terminate — so a dispatcher can
871
+ // genuinely outlive its device, and `mem` in particular pins the executor's
872
+ // whole WASM memory.
873
+ onQueryResult = onError = onShaderError = null;
874
+ uniformMap = null;
875
+ mem = null;
876
+ targetCtx = null;
877
+ enc = pass = null;
704
878
  }
705
879
 
706
880
  // Uniform table: Map<string, {bufferId, offset, size, type, elemCount}>
@@ -784,19 +958,36 @@ export function createCommandDispatcher(device, ctx) {
784
958
  tex[id].destroy?.();
785
959
  const desc = { size: [w || 1, h || 1, d.depth || 1], format: d.format, usage: d.usage, sampleCount: d.sampleCount || 1 };
786
960
  if (d.dimension) desc.dimension = d.dimension;
787
- tex[id] = device.createTexture(desc);
961
+ installTexture(id, device.createTexture(desc));
962
+ }
963
+ // Explicit (texture-view …) resources of a recreated texture, remade from
964
+ // their recorded source. Must run BEFORE the bind-group loop below, which
965
+ // reads txv. Skipped for views of ordinary textures: those textures were
966
+ // not touched, so their views are still valid.
967
+ for (let id = 0; id < txv.length; id++) {
968
+ const s = txs[id];
969
+ if (!s || !txd[s.tid]?.canvasBound || !tex[s.tid]) continue;
970
+ txv[id] = tex[s.tid].createView(s.desc);
788
971
  }
789
972
  // Bind groups that referenced a recreated texture still hold a stale view.
790
- // Rebuild any bind group that has a texture entry (rt === 1) pointing at a
791
- // canvas-bound texture.
973
+ // Rebuild any bind group with an entry pointing at a canvas-bound texture,
974
+ // by its default view (rt 1) or through an explicit one (rt 4). Missing the
975
+ // rt-4 half left the group binding a view of a texture whose memory this
976
+ // function had just freed — bounded, and permanently broken (LEAK-07-B).
792
977
  for (let id = 0; id < bg.length; id++) {
793
978
  const d = bgd[id];
794
979
  if (!d) continue;
795
- const needsRebuild = d.entries.some(e => e.rt === 1 && txd[e.rid]?.canvasBound);
980
+ const needsRebuild = d.entries.some(e => e.rt === 1
981
+ ? txd[e.rid]?.canvasBound
982
+ : e.rt === 4 && txd[txs[e.rid]?.tid]?.canvasBound);
796
983
  if (!needsRebuild) continue;
797
- const p = pip[d.layoutId];
798
- if (!p) continue;
799
- bg[id] = device.createBindGroup({ layout: p.getBindGroupLayout(d.gi), entries: buildBindGroupEntries(d.entries) });
984
+ // Drop the per-pipeline auto-layout cache too: its entries hold views of
985
+ // the textures just destroyed above, and set_bind_group would keep
986
+ // handing them out. They rebuild lazily on the next bind.
987
+ d.alt = null;
988
+ const layout = resolveBindGroupLayout(d.layoutId, d.gi);
989
+ if (!layout) continue;
990
+ bg[id] = device.createBindGroup({ layout, entries: buildBindGroupEntries(d.entries) });
800
991
  }
801
992
  }
802
993
 
@@ -805,7 +996,7 @@ export function createCommandDispatcher(device, ctx) {
805
996
  setDebug(v) { dbg = v; },
806
997
  setMemory(m) { mem = m; },
807
998
  setTime(t) { tdelta = t - time; time = t; },
808
- setPointer(s) { px = s[0]; py = s[1]; pcx = s[2]; pcy = s[3]; pdx = s[4]; pdy = s[5]; pb = s[6]; pp = s[7]; pm = s[8]; psx = s[9]; psy = s[10]; },
999
+ setPointer(s) { scratch.ptr.set(s); },
809
1000
  setCanvasSize(w, h) { cw = w; ch = h; },
810
1001
  resizeCanvasBound,
811
1002
  setRenderTargetContext(c) { targetCtx = c || ctx; },
@@ -815,6 +1006,7 @@ export function createCommandDispatcher(device, ctx) {
815
1006
  setUniformTable,
816
1007
  setUniform,
817
1008
  setUniforms,
1009
+ getStats,
818
1010
  execute,
819
1011
  destroy,
820
1012
  };