@codexo/exojs-tilemap 0.17.0 → 0.19.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.
Files changed (87) hide show
  1. package/README.md +84 -109
  2. package/dist/esm/ChunkStreamer.d.ts.map +1 -1
  3. package/dist/esm/ChunkStreamer.js +28 -6
  4. package/dist/esm/ChunkStreamer.js.map +1 -1
  5. package/dist/esm/ImageLayer.d.ts +1 -1
  6. package/dist/esm/ImageLayer.d.ts.map +1 -1
  7. package/dist/esm/ImageLayerNode.d.ts +5 -1
  8. package/dist/esm/ImageLayerNode.d.ts.map +1 -1
  9. package/dist/esm/ImageLayerNode.js +7 -2
  10. package/dist/esm/ImageLayerNode.js.map +1 -1
  11. package/dist/esm/MapObject.d.ts +2 -2
  12. package/dist/esm/MapObject.d.ts.map +1 -1
  13. package/dist/esm/MapObject.js.map +1 -1
  14. package/dist/esm/MapObjectSpawner.d.ts.map +1 -1
  15. package/dist/esm/MapSpawnSession.d.ts.map +1 -1
  16. package/dist/esm/MapWorld.d.ts +8 -8
  17. package/dist/esm/MapWorld.d.ts.map +1 -1
  18. package/dist/esm/MapWorldRuntime.d.ts.map +1 -1
  19. package/dist/esm/ObjectLayer.d.ts +26 -10
  20. package/dist/esm/ObjectLayer.d.ts.map +1 -1
  21. package/dist/esm/ObjectLayer.js +28 -0
  22. package/dist/esm/ObjectLayer.js.map +1 -1
  23. package/dist/esm/SampledChunkSource.d.ts.map +1 -1
  24. package/dist/esm/TileAnimator.d.ts.map +1 -1
  25. package/dist/esm/TileChunk.d.ts.map +1 -1
  26. package/dist/esm/TileChunkNode.js +47 -10
  27. package/dist/esm/TileChunkNode.js.map +1 -1
  28. package/dist/esm/TileLayer.d.ts +11 -2
  29. package/dist/esm/TileLayer.d.ts.map +1 -1
  30. package/dist/esm/TileLayer.js +20 -10
  31. package/dist/esm/TileLayer.js.map +1 -1
  32. package/dist/esm/TileLayerNode.d.ts +12 -5
  33. package/dist/esm/TileLayerNode.d.ts.map +1 -1
  34. package/dist/esm/TileLayerNode.js +44 -24
  35. package/dist/esm/TileLayerNode.js.map +1 -1
  36. package/dist/esm/TileMap.d.ts +6 -2
  37. package/dist/esm/TileMap.d.ts.map +1 -1
  38. package/dist/esm/TileMap.js +13 -12
  39. package/dist/esm/TileMap.js.map +1 -1
  40. package/dist/esm/TileMapBand.d.ts.map +1 -1
  41. package/dist/esm/TileMapNode.d.ts +6 -1
  42. package/dist/esm/TileMapNode.d.ts.map +1 -1
  43. package/dist/esm/TileMapNode.js +12 -4
  44. package/dist/esm/TileMapNode.js.map +1 -1
  45. package/dist/esm/TileMapView.d.ts +6 -1
  46. package/dist/esm/TileMapView.d.ts.map +1 -1
  47. package/dist/esm/TileMapView.js +9 -4
  48. package/dist/esm/TileMapView.js.map +1 -1
  49. package/dist/esm/TileProjection.d.ts +59 -0
  50. package/dist/esm/TileProjection.d.ts.map +1 -0
  51. package/dist/esm/TileProjection.js +106 -0
  52. package/dist/esm/TileProjection.js.map +1 -0
  53. package/dist/esm/TileSet.d.ts.map +1 -1
  54. package/dist/esm/WangSet.d.ts.map +1 -1
  55. package/dist/esm/WorkerSampledChunkSource.d.ts +4 -7
  56. package/dist/esm/WorkerSampledChunkSource.d.ts.map +1 -1
  57. package/dist/esm/WorkerSampledChunkSource.js +12 -18
  58. package/dist/esm/WorkerSampledChunkSource.js.map +1 -1
  59. package/dist/esm/autoTile.d.ts.map +1 -1
  60. package/dist/esm/chunkGeometry.js +78 -50
  61. package/dist/esm/chunkGeometry.js.map +1 -1
  62. package/dist/esm/index.js +2 -1
  63. package/dist/esm/projectObject.d.ts +4 -0
  64. package/dist/esm/projectObject.d.ts.map +1 -0
  65. package/dist/esm/projectObject.js +87 -0
  66. package/dist/esm/projectObject.js.map +1 -0
  67. package/dist/esm/public.d.ts +1 -0
  68. package/dist/esm/public.d.ts.map +1 -1
  69. package/dist/esm/tileCollision.d.ts +2 -2
  70. package/dist/esm/tileCollision.d.ts.map +1 -1
  71. package/dist/esm/tileCollision.js +48 -16
  72. package/dist/esm/tileCollision.js.map +1 -1
  73. package/dist/esm/tilemapSerializers.js +1 -1
  74. package/dist/esm/tilemapSerializers.js.map +1 -1
  75. package/dist/esm/types.d.ts +3 -3
  76. package/dist/esm/types.d.ts.map +1 -1
  77. package/dist/esm/webgl2/WebGl2TileChunkRenderer.js +8 -7
  78. package/dist/esm/webgl2/WebGl2TileChunkRenderer.js.map +1 -1
  79. package/dist/esm/webgl2/shaders/tile-chunk.frag.js +1 -1
  80. package/dist/esm/webgl2/shaders/tile-chunk.frag.js.map +1 -1
  81. package/dist/esm/webgl2/shaders/tile-chunk.vert.js +1 -1
  82. package/dist/esm/webgl2/shaders/tile-chunk.vert.js.map +1 -1
  83. package/dist/esm/webgpu/WebGpuTileChunkRenderer.js +67 -31
  84. package/dist/esm/webgpu/WebGpuTileChunkRenderer.js.map +1 -1
  85. package/dist/esm/webgpu/shaders/tile-chunk.wgsl.js +1 -1
  86. package/dist/esm/webgpu/shaders/tile-chunk.wgsl.js.map +1 -1
  87. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"WebGl2TileChunkRenderer.js","names":["tileVertexTemplate","tileFragmentSource"],"sources":["../../../src/webgl2/WebGl2TileChunkRenderer.ts"],"sourcesContent":["import type {\n RenderTexture,\n Texture,\n View,\n WebGl2Backend,\n WebGl2RenderBufferRuntime,\n WebGl2RetainedBatchPayload,\n WebGl2RetainedBatchReplayer,\n WebGl2RetainedNodeIndexRange,\n WebGl2VertexArrayObjectRuntime,\n} from '@codexo/exojs/renderer-sdk';\nimport {\n AbstractWebGl2Renderer,\n BlendModes,\n BufferTypes,\n BufferUsage,\n createWebGl2ShaderProgram,\n fillShaderSource,\n packedGroupChanged,\n RenderingPrimitives,\n Shader,\n uploadBufferRange,\n uploadBufferStore,\n WebGl2RenderBuffer,\n WebGl2VertexArrayObject,\n} from '@codexo/exojs/renderer-sdk';\n\nimport type { TileQuad } from '../chunkGeometry';\nimport type { TileChunkNode } from '../TileChunkNode';\nimport { TILE_DIAGONAL_BIT, TILE_ROW_MASK } from '../tileWord';\nimport tileFragmentSource from './shaders/tile-chunk.frag';\nimport tileVertexTemplate from './shaders/tile-chunk.vert';\n\n// One instance = one tile quad. Layout matches the engine's instanced-quad\n// convention (NineSlice/Repeating): float32x4 local rect, unorm16x4 UV bounds,\n// unorm8x4 tint, uint32 tile word (transform row + diagonal bit).\nconst instanceStrideBytes = 32;\nconst wordsPerInstance = instanceStrideBytes / Uint32Array.BYTES_PER_ELEMENT;\nconst transformTextureUnit = 1;\nconst identityGroupMat3 = new Float32Array([1, 0, 0, 0, 1, 0, 0, 0, 1]);\n\nconst tileVertexSource = fillShaderSource(tileVertexTemplate, { tileRowMask: TILE_ROW_MASK, tileDiagonalBit: TILE_DIAGONAL_BIT });\n\ninterface TileRendererConnection {\n readonly gl: WebGL2RenderingContext;\n readonly buffers: Map<WebGl2RenderBuffer, { handle: WebGLBuffer; dataByteLength: number }>;\n readonly vaoHandle: WebGLVertexArrayObject;\n}\n\n/**\n * Instanced WebGL2 renderer for {@link TileChunkNode}. Each tile is one\n * instanced quad; tiles are batched by `(shader, tileset texture)` and one\n * `drawArraysInstanced` is issued per batch. Per-chunk transforms ride on the\n * shared transform buffer (one row per chunk node), so the chunk geometry is\n * orientation-neutral and never re-uploaded for a camera pan.\n * @internal\n */\nexport class WebGl2TileChunkRenderer extends AbstractWebGl2Renderer<TileChunkNode> implements WebGl2RetainedBatchReplayer {\n /**\n * Retained-batch capability opt-in: a tile chunk's per-flush\n * instanced batches (fixed 32-byte layout, tile word at word 7) can be\n * recorded into a group's instruction set and replayed from group-owned\n * resources. Pixel-snapped draws are excluded by the collect-time\n * recordability predicate (and belt-and-braces poisoning in {@link render});\n * tile chunks have no custom-material path to exclude.\n * @internal\n */\n public readonly _supportsRetainedBatches = true;\n\n private readonly _shader: Shader;\n private readonly _batchSize: number;\n private readonly _instanceData: ArrayBuffer;\n private readonly _instanceFloat32: Float32Array;\n private readonly _instanceUint32: Uint32Array;\n\n private readonly _transformUnitScratch: Int32Array = new Int32Array([transformTextureUnit]);\n // Pinned unit index for the single tileset texture sampler (unit 0), reused\n // by the live flush and retained replay so both stay allocation-free.\n private readonly _baseTextureUnitScratch: Int32Array = new Int32Array([0]);\n // Reused single-slot texture list handed to the backend at record time; a\n // tile chunk batch always binds exactly one tileset texture (slot 0).\n private readonly _recordTextures: Array<Texture | RenderTexture | null> = [null];\n\n private _quadIndex = 0;\n private _maxNodeIndex = 0;\n // Chunk nodes booked against the PENDING batch, and whether the chunk being\n // rendered right now has already been booked. One chunk emits one tile\n // instance per tile, so the recorded batch's `submittedNodes` contribution is\n // this count and not `_quadIndex`. A chunk whose pages/runs span several\n // batches is booked once, against the batch its first run lands in.\n private _batchNodeCount = 0;\n private _nodeBooked = false;\n // Blend mode and tileset texture of the batch currently accumulating, used to\n // detect a batch break. Neither is a mirror of backend state: `flush()`\n // establishes both at the draw (see {@link _resetBatchState}).\n private _currentBlendMode: BlendModes | null = null;\n private _currentTexture: Texture | null = null;\n private _currentView: View | null = null;\n private _currentViewId = -1;\n private _hasWrittenGroup = false;\n private readonly _writtenGroupData = new Float32Array(9);\n\n private _instanceBuffer: WebGl2RenderBuffer | null = null;\n private _vao: WebGl2VertexArrayObject | null = null;\n private _connection: TileRendererConnection | null = null;\n\n public constructor(batchSize: number) {\n super();\n\n this._batchSize = batchSize;\n this._shader = new Shader(tileVertexSource, tileFragmentSource);\n this._instanceData = new ArrayBuffer(batchSize * instanceStrideBytes);\n this._instanceFloat32 = new Float32Array(this._instanceData);\n this._instanceUint32 = new Uint32Array(this._instanceData);\n }\n\n public render(node: TileChunkNode): void {\n const pages = node.pages;\n\n this._nodeBooked = false;\n\n if (pages.length === 0) {\n return;\n }\n\n const backend = this.getBackend();\n\n const blendMode = node.blendMode;\n const tintRgba = node.tint.toRgba8();\n\n const command = backend.activeDrawCommand;\n const nodeIndex = command !== null ? command.nodeIndex : backend.pushTransform(node);\n\n for (const page of pages) {\n this._renderPage(page.texture, page.quads, blendMode, tintRgba, nodeIndex);\n }\n }\n\n private _renderPage(texture: Texture, quads: readonly TileQuad[], blendMode: BlendModes, tintRgba: number, nodeIndex: number): void {\n if (quads.length === 0) {\n return;\n }\n\n const textureChanged = this._currentTexture !== null && texture !== this._currentTexture;\n const blendModeChanged = this._currentBlendMode !== null && blendMode !== this._currentBlendMode;\n\n if (this._quadIndex > 0 && (blendModeChanged || textureChanged || this._quadIndex + quads.length > this._batchSize)) {\n this.flush();\n }\n\n this._currentBlendMode = blendMode;\n this._currentTexture = texture;\n\n const flipY = texture.flipY;\n\n // A chunk page may hold more tiles than the fixed batch buffer; write in\n // batch-sized runs, flushing (and re-establishing state) between runs.\n let offset = 0;\n\n while (offset < quads.length) {\n const remaining = quads.length - offset;\n const runSize = Math.min(remaining, this._batchSize);\n\n this._writeRun(quads, offset, runSize, flipY, tintRgba, nodeIndex);\n\n offset += runSize;\n\n if (offset < quads.length) {\n this.flush();\n this._currentBlendMode = blendMode;\n this._currentTexture = texture;\n }\n }\n }\n\n private _writeRun(quads: readonly TileQuad[], offset: number, count: number, flipY: boolean, tintRgba: number, nodeIndex: number): void {\n const f32 = this._instanceFloat32;\n const u32 = this._instanceUint32;\n const baseWord = nodeIndex & TILE_ROW_MASK;\n\n // Booked here rather than in render(): any flush the page/run loops trigger\n // has already happened, so the chunk lands on the batch that actually holds\n // its first tile.\n if (!this._nodeBooked) {\n this._nodeBooked = true;\n this._batchNodeCount++;\n }\n\n for (let i = 0; i < count; i++) {\n const q = quads[offset + i]!;\n const idx = this._quadIndex * wordsPerInstance;\n\n f32[idx + 0] = q.x0;\n f32[idx + 1] = q.y0;\n f32[idx + 2] = q.x1;\n f32[idx + 3] = q.y1;\n\n // Bake flipX/flipY into the UV corner ordering; the diagonal axis swap is\n // resolved in the shader. Texture flipY (uploaded-flipped atlases) is an\n // additional vertical swap that composes with the tile flipY.\n const flipX = (q.orient & 1) !== 0;\n const tileFlipY = (q.orient & 2) !== 0;\n const diagonal = (q.orient & 4) !== 0;\n\n const uA = flipX ? q.u1 : q.u0;\n const uB = flipX ? q.u0 : q.u1;\n let vA = tileFlipY ? q.v1 : q.v0;\n let vB = tileFlipY ? q.v0 : q.v1;\n\n if (flipY) {\n const swap = vA;\n vA = vB;\n vB = swap;\n }\n\n const uMin = (uA * 0xffff) & 0xffff;\n const vMin = (vA * 0xffff) & 0xffff;\n const uMax = (uB * 0xffff) & 0xffff;\n const vMax = (vB * 0xffff) & 0xffff;\n\n u32[idx + 4] = uMin | (vMin << 16);\n u32[idx + 5] = uMax | (vMax << 16);\n u32[idx + 6] = tintRgba;\n u32[idx + 7] = (diagonal ? baseWord | TILE_DIAGONAL_BIT : baseWord) >>> 0;\n\n this._quadIndex++;\n }\n\n if (nodeIndex > this._maxNodeIndex) {\n this._maxNodeIndex = nodeIndex;\n }\n }\n\n public flush(): void {\n const backend = this.getBackendOrNull();\n const instanceBuffer = this._instanceBuffer;\n const vao = this._vao;\n\n if (this._quadIndex === 0 || backend === null || instanceBuffer === null || vao === null) {\n this._resetBatchState();\n return;\n }\n\n this._stageViewUniforms(backend);\n\n // Blend state and texture unit 0 are global and shared with every other\n // renderer - a sprite drawn between two tile layers binds its own texture\n // to the same unit - so this batch establishes both at its own draw. The\n // backend collapses a redundant call.\n if (this._currentTexture !== null) {\n backend.bindTexture(this._currentTexture, 0);\n this._shader.getUniform('u_texture').setValue(this._baseTextureUnitScratch);\n }\n\n backend.bindTransformBufferTexture(transformTextureUnit, this._maxNodeIndex + 1);\n this._shader.getUniform('u_transforms').setValue(this._transformUnitScratch);\n\n this._shader.sync();\n backend.bindVertexArrayObject(vao);\n instanceBuffer.upload(this._instanceFloat32, 0, this._quadIndex * wordsPerInstance);\n backend.setBlendMode(this._currentBlendMode ?? BlendModes.Normal);\n vao.drawInstanced(4, 0, this._quadIndex, RenderingPrimitives.TriangleStrip);\n backend.stats.batches++;\n backend.stats.drawCalls++;\n\n // Retained recording: while a capture window is open, hand the\n // exact packed instance words of this flush to the backend - byte-\n // identical to what just drew. A batch always binds a single tileset\n // texture (slot 0); a pixel-snapped node already poisoned the capture in\n // render().\n if (backend._isRetainedCapturing && this._currentTexture !== null) {\n this._recordTextures[0] = this._currentTexture;\n backend.recordRetainedBatch(\n this,\n this._instanceUint32.subarray(0, this._quadIndex * wordsPerInstance),\n this._quadIndex,\n this._currentBlendMode ?? BlendModes.Normal,\n this._recordTextures,\n 1,\n null,\n null,\n this._batchNodeCount,\n );\n }\n\n this._resetBatchState();\n }\n\n /**\n * Scope the batch memos to one batch: they describe what is accumulating, not\n * what GL holds, so a memo that outlived its flush would let the next batch\n * skip establishing state another renderer has since changed.\n */\n private _resetBatchState(): void {\n this._quadIndex = 0;\n this._maxNodeIndex = 0;\n this._batchNodeCount = 0;\n this._currentBlendMode = null;\n this._currentTexture = null;\n }\n\n /**\n * Stage `u_projection` (live view) and `u_group` (live composed group\n * matrix) on the shader, guarded by cached view/group stamps. Shared by the\n * live flush path and retained-batch replay - replay resolves exactly the\n * same live state a slow-path flush would.\n */\n private _stageViewUniforms(backend: WebGl2Backend): void {\n const view = backend.view;\n\n if (this._currentView !== view || this._currentViewId !== view.updateId) {\n this._currentView = view;\n this._currentViewId = view.updateId;\n this._shader.getUniform('u_projection').setValue(view.getTransform().toArray(false));\n }\n\n const groupTransform = backend.renderGroupTransform;\n const groupData = groupTransform !== null ? groupTransform.toArray(false) : identityGroupMat3;\n\n if (!this._hasWrittenGroup || packedGroupChanged(groupData, this._writtenGroupData, 0)) {\n this._shader.getUniform('u_group').setValue(groupData);\n this._writtenGroupData.set(groupData);\n this._hasWrittenGroup = true;\n }\n\n backend.stageViewportUniform(this._shader);\n }\n\n // ── Retained-batch record/replay ──────────────────────────────────────────\n // The bundle stores raw instance bytes; this renderer owns the 32-byte\n // layout (tile word at word 7: transform row in bits 0..28, diagonal flip in\n // bit 29), so the layout-aware finalize steps (node-index scan/rebase, VAO\n // attribute wiring) and the replay dispatch live here - mirroring\n // WebGl2NineSliceSpriteRenderer's seam.\n\n /** @internal See {@link WebGl2RetainedBatchReplayer.scanRetainedNodeIndexRange}. */\n public scanRetainedNodeIndexRange(payload: WebGl2RetainedBatchPayload, range: WebGl2RetainedNodeIndexRange): void {\n const words = payload.bundle.instanceWords;\n const start = payload.byteOffset / Uint32Array.BYTES_PER_ELEMENT;\n\n for (let i = 0; i < payload.instanceCount; i++) {\n // In-bounds: the payload's word range was appended to the bundle store.\n // The tile word is the last word of the 32-byte (8-word) instance\n // layout; only the low 29 bits address the transform buffer row - the\n // diagonal-flip flag (bit 29) is orientation, not a row index.\n const row = words[start + i * wordsPerInstance + 7]! & TILE_ROW_MASK;\n\n if (row < range.min) {\n range.min = row;\n }\n\n if (row > range.max) {\n range.max = row;\n }\n }\n }\n\n /** @internal See {@link WebGl2RetainedBatchReplayer.rebaseRetainedNodeIndices} (group-local indices). */\n public rebaseRetainedNodeIndices(payload: WebGl2RetainedBatchPayload, base: number): void {\n const words = payload.bundle.instanceWords;\n const start = payload.byteOffset / Uint32Array.BYTES_PER_ELEMENT;\n\n for (let i = 0; i < payload.instanceCount; i++) {\n const index = start + i * wordsPerInstance + 7;\n // In-bounds: see the scan above. Rebase ONLY the row field; the\n // diagonal-flip bit must survive untouched or tile orientation corrupts.\n const word = words[index]!;\n const diagonal = word & TILE_DIAGONAL_BIT;\n const row = word & TILE_ROW_MASK;\n\n words[index] = (diagonal | ((row - base) & TILE_ROW_MASK)) >>> 0;\n }\n }\n\n /**\n * Point the batch VAO's per-instance attributes at the bundle's persistent\n * instance buffer, based at the batch's byte offset (WebGL2 has no\n * baseInstance, hence one small VAO per recorded batch). Same attribute\n * set/locations as the live VAO in {@link onConnect}.\n * @internal\n */\n public configureRetainedVao(payload: WebGl2RetainedBatchPayload): void {\n const gl = this.getBackend().context;\n const buffer = payload.bundle.instanceBuffer;\n const vao = payload.vao;\n\n if (buffer === null || vao === null) {\n throw new Error('WebGl2TileChunkRenderer: retained batch VAO configuration requires an uploaded bundle.');\n }\n\n const base = payload.byteOffset;\n\n vao\n .addAttribute(buffer, this._shader.getAttribute('a_quadBounds'), gl.FLOAT, false, instanceStrideBytes, base + 0, false, 1)\n .addAttribute(buffer, this._shader.getAttribute('a_uvBounds'), gl.UNSIGNED_SHORT, true, instanceStrideBytes, base + 16, false, 1)\n .addAttribute(buffer, this._shader.getAttribute('a_color'), gl.UNSIGNED_BYTE, true, instanceStrideBytes, base + 24, false, 1)\n .addAttribute(buffer, this._shader.getAttribute('a_tileWord'), gl.UNSIGNED_INT, false, instanceStrideBytes, base + 28, true, 1);\n }\n\n /**\n * Replay one recorded batch: all STATE is resolved live - blend mode via\n * the backend's dedup, `u_projection`/`u_group` from the live view + live\n * composed group matrix (the camera-pan / group-move win), the single\n * tileset texture bound to unit 0 by recorded slot order - and only the\n * DATA is cached: the instance bytes in the bundle buffer (bound through\n * the per-batch VAO) and the group-owned transform texture on the shared\n * transform unit. The backend hook flushed any pending live batch before\n * dispatching here and bumps the stats from the instruction descriptor.\n * @internal\n */\n public replayRetainedBatch(payload: WebGl2RetainedBatchPayload): void {\n const backend = this.getBackendOrNull();\n const vao = payload.vao;\n const transformTexture = payload.bundle.transformTexture;\n\n if (backend === null || vao === null || transformTexture === null) {\n // Defensive: a bundle in this state never validates (generation), so a\n // spliced replay cannot reach here; skip rather than crash mid-frame.\n return;\n }\n\n backend.setBlendMode(payload.blendMode);\n this._stageViewUniforms(backend);\n\n const textures = payload.textures;\n\n for (let i = 0; i < textures.length; i++) {\n // In-bounds: i < textures.length.\n backend.bindTexture(textures[i]!, i);\n }\n\n this._shader.getUniform('u_texture').setValue(this._baseTextureUnitScratch);\n\n // The group-owned transform store replaces the shared frame buffer on the\n // SAME unit/sampler - zero GLSL changes. The next live flush re-binds the\n // shared texture through bindTransformBufferTexture.\n backend.bindTexture(transformTexture, transformTextureUnit);\n this._shader.getUniform('u_transforms').setValue(this._transformUnitScratch);\n\n this._shader.sync();\n backend.bindVertexArrayObject(vao);\n vao.drawInstanced(4, 0, payload.instanceCount, RenderingPrimitives.TriangleStrip);\n }\n\n protected onConnect(backend: WebGl2Backend): void {\n const gl = backend.context;\n\n this._shader.connect(createWebGl2ShaderProgram(gl));\n this._connection = this._createConnection(gl);\n this._instanceBuffer = new WebGl2RenderBuffer(BufferTypes.ArrayBuffer, this._instanceData, BufferUsage.DynamicDraw).connect(\n this._createBufferRuntime(this._connection),\n );\n this._shader.sync();\n\n this._vao = new WebGl2VertexArrayObject(RenderingPrimitives.TriangleStrip)\n .addAttribute(this._instanceBuffer, this._shader.getAttribute('a_quadBounds'), gl.FLOAT, false, instanceStrideBytes, 0, false, 1)\n .addAttribute(this._instanceBuffer, this._shader.getAttribute('a_uvBounds'), gl.UNSIGNED_SHORT, true, instanceStrideBytes, 16, false, 1)\n .addAttribute(this._instanceBuffer, this._shader.getAttribute('a_color'), gl.UNSIGNED_BYTE, true, instanceStrideBytes, 24, false, 1)\n .addAttribute(this._instanceBuffer, this._shader.getAttribute('a_tileWord'), gl.UNSIGNED_INT, false, instanceStrideBytes, 28, true, 1)\n .connect(this._createVaoRuntime(this._connection));\n }\n\n protected onDisconnect(): void {\n this._shader.disconnect();\n this._instanceBuffer?.destroy();\n this._instanceBuffer = null;\n this._vao?.destroy();\n this._vao = null;\n this._connection = null;\n this._currentBlendMode = null;\n this._currentTexture = null;\n this._currentView = null;\n this._currentViewId = -1;\n this._hasWrittenGroup = false;\n this._quadIndex = 0;\n this._maxNodeIndex = 0;\n this._batchNodeCount = 0;\n this._nodeBooked = false;\n }\n\n public destroy(): void {\n this.disconnect();\n this._shader.destroy();\n }\n\n private _createConnection(gl: WebGL2RenderingContext): TileRendererConnection {\n const vaoHandle = gl.createVertexArray();\n\n if (vaoHandle === null) {\n throw new Error('WebGl2TileChunkRenderer: could not create vertex array object.');\n }\n\n return { gl, buffers: new Map(), vaoHandle };\n }\n\n private _createBufferRuntime(connection: TileRendererConnection): WebGl2RenderBufferRuntime {\n const handle = connection.gl.createBuffer();\n\n if (handle === null) {\n throw new Error('WebGl2TileChunkRenderer: could not create render buffer.');\n }\n\n return {\n bind: (buffer): void => {\n connection.gl.bindBuffer(buffer.type, handle);\n },\n upload: (buffer, offset): void => {\n const gl = connection.gl;\n const state = connection.buffers.get(buffer);\n\n gl.bindBuffer(buffer.type, handle);\n\n if (state && state.dataByteLength >= buffer.uploadByteLength) {\n uploadBufferRange(gl, buffer, offset);\n state.dataByteLength = buffer.uploadByteLength;\n } else {\n uploadBufferStore(gl, buffer);\n connection.buffers.set(buffer, { handle, dataByteLength: buffer.uploadByteLength });\n }\n },\n destroy: (buffer): void => {\n connection.gl.deleteBuffer(handle);\n connection.buffers.delete(buffer);\n buffer.disconnect();\n },\n };\n }\n\n private _createVaoRuntime(connection: TileRendererConnection): WebGl2VertexArrayObjectRuntime {\n let appliedVersion = -1;\n\n return {\n bind: (vao): void => {\n const gl = connection.gl;\n\n gl.bindVertexArray(connection.vaoHandle);\n\n if (appliedVersion !== vao.version) {\n let lastBuffer: WebGl2RenderBuffer | null = null;\n\n for (const attribute of vao.attributes) {\n if (lastBuffer !== attribute.buffer) {\n attribute.buffer.bind();\n lastBuffer = attribute.buffer;\n }\n\n if (attribute.integer) {\n gl.vertexAttribIPointer(attribute.location, attribute.size, attribute.type, attribute.stride, attribute.start);\n } else {\n gl.vertexAttribPointer(attribute.location, attribute.size, attribute.type, attribute.normalized, attribute.stride, attribute.start);\n }\n\n gl.enableVertexAttribArray(attribute.location);\n gl.vertexAttribDivisor(attribute.location, attribute.divisor);\n }\n\n appliedVersion = vao.version;\n }\n },\n unbind: (): void => {\n connection.gl.bindVertexArray(null);\n },\n draw: (_vao, size, start, type): void => {\n connection.gl.drawArrays(type, start, size);\n },\n drawInstanced: (_vao, count, start, instanceCount, type): void => {\n connection.gl.drawArraysInstanced(type, start, count, instanceCount);\n },\n destroy: (vao): void => {\n connection.gl.deleteVertexArray(connection.vaoHandle);\n vao.disconnect();\n },\n };\n }\n}\n"],"mappings":";;;;;;AAoCA,MAAM,sB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GACA,UAAU,QAAc;IACtB,WAAW,GAAG,kBAAkB,WAAW,SAAS;IACpD,IAAI,WAAW;GACjB;EACF;CACF;AACF"}
