@holtjs/stage 0.13.0 → 0.15.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.
@@ -1669,14 +1669,24 @@ async function resolveWgpuLibPath(explicitPath) {
1669
1669
  if (envPath) return String(envPath);
1670
1670
  if (!proc) return null;
1671
1671
  try {
1672
- const [fsNs, pathNs] = await Promise.all([dynamicImport("node:fs"), dynamicImport("node:path")]);
1672
+ const [fsNs, pathNs, osNs] = await Promise.all([
1673
+ dynamicImport("node:fs"),
1674
+ dynamicImport("node:path"),
1675
+ dynamicImport("node:os")
1676
+ ]);
1673
1677
  const plat = proc.platform ?? "linux";
1674
1678
  const libNames = plat === "darwin" ? ["libwgpu_native.dylib"] : plat === "win32" ? ["wgpu_native.dll", "libwgpu_native.dll"] : ["libwgpu_native.so"];
1675
1679
  const cwd = typeof proc.cwd === "function" ? proc.cwd() : ".";
1680
+ const home = typeof osNs.homedir === "function" ? osNs.homedir() : "";
1676
1681
  const searchDirs = [
1677
1682
  cwd,
1678
1683
  pathNs.join(cwd, "lib"),
1679
1684
  pathNs.join(cwd, "native"),
1685
+ ...home ? [
1686
+ pathNs.join(home, ".cache", "holt-stage", "wgpu", "lib"),
1687
+ pathNs.join(home, ".cache", "holt-stage", "wgpu"),
1688
+ pathNs.join(home, ".local", "lib")
1689
+ ] : [],
1680
1690
  "/usr/local/lib",
1681
1691
  "/usr/lib",
1682
1692
  "/opt/homebrew/lib"
@@ -1688,6 +1698,67 @@ async function resolveWgpuLibPath(explicitPath) {
1688
1698
  } catch {}
1689
1699
  return null;
1690
1700
  }
1701
+ /**
1702
+ * On headless Linux servers without system `/usr/share/vulkan/icd.d/*.json`, automatically wire
1703
+ * Playwright / Chromium's bundled SwiftShader Vulkan ICD (`vk_swiftshader_icd.json`) into `VK_ICD_FILENAMES`
1704
+ * when the caller has not explicitly configured `VK_ICD_FILENAMES` or `VK_DRIVER_FILES`.
1705
+ */
1706
+ async function ensureHeadlessVulkanIcd() {
1707
+ const proc = getProcessLike();
1708
+ if (!proc?.env || proc.platform !== "linux") return;
1709
+ if (proc.env.VK_ICD_FILENAMES || proc.env.VK_DRIVER_FILES) return;
1710
+ try {
1711
+ const [fsNs, pathNs, osNs] = await Promise.all([
1712
+ dynamicImport("node:fs"),
1713
+ dynamicImport("node:path"),
1714
+ dynamicImport("node:os")
1715
+ ]);
1716
+ for (const dir of [
1717
+ "/usr/share/vulkan/icd.d",
1718
+ "/etc/vulkan/icd.d",
1719
+ "/usr/local/share/vulkan/icd.d"
1720
+ ]) {
1721
+ if (!fsNs.existsSync(dir)) continue;
1722
+ if (fsNs.readdirSync(dir).some((f) => f.endsWith(".json"))) return;
1723
+ }
1724
+ const home = typeof osNs.homedir === "function" ? osNs.homedir() : "";
1725
+ const pwRoots = [proc.env.PLAYWRIGHT_BROWSERS_PATH, home ? pathNs.join(home, ".cache", "ms-playwright") : ""].filter(Boolean);
1726
+ for (const root of pwRoots) {
1727
+ if (!fsNs.existsSync(root)) continue;
1728
+ const entries = fsNs.readdirSync(root).sort().reverse();
1729
+ for (const entry of entries) {
1730
+ if (!entry.startsWith("chromium")) continue;
1731
+ for (const sub of [
1732
+ "chrome-linux64",
1733
+ "chrome-linux",
1734
+ "chrome-headless-shell-linux64",
1735
+ "chrome-headless-shell-linux"
1736
+ ]) {
1737
+ const icd = pathNs.join(root, entry, sub, "vk_swiftshader_icd.json");
1738
+ if (fsNs.existsSync(icd)) {
1739
+ proc.env.VK_ICD_FILENAMES = icd;
1740
+ if (isBunRuntime()) try {
1741
+ const ffi = await dynamicImport("bun:ffi");
1742
+ const enc = new TextEncoder();
1743
+ const libc = ffi.dlopen("libc.so.6", { setenv: {
1744
+ args: [
1745
+ ffi.FFIType.ptr,
1746
+ ffi.FFIType.ptr,
1747
+ ffi.FFIType.i32
1748
+ ],
1749
+ returns: ffi.FFIType.i32
1750
+ } });
1751
+ const kBuf = enc.encode("VK_ICD_FILENAMES\0");
1752
+ const vBuf = enc.encode(`${icd}\0`);
1753
+ libc.symbols.setenv(ffi.ptr(kBuf), ffi.ptr(vBuf), 0);
1754
+ } catch {}
1755
+ return;
1756
+ }
1757
+ }
1758
+ }
1759
+ }
1760
+ } catch {}
1761
+ }
1691
1762
  const WGPUSType_ShaderSourceWGSL = 2;
1692
1763
  const WGPUCallbackMode_AllowSpontaneous = 3;
1693
1764
  const WGPUPowerPreference_LowPower = 1;
@@ -2992,6 +3063,7 @@ function createWgpuDeviceWrapper(drv, instance, adapter, devPtr, queuePtr) {
2992
3063
  async function openWgpuNativeFfi(options = {}) {
2993
3064
  const libPath = await resolveWgpuLibPath(options.libPath);
2994
3065
  if (!libPath) return null;
3066
+ await ensureHeadlessVulkanIcd();
2995
3067
  const wantRuntime = options.runtime ?? "auto";
2996
3068
  const useBun = wantRuntime === "bun" || wantRuntime === "auto" && isBunRuntime();
2997
3069
  let drv = null;
@@ -3128,11 +3200,11 @@ async function requestWebGpuDevice(canvas, options = {}) {
3128
3200
  return null;
3129
3201
  }
3130
3202
  }
3131
- const MAX_VERTS = 65536;
3132
- const MAX_INDICES = 98304;
3203
+ const INITIAL_VERTS = 65536;
3204
+ const INITIAL_INDICES = 98304;
3133
3205
  const VERT_FLOATS = 6;
3134
3206
  const VERT_STRIDE = 24;
3135
- const MAX_SDF_PANELS = 16384;
3207
+ const INITIAL_SDF_PANELS = 16384;
3136
3208
  const SDF_FLOATS = 16;
3137
3209
  const SDF_STRIDE = 64;
3138
3210
  const WGSL_BATCH_SRC = `
@@ -3405,18 +3477,27 @@ var RendererWebGpu = class extends EventEmitter {
3405
3477
  sdfQuadIbo;
3406
3478
  samplerLinear;
3407
3479
  samplerNearest;
3480
+ samplerLinearRepeat;
3481
+ samplerNearestRepeat;
3408
3482
  batchBgl;
3409
3483
  sdfBgl;
3410
3484
  sdfBindGroup;
3485
+ batchMod;
3486
+ batchLayout;
3487
+ sdfMod;
3488
+ sdfLayout;
3411
3489
  batchPipelines = /* @__PURE__ */ new Map();
3412
3490
  sdfPipelines = /* @__PURE__ */ new Map();
3413
3491
  texCache = /* @__PURE__ */ new WeakMap();
3414
3492
  dummyEntry;
3415
- vertRaw = new ArrayBuffer(MAX_VERTS * VERT_STRIDE);
3493
+ vertCap = INITIAL_VERTS;
3494
+ indexCap = INITIAL_INDICES;
3495
+ vertRaw = new ArrayBuffer(INITIAL_VERTS * VERT_STRIDE);
3416
3496
  f32 = new Float32Array(this.vertRaw);
3417
3497
  u32 = new Uint32Array(this.vertRaw);
3418
- indices = new Uint16Array(MAX_INDICES);
3419
- sdfRaw = new ArrayBuffer(MAX_SDF_PANELS * SDF_STRIDE);
3498
+ indices = new Uint32Array(INITIAL_INDICES);
3499
+ sdfCap = INITIAL_SDF_PANELS;
3500
+ sdfRaw = new ArrayBuffer(INITIAL_SDF_PANELS * SDF_STRIDE);
3420
3501
  sdfF32 = new Float32Array(this.sdfRaw);
3421
3502
  sdfU32 = new Uint32Array(this.sdfRaw);
3422
3503
  vertCount = 0;
@@ -3424,6 +3505,8 @@ var RendererWebGpu = class extends EventEmitter {
3424
3505
  cmdStartIndex = 0;
3425
3506
  sdfCount = 0;
3426
3507
  sdfCmdStart = 0;
3508
+ curTargetW = 1;
3509
+ curTargetH = 1;
3427
3510
  curBlend = BlendModes.NORMAL;
3428
3511
  curBindGroup = null;
3429
3512
  cmds = [];
@@ -3515,6 +3598,18 @@ var RendererWebGpu = class extends EventEmitter {
3515
3598
  magFilter: "nearest",
3516
3599
  minFilter: "nearest"
3517
3600
  });
3601
+ this.samplerLinearRepeat = dev.createSampler({
3602
+ magFilter: "linear",
3603
+ minFilter: "linear",
3604
+ addressModeU: "repeat",
3605
+ addressModeV: "repeat"
3606
+ });
3607
+ this.samplerNearestRepeat = dev.createSampler({
3608
+ magFilter: "nearest",
3609
+ minFilter: "nearest",
3610
+ addressModeU: "repeat",
3611
+ addressModeV: "repeat"
3612
+ });
3518
3613
  this.batchBgl = dev.createBindGroupLayout({ entries: [
3519
3614
  {
3520
3615
  binding: 0,
@@ -3544,101 +3639,18 @@ var RendererWebGpu = class extends EventEmitter {
3544
3639
  resource: { buffer: this.globalsBuf }
3545
3640
  }]
3546
3641
  });
3547
- const batchMod = dev.createShaderModule({ code: WGSL_BATCH_SRC });
3548
- const batchLayout = dev.createPipelineLayout({ bindGroupLayouts: [this.batchBgl] });
3549
- const sdfMod = dev.createShaderModule({ code: WGSL_SDF_SRC });
3550
- const sdfLayout = dev.createPipelineLayout({ bindGroupLayouts: [this.sdfBgl] });
3642
+ this.batchMod = dev.createShaderModule({ code: WGSL_BATCH_SRC });
3643
+ this.batchLayout = dev.createPipelineLayout({ bindGroupLayouts: [this.batchBgl] });
3644
+ this.sdfMod = dev.createShaderModule({ code: WGSL_SDF_SRC });
3645
+ this.sdfLayout = dev.createPipelineLayout({ bindGroupLayouts: [this.sdfBgl] });
3551
3646
  for (const mode of [
3552
3647
  BlendModes.NORMAL,
3553
3648
  BlendModes.ADD,
3554
3649
  BlendModes.MULTIPLY,
3555
3650
  BlendModes.SCREEN
3556
3651
  ]) {
3557
- this.batchPipelines.set(mode, dev.createRenderPipeline({
3558
- layout: batchLayout,
3559
- vertex: {
3560
- module: batchMod,
3561
- entryPoint: "vsMain",
3562
- buffers: [{
3563
- arrayStride: VERT_STRIDE,
3564
- attributes: [
3565
- {
3566
- shaderLocation: 0,
3567
- offset: 0,
3568
- format: "float32x2"
3569
- },
3570
- {
3571
- shaderLocation: 1,
3572
- offset: 8,
3573
- format: "float32x2"
3574
- },
3575
- {
3576
- shaderLocation: 2,
3577
- offset: 16,
3578
- format: "uint32"
3579
- },
3580
- {
3581
- shaderLocation: 3,
3582
- offset: 20,
3583
- format: "float32"
3584
- }
3585
- ]
3586
- }]
3587
- },
3588
- fragment: {
3589
- module: batchMod,
3590
- entryPoint: "fsMain",
3591
- targets: [blendTargetState(format, mode)]
3592
- },
3593
- primitive: { topology: "triangle-list" }
3594
- }));
3595
- this.sdfPipelines.set(mode, dev.createRenderPipeline({
3596
- layout: sdfLayout,
3597
- vertex: {
3598
- module: sdfMod,
3599
- entryPoint: "vsSdf",
3600
- buffers: [{
3601
- arrayStride: 8,
3602
- stepMode: "vertex",
3603
- attributes: [{
3604
- shaderLocation: 0,
3605
- offset: 0,
3606
- format: "float32x2"
3607
- }]
3608
- }, {
3609
- arrayStride: SDF_STRIDE,
3610
- stepMode: "instance",
3611
- attributes: [
3612
- {
3613
- shaderLocation: 1,
3614
- offset: 0,
3615
- format: "float32x4"
3616
- },
3617
- {
3618
- shaderLocation: 2,
3619
- offset: 16,
3620
- format: "float32x4"
3621
- },
3622
- {
3623
- shaderLocation: 3,
3624
- offset: 32,
3625
- format: "float32x4"
3626
- },
3627
- {
3628
- shaderLocation: 4,
3629
- offset: 48,
3630
- format: "float32x4"
3631
- }
3632
- ]
3633
- }]
3634
- },
3635
- fragment: {
3636
- module: sdfMod,
3637
- entryPoint: "fsSdf",
3638
- targets: [blendTargetState(format, mode)]
3639
- },
3640
- primitive: { topology: "triangle-list" }
3641
- }));
3652
+ this.getBatchPipeline(format, mode);
3653
+ this.getSdfPipeline(format, mode);
3642
3654
  }
3643
3655
  const dummyTex = dev.createTexture({
3644
3656
  size: [
@@ -3673,6 +3685,159 @@ var RendererWebGpu = class extends EventEmitter {
3673
3685
  bindGroupNearest: this.makeBatchBindGroup(dummyView, this.samplerNearest)
3674
3686
  };
3675
3687
  }
3688
+ getBatchPipeline(targetFormat, mode) {
3689
+ const key = `${targetFormat}:${mode}`;
3690
+ let p = this.batchPipelines.get(key);
3691
+ if (p) return p;
3692
+ p = this.device.createRenderPipeline({
3693
+ layout: this.batchLayout,
3694
+ vertex: {
3695
+ module: this.batchMod,
3696
+ entryPoint: "vsMain",
3697
+ buffers: [{
3698
+ arrayStride: VERT_STRIDE,
3699
+ attributes: [
3700
+ {
3701
+ shaderLocation: 0,
3702
+ offset: 0,
3703
+ format: "float32x2"
3704
+ },
3705
+ {
3706
+ shaderLocation: 1,
3707
+ offset: 8,
3708
+ format: "float32x2"
3709
+ },
3710
+ {
3711
+ shaderLocation: 2,
3712
+ offset: 16,
3713
+ format: "uint32"
3714
+ },
3715
+ {
3716
+ shaderLocation: 3,
3717
+ offset: 20,
3718
+ format: "float32"
3719
+ }
3720
+ ]
3721
+ }]
3722
+ },
3723
+ fragment: {
3724
+ module: this.batchMod,
3725
+ entryPoint: "fsMain",
3726
+ targets: [blendTargetState(targetFormat, mode)]
3727
+ },
3728
+ primitive: { topology: "triangle-list" }
3729
+ });
3730
+ this.batchPipelines.set(key, p);
3731
+ return p;
3732
+ }
3733
+ getSdfPipeline(targetFormat, mode) {
3734
+ const key = `${targetFormat}:${mode}`;
3735
+ let p = this.sdfPipelines.get(key);
3736
+ if (p) return p;
3737
+ p = this.device.createRenderPipeline({
3738
+ layout: this.sdfLayout,
3739
+ vertex: {
3740
+ module: this.sdfMod,
3741
+ entryPoint: "vsSdf",
3742
+ buffers: [{
3743
+ arrayStride: 8,
3744
+ stepMode: "vertex",
3745
+ attributes: [{
3746
+ shaderLocation: 0,
3747
+ offset: 0,
3748
+ format: "float32x2"
3749
+ }]
3750
+ }, {
3751
+ arrayStride: SDF_STRIDE,
3752
+ stepMode: "instance",
3753
+ attributes: [
3754
+ {
3755
+ shaderLocation: 1,
3756
+ offset: 0,
3757
+ format: "float32x4"
3758
+ },
3759
+ {
3760
+ shaderLocation: 2,
3761
+ offset: 16,
3762
+ format: "float32x4"
3763
+ },
3764
+ {
3765
+ shaderLocation: 3,
3766
+ offset: 32,
3767
+ format: "float32x4"
3768
+ },
3769
+ {
3770
+ shaderLocation: 4,
3771
+ offset: 48,
3772
+ format: "float32x4"
3773
+ }
3774
+ ]
3775
+ }]
3776
+ },
3777
+ fragment: {
3778
+ module: this.sdfMod,
3779
+ entryPoint: "fsSdf",
3780
+ targets: [blendTargetState(targetFormat, mode)]
3781
+ },
3782
+ primitive: { topology: "triangle-list" }
3783
+ });
3784
+ this.sdfPipelines.set(key, p);
3785
+ return p;
3786
+ }
3787
+ ensureBatchCapacity(extraVerts, extraIndices) {
3788
+ if (this.vertCount + extraVerts > this.vertCap) {
3789
+ let nextCap = this.vertCap;
3790
+ while (nextCap < this.vertCount + extraVerts) nextCap *= 2;
3791
+ const nextRaw = new ArrayBuffer(nextCap * VERT_STRIDE);
3792
+ const nextF32 = new Float32Array(nextRaw);
3793
+ nextF32.set(this.f32.subarray(0, this.vertCount * VERT_FLOATS));
3794
+ this.vertCap = nextCap;
3795
+ this.vertRaw = nextRaw;
3796
+ this.f32 = nextF32;
3797
+ this.u32 = new Uint32Array(nextRaw);
3798
+ try {
3799
+ this.vbo?.destroy?.();
3800
+ } catch {}
3801
+ this.vbo = this.device.createBuffer({
3802
+ size: nextRaw.byteLength,
3803
+ usage: 40
3804
+ });
3805
+ }
3806
+ if (this.indexCount + extraIndices > this.indexCap) {
3807
+ let nextCap = this.indexCap;
3808
+ while (nextCap < this.indexCount + extraIndices) nextCap *= 2;
3809
+ const nextInd = new Uint32Array(nextCap);
3810
+ nextInd.set(this.indices.subarray(0, this.indexCount));
3811
+ this.indexCap = nextCap;
3812
+ this.indices = nextInd;
3813
+ try {
3814
+ this.ibo?.destroy?.();
3815
+ } catch {}
3816
+ this.ibo = this.device.createBuffer({
3817
+ size: nextInd.byteLength,
3818
+ usage: 24
3819
+ });
3820
+ }
3821
+ }
3822
+ ensureSdfCapacity(extraInstances) {
3823
+ if (this.sdfCount + extraInstances <= this.sdfCap) return;
3824
+ let nextCap = this.sdfCap;
3825
+ while (nextCap < this.sdfCount + extraInstances) nextCap *= 2;
3826
+ const nextRaw = new ArrayBuffer(nextCap * SDF_STRIDE);
3827
+ const nextF32 = new Float32Array(nextRaw);
3828
+ nextF32.set(this.sdfF32.subarray(0, this.sdfCount * SDF_FLOATS));
3829
+ this.sdfCap = nextCap;
3830
+ this.sdfRaw = nextRaw;
3831
+ this.sdfF32 = nextF32;
3832
+ this.sdfU32 = new Uint32Array(nextRaw);
3833
+ try {
3834
+ this.sdfInstVbo?.destroy?.();
3835
+ } catch {}
3836
+ this.sdfInstVbo = this.device.createBuffer({
3837
+ size: nextRaw.byteLength,
3838
+ usage: 40
3839
+ });
3840
+ }
3676
3841
  makeBatchBindGroup(view, sampler) {
3677
3842
  return this.device.createBindGroup({
3678
3843
  layout: this.batchBgl,
@@ -3836,10 +4001,19 @@ var RendererWebGpu = class extends EventEmitter {
3836
4001
  if (dirty && entry && !isRenderTarget) this.extractAndUploadTexture(entry.tex, image, w, h, premultiply);
3837
4002
  return nearest ? entry.bindGroupNearest : entry.bindGroupLinear;
3838
4003
  }
3839
- ensureSourceBindGroup(src) {
3840
- const bg = this.ensureGpuTexture(src, src.image, src.width, src.height, src.filterMode === FilterMode.NEAREST, src.dirty, src.premultiplyAlpha, src.isRenderTarget);
4004
+ ensureSourceBindGroup(src, repeat = false) {
4005
+ const nearest = src.filterMode === FilterMode.NEAREST;
4006
+ const bg = this.ensureGpuTexture(src, src.image, src.width, src.height, nearest, src.dirty, src.premultiplyAlpha, src.isRenderTarget);
3841
4007
  src.dirty = false;
3842
- return bg;
4008
+ if (!repeat || !bg) return bg;
4009
+ const entry = this.texCache.get(src);
4010
+ if (!entry) return bg;
4011
+ if (nearest) {
4012
+ if (!entry.bindGroupNearestRepeat) entry.bindGroupNearestRepeat = this.makeBatchBindGroup(entry.view, this.samplerNearestRepeat);
4013
+ return entry.bindGroupNearestRepeat;
4014
+ }
4015
+ if (!entry.bindGroupLinearRepeat) entry.bindGroupLinearRepeat = this.makeBatchBindGroup(entry.view, this.samplerLinearRepeat);
4016
+ return entry.bindGroupLinearRepeat;
3843
4017
  }
3844
4018
  currentScissor() {
3845
4019
  return this.scissorStack.length > 0 ? { ...this.scissorStack[this.scissorStack.length - 1] } : null;
@@ -3880,36 +4054,45 @@ var RendererWebGpu = class extends EventEmitter {
3880
4054
  this.curBindGroup = bindGroup;
3881
4055
  }
3882
4056
  pushQuad(m, x0, y0, x1, y1, u0, v0, u1, v1, abgr, mode, blend, bindGroup) {
3883
- if (this.vertCount + 4 > MAX_VERTS || this.indexCount + 6 > MAX_INDICES) return;
4057
+ const a = m.a, b = m.b, c = m.c, d = m.d, tx = m.tx, ty = m.ty;
4058
+ const sx0 = a * x0 + c * y0 + tx, sy0 = b * x0 + d * y0 + ty;
4059
+ const sx1 = a * x1 + c * y0 + tx, sy1 = b * x1 + d * y0 + ty;
4060
+ const sx2 = a * x1 + c * y1 + tx, sy2 = b * x1 + d * y1 + ty;
4061
+ const sx3 = a * x0 + c * y1 + tx, sy3 = b * x0 + d * y1 + ty;
4062
+ const tw = this.curTargetW, th = this.curTargetH;
4063
+ if (sx0 < 0 && sx1 < 0 && sx2 < 0 && sx3 < 0 || sx0 > tw && sx1 > tw && sx2 > tw && sx3 > tw || sy0 < 0 && sy1 < 0 && sy2 < 0 && sy3 < 0 || sy0 > th && sy1 > th && sy2 > th && sy3 > th) {
4064
+ this.lastStats.culled++;
4065
+ return;
4066
+ }
4067
+ this.ensureBatchCapacity(4, 6);
3884
4068
  this.bindBatch(blend, bindGroup);
3885
4069
  const bv = this.vertCount;
3886
4070
  let fi = bv * VERT_FLOATS;
3887
4071
  const f32 = this.f32;
3888
4072
  const u32 = this.u32;
3889
- const a = m.a, b = m.b, c = m.c, d = m.d, tx = m.tx, ty = m.ty;
3890
- f32[fi] = a * x0 + c * y0 + tx;
3891
- f32[fi + 1] = b * x0 + d * y0 + ty;
4073
+ f32[fi] = sx0;
4074
+ f32[fi + 1] = sy0;
3892
4075
  f32[fi + 2] = u0;
3893
4076
  f32[fi + 3] = v0;
3894
4077
  u32[fi + 4] = abgr;
3895
4078
  f32[fi + 5] = mode;
3896
4079
  fi += VERT_FLOATS;
3897
- f32[fi] = a * x1 + c * y0 + tx;
3898
- f32[fi + 1] = b * x1 + d * y0 + ty;
4080
+ f32[fi] = sx1;
4081
+ f32[fi + 1] = sy1;
3899
4082
  f32[fi + 2] = u1;
3900
4083
  f32[fi + 3] = v0;
3901
4084
  u32[fi + 4] = abgr;
3902
4085
  f32[fi + 5] = mode;
3903
4086
  fi += VERT_FLOATS;
3904
- f32[fi] = a * x1 + c * y1 + tx;
3905
- f32[fi + 1] = b * x1 + d * y1 + ty;
4087
+ f32[fi] = sx2;
4088
+ f32[fi + 1] = sy2;
3906
4089
  f32[fi + 2] = u1;
3907
4090
  f32[fi + 3] = v1;
3908
4091
  u32[fi + 4] = abgr;
3909
4092
  f32[fi + 5] = mode;
3910
4093
  fi += VERT_FLOATS;
3911
- f32[fi] = a * x0 + c * y1 + tx;
3912
- f32[fi + 1] = b * x0 + d * y1 + ty;
4094
+ f32[fi] = sx3;
4095
+ f32[fi + 1] = sy3;
3913
4096
  f32[fi + 2] = u0;
3914
4097
  f32[fi + 3] = v1;
3915
4098
  u32[fi + 4] = abgr;
@@ -3926,29 +4109,37 @@ var RendererWebGpu = class extends EventEmitter {
3926
4109
  this.indexCount = ii + 6;
3927
4110
  }
3928
4111
  pushTri(m, x0, y0, x1, y1, x2, y2, abgr, blend) {
3929
- if (this.vertCount + 3 > MAX_VERTS || this.indexCount + 3 > MAX_INDICES) return;
4112
+ const a = m.a, b = m.b, c = m.c, d = m.d, tx = m.tx, ty = m.ty;
4113
+ const sx0 = a * x0 + c * y0 + tx, sy0 = b * x0 + d * y0 + ty;
4114
+ const sx1 = a * x1 + c * y1 + tx, sy1 = b * x1 + d * y1 + ty;
4115
+ const sx2 = a * x2 + c * y2 + tx, sy2 = b * x2 + d * y2 + ty;
4116
+ const tw = this.curTargetW, th = this.curTargetH;
4117
+ if (sx0 < 0 && sx1 < 0 && sx2 < 0 || sx0 > tw && sx1 > tw && sx2 > tw || sy0 < 0 && sy1 < 0 && sy2 < 0 || sy0 > th && sy1 > th && sy2 > th) {
4118
+ this.lastStats.culled++;
4119
+ return;
4120
+ }
4121
+ this.ensureBatchCapacity(3, 3);
3930
4122
  this.bindBatch(blend, this.dummyEntry.bindGroupLinear);
3931
4123
  const bv = this.vertCount;
3932
4124
  let fi = bv * VERT_FLOATS;
3933
4125
  const f32 = this.f32;
3934
4126
  const u32 = this.u32;
3935
- const a = m.a, b = m.b, c = m.c, d = m.d, tx = m.tx, ty = m.ty;
3936
- f32[fi] = a * x0 + c * y0 + tx;
3937
- f32[fi + 1] = b * x0 + d * y0 + ty;
4127
+ f32[fi] = sx0;
4128
+ f32[fi + 1] = sy0;
3938
4129
  f32[fi + 2] = 0;
3939
4130
  f32[fi + 3] = 0;
3940
4131
  u32[fi + 4] = abgr;
3941
4132
  f32[fi + 5] = 2;
3942
4133
  fi += VERT_FLOATS;
3943
- f32[fi] = a * x1 + c * y1 + tx;
3944
- f32[fi + 1] = b * x1 + d * y1 + ty;
4134
+ f32[fi] = sx1;
4135
+ f32[fi + 1] = sy1;
3945
4136
  f32[fi + 2] = 0;
3946
4137
  f32[fi + 3] = 0;
3947
4138
  u32[fi + 4] = abgr;
3948
4139
  f32[fi + 5] = 2;
3949
4140
  fi += VERT_FLOATS;
3950
- f32[fi] = a * x2 + c * y2 + tx;
3951
- f32[fi + 1] = b * x2 + d * y2 + ty;
4141
+ f32[fi] = sx2;
4142
+ f32[fi + 1] = sy2;
3952
4143
  f32[fi + 2] = 0;
3953
4144
  f32[fi + 3] = 0;
3954
4145
  u32[fi + 4] = abgr;
@@ -3961,12 +4152,21 @@ var RendererWebGpu = class extends EventEmitter {
3961
4152
  this.indexCount = ii + 3;
3962
4153
  }
3963
4154
  pushSdfInstance(m, rx, ry, w, h, rTL, rTR, rBR, rBL, borderW, pixelStep, fillAbgr, borderAbgr, blend) {
3964
- if (this.sdfCount >= MAX_SDF_PANELS || w <= 0 || h <= 0) return;
4155
+ if (w <= 0 || h <= 0) return;
4156
+ const tx = m.a * rx + m.c * ry + m.tx;
4157
+ const ty = m.b * rx + m.d * ry + m.ty;
4158
+ const sx1 = tx + m.a * w, sy1 = ty + m.b * w;
4159
+ const sx2 = sx1 + m.c * h, sy2 = sy1 + m.d * h;
4160
+ const sx3 = tx + m.c * h, sy3 = ty + m.d * h;
4161
+ const tw = this.curTargetW, th = this.curTargetH;
4162
+ if (tx < 0 && sx1 < 0 && sx2 < 0 && sx3 < 0 || tx > tw && sx1 > tw && sx2 > tw && sx3 > tw || ty < 0 && sy1 < 0 && sy2 < 0 && sy3 < 0 || ty > th && sy1 > th && sy2 > th && sy3 > th) {
4163
+ this.lastStats.culled++;
4164
+ return;
4165
+ }
4166
+ this.ensureSdfCapacity(1);
3965
4167
  if (this.indexCount > this.cmdStartIndex) this.flushPendingBatch();
3966
4168
  if (this.curBlend !== blend && this.sdfCount > this.sdfCmdStart) this.flushPendingSdf();
3967
4169
  this.curBlend = blend;
3968
- const tx = m.a * rx + m.c * ry + m.tx;
3969
- const ty = m.b * rx + m.d * ry + m.ty;
3970
4170
  const maxR = Math.min(w, h) * .5;
3971
4171
  const base = this.sdfCount * SDF_FLOATS;
3972
4172
  const f = this.sdfF32;
@@ -4230,27 +4430,86 @@ var RendererWebGpu = class extends EventEmitter {
4230
4430
  const txt = obj;
4231
4431
  const cv = txt.ensureCanvas();
4232
4432
  if (!cv || cv.width <= 0 || cv.height <= 0) break;
4233
- const prevRev = txt._wgpuRev ?? -1;
4234
- const curRev = txt.canvasDirty ? -2 : txt._wgpuSeq ?? 0;
4235
- const dirty = prevRev !== curRev || txt.glDirty;
4433
+ const dirty = Boolean(txt.glDirty);
4236
4434
  const bg = this.ensureGpuTexture(txt, cv, cv.width, cv.height, false, dirty);
4237
4435
  txt.glDirty = false;
4238
- txt._wgpuRev = curRev;
4239
4436
  if (!bg) break;
4240
4437
  const ox = txt.displayOriginX, oy = txt.displayOriginY;
4241
4438
  const rgb = txt.isTinted ? txt.tint : WHITE_RGB;
4242
- this.pushQuad(m, -ox, -oy, txt.width - ox, txt.height - oy, 0, 0, 1, 1, packColorAbgr(rgb, effAlpha), 0, txt.blendMode, bg);
4439
+ if (txt.isCropped && txt.width > 0 && txt.height > 0) {
4440
+ const cx0 = Math.max(0, Math.min(txt.width, txt.cropX));
4441
+ const cy0 = Math.max(0, Math.min(txt.height, txt.cropY));
4442
+ const cx1 = Math.max(cx0, Math.min(txt.width, txt.cropX + txt.cropW));
4443
+ const cy1 = Math.max(cy0, Math.min(txt.height, txt.cropY + txt.cropH));
4444
+ if (cx1 > cx0 && cy1 > cy0) this.pushQuad(m, cx0 - ox, cy0 - oy, cx1 - ox, cy1 - oy, cx0 / txt.width, cy0 / txt.height, cx1 / txt.width, cy1 / txt.height, packColorAbgr(rgb, effAlpha), 0, txt.blendMode, bg);
4445
+ } else this.pushQuad(m, -ox, -oy, txt.width - ox, txt.height - oy, 0, 0, 1, 1, packColorAbgr(rgb, effAlpha), 0, txt.blendMode, bg);
4243
4446
  break;
4244
4447
  }
4245
- case "NineSlice":
4246
- case "TileSprite": {
4448
+ case "NineSlice": {
4247
4449
  const ns = obj;
4248
4450
  const fr = ns.frame;
4249
- if (!fr) break;
4451
+ if (!fr || ns.width <= 0 || ns.height <= 0) break;
4250
4452
  const bg = this.ensureSourceBindGroup(fr.source);
4251
4453
  if (!bg) break;
4252
4454
  const ox = ns.displayOriginX, oy = ns.displayOriginY;
4253
- this.pushQuad(m, -ox, -oy, ns.width - ox, ns.height - oy, fr.u0, fr.v0, fr.u1, fr.v1, packColorAbgr(ns.isTinted ? ns.tint : WHITE_RGB, effAlpha), 0, ns.blendMode, bg);
4455
+ const abgr = packColorAbgr(ns.isTinted ? ns.tint : WHITE_RGB, effAlpha);
4456
+ const sw = fr.cutWidth, sh = fr.cutHeight;
4457
+ const lw = Math.min(ns.leftWidth, ns.width * .5, sw);
4458
+ const rw = Math.min(ns.rightWidth, ns.width * .5, sw - lw);
4459
+ const th = Math.min(ns.topHeight, ns.height * .5, sh);
4460
+ const bh = Math.min(ns.bottomHeight, ns.height * .5, sh - th);
4461
+ const xs = [
4462
+ -ox,
4463
+ lw - ox,
4464
+ ns.width - rw - ox,
4465
+ ns.width - ox
4466
+ ];
4467
+ const ys = [
4468
+ -oy,
4469
+ th - oy,
4470
+ ns.height - bh - oy,
4471
+ ns.height - oy
4472
+ ];
4473
+ const du = fr.u1 - fr.u0, dv = fr.v1 - fr.v0;
4474
+ const us = [
4475
+ fr.u0,
4476
+ fr.u0 + lw / sw * du,
4477
+ fr.u1 - rw / sw * du,
4478
+ fr.u1
4479
+ ];
4480
+ const vs = [
4481
+ fr.v0,
4482
+ fr.v0 + th / sh * dv,
4483
+ fr.v1 - bh / sh * dv,
4484
+ fr.v1
4485
+ ];
4486
+ for (let ry = 0; ry < 3; ry++) {
4487
+ if (ys[ry + 1] <= ys[ry]) continue;
4488
+ for (let rx = 0; rx < 3; rx++) {
4489
+ if (xs[rx + 1] <= xs[rx]) continue;
4490
+ this.pushQuad(m, xs[rx], ys[ry], xs[rx + 1], ys[ry + 1], us[rx], vs[ry], us[rx + 1], vs[ry + 1], abgr, 0, ns.blendMode, bg);
4491
+ }
4492
+ }
4493
+ break;
4494
+ }
4495
+ case "TileSprite": {
4496
+ const ts = obj;
4497
+ const fr = ts.frame;
4498
+ if (!fr || ts.width <= 0 || ts.height <= 0) break;
4499
+ const isFullTex = fr.cutX === 0 && fr.cutY === 0 && fr.cutWidth === fr.source.width && fr.cutHeight === fr.source.height;
4500
+ const bg = this.ensureSourceBindGroup(fr.source, isFullTex);
4501
+ if (!bg) break;
4502
+ const ox = ts.displayOriginX, oy = ts.displayOriginY;
4503
+ const abgr = packColorAbgr(ts.isTinted ? ts.tint : WHITE_RGB, effAlpha);
4504
+ if (isFullTex) {
4505
+ const sx = Math.max(1e-4, ts.tileScaleX);
4506
+ const sy = Math.max(1e-4, ts.tileScaleY);
4507
+ const u0 = ts.tilePositionX / fr.width;
4508
+ const v0 = ts.tilePositionY / fr.height;
4509
+ const u1 = u0 + ts.width / (fr.width * sx);
4510
+ const v1 = v0 + ts.height / (fr.height * sy);
4511
+ this.pushQuad(m, -ox, -oy, ts.width - ox, ts.height - oy, u0, v0, u1, v1, abgr, 0, ts.blendMode, bg);
4512
+ } else this.pushQuad(m, -ox, -oy, ts.width - ox, ts.height - oy, fr.u0, fr.v0, fr.u1, fr.v1, abgr, 0, ts.blendMode, bg);
4254
4513
  break;
4255
4514
  }
4256
4515
  case "Graphics":
@@ -4359,8 +4618,8 @@ var RendererWebGpu = class extends EventEmitter {
4359
4618
  const sy1 = cm.b * wx1 + cm.d * wy1 + cm.ty;
4360
4619
  const l = Math.max(0, Math.floor(Math.min(sx0, sx1)));
4361
4620
  const t = Math.max(0, Math.floor(Math.min(sy0, sy1)));
4362
- const r = Math.min(this.width, Math.ceil(Math.max(sx0, sx1)));
4363
- const b = Math.min(this.height, Math.ceil(Math.max(sy0, sy1)));
4621
+ const r = Math.min(this.curTargetW, Math.ceil(Math.max(sx0, sx1)));
4622
+ const b = Math.min(this.curTargetH, Math.ceil(Math.max(sy0, sy1)));
4364
4623
  this.scissorStack.push({
4365
4624
  x: l,
4366
4625
  y: t,
@@ -4385,31 +4644,53 @@ var RendererWebGpu = class extends EventEmitter {
4385
4644
  }
4386
4645
  }
4387
4646
  }
4388
- render(displayList, camera) {
4647
+ executePass(targetView, targetFormat, targetW, targetH, displayList, camera, recordMainStats) {
4648
+ const savedState = this.cmds.length > 0 || this.vertCount > 0 || this.sdfCount > 0 ? {
4649
+ vertCount: this.vertCount,
4650
+ indexCount: this.indexCount,
4651
+ cmdStartIndex: this.cmdStartIndex,
4652
+ sdfCount: this.sdfCount,
4653
+ sdfCmdStart: this.sdfCmdStart,
4654
+ curTargetW: this.curTargetW,
4655
+ curTargetH: this.curTargetH,
4656
+ curBlend: this.curBlend,
4657
+ curBindGroup: this.curBindGroup,
4658
+ cmds: this.cmds,
4659
+ scissorStack: this.scissorStack,
4660
+ vertSnap: this.vertCount > 0 ? this.f32.slice(0, this.vertCount * VERT_FLOATS) : null,
4661
+ idxSnap: this.indexCount > 0 ? this.indices.slice(0, this.indexCount) : null,
4662
+ sdfSnap: this.sdfCount > 0 ? this.sdfF32.slice(0, this.sdfCount * SDF_FLOATS) : null
4663
+ } : null;
4664
+ if (savedState) {
4665
+ this.cmds = [];
4666
+ this.scissorStack = [];
4667
+ }
4389
4668
  camera.syncMetrics();
4390
4669
  this.vertCount = 0;
4391
4670
  this.indexCount = 0;
4392
4671
  this.cmdStartIndex = 0;
4393
4672
  this.sdfCount = 0;
4394
4673
  this.sdfCmdStart = 0;
4674
+ this.curTargetW = targetW;
4675
+ this.curTargetH = targetH;
4395
4676
  this.cmds.length = 0;
4396
4677
  this.scissorStack.length = 0;
4397
4678
  this.curBlend = BlendModes.NORMAL;
4398
4679
  this.curBindGroup = null;
4680
+ if (recordMainStats) this.lastStats.culled = 0;
4399
4681
  const list = displayList.sorted();
4400
4682
  const camAlpha = camera.alpha;
4401
4683
  for (let i = 0; i < list.length; i++) this.renderNode(list[i], camera, null, camAlpha, 0);
4402
4684
  this.flushAllPending();
4403
4685
  this.device.queue.writeBuffer(this.globalsBuf, 0, new Float32Array([
4404
- this.width,
4405
- this.height,
4686
+ targetW,
4687
+ targetH,
4406
4688
  0,
4407
4689
  0
4408
4690
  ]));
4409
4691
  if (this.vertCount > 0) {
4410
4692
  this.device.queue.writeBuffer(this.vbo, 0, this.f32.subarray(0, this.vertCount * VERT_FLOATS));
4411
- const idxWriteCount = this.indexCount + 1 & -2;
4412
- this.device.queue.writeBuffer(this.ibo, 0, this.indices.subarray(0, idxWriteCount));
4693
+ this.device.queue.writeBuffer(this.ibo, 0, this.indices.subarray(0, this.indexCount));
4413
4694
  }
4414
4695
  if (this.sdfCount > 0) this.device.queue.writeBuffer(this.sdfInstVbo, 0, this.sdfF32.subarray(0, this.sdfCount * SDF_FLOATS));
4415
4696
  const bg = camera.backgroundColor;
@@ -4424,10 +4705,9 @@ var RendererWebGpu = class extends EventEmitter {
4424
4705
  b: bg.b * bg.a,
4425
4706
  a: bg.a
4426
4707
  };
4427
- const view = this.gpuContext ? this.gpuContext.getCurrentTexture().createView() : this.ensureOffscreenTarget();
4428
4708
  const encoder = this.device.createCommandEncoder();
4429
4709
  const pass = encoder.beginRenderPass({ colorAttachments: [{
4430
- view,
4710
+ view: targetView,
4431
4711
  clearValue: clearColor,
4432
4712
  loadOp: "clear",
4433
4713
  storeOp: "store"
@@ -4438,16 +4718,16 @@ var RendererWebGpu = class extends EventEmitter {
4438
4718
  if (cmd.scissor) {
4439
4719
  if (cmd.scissor.w <= 0 || cmd.scissor.h <= 0) continue;
4440
4720
  pass.setScissorRect(cmd.scissor.x, cmd.scissor.y, cmd.scissor.w, cmd.scissor.h);
4441
- } else pass.setScissorRect(0, 0, this.width, this.height);
4721
+ } else pass.setScissorRect(0, 0, targetW, targetH);
4442
4722
  if (cmd.kind === "batch") {
4443
- pass.setPipeline(this.batchPipelines.get(cmd.blend) ?? this.batchPipelines.get(BlendModes.NORMAL));
4723
+ pass.setPipeline(this.getBatchPipeline(targetFormat, cmd.blend));
4444
4724
  pass.setBindGroup(0, cmd.bindGroup);
4445
4725
  pass.setVertexBuffer(0, this.vbo);
4446
- pass.setIndexBuffer(this.ibo, "uint16");
4726
+ pass.setIndexBuffer(this.ibo, "uint32");
4447
4727
  pass.drawIndexed(cmd.indexCount, 1, cmd.firstIndex, 0, 0);
4448
4728
  } else {
4449
4729
  sdfDraws++;
4450
- pass.setPipeline(this.sdfPipelines.get(cmd.blend) ?? this.sdfPipelines.get(BlendModes.NORMAL));
4730
+ pass.setPipeline(this.getSdfPipeline(targetFormat, cmd.blend));
4451
4731
  pass.setBindGroup(0, this.sdfBindGroup);
4452
4732
  pass.setVertexBuffer(0, this.sdfCornerVbo);
4453
4733
  pass.setVertexBuffer(1, this.sdfInstVbo);
@@ -4457,12 +4737,36 @@ var RendererWebGpu = class extends EventEmitter {
4457
4737
  }
4458
4738
  pass.end();
4459
4739
  this.device.queue.submit([encoder.finish()]);
4460
- this.lastStats.drawCalls = this.cmds.length;
4461
- this.lastStats.flushes = this.cmds.length;
4462
- this.lastStats.tris = (this.indexCount / 3 | 0) + this.sdfCount * 2;
4463
- this.lastStats.quads = (this.vertCount >> 2) + this.sdfCount;
4464
- this.lastStats.sdfPanels = this.sdfCount;
4465
- this.lastStats.sdfDraws = sdfDraws;
4740
+ if (recordMainStats) {
4741
+ this.lastStats.drawCalls = this.cmds.length;
4742
+ this.lastStats.flushes = this.cmds.length;
4743
+ this.lastStats.tris = (this.indexCount / 3 | 0) + this.sdfCount * 2;
4744
+ this.lastStats.quads = (this.vertCount >> 2) + this.sdfCount;
4745
+ this.lastStats.sdfPanels = this.sdfCount;
4746
+ this.lastStats.sdfDraws = sdfDraws;
4747
+ }
4748
+ if (savedState) {
4749
+ this.ensureBatchCapacity(savedState.vertCount, savedState.indexCount);
4750
+ this.ensureSdfCapacity(savedState.sdfCount);
4751
+ if (savedState.vertSnap) this.f32.set(savedState.vertSnap, 0);
4752
+ if (savedState.idxSnap) this.indices.set(savedState.idxSnap, 0);
4753
+ if (savedState.sdfSnap) this.sdfF32.set(savedState.sdfSnap, 0);
4754
+ this.vertCount = savedState.vertCount;
4755
+ this.indexCount = savedState.indexCount;
4756
+ this.cmdStartIndex = savedState.cmdStartIndex;
4757
+ this.sdfCount = savedState.sdfCount;
4758
+ this.sdfCmdStart = savedState.sdfCmdStart;
4759
+ this.curTargetW = savedState.curTargetW;
4760
+ this.curTargetH = savedState.curTargetH;
4761
+ this.curBlend = savedState.curBlend;
4762
+ this.curBindGroup = savedState.curBindGroup;
4763
+ this.cmds = savedState.cmds;
4764
+ this.scissorStack = savedState.scissorStack;
4765
+ }
4766
+ }
4767
+ render(displayList, camera) {
4768
+ const view = this.gpuContext ? this.gpuContext.getCurrentTexture().createView() : this.ensureOffscreenTarget();
4769
+ this.executePass(view, this.format, this.width, this.height, displayList, camera, true);
4466
4770
  }
4467
4771
  encodeCopyToStaging() {
4468
4772
  if (!this.offscreenTex) this.ensureOffscreenTarget();
@@ -4555,50 +4859,109 @@ var RendererWebGpu = class extends EventEmitter {
4555
4859
  buf.unmap();
4556
4860
  }
4557
4861
  }
4558
- /** Create an offscreen render target backed by a registered Stage `Texture` (`key`) for WebGPU passes (e.g. `Lighting2DSystem`). */
4862
+ /** Create an offscreen GPU render target backed by a registered Stage `Texture` (`key`) for WebGPU passes (e.g. `Lighting2DSystem`). */
4559
4863
  createRenderTarget(key, width, height, textures, filterMode = FilterMode.LINEAR) {
4560
4864
  const w = Math.max(1, Math.round(width));
4561
4865
  const h = Math.max(1, Math.round(height));
4562
- const doc = this.canvas?.ownerDocument ?? (typeof document !== "undefined" ? document : void 0);
4563
- if (!doc) throw new Error("Stage: ownerDocument unavailable for WebGPU RenderTarget");
4564
- const rtCanvas = doc.createElement("canvas");
4565
- rtCanvas.width = w;
4566
- rtCanvas.height = h;
4567
- const tex = textures.addCanvas(key, rtCanvas);
4866
+ const tex = textures.addImage(key, {
4867
+ width: w,
4868
+ height: h
4869
+ }, {
4870
+ filterMode,
4871
+ isRenderTarget: true
4872
+ });
4568
4873
  if (!tex) throw new Error("Stage: failed to register WebGPU RenderTarget texture");
4569
- tex.setFilter(filterMode);
4874
+ const src = tex.source[0];
4875
+ this.ensureSourceBindGroup(src);
4876
+ const gpuEntry = this.texCache.get(src);
4570
4877
  const rtCamera = new Camera(w, h, true);
4571
- const rtRenderer = new Renderer2D(rtCanvas, w, h);
4878
+ let lazy2D = null;
4879
+ let lazyCanvas = null;
4880
+ let lastUsed2D = false;
4572
4881
  return {
4573
4882
  key,
4574
4883
  width: w,
4575
4884
  height: h,
4576
4885
  texture: tex,
4577
4886
  camera: rtCamera,
4578
- _rtRenderer: rtRenderer,
4887
+ _gpuEntry: gpuEntry,
4888
+ _markGpuRendered: () => {
4889
+ lastUsed2D = false;
4890
+ },
4891
+ _render2DCallback: (cb, cam) => {
4892
+ if (!lazy2D || !lazyCanvas) {
4893
+ const doc = this.canvas?.ownerDocument ?? (typeof document !== "undefined" ? document : void 0);
4894
+ if (!doc) throw new Error("Stage: ownerDocument unavailable for 2D callback RenderTarget");
4895
+ lazyCanvas = doc.createElement("canvas");
4896
+ lazyCanvas.width = w;
4897
+ lazyCanvas.height = h;
4898
+ lazy2D = new Renderer2D(lazyCanvas, w, h);
4899
+ }
4900
+ cam.syncMetrics();
4901
+ cb(lazy2D, cam);
4902
+ this.extractAndUploadTexture(gpuEntry.tex, lazyCanvas, w, h, true);
4903
+ lastUsed2D = true;
4904
+ },
4579
4905
  readPixels: (out) => {
4580
4906
  const byteLen = w * h * 4;
4581
4907
  const dst = out && out.length >= byteLen ? out : new Uint8Array(byteLen);
4582
- const img = rtRenderer.ctx.getImageData(0, 0, w, h);
4583
- dst.set(img.data.subarray(0, byteLen));
4908
+ if (lastUsed2D && lazy2D) {
4909
+ const img = lazy2D.ctx.getImageData(0, 0, w, h);
4910
+ dst.set(img.data.subarray(0, byteLen));
4911
+ return dst;
4912
+ }
4913
+ if (typeof this.device._readBufferSync === "function") {
4914
+ const bytesPerRow = w * 4 + 255 & -256;
4915
+ const totalBuf = bytesPerRow * h;
4916
+ const tmpBuf = this.device.createBuffer({
4917
+ size: totalBuf,
4918
+ usage: 9
4919
+ });
4920
+ const enc = this.device.createCommandEncoder();
4921
+ enc.copyTextureToBuffer({ texture: gpuEntry.tex }, {
4922
+ buffer: tmpBuf,
4923
+ offset: 0,
4924
+ bytesPerRow,
4925
+ rowsPerImage: h
4926
+ }, [
4927
+ w,
4928
+ h,
4929
+ 1
4930
+ ]);
4931
+ this.device.queue.submit([enc.finish()]);
4932
+ if (bytesPerRow === w * 4) this.device._readBufferSync(tmpBuf, dst, byteLen);
4933
+ else {
4934
+ const raw = new Uint8Array(totalBuf);
4935
+ this.device._readBufferSync(tmpBuf, raw, totalBuf);
4936
+ for (let y = 0; y < h; y++) dst.set(raw.subarray(y * bytesPerRow, y * bytesPerRow + w * 4), y * w * 4);
4937
+ }
4938
+ try {
4939
+ tmpBuf.destroy?.();
4940
+ } catch {}
4941
+ return dst;
4942
+ }
4584
4943
  return dst;
4585
4944
  },
4586
4945
  destroy: () => {
4587
- rtRenderer.destroy();
4946
+ lazy2D?.destroy();
4947
+ try {
4948
+ gpuEntry.tex?.destroy?.();
4949
+ } catch {}
4588
4950
  textures.remove(key);
4589
4951
  }
4590
4952
  };
4591
4953
  }
4592
- /** Render a `DisplayList` (or callback) into an offscreen `StageRenderTarget` and mark its texture dirty for WebGPU upload (`camera` defaults to `target.camera`). */
4954
+ /** Render a `DisplayList` natively on the GPU into an offscreen `StageRenderTarget` (zero CPU Canvas2D copy!). */
4593
4955
  renderToTarget(target, content, camera = target.camera) {
4594
- const sub = target._rtRenderer;
4595
- if (!sub) return;
4956
+ const ext = target;
4596
4957
  if (typeof content === "function") {
4597
- camera.syncMetrics();
4598
- content(sub, camera);
4599
- } else sub.render(content, camera);
4600
- const src = target.texture.source[0];
4601
- if (src) src.dirty = true;
4958
+ ext._render2DCallback?.(content, camera);
4959
+ return;
4960
+ }
4961
+ const entry = ext._gpuEntry ?? this.texCache.get(target.texture.source[0]);
4962
+ if (!entry) return;
4963
+ ext._markGpuRendered?.();
4964
+ this.executePass(entry.view, "rgba8unorm", target.width, target.height, content, camera, false);
4602
4965
  }
4603
4966
  destroy() {
4604
4967
  this.removeAllListeners();