@next2d/webgpu 3.11.1 → 3.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/package.json +3 -3
  2. package/src/Blend/BlendInstancedManager.d.ts +2 -1
  3. package/src/Blend/BlendInstancedManager.js +18 -15
  4. package/src/Blend/usecase/BlendApplyComplexBlendUseCase.d.ts +3 -1
  5. package/src/Blend/usecase/BlendApplyComplexBlendUseCase.js +24 -17
  6. package/src/BufferManager.d.ts +14 -0
  7. package/src/BufferManager.js +47 -0
  8. package/src/Context/usecase/ContextApplyFilterUseCase.js +12 -12
  9. package/src/Context/usecase/ContextContainerEndLayerUseCase.js +8 -8
  10. package/src/Context/usecase/ContextDrawArraysInstancedUseCase.js +4 -3
  11. package/src/Context/usecase/ContextDrawIndirectUseCase.d.ts +3 -1
  12. package/src/Context/usecase/ContextDrawIndirectUseCase.js +33 -15
  13. package/src/Context/usecase/ContextProcessComplexBlendQueueUseCase.js +18 -62
  14. package/src/Context.d.ts +20 -19
  15. package/src/Context.js +203 -105
  16. package/src/ExternalImageUploadBatch.d.ts +24 -0
  17. package/src/ExternalImageUploadBatch.js +133 -0
  18. package/src/Filter/BevelFilter/FilterApplyBevelFilterUseCase.js +5 -20
  19. package/src/Filter/BlurFilter/FilterApplyBlurFilterUseCase.js +38 -11
  20. package/src/Filter/ColorMatrixFilter/FilterApplyColorMatrixFilterUseCase.js +3 -10
  21. package/src/Filter/ConvolutionFilter/FilterApplyConvolutionFilterUseCase.js +3 -10
  22. package/src/Filter/DisplacementMapFilter/FilterApplyDisplacementMapFilterUseCase.js +5 -11
  23. package/src/Filter/DropShadowFilter/FilterApplyDropShadowFilterUseCase.js +8 -5
  24. package/src/Filter/GlowFilter/FilterApplyGlowFilterUseCase.js +8 -5
  25. package/src/Filter/GradientBevelFilter/FilterApplyGradientBevelFilterUseCase.js +5 -20
  26. package/src/Filter/GradientGlowFilter/FilterApplyGradientGlowFilterUseCase.js +3 -10
  27. package/src/Filter/service/FilterAllocateUniformBindingService.d.ts +11 -0
  28. package/src/Filter/service/FilterAllocateUniformBindingService.js +20 -0
  29. package/src/FrameBufferManager/usecase/FrameBufferManagerCreateAttachmentUseCase.js +2 -1
  30. package/src/InstanceBufferAllocator.d.ts +24 -0
  31. package/src/InstanceBufferAllocator.js +123 -0
  32. package/src/Shader/PipelineManager.d.ts +5 -0
  33. package/src/Shader/PipelineManager.js +55 -7
  34. package/src/Shader/ShaderSource.d.ts +9 -1
  35. package/src/Shader/ShaderSource.js +28 -6
  36. package/src/Shader/wgsl/fragment/FilterFragment.d.ts +4 -6
  37. package/src/Shader/wgsl/fragment/FilterFragment.js +10 -4
  38. package/src/TexturePool/service/TexturePoolCleanupService.d.ts +2 -2
  39. package/src/TexturePool/service/TexturePoolCleanupService.js +2 -1
  40. package/src/TexturePool/service/TexturePoolReleaseService.d.ts +2 -2
  41. package/src/TexturePool/service/TexturePoolReleaseService.js +8 -1
  42. package/src/TexturePool/usecase/TexturePoolAcquireUseCase.d.ts +2 -2
  43. package/src/TexturePool/usecase/TexturePoolAcquireUseCase.js +3 -1
  44. package/src/TexturePool.d.ts +1 -0
  45. package/src/TexturePool.js +11 -3
  46. package/src/interface/IFilterConfig.d.ts +1 -0
package/src/Context.js CHANGED
@@ -4,6 +4,7 @@ import { WebGPUUtil, $setContext } from "./WebGPUUtil";
4
4
  import { PathCommand } from "./PathCommand";
5
5
  import { BufferManager } from "./BufferManager";
6
6
  import { TextureManager } from "./TextureManager";
7
+ import { ExternalImageUploadBatch } from "./ExternalImageUploadBatch";
7
8
  import { FrameBufferManager } from "./FrameBufferManager";
8
9
  import { PipelineManager } from "./Shader/PipelineManager";
9
10
  import { $rootNodes, $resetAtlas, $getActiveAtlasIndex, $setActiveAtlasIndex, $setAtlasCreator, $getAtlasAttachmentObject, $getAtlasAttachmentObjectByIndex } from "./AtlasManager";