1
+ {"version":3,"file":"WebGl2TileChunkRenderer.js","names":["tileVertexTemplate","tileFragmentSource"],"sources":["../../../src/webgl2/WebGl2TileChunkRenderer.ts"],"sourcesContent":["import type {\n RenderTexture,\n Texture,\n View,\n WebGl2Backend,\n WebGl2RenderBufferRuntime,\n WebGl2RetainedBatchPayload,\n WebGl2RetainedBatchReplayer,\n WebGl2RetainedNodeIndexRange,\n WebGl2VertexArrayObjectRuntime,\n} from '@codexo/exojs/renderer-sdk';\nimport {\n AbstractWebGl2Renderer,\n BlendModes,\n BufferTypes,\n BufferUsage,\n colorShaderSourcesGlsl,\n createWebGl2ShaderProgram,\n fillShaderSource,\n packedGroupChanged,\n RenderingPrimitives,\n spliceGlslPrologue,\n uploadBufferRange,\n uploadBufferStore,\n WebGl2RenderBuffer,\n WebGl2Shader,\n WebGl2VertexArrayObject,\n} from '@codexo/exojs/renderer-sdk';\n\nimport type { TileQuad } from '../chunkGeometry';\nimport type { TileChunkNode } from '../TileChunkNode';\nimport { TILE_DIAGONAL_BIT, TILE_ROW_MASK } from '../tileWord';\nimport tileFragmentSource from './shaders/tile-chunk.frag';\nimport tileVertexTemplate from './shaders/tile-chunk.vert';\n\n// One instance = one tile quad. Layout matches the engine's instanced-quad\n// convention (NineSlice/Repeating): float32x4 local rect, unorm16x4 UV bounds,\n// unorm8x4 tint, uint32 tile word (transform row + diagonal bit).\nconst instanceStrideBytes = 32;\nconst wordsPerInstance = instanceStrideBytes / Uint32Array.BYTES_PER_ELEMENT;\nconst transformTextureUnit = 1;\nconst identityGroupMat3 = new Float32Array([1, 0, 0, 0, 1, 0, 0, 0, 1]);\n\nconst tileVertexSource = spliceGlslPrologue(\n fillShaderSource(tileVertexTemplate, { tileRowMask: TILE_ROW_MASK, tileDiagonalBit: TILE_DIAGONAL_BIT }),\n colorShaderSourcesGlsl,\n);\n\ninterface TileRendererConnection {\n readonly gl: WebGL2RenderingContext;\n readonly buffers: Map<WebGl2RenderBuffer, { handle: WebGLBuffer; dataByteLength: number }>;\n readonly vaoHandle: WebGLVertexArrayObject;\n}\n\n/**\n * Instanced WebGL2 renderer for {@link TileChunkNode}. Each tile is one\n * instanced quad; tiles are batched by `(shader, tileset texture)` and one\n * `drawArraysInstanced` is issued per batch. Per-chunk transforms ride on the\n * shared transform buffer (one row per chunk node), so the chunk geometry is\n * orientation-neutral and never re-uploaded for a camera pan.\n * @internal\n */\nexport class WebGl2TileChunkRenderer extends AbstractWebGl2Renderer<TileChunkNode> implements WebGl2RetainedBatchReplayer {\n /**\n * Retained-batch capability opt-in: a tile chunk's per-flush\n * instanced batches (fixed 32-byte layout, tile word at word 7) can be\n * recorded into a group's instruction set and replayed from group-owned\n * resources. Pixel-snapped draws are excluded by the collect-time\n * recordability predicate (and belt-and-braces poisoning in {@link render});\n * tile chunks have no custom-material path to exclude.\n * @internal\n */\n public readonly supportsRetainedBatches = true;\n\n private readonly _shader: WebGl2Shader;\n private readonly _batchSize: number;\n private readonly _instanceData: ArrayBuffer;\n private readonly _instanceFloat32: Float32Array;\n private readonly _instanceUint32: Uint32Array;\n\n private readonly _transformUnitScratch: Int32Array = new Int32Array([transformTextureUnit]);\n // Pinned unit index for the single tileset texture sampler (unit 0), reused\n // by the live flush and retained replay so both stay allocation-free.\n private readonly _baseTextureUnitScratch: Int32Array = new Int32Array([0]);\n // Reused single-slot texture list handed to the backend at record time; a\n // tile chunk batch always binds exactly one tileset texture (slot 0).\n private readonly _recordTextures: Array<Texture | RenderTexture | null> = [null];\n\n private _quadIndex = 0;\n private _maxNodeIndex = 0;\n // Chunk nodes booked against the PENDING batch, and whether the chunk being\n // rendered right now has already been booked. One chunk emits one tile\n // instance per tile, so the recorded batch's `submittedNodes` contribution is\n // this count and not `_quadIndex`. A chunk whose pages/runs span several\n // batches is booked once, against the batch its first run lands in.\n private _batchNodeCount = 0;\n private _nodeBooked = false;\n // Blend mode and tileset texture of the batch currently accumulating, used to\n // detect a batch break. Neither is a mirror of backend state: `flush()`\n // establishes both at the draw (see {@link _resetBatchState}).\n private _currentBlendMode: BlendModes | null = null;\n private _currentTexture: Texture | null = null;\n private _currentView: View | null = null;\n private _currentViewId = -1;\n private _hasWrittenGroup = false;\n private readonly _writtenGroupData = new Float32Array(9);\n\n private _instanceBuffer: WebGl2RenderBuffer | null = null;\n private _vao: WebGl2VertexArrayObject | null = null;\n private _connection: TileRendererConnection | null = null;\n\n public constructor(batchSize: number) {\n super();\n\n this._batchSize = batchSize;\n this._shader = new WebGl2Shader(tileVertexSource, tileFragmentSource);\n this._instanceData = new ArrayBuffer(batchSize * instanceStrideBytes);\n this._instanceFloat32 = new Float32Array(this._instanceData);\n this._instanceUint32 = new Uint32Array(this._instanceData);\n }\n\n public render(node: TileChunkNode): void {\n const pages = node.pages;\n\n this._nodeBooked = false;\n\n if (pages.length === 0) {\n return;\n }\n\n const backend = this.getBackend();\n\n const blendMode = node.blendMode;\n const tintRgba = node.tint.toRgba8();\n\n const command = backend.activeDrawCommand;\n const nodeIndex = command !== null ? command.nodeIndex : backend.pushTransform(node);\n\n for (const page of pages) {\n this._renderPage(page.texture, page.quads, blendMode, tintRgba, nodeIndex);\n }\n }\n\n private _renderPage(texture: Texture, quads: readonly TileQuad[], blendMode: BlendModes, tintRgba: number, nodeIndex: number): void {\n if (quads.length === 0) {\n return;\n }\n\n const textureChanged = this._currentTexture !== null && texture !== this._currentTexture;\n const blendModeChanged = this._currentBlendMode !== null && blendMode !== this._currentBlendMode;\n\n if (this._quadIndex > 0 && (blendModeChanged || textureChanged || this._quadIndex + quads.length > this._batchSize)) {\n this.flush();\n }\n\n this._currentBlendMode = blendMode;\n this._currentTexture = texture;\n\n const flipY = texture.flipY;\n\n // A chunk page may hold more tiles than the fixed batch buffer; write in\n // batch-sized runs, flushing (and re-establishing state) between runs.\n let offset = 0;\n\n while (offset < quads.length) {\n const remaining = quads.length - offset;\n const runSize = Math.min(remaining, this._batchSize);\n\n this._writeRun(quads, offset, runSize, flipY, tintRgba, nodeIndex);\n\n offset += runSize;\n\n if (offset < quads.length) {\n this.flush();\n this._currentBlendMode = blendMode;\n this._currentTexture = texture;\n }\n }\n }\n\n private _writeRun(quads: readonly TileQuad[], offset: number, count: number, flipY: boolean, tintRgba: number, nodeIndex: number): void {\n const f32 = this._instanceFloat32;\n const u32 = this._instanceUint32;\n const baseWord = nodeIndex & TILE_ROW_MASK;\n\n // Booked here rather than in render(): any flush the page/run loops trigger\n // has already happened, so the chunk lands on the batch that actually holds\n // its first tile.\n if (!this._nodeBooked) {\n this._nodeBooked = true;\n this._batchNodeCount++;\n }\n\n for (let i = 0; i < count; i++) {\n const q = quads[offset + i]!;\n const idx = this._quadIndex * wordsPerInstance;\n\n f32[idx + 0] = q.x0;\n f32[idx + 1] = q.y0;\n f32[idx + 2] = q.x1;\n f32[idx + 3] = q.y1;\n\n // Bake flipX/flipY into the UV corner ordering; the diagonal axis swap is\n // resolved in the shader. Texture flipY (uploaded-flipped atlases) is an\n // additional vertical swap that composes with the tile flipY.\n const flipX = (q.orient & 1) !== 0;\n const tileFlipY = (q.orient & 2) !== 0;\n const diagonal = (q.orient & 4) !== 0;\n\n const uA = flipX ? q.u1 : q.u0;\n const uB = flipX ? q.u0 : q.u1;\n let vA = tileFlipY ? q.v1 : q.v0;\n let vB = tileFlipY ? q.v0 : q.v1;\n\n if (flipY) {\n const swap = vA;\n vA = vB;\n vB = swap;\n }\n\n const uMin = (uA * 0xffff) & 0xffff;\n const vMin = (vA * 0xffff) & 0xffff;\n const uMax = (uB * 0xffff) & 0xffff;\n const vMax = (vB * 0xffff) & 0xffff;\n\n u32[idx + 4] = uMin | (vMin << 16);\n u32[idx + 5] = uMax | (vMax << 16);\n u32[idx + 6] = tintRgba;\n u32[idx + 7] = (diagonal ? baseWord | TILE_DIAGONAL_BIT : baseWord) >>> 0;\n\n this._quadIndex++;\n }\n\n if (nodeIndex > this._maxNodeIndex) {\n this._maxNodeIndex = nodeIndex;\n }\n }\n\n public flush(): void {\n const backend = this.getBackendOrNull();\n const instanceBuffer = this._instanceBuffer;\n const vao = this._vao;\n\n if (this._quadIndex === 0 || backend === null || instanceBuffer === null || vao === null) {\n this._resetBatchState();\n return;\n }\n\n this._stageViewUniforms(backend);\n\n // Blend state and texture unit 0 are global and shared with every other\n // renderer - a sprite drawn between two tile layers binds its own texture\n // to the same unit - so this batch establishes both at its own draw. The\n // backend collapses a redundant call.\n if (this._currentTexture !== null) {\n backend.bindTexture(this._currentTexture, 0);\n this._shader.getUniform('u_texture').setValue(this._baseTextureUnitScratch);\n }\n\n backend.bindTransformBufferTexture(transformTextureUnit, this._maxNodeIndex + 1);\n this._shader.getUniform('u_transforms').setValue(this._transformUnitScratch);\n\n this._shader.sync();\n backend.bindVertexArrayObject(vao);\n instanceBuffer.upload(this._instanceFloat32, 0, this._quadIndex * wordsPerInstance);\n backend.setBlendMode(this._currentBlendMode ?? BlendModes.Normal);\n vao.drawInstanced(4, 0, this._quadIndex, RenderingPrimitives.TriangleStrip);\n backend.stats.batches++;\n backend.stats.drawCalls++;\n\n // Retained recording: while a capture window is open, hand the\n // exact packed instance words of this flush to the backend - byte-\n // identical to what just drew. A batch always binds a single tileset\n // texture (slot 0); a pixel-snapped node already poisoned the capture in\n // render().\n if (backend._isRetainedCapturing && this._currentTexture !== null) {\n this._recordTextures[0] = this._currentTexture;\n backend.recordRetainedBatch(\n this,\n this._instanceUint32.subarray(0, this._quadIndex * wordsPerInstance),\n this._quadIndex,\n this._currentBlendMode ?? BlendModes.Normal,\n this._recordTextures,\n 1,\n null,\n null,\n this._batchNodeCount,\n );\n }\n\n this._resetBatchState();\n }\n\n /**\n * Scope the batch memos to one batch: they describe what is accumulating, not\n * what GL holds, so a memo that outlived its flush would let the next batch\n * skip establishing state another renderer has since changed.\n */\n private _resetBatchState(): void {\n this._quadIndex = 0;\n this._maxNodeIndex = 0;\n this._batchNodeCount = 0;\n this._currentBlendMode = null;\n this._currentTexture = null;\n }\n\n /**\n * Stage `u_projection` (live view) and `u_group` (live composed group\n * matrix) on the shader, guarded by cached view/group stamps. Shared by the\n * live flush path and retained-batch replay - replay resolves exactly the\n * same live state a slow-path flush would.\n */\n private _stageViewUniforms(backend: WebGl2Backend): void {\n const view = backend.view;\n\n if (this._currentView !== view || this._currentViewId !== view.updateId) {\n this._currentView = view;\n this._currentViewId = view.updateId;\n this._shader.getUniform('u_projection').setValue(view.getTransform().toArray(false));\n }\n\n const groupTransform = backend.renderGroupTransform;\n const groupData = groupTransform !== null ? groupTransform.toArray(false) : identityGroupMat3;\n\n if (!this._hasWrittenGroup || packedGroupChanged(groupData, this._writtenGroupData, 0)) {\n this._shader.getUniform('u_group').setValue(groupData);\n this._writtenGroupData.set(groupData);\n this._hasWrittenGroup = true;\n }\n\n backend.stageViewportUniform(this._shader);\n }\n\n // ── Retained-batch record/replay ──────────────────────────────────────────\n // The bundle stores raw instance bytes; this renderer owns the 32-byte\n // layout (tile word at word 7: transform row in bits 0..28, diagonal flip in\n // bit 29), so the layout-aware finalize steps (node-index scan/rebase, VAO\n // attribute wiring) and the replay dispatch live here - mirroring\n // WebGl2NineSliceSpriteRenderer's seam.\n\n /** @internal See {@link WebGl2RetainedBatchReplayer.scanRetainedNodeIndexRange}. */\n public scanRetainedNodeIndexRange(payload: WebGl2RetainedBatchPayload, range: WebGl2RetainedNodeIndexRange): void {\n const words = payload.bundle.instanceWords;\n const start = payload.byteOffset / Uint32Array.BYTES_PER_ELEMENT;\n\n for (let i = 0; i < payload.instanceCount; i++) {\n // In-bounds: the payload's word range was appended to the bundle store.\n // The tile word is the last word of the 32-byte (8-word) instance\n // layout; only the low 29 bits address the transform buffer row - the\n // diagonal-flip flag (bit 29) is orientation, not a row index.\n const row = words[start + i * wordsPerInstance + 7]! & TILE_ROW_MASK;\n\n if (row < range.min) {\n range.min = row;\n }\n\n if (row > range.max) {\n range.max = row;\n }\n }\n }\n\n /** @internal See {@link WebGl2RetainedBatchReplayer.rebaseRetainedNodeIndices} (group-local indices). */\n public rebaseRetainedNodeIndices(payload: WebGl2RetainedBatchPayload, base: number): void {\n const words = payload.bundle.instanceWords;\n const start = payload.byteOffset / Uint32Array.BYTES_PER_ELEMENT;\n\n for (let i = 0; i < payload.instanceCount; i++) {\n const index = start + i * wordsPerInstance + 7;\n // In-bounds: see the scan above. Rebase ONLY the row field; the\n // diagonal-flip bit must survive untouched or tile orientation corrupts.\n const word = words[index]!;\n const diagonal = word & TILE_DIAGONAL_BIT;\n const row = word & TILE_ROW_MASK;\n\n words[index] = (diagonal | ((row - base) & TILE_ROW_MASK)) >>> 0;\n }\n }\n\n /**\n * Point the batch VAO's per-instance attributes at the bundle's persistent\n * instance buffer, based at the batch's byte offset (WebGL2 has no\n * baseInstance, hence one small VAO per recorded batch). Same attribute\n * set/locations as the live VAO in {@link onConnect}.\n * @internal\n */\n public configureRetainedVao(payload: WebGl2RetainedBatchPayload): void {\n const gl = this.getBackend().context;\n const buffer = payload.bundle.instanceBuffer;\n const vao = payload.vao;\n\n if (buffer === null || vao === null) {\n throw new Error('WebGl2TileChunkRenderer: retained batch VAO configuration requires an uploaded bundle.');\n }\n\n const base = payload.byteOffset;\n\n vao\n .addAttribute(buffer, this._shader.getAttribute('a_quadBounds'), gl.FLOAT, false, instanceStrideBytes, base + 0, false, 1)\n .addAttribute(buffer, this._shader.getAttribute('a_uvBounds'), gl.UNSIGNED_SHORT, true, instanceStrideBytes, base + 16, false, 1)\n .addAttribute(buffer, this._shader.getAttribute('a_color'), gl.UNSIGNED_BYTE, true, instanceStrideBytes, base + 24, false, 1)\n .addAttribute(buffer, this._shader.getAttribute('a_tileWord'), gl.UNSIGNED_INT, false, instanceStrideBytes, base + 28, true, 1);\n }\n\n /**\n * Replay one recorded batch: all STATE is resolved live - blend mode via\n * the backend's dedup, `u_projection`/`u_group` from the live view + live\n * composed group matrix (the camera-pan / group-move win), the single\n * tileset texture bound to unit 0 by recorded slot order - and only the\n * DATA is cached: the instance bytes in the bundle buffer (bound through\n * the per-batch VAO) and the group-owned transform texture on the shared\n * transform unit. The backend hook flushed any pending live batch before\n * dispatching here and bumps the stats from the instruction descriptor.\n * @internal\n */\n public replayRetainedBatch(payload: WebGl2RetainedBatchPayload): boolean {\n const backend = this.getBackendOrNull();\n const vao = payload.vao;\n const transformTexture = payload.bundle.transformTexture;\n\n if (backend === null || vao === null || transformTexture === null) {\n // Defensive: a bundle in this state never validates (generation), so a\n // spliced replay cannot reach here; skip rather than crash mid-frame.\n return false;\n }\n\n backend.setBlendMode(payload.blendMode);\n this._stageViewUniforms(backend);\n\n const textures = payload.textures;\n\n for (let i = 0; i < textures.length; i++) {\n // In-bounds: i < textures.length.\n backend.bindTexture(textures[i]!, i);\n }\n\n this._shader.getUniform('u_texture').setValue(this._baseTextureUnitScratch);\n\n // The group-owned transform store replaces the shared frame buffer on the\n // SAME unit/sampler - zero GLSL changes. The next live flush re-binds the\n // shared texture through bindTransformBufferTexture.\n backend.bindTexture(transformTexture, transformTextureUnit);\n this._shader.getUniform('u_transforms').setValue(this._transformUnitScratch);\n\n this._shader.sync();\n backend.bindVertexArrayObject(vao);\n vao.drawInstanced(4, 0, payload.instanceCount, RenderingPrimitives.TriangleStrip);\n\n return true;\n }\n\n protected onConnect(backend: WebGl2Backend): void {\n const gl = backend.context;\n\n this._shader.connect(createWebGl2ShaderProgram(gl));\n this._connection = this._createConnection(gl);\n this._instanceBuffer = new WebGl2RenderBuffer(BufferTypes.ArrayBuffer, this._instanceData, BufferUsage.DynamicDraw).connect(\n this._createBufferRuntime(this._connection),\n );\n this._shader.sync();\n\n this._vao = new WebGl2VertexArrayObject(RenderingPrimitives.TriangleStrip)\n .addAttribute(this._instanceBuffer, this._shader.getAttribute('a_quadBounds'), gl.FLOAT, false, instanceStrideBytes, 0, false, 1)\n .addAttribute(this._instanceBuffer, this._shader.getAttribute('a_uvBounds'), gl.UNSIGNED_SHORT, true, instanceStrideBytes, 16, false, 1)\n .addAttribute(this._instanceBuffer, this._shader.getAttribute('a_color'), gl.UNSIGNED_BYTE, true, instanceStrideBytes, 24, false, 1)\n .addAttribute(this._instanceBuffer, this._shader.getAttribute('a_tileWord'), gl.UNSIGNED_INT, false, instanceStrideBytes, 28, true, 1)\n .connect(this._createVaoRuntime(this._connection));\n }\n\n protected onDisconnect(): void {\n this._shader.destroy();\n this._instanceBuffer?.destroy();\n this._instanceBuffer = null;\n this._vao?.destroy();\n this._vao = null;\n this._connection = null;\n this._currentBlendMode = null;\n this._currentTexture = null;\n this._currentView = null;\n this._currentViewId = -1;\n this._hasWrittenGroup = false;\n this._quadIndex = 0;\n this._maxNodeIndex = 0;\n this._batchNodeCount = 0;\n this._nodeBooked = false;\n }\n\n public destroy(): void {\n this.disconnect();\n this._shader.destroy();\n }\n\n private _createConnection(gl: WebGL2RenderingContext): TileRendererConnection {\n const vaoHandle = gl.createVertexArray();\n\n if (vaoHandle === null) {\n throw new Error('WebGl2TileChunkRenderer: could not create vertex array object.');\n }\n\n return { gl, buffers: new Map(), vaoHandle };\n }\n\n private _createBufferRuntime(connection: TileRendererConnection): WebGl2RenderBufferRuntime {\n const handle = connection.gl.createBuffer();\n\n if (handle === null) {\n throw new Error('WebGl2TileChunkRenderer: could not create render buffer.');\n }\n\n return {\n bind: (buffer): void => {\n connection.gl.bindBuffer(buffer.type, handle);\n },\n upload: (buffer, offset): void => {\n const gl = connection.gl;\n const state = connection.buffers.get(buffer);\n\n gl.bindBuffer(buffer.type, handle);\n\n if (state && state.dataByteLength >= buffer.uploadByteLength) {\n uploadBufferRange(gl, buffer, offset);\n state.dataByteLength = buffer.uploadByteLength;\n } else {\n uploadBufferStore(gl, buffer);\n connection.buffers.set(buffer, { handle, dataByteLength: buffer.uploadByteLength });\n }\n },\n destroy: (buffer): void => {\n connection.gl.deleteBuffer(handle);\n connection.buffers.delete(buffer);\n buffer.disconnect();\n },\n };\n }\n\n private _createVaoRuntime(connection: TileRendererConnection): WebGl2VertexArrayObjectRuntime {\n let appliedVersion = -1;\n\n return {\n bind: (vao): void => {\n const gl = connection.gl;\n\n gl.bindVertexArray(connection.vaoHandle);\n\n if (appliedVersion !== vao.version) {\n let lastBuffer: WebGl2RenderBuffer | null = null;\n\n for (const attribute of vao.attributes) {\n if (lastBuffer !== attribute.buffer) {\n attribute.buffer.bind();\n lastBuffer = attribute.buffer;\n }\n\n if (attribute.integer) {\n gl.vertexAttribIPointer(attribute.location, attribute.size, attribute.type, attribute.stride, attribute.start);\n } else {\n gl.vertexAttribPointer(attribute.location, attribute.size, attribute.type, attribute.normalized, attribute.stride, attribute.start);\n }\n\n gl.enableVertexAttribArray(attribute.location);\n gl.vertexAttribDivisor(attribute.location, attribute.divisor);\n }\n\n appliedVersion = vao.version;\n }\n },\n unbind: (): void => {\n connection.gl.bindVertexArray(null);\n },\n draw: (_vao, size, start, type): void => {\n connection.gl.drawArrays(type, start, size);\n },\n drawInstanced: (_vao, count, start, instanceCount, type): void => {\n connection.gl.drawArraysInstanced(type, start, count, instanceCount);\n },\n destroy: (vao): void => {\n connection.gl.deleteVertexArray(connection.vaoHandle);\n vao.disconnect();\n },\n };\n }\n}\n"],"mappings":";;;;;;AAsCA,MAAM,sBAAsB;AAC5B,MAAM,mBAAmB,sBAAsB,YAAY;AAC3D,MAAM,uBAAuB;AAC7B,MAAM,oBAAoB,IAAI,aAAa;CAAC;CAAG;CAAG;CAAG;CAAG;CAAG;CAAG;CAAG;CAAG;AAAC,CAAC;AAEtE,MAAM,mBAAmB,mBACvB,iBAAiBA,sBAAoB;CAAE,aAAa;CAAe,iBAAiB;AAAkB,CAAC,GACvG,sBACF;;;;;;;;;AAgBA,IAAa,0BAAb,cAA6C,uBAA6E;;;;;;;;;;CAUxH,AAAgB,0BAA0B;CAE1C,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CAEjB,AAAiB,wBAAoC,IAAI,WAAW,CAAC,oBAAoB,CAAC;CAG1F,AAAiB,0BAAsC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QAAc;IACnB,MAAM,KAAK,WAAW;IAEtB,GAAG,gBAAgB,WAAW,SAAS;IAEvC,IAAI,mBAAmB,IAAI,SAAS;KAClC,IAAI,aAAwC;KAE5C,KAAK,MAAM,aAAa,IAAI,YAAY;MACtC,IAAI,eAAe,UAAU,QAAQ;OACnC,UAAU,OAAO,KAAK;OACtB,aAAa,UAAU;MACzB;MAEA,IAAI,UAAU,SACZ,GAAG,qBAAqB,UAAU,UAAU,UAAU,MAAM,UAAU,MAAM,UAAU,QAAQ,UAAU,KAAK;WAE7G,GAAG,oBAAoB,UAAU,UAAU,UAAU,MAAM,UAAU,MAAM,UAAU,YAAY,UAAU,QAAQ,UAAU,KAAK;MAGpI,GAAG,wBAAwB,UAAU,QAAQ;MAC7C,GAAG,oBAAoB,UAAU,UAAU,UAAU,OAAO;KAC9D;KAEA,iBAAiB,IAAI;IACvB;GACF;GACA,cAAoB;IAClB,WAAW,GAAG,gBAAgB,IAAI;GACpC;GACA,OAAO,MAAM,MAAM,OAAO,SAAe;IACvC,WAAW,GAAG,WAAW,MAAM,OAAO,IAAI;GAC5C;GACA,gBAAgB,MAAM,OAAO,OAAO,eAAe,SAAe;IAChE,WAAW,GAAG,oBAAoB,MAAM,OAAO,OAAO,aAAa;GACrE;GACA,UAAU,QAAc;IACtB,WAAW,GAAG,kBAAkB,WAAW,SAAS;IACpD,IAAI,WAAW;GACjB;EACF;CACF;AACF"}
@@ -1,5 +1,5 @@
1
1
  //#region src/webgl2/shaders/tile-chunk.frag
2
- var tile_chunk_default = "#version 300 es\nprecision highp float;\n\nuniform sampler2D u_texture;\n\nin vec2 v_texcoord;\nin vec4 v_color;\n\nlayout(location = 0) out vec4 fragColor;\n\nvoid main(void) {\n vec4 sampleColor = texture(u_texture, v_texcoord);\n fragColor = sampleColor * v_color;\n}\n";
2
+ var tile_chunk_default = "#version 300 es\nprecision highp float;\nuniform sampler2D u_texture;\nin vec2 v_texcoord;\nin vec4 v_color;\nlayout(location = 0) out vec4 fragColor;\nvoid main(void) {\nvec4 sampleColor = texture(u_texture, v_texcoord);\nfragColor = sampleColor * v_color;\n}";
3
3
 
4
4
  //#endregion
5
5
  export { tile_chunk_default as default };
@@ -1 +1 @@
1
- {"version":3,"file":"tile-chunk.frag.js","names":[],"sources":["../../../../src/webgl2/shaders/tile-chunk.frag"],"sourcesContent":["export default \"#version 300 es\\nprecision highp float;\\n\\nuniform sampler2D u_texture;\\n\\nin vec2 v_texcoord;\\nin vec4 v_color;\\n\\nlayout(location = 0) out vec4 fragColor;\\n\\nvoid main(void) {\\n vec4 sampleColor = texture(u_texture, v_texcoord);\\n fragColor = sampleColor * v_color;\\n}\\n\";"],"mappings":";AAAA,yBAAe"}
1
+ {"version":3,"file":"tile-chunk.frag.js","names":[],"sources":["../../../../src/webgl2/shaders/tile-chunk.frag"],"sourcesContent":["export default \"#version 300 es\\nprecision highp float;\\nuniform sampler2D u_texture;\\nin vec2 v_texcoord;\\nin vec4 v_color;\\nlayout(location = 0) out vec4 fragColor;\\nvoid main(void) {\\nvec4 sampleColor = texture(u_texture, v_texcoord);\\nfragColor = sampleColor * v_color;\\n}\";"],"mappings":";AAAA,yBAAe"}
@@ -1,5 +1,5 @@
1
1
  //#region src/webgl2/shaders/tile-chunk.vert