@@ -162,6 +163,12 @@ export class Context {
162
163
  * @param {number} device_pixel_ratio - デバイスピクセル比 / Device pixel ratio
163
164
  */
164
165
  constructor(device, canvas_context, preferred_format, device_pixel_ratio = 1) {
166
+ Object.defineProperty(this, "_nodeRoots", {
167
+ enumerable: true,
168
+ configurable: true,
169
+ writable: true,
170
+ value: new WeakMap()
171
+ });
165
172
  /** @description 変換行列スタック / Transform matrix stack */
166
173
  Object.defineProperty(this, "$stack", {
167
174
  enumerable: true,
@@ -323,6 +330,26 @@ export class Context {
323
330
  writable: true,
324
331
  value: null
325
332
  });
333
+ /** @description 連続するキャッシュ出力だけで再利用するパスと出力先 / Pass owned by consecutive cached-filter output */
334
+ Object.defineProperty(this, "cachedFilterPass", {
335
+ enumerable: true,
336
+ configurable: true,
337
+ writable: true,
338
+ value: null
339
+ });
340
+ Object.defineProperty(this, "cachedFilterPassColorView", {
341
+ enumerable: true,
342
+ configurable: true,
343
+ writable: true,
344
+ value: null
345
+ });
346
+ /** @description このContextの固定UV・sampler・layoutだけを使う弱参照キャッシュ / Context-owned immutable identity bindings */
347
+ Object.defineProperty(this, "cachedFilterBindGroups", {
348
+ enumerable: true,
349
+ configurable: true,
350
+ writable: true,
351
+ value: new WeakMap()
352
+ });
326
353
  /**
327
354
  * @description 現在openなrenderPassEncoderがインスタンスバッチ用パスかどうか。
328
355
  * インスタンスパスは連続バッチ間で再利用されるが、fill/clip等の
@@ -379,6 +406,12 @@ export class Context {
379
406
  writable: true,
380
407
  value: []
381
408
  });
409
+ Object.defineProperty(this, "externalImageUploadBatch", {
410
+ enumerable: true,
411
+ configurable: true,
412
+ writable: true,
413
+ value: null
414
+ });
382
415
  /** @description 現在のレンダーターゲット(メインまたはアトラス) / Current render target (could be main or atlas) */
383
416
  Object.defineProperty(this, "currentRenderTarget", {
384
417
  enumerable: true,
@@ -708,6 +741,8 @@ export class Context {
708
741
  * @return {void}
709
742
  */
710
743
  resize(width, height, cache_clear = true) {
744
+ this.externalImageUploadBatch?.dispose();
745
+ this.externalImageUploadBatch = null;
711
746
  // インスタンス配列をクリア(WebGL版と同じ)
712
747
  this.clearArraysInstanced();
713
748
  // フレームごとの一時テクスチャをクリア
@@ -729,6 +764,8 @@ export class Context {
729
764
  this.frameStarted = false;
730
765
  this.commandEncoder = null;
731
766
  this.renderPassEncoder = null;
767
+ this.cachedFilterPass = null;
768
+ this.cachedFilterPassColorView = null;
732
769
  this.currentRenderTarget = null;
733
770
  // マスク状態をリセット
734
771
  $resetMaskState();
@@ -772,10 +809,9 @@ export class Context {
772
809
  $clearFilterLUTCache();
773
810
  // アトラスのパッキングデータをリセット(WebGL版と同じ)
774
811
  $resetAtlas();
775
- // FrameBufferManagerのアトラステクスチャを再作成(古いコンテンツをクリア)
776
- // ステンシルバッファを有効にする(2パスステンシルフィル用)
812
+ // アトラスページはAtlasManagerのcreatorが必要時に生成する。
813
+ // 予備の4096平方MSAAアトラスを別途確保しない。
777
814
  this.frameBufferManager.destroyAttachment("atlas");
778
- this.frameBufferManager.createAttachment("atlas", 4096, 4096, false, true);
779
815
  }
780
816
  // アンバインド(WebGL版と同じ)
781
817
  this.frameBufferManager.setCurrentAttachment(null);
@@ -1004,7 +1040,7 @@ export class Context {
1004
1040
  // 既存のレンダーパスがある場合はearlyリターン(ノード領域クリアのみ確認)
1005
1041
  // ただしインスタンスバッチ用パスはステンシル構成が異なるため引き継がず閉じる
1006
1042
  if (this.renderPassEncoder) {
1007
- if (!this.renderPassIsInstanced) {
1043
+ if (!this.renderPassIsInstanced && this.renderPassEncoder !== this.cachedFilterPass) {
1008
1044
  if (this.currentRenderTarget) {
1009
1045
  this.ensureNodeAreaCleared();
1010
1046
  }
@@ -1461,7 +1497,8 @@ export class Context {
1461
1497
  return;
1462
1498
  }
1463
1499
  // インスタンスバッチ用パスはステンシル構成が異なるため引き継がず閉じる
1464
- if (this.renderPassEncoder && this.renderPassIsInstanced) {
1500
+ if (this.renderPassEncoder && (this.renderPassIsInstanced
1501
+ || this.renderPassEncoder === this.cachedFilterPass)) {
1465
1502
  this.renderPassEncoder.end();
1466
1503
  this.renderPassEncoder = null;
1467
1504
  this.renderPassIsInstanced = false;
@@ -1497,6 +1534,14 @@ export class Context {
1497
1534
  * @return {void}
1498
1535
  */
1499
1536
  bind(attachment_object) {
1537
+ if (this.renderPassEncoder && this.renderPassEncoder === this.cachedFilterPass) {
1538
+ const colorView = attachment_object.msaa && attachment_object.msaaTexture?.view
1539
+ ? attachment_object.msaaTexture.view : attachment_object.texture?.view;
1540
+ if (this.cachedFilterPassColorView !== colorView) {
1541
+ this.renderPassEncoder.end();
1542
+ this.renderPassEncoder = null;
1543
+ }
1544
+ }
1500
1545
  this.frameBufferManager.setCurrentAttachment(attachment_object);
1501
1546
  // WebGL版と同じ: ビューポートサイズをアタッチメントのサイズに設定
1502
1547
  this.viewportWidth = attachment_object.width;
@@ -1703,23 +1748,22 @@ export class Context {
1703
1748
  * @param {number} x_max - バウンディングボックス右端 / Bounding box right
1704
1749
  * @param {number} y_max - バウンディングボックス下端 / Bounding box bottom
1705
1750
  * @param {Float32Array} color_transform - カラー変換パラメータ / Color transform parameters
1751
+ * @param {number} color_transform_offset - 要素単位の開始位置 / Start offset in elements
1706
1752
  * @return {void}
1707
1753
  */
1708
- drawDisplayObject(node, x_min, y_min, x_max, y_max, color_transform) {
1754
+ drawDisplayObject(node, x_min, y_min, x_max, y_max, color_transform, color_transform_offset = 0) {
1709
1755
  // WebGPU display object drawing
1710
1756
  // インスタンス配列に追加
1711
1757
  // WebGL版と同じ: ビューポートサイズを使用(コンテナレイヤー時はレイヤーサイズ)
1712
1758
  const renderMaxSize = WebGPUUtil.getRenderMaxSize();
1713
- addDisplayObjectToInstanceArray(node, x_min, y_min, x_max, y_max, color_transform, this.$matrix, this.globalCompositeOperation, this.viewportWidth, this.viewportHeight, renderMaxSize, this.globalAlpha // WebGL版と同じ: globalAlphaを渡す
1714
- );
1759
+ addDisplayObjectToInstanceArray(node, x_min, y_min, x_max, y_max, color_transform, this.$matrix, this.globalCompositeOperation, this.viewportWidth, this.viewportHeight, renderMaxSize, this.globalAlpha, // WebGL版と同じ: globalAlphaを渡す
1760
+ color_transform_offset);
1715
1761
  }
1716
1762
  /**
1717
1763
  * @description インスタンス配列を描画
1718
1764
  * Draw instanced arrays
1719
1765
  *
1720
- * useOptimizedInstancingがtrueの場合、Storage BufferとIndirect Drawingを使用。
1721
- * - Storage Buffer: メモリアロケーション削減、CPU負荷15-25%軽減
1722
- * - Indirect Drawing: CPU-GPUオーバーヘッド5-15%削減
1766
+ * useOptimizedInstancingがtrueの場合、連続バッチの描画パスを再利用する。
1723
1767
  *
1724
1768
  * @return {void}
1725
1769
  */
@@ -1774,14 +1818,15 @@ export class Context {
1774
1818
  return;
1775
1819
  }
1776
1820
  if (this.useOptimizedInstancing) {
1777
- // 最適化版: Storage Buffer + Indirect Drawing
1821
+ // 連続バッチでレンダーパスを再利用する
1778
1822
  const previousPass = this.renderPassEncoder;
1779
1823
  this.renderPassEncoder = contextDrawIndirectUseCase(this.device, this.commandEncoder, this.renderPassEncoder, this.$mainAttachmentObject, this.bufferManager, this.frameBufferManager, this.textureManager, this.pipelineManager,
1780
1824
  // インスタンス数はCPU側で確定しているため間接描画は不要。
1781
1825
  // indirectバッファ生成+writeBufferのバッチ毎オーバーヘッドを避けて直接draw()する。
1782
1826
  false, // useIndirect
1783
- true, // useStorageBuffer
1784
- this.renderPassIsInstanced);
1827
+ false, // useStorageBuffer
1828
+ this.renderPassIsInstanced, true // useInstanceBuffer: フレーム内でサブアロケートし一括転送
1829
+ );
1785
1830
  // count===0で未変更返却の場合はフラグ維持、新規/再利用パスならinstanced扱い
1786
1831
  this.renderPassIsInstanced = this.renderPassEncoder !== null
1787
1832
  && (this.renderPassEncoder !== previousPass || this.renderPassIsInstanced);
@@ -1805,14 +1850,13 @@ export class Context {
1805
1850
  if (!getComplexBlendQueue().length) {
1806
1851
  return;
1807
1852
  }
1808
- // 複雑ブレンドはリゾルブ済みのメインテクスチャを読むため、
1809
- // 開いているレンダーパスを終了し、未リゾルブ分を解決する
1853
+ // 背景テクスチャを読む前に書き込みパスを終了する。
1854
+ // 全画面resolveの要否はUseCaseで判定(対応するMSAA背景は領域内で解決)。
1810
1855
  if (this.renderPassEncoder) {
1811
1856
  this.renderPassEncoder.end();
1812
1857
  this.renderPassEncoder = null;
1813
1858
  this.renderPassIsInstanced = false;
1814
1859
  }
1815
- this.resolveMainAttachment();
1816
1860
  // コマンドエンコーダーを確保
1817
1861
  this.ensureCommandEncoder();
1818
1862
  // $mainAttachmentObjectを渡す(レンダーパスベースのコピーに必要)
@@ -1851,7 +1895,9 @@ export class Context {
1851
1895
  const height = node.h;
1852
1896
  // レンダーパスがアクティブな場合はマージンクリアしてから終了
1853
1897
  if (this.renderPassEncoder) {
1854
- this.ensureNodeAreaCleared();
1898
+ if (this.renderPassEncoder !== this.cachedFilterPass) {
1899
+ this.ensureNodeAreaCleared();
1900
+ }
1855
1901
  this.renderPassEncoder.end();
1856
1902
  this.renderPassEncoder = null;
1857
1903
  }
@@ -1976,15 +2022,29 @@ export class Context {
1976
2022
  }
1977
2023
  const width = node.w;
1978
2024
  const height = node.h;
1979
- // レンダーパスがアクティブな場合は終了
1980
- if (this.renderPassEncoder) {
2025
+ // Clear and upload in the same node pass. Uploaded temporary textures
2026
+ // remain owned by this frame until submission, including consecutive nodes.
2027
+ const reuseNodePass = this.renderPassEncoder
2028
+ && this.renderPassEncoder !== this.cachedFilterPass
2029
+ && node.index >= 0
2030
+ && this.nodeRenderPassAtlasIndex === node.index
2031
+ && this.currentNodeScissor
2032
+ && this.currentRenderTarget === attachment.texture.view;
2033
+ if (reuseNodePass) {
1981
2034
  this.ensureNodeAreaCleared();
2035
+ }
2036
+ else if (this.renderPassEncoder) {
2037
+ if (this.renderPassEncoder !== this.cachedFilterPass) {
2038
+ this.ensureNodeAreaCleared();
2039
+ }
1982
2040
  this.renderPassEncoder.end();
1983
2041
  this.renderPassEncoder = null;
1984
2042
  }
1985
2043
  // commandEncoderはsubmitしない — drawElementToMsaa()/drawElementToTexture()内で同じエンコーダを再利用
1986
2044
  // copyExternalImageToTexture()はキュー操作でありエンコーダ不要
1987
- this.nodeRenderPassAtlasIndex = -1;
2045
+ if (!reuseNodePass) {
2046
+ this.nodeRenderPassAtlasIndex = -1;
2047
+ }
1988
2048
  // MSAAが有効な場合は一時テクスチャ経由でMSAAテクスチャに直接描画
1989
2049
  // MSAAが無効な場合もシェーダー経由で描画(WebGLと同じ処理フロー)
1990
2050
  if (attachment.msaa && attachment.msaaTexture?.view) {
@@ -1994,31 +2054,20 @@ export class Context {
1994
2054
  this.drawElementToTexture(attachment, node, element, width, height, flip_y);
1995
2055
  }
1996
2056
  }
1997
- /**
1998
- * @description 一時テクスチャ経由でMSAAテクスチャに直接描画
1999
- * Draw to MSAA texture directly via a temporary texture
2000
- *
2001
- * @param {IAttachmentObject} attachment - アタッチメントオブジェクト / Attachment object
2002
- * @param {Node} node - 描画対象ノード / Target node
2003
- * @param {OffscreenCanvas | ImageBitmap} element - 描画要素 / Element to draw
2004
- * @param {number} width - 幅 / Width
2005
- * @param {number} height - 高さ / Height
2006
- * @param {boolean} flip_y - Y軸反転フラグ / Y-axis flip flag
2007
- * @return {void}
2008
- */
2057
+ /** Snapshot eligible text canvases into the batch; other images upload directly. */
2058
+ uploadElementTexture(element, texture, width, height, flip_y) {
2059
+ if (!flip_y && typeof OffscreenCanvas !== "undefined" && element instanceof OffscreenCanvas) {
2060
+ this.externalImageUploadBatch || (this.externalImageUploadBatch = new ExternalImageUploadBatch(this.device));
2061
+ if (this.externalImageUploadBatch.append(element, texture, width, height)) {
2062
+ return;
2063
+ }
2064
+ }
2065
+ this.device.queue.copyExternalImageToTexture({ "source": element, "flipY": flip_y }, { "texture": texture, "premultipliedAlpha": true }, { width, height });
2066
+ }
2067
+ /** Draw to the MSAA atlas through a frame-owned temporary image texture. */
2009
2068
  drawElementToMsaa(attachment, node, element, width, height, flip_y) {
2010
2069
  // 一時テクスチャをプールから取得
2011
2070
  const tempTexture = $acquireRenderTexture(this.device, width, height);
2012
- this.device.queue.copyExternalImageToTexture({
2013
- "source": element,
2014
- "flipY": flip_y
2015
- }, {
2016
- "texture": tempTexture,
2017
- "premultipliedAlpha": true
2018
- }, {
2019
- "width": width,
2020
- "height": height
2021
- });
2022
2071
  const pipeline = this.pipelineManager.getPipeline("bitmap_render_msaa");
2023
2072
  if (!pipeline) {
2024
2073
  $releaseRenderTexture(tempTexture);
@@ -2029,6 +2078,7 @@ export class Context {
2029
2078
  $releaseRenderTexture(tempTexture);
2030
2079
  return;
2031
2080
  }
2081
+ this.uploadElementTexture(element, tempTexture, width, height, flip_y);
2032
2082
  const uniformData = this.$uniformData8;
2033
2083
  uniformData[0] = node.x;
2034
2084
  uniformData[1] = node.y;
@@ -2062,13 +2112,16 @@ export class Context {
2062
2112
  else {
2063
2113
  $msaaDescriptor.depthStencilAttachment = undefined;
2064
2114
  }
2065
- const renderPass = this.commandEncoder.beginRenderPass($msaaDescriptor);
2115
+ const renderPass = this.renderPassEncoder
2116
+ || this.commandEncoder.beginRenderPass($msaaDescriptor);
2066
2117
  renderPass.setViewport(0, 0, attachment.width, attachment.height, 0, 1);
2067
2118
  renderPass.setScissorRect(node.x, node.y, width, height);
2068
2119
  renderPass.setPipeline(pipeline);
2069
2120
  renderPass.setBindGroup(0, bindGroup);
2070
2121
  renderPass.draw(6);
2071
- renderPass.end();
2122
+ if (!this.renderPassEncoder) {
2123
+ renderPass.end();
2124
+ }
2072
2125
  // endFrame()でプールに返却
2073
2126
  this.pooledRenderTextures.push(tempTexture);
2074
2127
  }
@@ -2087,18 +2140,6 @@ export class Context {
2087
2140
  drawElementToTexture(attachment, node, element, width, height, flip_y) {
2088
2141
  // 一時テクスチャをプールから取得
2089
2142
  const tempTexture = $acquireRenderTexture(this.device, width, height);
2090
- // ImageBitmapを一時テクスチャにコピー
2091
- // flipYパラメータで画像の上下反転を制御(Videoはtrue、TextFieldはfalse)
2092
- this.device.queue.copyExternalImageToTexture({
2093
- "source": element,
2094
- "flipY": flip_y
2095
- }, {
2096
- "texture": tempTexture,
2097
- "premultipliedAlpha": true
2098
- }, {
2099
- "width": width,
2100
- "height": height
2101
- });
2102
2143
  const pipeline = this.pipelineManager.getPipeline("bitmap_render");
2103
2144
  if (!pipeline) {
2104
2145
  $releaseRenderTexture(tempTexture);
@@ -2109,6 +2150,7 @@ export class Context {
2109
2150
  $releaseRenderTexture(tempTexture);
2110
2151
  return;
2111
2152
  }
2153
+ this.uploadElementTexture(element, tempTexture, width, height, flip_y);
2112
2154
  const uniformData = this.$uniformData8;
2113
2155
  uniformData[0] = node.x;
2114
2156
  uniformData[1] = node.y;
@@ -2140,13 +2182,16 @@ export class Context {
2140
2182
  else {
2141
2183
  $msaaDescriptor.depthStencilAttachment = undefined;
2142
2184
  }
2143
- const renderPass = this.commandEncoder.beginRenderPass($msaaDescriptor);
2185
+ const renderPass = this.renderPassEncoder
2186
+ || this.commandEncoder.beginRenderPass($msaaDescriptor);
2144
2187
  renderPass.setViewport(0, 0, attachment.width, attachment.height, 0, 1);
2145
2188
  renderPass.setScissorRect(node.x, node.y, width, height);
2146
2189
  renderPass.setPipeline(pipeline);
2147
2190
  renderPass.setBindGroup(0, bindGroup);
2148
2191
  renderPass.draw(6);
2149
- renderPass.end();
2192
+ if (!this.renderPassEncoder) {
2193
+ renderPass.end();
2194
+ }
2150
2195
  // endFrame()でプールに返却
2151
2196
  this.pooledRenderTextures.push(tempTexture);
2152
2197
  }
@@ -2388,39 +2433,60 @@ export class Context {
2388
2433
  if (!cachedAttachment || !cachedAttachment.texture) {
2389
2434
  return;
2390
2435
  }
2391
- this.drawArraysInstanced();
2436
+ // Pending ordinary/complex draws are an ordering boundary. With no queued
2437
+ // work, only our own cached-output pass may survive this call.
2438
+ if (!this.renderPassEncoder || this.renderPassEncoder !== this.cachedFilterPass
2439
+ || getInstancedShaderManager().count > 0 || getComplexBlendQueue().length > 0) {
2440
+ this.drawArraysInstanced();
2441
+ }
2392
2442
  if (!this.frameStarted) {
2393
2443
  this.beginFrame();
2394
2444
  }
2395
- if (this.renderPassEncoder) {
2445
+ if (this.renderPassEncoder && this.renderPassEncoder !== this.cachedFilterPass) {
2396
2446
  this.renderPassEncoder.end();
2397
2447
  this.renderPassEncoder = null;
2448
+ this.renderPassIsInstanced = false;
2398
2449
  }
2399
2450
  this.ensureCommandEncoder();
2400
2451
  const mainAttachment = this.$mainAttachmentObject;
2401
2452
  if (!mainAttachment || !mainAttachment.texture) {
2402
2453
  return;
2403
2454
  }
2404
- // ColorTransformが恒等変換でない場合、キャッシュのコピーにCTを適用
2455
+ // Nonidentity CT can be fused only for integer, 1:1 cached output.
2456
+ // Quantization in the fused shader preserves the intermediate RGBA8 store.
2405
2457
  let drawAttachment = cachedAttachment;
2406
2458
  let ctAttachment = null;
2407
2459
  const isIdentityCt = color_transform[0] === 1 && color_transform[1] === 1
2408
2460
  && color_transform[2] === 1 && color_transform[3] === 1
2409
2461
  && color_transform[4] === 0 && color_transform[5] === 0
2410
2462
  && color_transform[6] === 0 && color_transform[7] === 0;
2463
+ const useMsaa = mainAttachment.msaa && mainAttachment.msaaTexture?.view;
2464
+ const blendSuffix = blend_mode === "add" || blend_mode === "screen"
2465
+ || blend_mode === "alpha" || blend_mode === "erase" ? `_${blend_mode}` : "";
2466
+ const fusedPipeline = !isIdentityCt
2467
+ && cachedAttachment.width > 0 && cachedAttachment.height > 0
2468
+ && cachedAttachment.width === cachedAttachment.texture.width
2469
+ && cachedAttachment.height === cachedAttachment.texture.height
2470
+ ? this.pipelineManager.getPipeline(`cached_ct${blendSuffix}${useMsaa ? "_msaa" : ""}`) : null;
2411
2471
  if (!isIdentityCt) {
2472
+ for (let idx = 0; idx < 7; idx++) {
2473
+ $ctUniform8[idx] = color_transform[idx];
2474
+ }
2475
+ // Preserve the cached path's existing alpha-offset behavior.
2476
+ $ctUniform8[7] = 0;
2477
+ }
2478
+ if (!isIdentityCt && !fusedPipeline) {
2479
+ // CT reads/writes a separate attachment and cannot be encoded inside
2480
+ // the open output pass. Keep the original CT/output draw order.
2481
+ if (this.renderPassEncoder) {
2482
+ this.renderPassEncoder.end();
2483
+ this.renderPassEncoder = null;
2484
+ this.renderPassIsInstanced = false;
2485
+ }
2412
2486
  ctAttachment = this.frameBufferManager.createTemporaryAttachment(cachedAttachment.width, cachedAttachment.height);
2413
2487
  const ctPipeline = this.pipelineManager.getPipeline("color_transform");
2414
2488
  const ctBindGroupLayout = this.pipelineManager.getBindGroupLayout("texture_copy");
2415
2489
  if (ctPipeline && ctBindGroupLayout && ctAttachment.texture) {
2416
- $ctUniform8[0] = color_transform[0];
2417
- $ctUniform8[1] = color_transform[1];
2418
- $ctUniform8[2] = color_transform[2];
2419
- $ctUniform8[3] = color_transform[3];
2420
- $ctUniform8[4] = color_transform[4];
2421
- $ctUniform8[5] = color_transform[5];
2422
- $ctUniform8[6] = color_transform[6];
2423
- $ctUniform8[7] = 0;
2424
2490
  const ctUniformData = $ctUniform8;
2425
2491
  const ctUniformBuffer = this.bufferManager.acquireAndWriteUniformBuffer(ctUniformData);
2426
2492
  const ctSampler = this.textureManager.createSampler("cached_ct_sampler", false);
@@ -2449,45 +2515,45 @@ export class Context {
2449
2515
  const drawX = Math.floor(boundsXMin + matrix[4]);
2450
2516
  const drawY = Math.floor(boundsYMin + matrix[5]);
2451
2517
  // シンプルなブレンドモード判定
2452
- const useMsaa = mainAttachment.msaa && mainAttachment.msaaTexture?.view;
2453
- let pipelineName;
2454
- switch (blend_mode) {
2455
- case "add":
2456
- pipelineName = useMsaa ? "filter_output_add_msaa" : "filter_output_add";
2457
- break;
2458
- case "screen":
2459
- pipelineName = useMsaa ? "filter_output_screen_msaa" : "filter_output_screen";
2460
- break;
2461
- case "alpha":
2462
- pipelineName = useMsaa ? "filter_output_alpha_msaa" : "filter_output_alpha";
2463
- break;
2464
- case "erase":
2465
- pipelineName = useMsaa ? "filter_output_erase_msaa" : "filter_output_erase";
2466
- break;
2467
- default:
2468
- pipelineName = useMsaa ? "filter_output_msaa" : "filter_output";
2469
- break;
2470
- }
2471
- const pipeline = this.pipelineManager.getPipeline(pipelineName);
2518
+ const pipelineName = `filter_output${blendSuffix}${useMsaa ? "_msaa" : ""}`;
2519
+ const pipeline = fusedPipeline || this.pipelineManager.getPipeline(pipelineName);
2472
2520
  const bindGroupLayout = this.pipelineManager.getBindGroupLayout("texture_copy");
2473
2521
  if (!pipeline || !bindGroupLayout) {
2522
+ if (ctAttachment) {
2523
+ this.frameBufferManager.releaseTemporaryAttachment(ctAttachment);
2524
+ }
2474
2525
  return;
2475
2526
  }
2476
- const sampler = this.textureManager.createSampler("cached_filter_sampler", true);
2477
- const uniformBuffer = this.bufferManager.acquireAndWriteUniformBuffer($IDENTITY_UV);
2478
- $entries3[0].resource.buffer = uniformBuffer;
2479
- $entries3[1].resource = sampler;
2480
- $entries3[2].resource = drawAttachment.texture.view;
2481
- const bindGroup = this.device.createBindGroup({
2482
- "layout": bindGroupLayout,
2483
- "entries": $entries3
2484
- });
2527
+ const sourceView = drawAttachment.texture.view;
2528
+ let bindGroup;
2529
+ if (fusedPipeline) {
2530
+ // Keep CT on independent buffers: the arena variant regressed GPU time.
2531
+ $entries3[0].resource.buffer = this.bufferManager.acquireAndWriteUniformBuffer($ctUniform8);
2532
+ $entries3[1].resource = this.textureManager.createSampler("cached_ct_sampler", false);
2533
+ $entries3[2].resource = sourceView;
2534
+ bindGroup = this.device.createBindGroup({ "layout": bindGroupLayout, "entries": $entries3 });
2535
+ }
2536
+ else {
2537
+ bindGroup = this.cachedFilterBindGroups.get(sourceView);
2538
+ }
2539
+ if (!bindGroup) {
2540
+ const binding = { "buffer": this.bufferManager.getIdentityUVBuffer(), "offset": 0, "size": 16 };
2541
+ const sampler = this.textureManager.createSampler("cached_filter_sampler", true);
2542
+ bindGroup = this.device.createBindGroup({
2543
+ "layout": bindGroupLayout,
2544
+ "entries": [
2545
+ { "binding": 0, "resource": binding },
2546
+ { "binding": 1, "resource": sampler },
2547
+ { "binding": 2, "resource": sourceView }
2548
+ ]
2549
+ });
2550
+ this.cachedFilterBindGroups.set(sourceView, bindGroup);
2551
+ }
2485
2552
  const colorView = useMsaa ? mainAttachment.msaaTexture.view : mainAttachment.texture.view;
2486
2553
  // リゾルブ遅延: 書き込みパスでは解決しない
2487
2554
  if (useMsaa) {
2488
2555
  mainAttachment.msaaDirty = true;
2489
2556
  }
2490
- const renderPassDescriptor = this.frameBufferManager.createRenderPassDescriptor(colorView, 0, 0, 0, 0, "load", null);
2491
2557
  const vpX = Math.max(0, drawX);
2492
2558
  const vpY = Math.max(0, drawY);
2493
2559
  const vpW = Math.max(1, drawAttachment.width);
@@ -2502,13 +2568,25 @@ export class Context {
2502
2568
  }
2503
2569
  return;
2504
2570
  }
2505
- const passEncoder = this.commandEncoder.beginRenderPass(renderPassDescriptor);
2571
+ let passEncoder = this.renderPassEncoder;
2572
+ if (!passEncoder || passEncoder !== this.cachedFilterPass
2573
+ || this.cachedFilterPassColorView !== colorView) {
2574
+ if (passEncoder) {
2575
+ passEncoder.end();
2576
+ }
2577
+ const renderPassDescriptor = this.frameBufferManager.createRenderPassDescriptor(colorView, 0, 0, 0, 0, "load", null);
2578
+ passEncoder = this.commandEncoder.beginRenderPass(renderPassDescriptor);
2579
+ this.renderPassEncoder = passEncoder;
2580
+ this.cachedFilterPass = passEncoder;
2581
+ this.cachedFilterPassColorView = colorView;
2582
+ this.renderPassIsInstanced = false;
2583
+ this.nodeRenderPassAtlasIndex = -1;
2584
+ }
2506
2585
  passEncoder.setPipeline(pipeline);
2507
2586
  passEncoder.setBindGroup(0, bindGroup);
2508
2587
  passEncoder.setViewport(vpX, vpY, vpW, vpH, 0, 1);
2509
2588
  passEncoder.setScissorRect(vpX, vpY, scissorW, scissorH);
2510
2589
  passEncoder.draw(6, 1, 0, 0);
2511
- passEncoder.end();
2512
2590
  // CT一時アタッチメントを解放
2513
2591
  if (ctAttachment) {
2514
2592
  this.frameBufferManager.releaseTemporaryAttachment(ctAttachment);
@@ -2592,11 +2670,15 @@ export class Context {
2592
2670
  this.pooledTextures.push(texture);
2593
2671
  }
2594
2672
  /**
2595
- * @description フレーム終了とコマンド送信(レンダリング完了後に呼ぶ)
2596
- * End the frame and submit commands (call after rendering is complete)
2673
+ * @description 提出済みGPU処理の完了を通知する(画面提示の完了ではない)
2674
+ * Observe submitted GPU work, not presentation completion.
2597
2675
  *
2598
- * @return {void}
2676
+ * @return {Promise<void>}
2599
2677
  */
2678
+ getRenderCompletion() {
2679
+ return this.device.queue.onSubmittedWorkDone();
2680
+ }
2681
+ /** End the frame and submit commands before returning temporary resources. */
2600
2682
  endFrame() {
2601
2683
  if (!this.frameStarted) {
2602
2684
  return;
@@ -2606,8 +2688,10 @@ export class Context {
2606
2688
  this.renderPassEncoder.end();
2607
2689
  this.renderPassEncoder = null;
2608
2690
  }
2691
+ this.externalImageUploadBatch?.flush();
2609
2692
  // DynamicUniformAllocatorのステージングバッファをGPUに一括書き込み
2610
2693
  this.bufferManager.dynamicUniform.flush();
2694
+ this.bufferManager.instanceBuffer.flush();
2611
2695
  // コマンドをsubmit
2612
2696
  if (this.commandEncoder) {
2613
2697
  try {
@@ -2646,6 +2730,8 @@ export class Context {
2646
2730
  // 次のフレーム用にクリア
2647
2731
  this.commandEncoder = null;
2648
2732
  this.renderPassEncoder = null;
2733
+ this.cachedFilterPass = null;
2734
+ this.cachedFilterPassColorView = null;
2649
2735
  this.currentRenderTarget = null;
2650
2736
  this.nodeRenderPassAtlasIndex = -1;
2651
2737
  // テクスチャ参照をクリア(次フレームで新しく取得)
@@ -2685,8 +2771,18 @@ export class Context {
2685
2771
  $setActiveAtlasIndex(index + 1);
2686
2772
  return this.createNode(width, height);
2687
2773
  }
2774
+ this._nodeRoots.set(node, rootNode);
2688
2775
  return node;
2689
2776
  }
2777
+ /** Select the page of a live cached node without reallocating its rectangle. */
2778
+ reuseNode(node) {
2779
+ const root = this._nodeRoots.get(node);
2780
+ if (!root || root !== $rootNodes[node.index] || !node.used) {
2781
+ return false;
2782
+ }
2783
+ $setActiveAtlasIndex(node.index);
2784
+ return true;
2785
+ }
2690
2786
  /**
2691
2787
  * @description ノードを削除
2692
2788
  * Remove a node from the texture atlas
@@ -2701,6 +2797,7 @@ export class Context {
2701
2797
  if (rootNode) {
2702
2798
  rootNode.dispose(node.x, node.y, node.w, node.h);
2703
2799
  }
2800
+ this._nodeRoots.delete(node);
2704
2801
  }
2705
2802
  /**
2706
2803
  * @description CacheStore に格納された任意の値を解放する。
@@ -2723,6 +2820,7 @@ export class Context {
2723
2820
  if (rootNode) {
2724
2821
  rootNode.dispose(node.x, node.y, node.w, node.h);
2725
2822
  }
2823
+ this._nodeRoots.delete(node);
2726
2824
  }
2727
2825
  else if ("color" in value || "texture" in value) {
2728
2826
  this.frameBufferManager.releaseTemporaryAttachment(value);
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Packs canvas snapshots before uploading them. Each flush submits copies to
3
+ * distinct, frame-owned destination textures before the renderer submits draws.
4
+ * A single 1024-square canvas and GPU staging texture are retained (4 MiB each,
5
+ * excluding browser/driver overhead). No render target is reordered or reused.
6
+ */
7
+ export declare class ExternalImageUploadBatch {
8
+ private readonly device;
9
+ private readonly size;
10
+ private canvas;
11
+ private context;
12
+ private texture;
13
+ private readonly copies;
14
+ private x;
15
+ private y;
16
+ private rowHeight;
17
+ private usedWidth;
18
+ constructor(device: GPUDevice);
19
+ /** Copies the source synchronously, so the caller may immediately reuse it. */
20
+ append(source: OffscreenCanvas, destination: GPUTexture, width: number, height: number): boolean;
21
+ flush(): void;
22
+ /** Discard pending copies when resize discards the corresponding draw frame. */
23
+ dispose(): void;
24
+ }