2
- var tile_chunk_default = "#version 300 es\nprecision highp float;\nprecision highp int;\n\n// Per-instance attributes (divisor = 1). One entry per tile quad.\n// gl_VertexID 0..3 selects which corner of the quad this invocation computes.\nlayout(location = 0) in vec4 a_quadBounds; // x0, y0, x1, y1 (chunk-local)\nlayout(location = 1) in vec4 a_uvBounds; // uMin, vMin, uMax, vMax (flipX/Y + texture flipY baked)\nlayout(location = 2) in vec4 a_color; // RGBA tint (layer opacity in alpha)\nlayout(location = 3) in uint a_tileWord; // transform row (bits 0..28) | diagonal (bit 29)\n\nuniform mat3 u_projection;\nuniform mat3 u_group;\nuniform vec4 u_viewport; // device-pixel viewport rect (x, y, width, height)\nuniform sampler2D u_transforms; // shared per-frame transform buffer (2 texels/row)\n\n// #exo-include transform-texture\n\nout vec2 v_texcoord;\nout vec4 v_color;\n\nvoid main(void) {\n // gl_VertexID 0..3 -> corner: 0=TL, 1=TR, 2=BL, 3=BR (TRIANGLE_STRIP order)\n int vid = gl_VertexID;\n int cornerX = vid & 1;\n int cornerY = (vid >> 1) & 1;\n\n float localX = (cornerX == 0) ? a_quadBounds.x : a_quadBounds.z;\n float localY = (cornerY == 0) ? a_quadBounds.y : a_quadBounds.w;\n\n int row = int(a_tileWord & {{tileRowMask}}u);\n bool diagonal = (a_tileWord & {{tileDiagonalBit}}u) != 0u;\n\n vec4 m0 = texelFetch(u_transforms, exoTransformTexel(row, 0), 0); // a, b, c, d\n vec4 m1 = texelFetch(u_transforms, exoTransformTexel(row, 1), 0); // tx, ty, snapMode, 0\n\n float worldX = (m0.x * localX) + (m0.y * localY) + m1.x;\n float worldY = (m0.z * localX) + (m0.w * localY) + m1.y;\n\n vec2 clip = (u_projection * u_group * vec3(worldX, worldY, 1.0)).xy;\n\n // Render-only pixel snapping (m1.z: 0 = none, 1 = position, 2 = geometry —\n // both non-zero modes snap the origin). Snap the chunk ORIGIN's device-pixel\n // position and rigid-shift the whole tile quad by the same delta. floor(x+0.5)\n // matches the CPU Math.round policy; GLSL round() is undefined at .5. Grid\n // alignment is independent of the y-axis convention because the staged\n // viewport rect is whole device pixels.\n if (m1.z != 0.0) {\n vec2 originClip = (u_projection * u_group * vec3(m1.x, m1.y, 1.0)).xy;\n vec2 originDevice = u_viewport.xy + (originClip * 0.5 + 0.5) * u_viewport.zw;\n clip += (floor(originDevice + 0.5) - originDevice) * 2.0 / max(u_viewport.zw, vec2(1.0));\n }\n\n gl_Position = vec4(clip, 0.0, 1.0);\n\n // Tile orientation: the diagonal flip transposes the corner-coordinate axes\n // before the UV corner is selected; flipX/flipY are already baked into the\n // (uMin,uMax)/(vMin,vMax) ordering by the CPU writer.\n int su = cornerX;\n int sv = cornerY;\n if (diagonal) { int t = su; su = sv; sv = t; }\n\n float u = (su == 0) ? a_uvBounds.x : a_uvBounds.z;\n float v = (sv == 0) ? a_uvBounds.y : a_uvBounds.w;\n v_texcoord = vec2(u, v);\n\n v_color = vec4(a_color.rgb * a_color.a, a_color.a);\n}\n";
2
+ var tile_chunk_default = "#version 300 es\nprecision highp float;\nprecision highp int;\nlayout(location = 0) in vec4 a_quadBounds;\nlayout(location = 1) in vec4 a_uvBounds;\nlayout(location = 2) in vec4 a_color;\nlayout(location = 3) in uint a_tileWord;\nuniform mat3 u_projection;\nuniform mat3 u_group;\nuniform vec4 u_viewport;\nuniform sampler2D u_transforms;\n// #exo-include transform-texture\nout vec2 v_texcoord;\nout vec4 v_color;\nvoid main(void) {\nint vid = gl_VertexID;\nint cornerX = vid & 1;\nint cornerY = (vid >> 1) & 1;\nfloat localX = (cornerX == 0) ? a_quadBounds.x : a_quadBounds.z;\nfloat localY = (cornerY == 0) ? a_quadBounds.y : a_quadBounds.w;\nint row = int(a_tileWord & {{tileRowMask}}u);\nbool diagonal = (a_tileWord & {{tileDiagonalBit}}u) != 0u;\nvec4 m0 = texelFetch(u_transforms, exoTransformTexel(row, 0), 0);\nvec4 m1 = texelFetch(u_transforms, exoTransformTexel(row, 1), 0);\nfloat worldX = (m0.x * localX) + (m0.y * localY) + m1.x;\nfloat worldY = (m0.z * localX) + (m0.w * localY) + m1.y;\nvec2 clip = (u_projection * u_group * vec3(worldX, worldY, 1.0)).xy;\nif (m1.z != 0.0) {\nvec2 originClip = (u_projection * u_group * vec3(m1.x, m1.y, 1.0)).xy;\nvec2 originDevice = u_viewport.xy + (originClip * 0.5 + 0.5) * u_viewport.zw;\nclip += (floor(originDevice + 0.5) - originDevice) * 2.0 / max(u_viewport.zw, vec2(1.0));\n}\ngl_Position = vec4(clip, 0.0, 1.0);\nint su = cornerX;\nint sv = cornerY;\nif (diagonal) { int t = su; su = sv; sv = t; }\nfloat u = (su == 0) ? a_uvBounds.x : a_uvBounds.z;\nfloat v = (sv == 0) ? a_uvBounds.y : a_uvBounds.w;\nv_texcoord = vec2(u, v);\nhighp vec3 linearTint = srgbToLinear(a_color.rgb);\nv_color = vec4(linearTint * a_color.a, a_color.a);\n}";
3
3
 
4
4
  //#endregion
5
5
  export { tile_chunk_default as default };
@@ -1 +1 @@
1
- {"version":3,"file":"tile-chunk.vert.js","names":[],"sources":["../../../../src/webgl2/shaders/tile-chunk.vert"],"sourcesContent":["export default \"#version 300 es\\nprecision highp float;\\nprecision highp int;\\n\\n// Per-instance attributes (divisor = 1). One entry per tile quad.\\n// gl_VertexID 0..3 selects which corner of the quad this invocation computes.\\nlayout(location = 0) in vec4 a_quadBounds; // x0, y0, x1, y1 (chunk-local)\\nlayout(location = 1) in vec4 a_uvBounds; // uMin, vMin, uMax, vMax (flipX/Y + texture flipY baked)\\nlayout(location = 2) in vec4 a_color; // RGBA tint (layer opacity in alpha)\\nlayout(location = 3) in uint a_tileWord; // transform row (bits 0..28) | diagonal (bit 29)\\n\\nuniform mat3 u_projection;\\nuniform mat3 u_group;\\nuniform vec4 u_viewport; // device-pixel viewport rect (x, y, width, height)\\nuniform sampler2D u_transforms; // shared per-frame transform buffer (2 texels/row)\\n\\n// #exo-include transform-texture\\n\\nout vec2 v_texcoord;\\nout vec4 v_color;\\n\\nvoid main(void) {\\n // gl_VertexID 0..3 -> corner: 0=TL, 1=TR, 2=BL, 3=BR (TRIANGLE_STRIP order)\\n int vid = gl_VertexID;\\n int cornerX = vid & 1;\\n int cornerY = (vid >> 1) & 1;\\n\\n float localX = (cornerX == 0) ? a_quadBounds.x : a_quadBounds.z;\\n float localY = (cornerY == 0) ? a_quadBounds.y : a_quadBounds.w;\\n\\n int row = int(a_tileWord & {{tileRowMask}}u);\\n bool diagonal = (a_tileWord & {{tileDiagonalBit}}u) != 0u;\\n\\n vec4 m0 = texelFetch(u_transforms, exoTransformTexel(row, 0), 0); // a, b, c, d\\n vec4 m1 = texelFetch(u_transforms, exoTransformTexel(row, 1), 0); // tx, ty, snapMode, 0\\n\\n float worldX = (m0.x * localX) + (m0.y * localY) + m1.x;\\n float worldY = (m0.z * localX) + (m0.w * localY) + m1.y;\\n\\n vec2 clip = (u_projection * u_group * vec3(worldX, worldY, 1.0)).xy;\\n\\n // Render-only pixel snapping (m1.z: 0 = none, 1 = position, 2 = geometry —\\n // both non-zero modes snap the origin). Snap the chunk ORIGIN's device-pixel\\n // position and rigid-shift the whole tile quad by the same delta. floor(x+0.5)\\n // matches the CPU Math.round policy; GLSL round() is undefined at .5. Grid\\n // alignment is independent of the y-axis convention because the staged\\n // viewport rect is whole device pixels.\\n if (m1.z != 0.0) {\\n vec2 originClip = (u_projection * u_group * vec3(m1.x, m1.y, 1.0)).xy;\\n vec2 originDevice = u_viewport.xy + (originClip * 0.5 + 0.5) * u_viewport.zw;\\n clip += (floor(originDevice + 0.5) - originDevice) * 2.0 / max(u_viewport.zw, vec2(1.0));\\n }\\n\\n gl_Position = vec4(clip, 0.0, 1.0);\\n\\n // Tile orientation: the diagonal flip transposes the corner-coordinate axes\\n // before the UV corner is selected; flipX/flipY are already baked into the\\n // (uMin,uMax)/(vMin,vMax) ordering by the CPU writer.\\n int su = cornerX;\\n int sv = cornerY;\\n if (diagonal) { int t = su; su = sv; sv = t; }\\n\\n float u = (su == 0) ? a_uvBounds.x : a_uvBounds.z;\\n float v = (sv == 0) ? a_uvBounds.y : a_uvBounds.w;\\n v_texcoord = vec2(u, v);\\n\\n v_color = vec4(a_color.rgb * a_color.a, a_color.a);\\n}\\n\";"],"mappings":";AAAA,yBAAe"}
1
+ {"version":3,"file":"tile-chunk.vert.js","names":[],"sources":["../../../../src/webgl2/shaders/tile-chunk.vert"],"sourcesContent":["export default \"#version 300 es\\nprecision highp float;\\nprecision highp int;\\nlayout(location = 0) in vec4 a_quadBounds;\\nlayout(location = 1) in vec4 a_uvBounds;\\nlayout(location = 2) in vec4 a_color;\\nlayout(location = 3) in uint a_tileWord;\\nuniform mat3 u_projection;\\nuniform mat3 u_group;\\nuniform vec4 u_viewport;\\nuniform sampler2D u_transforms;\\n// #exo-include transform-texture\\nout vec2 v_texcoord;\\nout vec4 v_color;\\nvoid main(void) {\\nint vid = gl_VertexID;\\nint cornerX = vid & 1;\\nint cornerY = (vid >> 1) & 1;\\nfloat localX = (cornerX == 0) ? a_quadBounds.x : a_quadBounds.z;\\nfloat localY = (cornerY == 0) ? a_quadBounds.y : a_quadBounds.w;\\nint row = int(a_tileWord & {{tileRowMask}}u);\\nbool diagonal = (a_tileWord & {{tileDiagonalBit}}u) != 0u;\\nvec4 m0 = texelFetch(u_transforms, exoTransformTexel(row, 0), 0);\\nvec4 m1 = texelFetch(u_transforms, exoTransformTexel(row, 1), 0);\\nfloat worldX = (m0.x * localX) + (m0.y * localY) + m1.x;\\nfloat worldY = (m0.z * localX) + (m0.w * localY) + m1.y;\\nvec2 clip = (u_projection * u_group * vec3(worldX, worldY, 1.0)).xy;\\nif (m1.z != 0.0) {\\nvec2 originClip = (u_projection * u_group * vec3(m1.x, m1.y, 1.0)).xy;\\nvec2 originDevice = u_viewport.xy + (originClip * 0.5 + 0.5) * u_viewport.zw;\\nclip += (floor(originDevice + 0.5) - originDevice) * 2.0 / max(u_viewport.zw, vec2(1.0));\\n}\\ngl_Position = vec4(clip, 0.0, 1.0);\\nint su = cornerX;\\nint sv = cornerY;\\nif (diagonal) { int t = su; su = sv; sv = t; }\\nfloat u = (su == 0) ? a_uvBounds.x : a_uvBounds.z;\\nfloat v = (sv == 0) ? a_uvBounds.y : a_uvBounds.w;\\nv_texcoord = vec2(u, v);\\nhighp vec3 linearTint = srgbToLinear(a_color.rgb);\\nv_color = vec4(linearTint * a_color.a, a_color.a);\\n}\";"],"mappings":";AAAA,yBAAe"}
@@ -1,6 +1,6 @@
1
1
  import { TILE_DIAGONAL_BIT, TILE_ROW_MASK } from "../tileWord.js";
2
2
  import tile_chunk_default from "./shaders/tile-chunk.wgsl.js";
3
- import { AbstractWebGpuRenderer, DataTexture, Texture, fillShaderSource, getWebGpuBlendState, isSampleableTexture, packAffineMat4, packSnapViewport, packedGroupChanged, retainedGroupUniformBytes, stencilContentDepthStencilState } from "@codexo/exojs/renderer-sdk";
3
+ import { AbstractWebGpuRenderer, DataTexture, Texture, colorShaderSourcesWgsl, fillShaderSource, getWebGpuBlendState, isSampleableTexture, packAffineMat4, packSnapViewport, packedGroupChanged, retainedGroupUniformBytes, stencilContentDepthStencilState } from "@codexo/exojs/renderer-sdk";
4
4
  import { Matrix } from "@codexo/exojs";
5
5
 
6
6
  //#region src/webgpu/WebGpuTileChunkRenderer.ts
@@ -17,10 +17,10 @@ const quadIndices = new Uint16Array([
17
17
  2,
18
18
  3
19
19
  ]);
20
- const tileShaderSource = fillShaderSource(tile_chunk_default, {
20
+ const tileShaderSource = `${colorShaderSourcesWgsl}${fillShaderSource(tile_chunk_default, {
21
21
  tileRowMask: TILE_ROW_MASK,
22
22
  tileDiagonalBit: TILE_DIAGONAL_BIT
23
- });
23
+ })}`;
24
24
  /**
25
25
  * Instanced WebGPU renderer for {@link TileChunkNode}, the parity counterpart of
26
26
  * the WebGL2 renderer. Same instance layout and orientation handling; per-chunk
@@ -37,7 +37,7 @@ var WebGpuTileChunkRenderer = class extends AbstractWebGpuRenderer {
37
37
  * in {@link render}); tile chunks have no custom-material path to exclude.
38
38
  * @internal
39
39
  */
40
- _supportsRetainedBatches = true;
40
+ supportsRetainedBatches = true;
41
41
  _projectionData = new Float32Array(projectionByteLength / Float32Array.BYTES_PER_ELEMENT);
42
42
  _writtenView = null;
43
43
  _writtenViewUpdateId = -1;
@@ -49,6 +49,7 @@ var WebGpuTileChunkRenderer = class extends AbstractWebGpuRenderer {
49
49
  _textureBindGroupLayout = null;
50
50
  _pipelineLayout = null;
51
51
  _uniformBuffer = null;
52
+ _sampleAlphaBuffers = [];
52
53
  _transformBindGroup = null;
53
54
  _transformStorageBuffer = null;
54
55
  _indexBuffer = null;
@@ -83,20 +84,38 @@ var WebGpuTileChunkRenderer = class extends AbstractWebGpuRenderer {
83
84
  visibility: GPUShaderStage.VERTEX,
84
85
  buffer: { type: "read-only-storage" }
85
86
  }] });
86
- this._textureBindGroupLayout = this._device.createBindGroupLayout({ entries: [{
87
- binding: 0,
88
- visibility: GPUShaderStage.FRAGMENT,
89
- texture: { sampleType: "float" }
90
- }, {
91
- binding: 1,
92
- visibility: GPUShaderStage.FRAGMENT,
93
- sampler: { type: "filtering" }
94
- }] });
87
+ this._textureBindGroupLayout = this._device.createBindGroupLayout({ entries: [
88
+ {
89
+ binding: 0,
90
+ visibility: GPUShaderStage.FRAGMENT,
91
+ texture: { sampleType: "float" }
92
+ },
93
+ {
94
+ binding: 1,
95
+ visibility: GPUShaderStage.FRAGMENT,
96
+ sampler: { type: "filtering" }
97
+ },
98
+ {
99
+ binding: 2,
100
+ visibility: GPUShaderStage.FRAGMENT,
101
+ buffer: { type: "uniform" }
102
+ }
103
+ ] });
95
104
  this._pipelineLayout = this._device.createPipelineLayout({ bindGroupLayouts: [this._uniformBindGroupLayout, this._textureBindGroupLayout] });
96
105
  this._uniformBuffer = this._device.createBuffer({
97
106
  size: projectionByteLength,
98
107
  usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
99
108
  });
109
+ for (const premultiply of [0, 1]) {
110
+ const buffer = this._device.createBuffer({
111
+ size: 16,
112
+ usage: GPUBufferUsage.UNIFORM,
113
+ mappedAtCreation: true
114
+ });
115
+ new Float32Array(buffer.getMappedRange())[0] = premultiply;
116
+ buffer.unmap();
117
+ this._sampleAlphaBuffers.push(buffer);
118
+ }
100
119
  this._indexBuffer = this._device.createBuffer({
101
120
  size: quadIndices.byteLength,
102
121
  usage: GPUBufferUsage.INDEX | GPUBufferUsage.COPY_DST
@@ -104,11 +123,13 @@ var WebGpuTileChunkRenderer = class extends AbstractWebGpuRenderer {
104
123
  this._device.queue.writeBuffer(this._indexBuffer, 0, quadIndices.buffer, quadIndices.byteOffset, quadIndices.byteLength);
105
124
  }
106
125
  onDisconnect() {
107
- const coordinator = this._backend?._passCoordinator ?? null;
126
+ const coordinator = this._backend?.passCoordinator ?? null;
108
127
  if (coordinator !== null && this._passDraws !== null && this._passDraws === coordinator.activePass) coordinator.endPass();
109
128
  this._instanceBuffer?.destroy();
110
129
  this._indexBuffer?.destroy();
111
130
  this._uniformBuffer?.destroy();
131
+ for (const buffer of this._sampleAlphaBuffers) buffer.destroy();
132
+ this._sampleAlphaBuffers.length = 0;
112
133
  this._pipelines.clear();
113
134
  this._instanceBuffer = null;
114
135
  this._indexBuffer = null;
@@ -212,7 +233,7 @@ var WebGpuTileChunkRenderer = class extends AbstractWebGpuRenderer {
212
233
  const projectionChanged = !this._hasWrittenProjection || this._writtenView !== view || this._writtenViewUpdateId !== view.updateId || viewportChanged || this._groupContentChanged(backend);
213
234
  const scissor = backend.getScissorRect();
214
235
  const maskClipsAll = scissor !== null && (scissor.width <= 0 || scissor.height <= 0);
215
- const coordinator = backend._passCoordinator;
236
+ const coordinator = backend.passCoordinator;
216
237
  const texture = this._currentTexture;
217
238
  const blendMode = this._currentBlendMode;
218
239
  const indexBuffer = this._indexBuffer;
@@ -304,22 +325,31 @@ var WebGpuTileChunkRenderer = class extends AbstractWebGpuRenderer {
304
325
  */
305
326
  _getOrCreateTextureBindGroup(device, backend, texture) {
306
327
  const { view, sampler } = backend.getTextureBinding(texture);
328
+ const premultiply = backend.shouldPremultiplyTextureSample(texture);
307
329
  const cached = this._textureBindGroups.get(texture);
308
- if (cached?.view === view && cached.sampler === sampler) return cached.group;
330
+ if (cached?.view === view && cached.sampler === sampler && cached.premultiply === premultiply) return cached.group;
309
331
  const group = device.createBindGroup({
310
332
  layout: this._textureBindGroupLayout,
311
- entries: [{
312
- binding: 0,
313
- resource: view
314
- }, {
315
- binding: 1,
316
- resource: sampler
317
- }]
333
+ entries: [
334
+ {
335
+ binding: 0,
336
+ resource: view
337
+ },
338
+ {
339
+ binding: 1,
340
+ resource: sampler
341
+ },
342
+ {
343
+ binding: 2,
344
+ resource: { buffer: this._sampleAlphaBuffers[premultiply ? 1 : 0] }
345
+ }
346
+ ]
318
347
  });
319
348
  this._textureBindGroups.set(texture, {
320
349
  group,
321
350
  view,
322
- sampler
351
+ sampler,
352
+ premultiply
323
353
  });
324
354
  return group;
325
355
  }
@@ -362,7 +392,7 @@ var WebGpuTileChunkRenderer = class extends AbstractWebGpuRenderer {
362
392
  this.flush();
363
393
  const scissor = backend.getScissorRect();
364
394
  if (scissor !== null && (scissor.width <= 0 || scissor.height <= 0)) return;
365
- const coordinator = backend._passCoordinator;
395
+ const coordinator = backend.passCoordinator;
366
396
  if (coordinator.passHasDraws) {
367
397
  for (const texture of payload.textures) if (backend.textureUploadWouldMutate(texture)) {
368
398
  coordinator.endPass();
@@ -393,12 +423,18 @@ var WebGpuTileChunkRenderer = class extends AbstractWebGpuRenderer {
393
423
  }
394
424
  const active = coordinator.acquirePass();
395
425
  const pass = active.pass;
396
- pass.setPipeline(this._getPipeline(payload.blendMode, backend.renderTargetFormat, coordinator.stencilActive));
397
- pass.setBindGroup(0, bundle.getBindGroup(device, this._uniformBindGroupLayout, false));
398
- pass.setBindGroup(1, textureBindGroup);
399
- pass.setVertexBuffer(0, bundle.instanceBuffer, payload.byteOffset);
400
- pass.setIndexBuffer(this._indexBuffer, "uint16");
401
- pass.drawIndexed(indicesPerInstance, payload.instanceCount, 0, 0, 0);
426
+ const nativePipeline = this._getPipeline(payload.blendMode, backend.renderTargetFormat, coordinator.stencilActive);
427
+ const nativeFrameBindGroup = bundle.getBindGroup(device, this._uniformBindGroupLayout, false);
428
+ const nativeCompatible = backend.colorAttachmentCount === 1;
429
+ if (!nativeCompatible) bundle.nativeReplay.skipPass();
430
+ if (!nativeCompatible || !bundle.nativeReplay.draw(device, active, payload, backend.renderTargetFormat, nativePipeline, nativeFrameBindGroup, textureBindGroup, this._indexBuffer, "uint16", indicesPerInstance, payload.instanceCount)) {
431
+ pass.setPipeline(nativePipeline);
432
+ pass.setBindGroup(0, nativeFrameBindGroup);
433
+ pass.setBindGroup(1, textureBindGroup);
434
+ pass.setVertexBuffer(0, bundle.instanceBuffer, payload.byteOffset);
435
+ pass.setIndexBuffer(this._indexBuffer, "uint16");
436
+ pass.drawIndexed(indicesPerInstance, payload.instanceCount, 0, 0, 0);
437
+ }
402
438
  bundle.drawsInPass = active;
403
439
  coordinator.markPassDraws();
404
440
  backend.stats.batches++;