@codexo/exojs-tilemap 0.17.0 → 0.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +28 -75
- package/dist/esm/ImageLayerNode.d.ts +5 -1
- package/dist/esm/ImageLayerNode.d.ts.map +1 -1
- package/dist/esm/ImageLayerNode.js +7 -2
- package/dist/esm/ImageLayerNode.js.map +1 -1
- package/dist/esm/TileLayerNode.d.ts +6 -1
- package/dist/esm/TileLayerNode.d.ts.map +1 -1
- package/dist/esm/TileLayerNode.js +8 -3
- package/dist/esm/TileLayerNode.js.map +1 -1
- package/dist/esm/TileMapNode.d.ts +6 -1
- package/dist/esm/TileMapNode.d.ts.map +1 -1
- package/dist/esm/TileMapNode.js +8 -3
- package/dist/esm/TileMapNode.js.map +1 -1
- package/dist/esm/TileMapView.d.ts +6 -1
- package/dist/esm/TileMapView.d.ts.map +1 -1
- package/dist/esm/TileMapView.js +9 -4
- package/dist/esm/TileMapView.js.map +1 -1
- package/dist/esm/WorkerSampledChunkSource.d.ts +4 -7
- package/dist/esm/WorkerSampledChunkSource.d.ts.map +1 -1
- package/dist/esm/WorkerSampledChunkSource.js +12 -18
- package/dist/esm/WorkerSampledChunkSource.js.map +1 -1
- package/dist/esm/webgl2/WebGl2TileChunkRenderer.js +4 -4
- package/dist/esm/webgl2/WebGl2TileChunkRenderer.js.map +1 -1
- package/dist/esm/webgl2/shaders/tile-chunk.frag.js +1 -1
- package/dist/esm/webgl2/shaders/tile-chunk.frag.js.map +1 -1
- package/dist/esm/webgl2/shaders/tile-chunk.vert.js +1 -1
- package/dist/esm/webgl2/shaders/tile-chunk.vert.js.map +1 -1
- package/dist/esm/webgpu/WebGpuTileChunkRenderer.js +4 -4
- package/dist/esm/webgpu/WebGpuTileChunkRenderer.js.map +1 -1
- package/dist/esm/webgpu/shaders/tile-chunk.wgsl.js +1 -1
- package/dist/esm/webgpu/shaders/tile-chunk.wgsl.js.map +1 -1
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"TileMapView.js","names":[],"sources":["../../src/TileMapView.ts"],"sourcesContent":["import { PixelSnapMode } from '@codexo/exojs/renderer-sdk';\n\nimport { ImageLayer } from './ImageLayer';\nimport { ImageLayerNode } from './ImageLayerNode';\nimport { assertPixelSnapMode } from './pixelSnap';\nimport type { TileLayer } from './TileLayer';\nimport { TileLayerNode } from './TileLayerNode';\nimport type { TileMap } from './TileMap';\nimport { TileMapBand } from './TileMapBand';\n\n/**\n * A layer selector inside a {@link TileMapBandDefinition}: either a stable\n * layer **id** (`number`) or a **unique** layer **name** (`string`). Selectors\n * resolve across the map's tile **and** image layers. Names that are shared by\n * more than one layer (of either kind) are rejected as ambiguous - reference\n * such layers by id. An id shared by a tile layer and an image layer (possible\n * only in fallback-ordered maps, which never validated cross-kind uniqueness)\n * is equally ambiguous - reference such layers by a unique name.\n * @advanced\n */\nexport type TileLayerSelector = number | string;\n\n/**\n * The layers composing one band, by id or unique name, in any order. Tile and\n * image layers may be freely mixed. Rendering order always follows the map's\n * combined document order ({@link import('./TileMap').TileMap.renderableLayers})\n * regardless of the order listed here - a definition *selects* layers, it never\n * reorders them. The band's name is the key it is registered under in\n * {@link TileMapViewOptions.bands}.\n * @advanced\n */\nexport type TileMapBandDefinition = readonly TileLayerSelector[];\n\n/**\n * Options for a {@link TileMapView}.\n * @advanced\n */\nexport interface TileMapViewOptions {\n /**\n * Named bands, keyed by band name (keys are unique, so duplicate band names\n * cannot occur). Each value lists the layers that compose the band - tile\n * and image layers alike. Layers not listed in any band remain reachable\n * through {@link TileMapView.getLayerNodeById} and friends and are owned\n * directly by the view (no implicit fallback band). The definition is copied\n * and frozen; mutating the caller's object afterwards does not change band\n * assignments.\n *\n * @throws (at construction) on an unknown layer id, an unknown or ambiguous\n * layer name, a cross-kind ambiguous layer id, a layer listed twice within\n * one band, or a layer assigned to more than one band.\n */\n readonly bands?: Readonly<Record<string, TileMapBandDefinition>>;\n /**\n * Whether the generated {@link TileLayerNode}s' chunks participate in\n * per-chunk view culling. Forwarded to every layer node. Default `true`.\n */\n readonly cullable?: boolean;\n}\n\ninterface ResolvedBandDef {\n readonly name: string;\n readonly selectors: TileMapBandDefinition;\n}\n\n/**\n * Groups a {@link TileMap}'s layers into independently placeable scene nodes so\n * application actors can be interleaved **between** tile layers.\n *\n * A view produces exactly one canonical {@link TileLayerNode} per map layer\n * (stable identity, map document order) and, optionally, named {@link TileMapBand}s\n * grouping subsets of those nodes. The application parents the bands / layer\n * nodes wherever it wants - typically as siblings of its own actor containers:\n *\n * ```ts\n * const view = map.createView({ bands: { ground: ['background', 'ground'], roof: ['roofs'] } });\n * worldRoot.addChild(view.band('ground'), actors, view.band('roof'));\n * // or without bands:\n * worldRoot.addChild(view.getLayerNodeById(groundId)!, actors, view.getLayerNodeById(roofId)!);\n * ```\n *\n * **Actors are application-owned siblings.** A `TileMapView` never adopts or\n * destroys actors. The view is a helper, not a scene node - it does not own the\n * world container, the {@link TileMap}, the {@link TileLayer}s, or tileset\n * textures.\n *\n * **Ownership:** the view owns its generated layer nodes and bands. A layer\n * assigned to a band is owned by that band; an unbanded layer is owned by the\n * view directly. {@link TileMapView.destroy} destroys every band and layer node\n * (detaching them from their application parents) but leaves actors, the map,\n * its layers, and Loader-owned textures untouched. There is no map-replacement\n * mutation API: to swap maps, destroy the old view, construct a new one, and\n * re-parent its bands - the actor tree is never involved.\n *\n * **Image layers.** A view also produces exactly one canonical\n * {@link ImageLayerNode} per {@link TileMap.imageLayers} entry (stable identity,\n * map document order), reachable through {@link imageLayerNodes},\n * {@link getImageLayerNodeById}, and {@link getImageLayerNodeByName}. Image\n * layers are selectable in {@link TileMapViewOptions.bands} exactly like tile\n * layers: a band member list may mix both kinds, and the band stacks its\n * members by the map's combined document order\n * ({@link import('./TileMap').TileMap.renderableLayers}). A banded image node\n * is owned by its band; an unbanded one is owned by the view directly, and the\n * application parents it wherever the image belongs in draw order - the same\n * way actors are interleaved.\n *\n * @advanced\n */\nexport class TileMapView {\n private readonly _map: TileMap;\n private readonly _cullable: boolean;\n\n /** All canonical tile-layer nodes, in map document order. */\n private readonly _layerNodes: TileLayerNode[] = [];\n /** Tile layer id → its canonical layer node. */\n private readonly _layerNodeById = new Map<number, TileLayerNode>();\n\n /** Bands in definition (insertion) order. */\n private readonly _bands: TileMapBand[] = [];\n /** Band name → band. */\n private readonly _bandByName = new Map<string, TileMapBand>();\n /** Original band definitions (frozen) for re-resolution on refresh. */\n private readonly _bandDefs: ResolvedBandDef[] = [];\n /** Layer node → its owning band (absent = view-owned / unbanded). */\n private readonly _nodeBand = new Map<TileLayerNode | ImageLayerNode, TileMapBand>();\n /** Unbanded tile-layer nodes owned directly by the view, in map document order. */\n private readonly _directLayerNodes: TileLayerNode[] = [];\n\n /** All canonical image layer nodes, in map document order. */\n private readonly _imageLayerNodes: ImageLayerNode[] = [];\n /** Image layer id → its canonical image layer node. */\n private readonly _imageLayerNodeById = new Map<number, ImageLayerNode>();\n\n private _destroyed = false;\n private _pixelSnapMode: PixelSnapMode = PixelSnapMode.None;\n\n /**\n * @param map The runtime map to compose. Referenced, never owned.\n * @param options Band definitions and culling.\n * @throws When a band definition references an unknown/ambiguous layer or\n * assigns a layer twice / to multiple bands.\n */\n public constructor(map: TileMap, options?: TileMapViewOptions) {\n this._map = map;\n this._cullable = options?.cullable ?? true;\n\n for (const layer of map.layers) {\n const node = new TileLayerNode(layer, { cullable: this._cullable });\n\n this._layerNodes.push(node);\n this._layerNodeById.set(layer.id, node);\n }\n\n for (const imageLayer of map.imageLayers) {\n const imageNode = new ImageLayerNode(imageLayer);\n\n this._imageLayerNodes.push(imageNode);\n this._imageLayerNodeById.set(imageLayer.id, imageNode);\n }\n\n if (options?.bands) {\n for (const [name, selectors] of Object.entries(options.bands)) {\n this._defineBand(name, selectors);\n }\n }\n\n for (const node of this._layerNodes) {\n if (!this._nodeBand.has(node)) {\n this._directLayerNodes.push(node);\n }\n }\n }\n\n /** The runtime map this view composes. Referenced, never owned. */\n public get map(): TileMap {\n return this._map;\n }\n\n /** All canonical tile-layer nodes, one per map tile layer, in map document order. */\n public get layers(): readonly TileLayerNode[] {\n return this._layerNodes;\n }\n\n /** The bands, in definition (insertion) order. */\n public get bands(): readonly TileMapBand[] {\n return this._bands;\n }\n\n /** Whether this view has been destroyed. */\n public get destroyed(): boolean {\n return this._destroyed;\n }\n\n /**\n * Render-only pixel-snap mode applied to every layer node this view owns (and\n * forwarded to every chunk drawable, current and rebuilt by\n * {@link refreshLayers}). Snaps tile chunk origins to the active render\n * target's device-pixel grid for crisp tiles; with integer tile pitch the grid\n * stays exact and adjacent chunks cannot drift apart. Purely visual - tile\n * data, layer offsets, chunk revisions, and culling are unchanged. Setting the\n * current value is a no-op; an invalid value throws and leaves the prior mode\n * unchanged.\n *\n * @default PixelSnapMode.None\n * @stable\n */\n public get pixelSnapMode(): PixelSnapMode {\n return this._pixelSnapMode;\n }\n\n public set pixelSnapMode(mode: PixelSnapMode) {\n if (mode === this._pixelSnapMode) {\n return;\n }\n\n assertPixelSnapMode(mode);\n this._pixelSnapMode = mode;\n\n for (const node of this._layerNodes) {\n node.pixelSnapMode = mode;\n }\n\n for (const node of this._imageLayerNodes) {\n node.pixelSnapMode = mode;\n }\n }\n\n /**\n * The canonical layer node for the **tile** layer with the given **id**, or\n * `undefined`. Tile ids are authoritative and unique - this is the\n * unambiguous lookup. The returned node may be reparented into the caller's\n * own containers; the view still tracks it for refresh and destruction.\n */\n public getLayerNodeById(id: number): TileLayerNode | undefined {\n return this._layerNodeById.get(id);\n }\n\n /**\n * Every canonical tile-layer node whose layer has the given **name**, in map\n * document order. Layer names are not guaranteed unique, so this returns an\n * array (empty when no layer matches). Prefer {@link getLayerNodeById} when\n * you have the id.\n */\n public getLayerNodesByName(name: string): readonly TileLayerNode[] {\n return this._layerNodes.filter(node => node.layer.name === name);\n }\n\n /** All canonical image layer nodes, one per map image layer, in map document order. */\n public get imageLayerNodes(): readonly ImageLayerNode[] {\n return this._imageLayerNodes;\n }\n\n /**\n * The canonical image layer node for the image layer with the given **id**,\n * or `undefined`. Ids are authoritative and unique - this is the unambiguous\n * lookup. The returned node may be reparented into the caller's own\n * containers; the view still tracks it for refresh and destruction.\n */\n public getImageLayerNodeById(id: number): ImageLayerNode | undefined {\n return this._imageLayerNodeById.get(id);\n }\n\n /**\n * The canonical image layer node for the image layer with the given\n * **name**, or `undefined` if no image layer has that name. Prefer\n * {@link getImageLayerNodeById} when you have the id.\n * @throws If more than one image layer shares that name (reference such\n * layers by id instead).\n */\n public getImageLayerNodeByName(name: string): ImageLayerNode | undefined {\n const matches = this._map.imageLayers.filter(layer => layer.name === name);\n\n if (matches.length === 0) {\n return undefined;\n }\n\n if (matches.length > 1) {\n throw new Error(`TileMapView image layer name \"${name}\" is ambiguous ` + `(${matches.length} image layers share it); reference it by id instead.`);\n }\n\n return this._imageLayerNodeById.get(matches[0]!.id);\n }\n\n /**\n * The band registered under `name`.\n * @throws If no band with that name was defined.\n */\n public band(name: string): TileMapBand {\n const band = this._bandByName.get(name);\n\n if (!band) {\n throw new Error(\n `TileMapView has no band named \"${name}\". Defined bands: ${this._bands.length > 0 ? this._bands.map(b => `\"${b.name}\"`).join(', ') : '(none)'}.`,\n );\n }\n\n return band;\n }\n\n /** Whether a band with the given name was defined. */\n public hasBand(name: string): boolean {\n return this._bandByName.has(name);\n }\n\n /**\n * Rebuild the view after **structural** map changes (tile or image layers\n * added to or removed from the map). Ordinary tile edits and chunk\n * creation/removal do NOT need this - those are handled by chunk revisions\n * and {@link TileLayerNode.refresh} respectively.\n *\n * - Removed layers (tile or image): their generated node is detached and\n * destroyed.\n * - Unchanged layers: keep their existing node (stable identity).\n * - Added layers (tile or image): a new node is created and assigned to the\n * first band whose definition selects it (by a currently-unambiguous id or\n * name), otherwise owned directly by the view.\n * - Every band's children are re-ordered to the map's combined document\n * order ({@link import('./TileMap').TileMap.renderableLayers}).\n *\n * Application actors are never touched, and bands keep their placement in the\n * application scene graph.\n *\n * @throws If the view has been destroyed.\n */\n public refreshLayers(): this {\n if (this._destroyed) {\n throw new Error('Cannot refresh a destroyed TileMapView.');\n }\n\n const currentLayers = this._map.layers;\n const currentIds = new Set<number>();\n\n for (const layer of currentLayers) {\n currentIds.add(layer.id);\n }\n\n // 1. Remove nodes whose layer no longer exists.\n for (const node of [...this._layerNodes]) {\n if (!currentIds.has(node.layer.id)) {\n this._removeTileNode(node);\n }\n }\n\n const currentImageLayers = new Set(this._map.imageLayers);\n\n for (const node of [...this._imageLayerNodes]) {\n if (!currentImageLayers.has(node.layer)) {\n this._removeImageNode(node);\n }\n }\n\n // 2. Re-derive the doc-ordered node lists, creating + assigning new nodes.\n const newOrder: TileLayerNode[] = [];\n\n for (const layer of currentLayers) {\n let node = this._layerNodeById.get(layer.id);\n\n if (!node) {\n node = new TileLayerNode(layer, { cullable: this._cullable });\n\n if (this._pixelSnapMode !== PixelSnapMode.None) {\n node.pixelSnapMode = this._pixelSnapMode;\n }\n\n this._layerNodeById.set(layer.id, node);\n this._assignNewNode(node, layer);\n }\n\n newOrder.push(node);\n }\n\n this._layerNodes.length = 0;\n this._layerNodes.push(...newOrder);\n\n const newImageOrder: ImageLayerNode[] = [];\n\n for (const imageLayer of this._map.imageLayers) {\n let node = this._imageLayerNodes.find(candidate => candidate.layer === imageLayer);\n\n if (!node) {\n node = new ImageLayerNode(imageLayer);\n\n if (this._pixelSnapMode !== PixelSnapMode.None) {\n node.pixelSnapMode = this._pixelSnapMode;\n }\n\n this._imageLayerNodeById.set(imageLayer.id, node);\n this._assignNewNode(node, imageLayer);\n }\n\n newImageOrder.push(node);\n }\n\n this._imageLayerNodes.length = 0;\n this._imageLayerNodes.push(...newImageOrder);\n\n // 3. Re-order each band's children to the combined document order. Keyed\n // by layer instance: fallback-ordered maps may share an id across kinds.\n const documentIndex = new Map<TileLayer | ImageLayer, number>();\n\n for (const [index, layer] of this._map.renderableLayers.entries()) {\n documentIndex.set(layer, index);\n }\n\n for (const band of this._bands) {\n band._reorder(documentIndex);\n }\n\n // 4. Rebuild the unbanded set in doc order.\n this._directLayerNodes.length = 0;\n\n for (const node of newOrder) {\n if (!this._nodeBand.has(node)) {\n this._directLayerNodes.push(node);\n }\n }\n\n return this;\n }\n\n /**\n * Destroy the view: every band, generated tile-layer node, and generated\n * {@link ImageLayerNode} is destroyed (and detached from its application\n * parent), freeing cached chunk geometry. Banded nodes are destroyed by\n * their band; unbanded ones by the view directly. Idempotent. Application\n * actors, sibling content, the {@link TileMap}, its {@link TileLayer}s and\n * image layers, and Loader-owned textures all survive.\n */\n public destroy(): void {\n if (this._destroyed) {\n return;\n }\n\n this._destroyed = true;\n\n for (const band of this._bands) {\n band.destroy();\n }\n\n for (const node of this._directLayerNodes) {\n node.parent?.removeChild(node);\n node.destroy();\n }\n\n for (const node of this._imageLayerNodes) {\n if (this._nodeBand.has(node)) {\n continue; // Owned and already destroyed by its band.\n }\n\n node.parent?.removeChild(node);\n node.destroy();\n }\n\n this._bands.length = 0;\n this._bandByName.clear();\n this._bandDefs.length = 0;\n this._directLayerNodes.length = 0;\n this._layerNodes.length = 0;\n this._layerNodeById.clear();\n this._nodeBand.clear();\n this._imageLayerNodes.length = 0;\n this._imageLayerNodeById.clear();\n }\n\n // ── Internals ──────────────────────────────────────────────────────────\n\n /** Resolve one band definition into a {@link TileMapBand} and record it. */\n private _defineBand(name: string, selectors: TileMapBandDefinition): void {\n const members = new Set<TileLayer | ImageLayer>();\n\n for (const selector of selectors) {\n const layer = this._resolveSelector(name, selector);\n\n if (members.has(layer)) {\n throw new Error(`TileMapView band \"${name}\" lists layer ${layer.id} more than once.`);\n }\n\n const existing = this._nodeFor(layer);\n\n if (existing && this._nodeBand.has(existing)) {\n throw new Error(`TileMapView layer ${layer.id} is assigned to multiple bands ` + `(\"${this._nodeBand.get(existing)!.name}\" and \"${name}\").`);\n }\n\n members.add(layer);\n }\n\n // Order members by combined document order (membership selects; doc order\n // renders - tile and image members interleave).\n const orderedNodes: Array<TileLayerNode | ImageLayerNode> = [];\n\n for (const layer of this._map.renderableLayers) {\n if (members.has(layer)) {\n orderedNodes.push(this._nodeFor(layer)!);\n }\n }\n\n const band = new TileMapBand(name, orderedNodes);\n\n for (const node of orderedNodes) {\n this._nodeBand.set(node, band);\n }\n\n this._bands.push(band);\n this._bandByName.set(name, band);\n this._bandDefs.push({ name, selectors: Object.freeze([...selectors]) });\n }\n\n /**\n * Resolve a single selector to a tile or image layer instance, throwing on\n * unknown/ambiguous. Instances (not ids) disambiguate fallback-ordered maps\n * in which a tile layer and an image layer share an id.\n */\n private _resolveSelector(bandName: string, selector: TileLayerSelector): TileLayer | ImageLayer {\n if (typeof selector === 'number') {\n const tileLayer = this._map.getTileLayerById(selector);\n const imageLayer = this._map.imageLayers.find(layer => layer.id === selector);\n\n if (tileLayer && imageLayer) {\n throw new Error(\n `TileMapView band \"${bandName}\": layer id ${selector} is ambiguous ` +\n `(a tile layer and an image layer share it); reference it by a unique name instead.`,\n );\n }\n\n const layer = tileLayer ?? imageLayer;\n\n if (!layer) {\n throw new Error(`TileMapView band \"${bandName}\": no layer with id ${selector} in map \"${this._map.name}\".`);\n }\n\n return layer;\n }\n\n const matches: Array<TileLayer | ImageLayer> = [\n ...this._map.layers.filter(layer => layer.name === selector),\n ...this._map.imageLayers.filter(layer => layer.name === selector),\n ];\n\n if (matches.length === 0) {\n throw new Error(`TileMapView band \"${bandName}\": no layer named \"${selector}\" in map \"${this._map.name}\".`);\n }\n\n if (matches.length > 1) {\n throw new Error(\n `TileMapView band \"${bandName}\": layer name \"${selector}\" is ambiguous ` + `(${matches.length} layers share it); reference it by id instead.`,\n );\n }\n\n return matches[0]!;\n }\n\n /** The canonical node for a tile or image layer instance, if one exists. */\n private _nodeFor(layer: TileLayer | ImageLayer): TileLayerNode | ImageLayerNode | undefined {\n if (layer instanceof ImageLayer) {\n // Instance scan rather than the id map: image ids are not validated\n // unique, and fallback maps may collide with tile ids anyway.\n return this._imageLayerNodes.find(node => node.layer === layer);\n }\n\n return this._layerNodeById.get(layer.id);\n }\n\n /** Assign a freshly created node to the first band that selects its layer. */\n private _assignNewNode(node: TileLayerNode | ImageLayerNode, layer: TileLayer | ImageLayer): void {\n for (const def of this._bandDefs) {\n if (this._definitionSelects(def, layer)) {\n const band = this._bandByName.get(def.name)!;\n\n band._adopt(node);\n this._nodeBand.set(node, band);\n\n return;\n }\n }\n }\n\n /**\n * Whether a band definition selects the given layer - only by a selector\n * that is currently unambiguous (a unique name, or an id not shared across\n * kinds), mirroring {@link _resolveSelector}'s construction-time rules.\n */\n private _definitionSelects(def: ResolvedBandDef, layer: TileLayer | ImageLayer): boolean {\n for (const selector of def.selectors) {\n if (typeof selector === 'number') {\n if (selector === layer.id && !this._isCrossKindId(selector)) {\n return true;\n }\n } else if (selector === layer.name) {\n const sameName =\n this._map.layers.filter(other => other.name === selector).length + this._map.imageLayers.filter(other => other.name === selector).length;\n\n if (sameName === 1) {\n return true;\n }\n }\n }\n\n return false;\n }\n\n /** Whether an id currently belongs to both a tile layer and an image layer. */\n private _isCrossKindId(id: number): boolean {\n return this._map.getTileLayerById(id) !== undefined && this._map.imageLayers.some(layer => layer.id === id);\n }\n\n /** Detach + destroy a tile node, dropping it from bands and registries. */\n private _removeTileNode(node: TileLayerNode): void {\n this._releaseFromOwner(node);\n\n node.parent?.removeChild(node);\n this._layerNodeById.delete(node.layer.id);\n\n const orderIndex = this._layerNodes.indexOf(node);\n\n if (orderIndex !== -1) {\n this._layerNodes.splice(orderIndex, 1);\n }\n\n node.destroy();\n }\n\n /** Detach + destroy an image node, dropping it from bands and registries. */\n private _removeImageNode(node: ImageLayerNode): void {\n this._releaseFromOwner(node);\n\n node.parent?.removeChild(node);\n\n if (this._imageLayerNodeById.get(node.layer.id) === node) {\n this._imageLayerNodeById.delete(node.layer.id);\n }\n\n const orderIndex = this._imageLayerNodes.indexOf(node);\n\n if (orderIndex !== -1) {\n this._imageLayerNodes.splice(orderIndex, 1);\n }\n\n node.destroy();\n }\n\n /** Release a node from its band, or from the view's direct-ownership list. */\n private _releaseFromOwner(node: TileLayerNode | ImageLayerNode): void {\n const band = this._nodeBand.get(node);\n\n if (band) {\n band._release(node);\n this._nodeBand.delete(node);\n } else if (node instanceof TileLayerNode) {\n const directIndex = this._directLayerNodes.indexOf(node);\n\n if (directIndex !== -1) {\n this._directLayerNodes.splice(directIndex, 1);\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2GA,IAAa,cAAb,MAAyB;CACvB,AAAiB;CACjB,AAAiB;;CAGjB,AAAiB,cAA+B,CAAC;;CAEjD,AAAiB,iCAAiB,IAAI,IAA2B;;CAGjE,AAAiB,SAAwB,CAAC;;CAE1C,AAAiB,8BAAc,IAAI,IAAyB;;CAE5D,AAAiB,YAA+B,CAAC;;CAEjD,AAAiB,4BAAY,IAAI,IAAiD;;CAElF,AAAiB,oBAAqC,CAAC;;CAGvD,AAAiB,mBAAqC,CAAC;;CAEvD,AAAiB,sCAAsB,IAAI,IAA4B;CAEvE,AAAQ,aAAa;CACrB,AAAQ,iBAAgC,cAAc;;;;;;;CAQtD,AAAO,YAAY,KAAc,SAA8B;EAC7D,KAAK,OAAO;EACZ,KAAK,YAAY,SAAS,YAAY;EAEtC,KAAK,MAAM,SAAS,IAAI,QAAQ;GAC9B,MAAM,OAAO,IAAI,cAAc,OAAO,EAAE,UAAU,KAAK,UAAU,CAAC;GAElE,KAAK,YAAY,KAAK,IAAI;GAC1B,KAAK,eAAe,IAAI,MAAM,IAAI,IAAI;EACxC;EAEA,KAAK,MAAM,cAAc,IAAI,aAAa;GACxC,MAAM,YAAY,IAAI,eAAe,UAAU;GAE/C,KAAK,iBAAiB,KAAK,SAAS;GACpC,KAAK,oBAAoB,IAAI,WAAW,IAAI,SAAS;EACvD;EAEA,IAAI,SAAS,OACX,KAAK,MAAM,CAAC,MAAM,cAAc,OAAO,QAAQ,QAAQ,KAAK,GAC1D,KAAK,YA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} from './ImageLayer';\nimport { ImageLayerNode } from './ImageLayerNode';\nimport { assertPixelSnapMode } from './pixelSnap';\nimport type { TileLayer } from './TileLayer';\nimport { TileLayerNode } from './TileLayerNode';\nimport type { TileMap } from './TileMap';\nimport { TileMapBand } from './TileMapBand';\n\n/**\n * A layer selector inside a {@link TileMapBandDefinition}: either a stable\n * layer **id** (`number`) or a **unique** layer **name** (`string`). Selectors\n * resolve across the map's tile **and** image layers. Names that are shared by\n * more than one layer (of either kind) are rejected as ambiguous - reference\n * such layers by id. An id shared by a tile layer and an image layer (possible\n * only in fallback-ordered maps, which never validated cross-kind uniqueness)\n * is equally ambiguous - reference such layers by a unique name.\n * @advanced\n */\nexport type TileLayerSelector = number | string;\n\n/**\n * The layers composing one band, by id or unique name, in any order. Tile and\n * image layers may be freely mixed. Rendering order always follows the map's\n * combined document order ({@link import('./TileMap').TileMap.renderableLayers})\n * regardless of the order listed here - a definition *selects* layers, it never\n * reorders them. The band's name is the key it is registered under in\n * {@link TileMapViewOptions.bands}.\n * @advanced\n */\nexport type TileMapBandDefinition = readonly TileLayerSelector[];\n\n/**\n * Options for a {@link TileMapView}.\n * @advanced\n */\nexport interface TileMapViewOptions {\n /**\n * Named bands, keyed by band name (keys are unique, so duplicate band names\n * cannot occur). Each value lists the layers that compose the band - tile\n * and image layers alike. Layers not listed in any band remain reachable\n * through {@link TileMapView.getLayerNodeById} and friends and are owned\n * directly by the view (no implicit fallback band). The definition is copied\n * and frozen; mutating the caller's object afterwards does not change band\n * assignments.\n *\n * @throws (at construction) on an unknown layer id, an unknown or ambiguous\n * layer name, a cross-kind ambiguous layer id, a layer listed twice within\n * one band, or a layer assigned to more than one band.\n */\n readonly bands?: Readonly<Record<string, TileMapBandDefinition>>;\n /**\n * Whether the generated {@link TileLayerNode}s' chunks participate in\n * per-chunk view culling. Forwarded to every layer node. Default `true`.\n */\n readonly cullable?: boolean;\n}\n\ninterface ResolvedBandDef {\n readonly name: string;\n readonly selectors: TileMapBandDefinition;\n}\n\n/**\n * Groups a {@link TileMap}'s layers into independently placeable scene nodes so\n * application actors can be interleaved **between** tile layers.\n *\n * A view produces exactly one canonical {@link TileLayerNode} per map layer\n * (stable identity, map document order) and, optionally, named {@link TileMapBand}s\n * grouping subsets of those nodes. The application parents the bands / layer\n * nodes wherever it wants - typically as siblings of its own actor containers:\n *\n * ```ts\n * const view = map.createView({ bands: { ground: ['background', 'ground'], roof: ['roofs'] } });\n * worldRoot.addChild(view.band('ground'), actors, view.band('roof'));\n * // or without bands:\n * worldRoot.addChild(view.getLayerNodeById(groundId)!, actors, view.getLayerNodeById(roofId)!);\n * ```\n *\n * **Actors are application-owned siblings.** A `TileMapView` never adopts or\n * destroys actors. The view is a helper, not a scene node - it does not own the\n * world container, the {@link TileMap}, the {@link TileLayer}s, or tileset\n * textures.\n *\n * **Ownership:** the view owns its generated layer nodes and bands. A layer\n * assigned to a band is owned by that band; an unbanded layer is owned by the\n * view directly. {@link TileMapView.destroy} destroys every band and layer node\n * (detaching them from their application parents) but leaves actors, the map,\n * its layers, and Loader-owned textures untouched. There is no map-replacement\n * mutation API: to swap maps, destroy the old view, construct a new one, and\n * re-parent its bands - the actor tree is never involved.\n *\n * **Image layers.** A view also produces exactly one canonical\n * {@link ImageLayerNode} per {@link TileMap.imageLayers} entry (stable identity,\n * map document order), reachable through {@link imageLayerNodes},\n * {@link getImageLayerNodeById}, and {@link getImageLayerNodeByName}. Image\n * layers are selectable in {@link TileMapViewOptions.bands} exactly like tile\n * layers: a band member list may mix both kinds, and the band stacks its\n * members by the map's combined document order\n * ({@link import('./TileMap').TileMap.renderableLayers}). A banded image node\n * is owned by its band; an unbanded one is owned by the view directly, and the\n * application parents it wherever the image belongs in draw order - the same\n * way actors are interleaved.\n *\n * @advanced\n */\nexport class TileMapView {\n private readonly _map: TileMap;\n private readonly _cullable: boolean;\n\n /** All canonical tile-layer nodes, in map document order. */\n private readonly _layerNodes: TileLayerNode[] = [];\n /** Tile layer id → its canonical layer node. */\n private readonly _layerNodeById = new Map<number, TileLayerNode>();\n\n /** Bands in definition (insertion) order. */\n private readonly _bands: TileMapBand[] = [];\n /** Band name → band. */\n private readonly _bandByName = new Map<string, TileMapBand>();\n /** Original band definitions (frozen) for re-resolution on refresh. */\n private readonly _bandDefs: ResolvedBandDef[] = [];\n /** Layer node → its owning band (absent = view-owned / unbanded). */\n private readonly _nodeBand = new Map<TileLayerNode | ImageLayerNode, TileMapBand>();\n /** Unbanded tile-layer nodes owned directly by the view, in map document order. */\n private readonly _directLayerNodes: TileLayerNode[] = [];\n\n /** All canonical image layer nodes, in map document order. */\n private readonly _imageLayerNodes: ImageLayerNode[] = [];\n /** Image layer id → its canonical image layer node. */\n private readonly _imageLayerNodeById = new Map<number, ImageLayerNode>();\n\n private _destroyed = false;\n private _pixelSnapMode: PixelSnapMode = PixelSnapMode.Geometry;\n\n /**\n * @param map The runtime map to compose. Referenced, never owned.\n * @param options Band definitions and culling.\n * @throws When a band definition references an unknown/ambiguous layer or\n * assigns a layer twice / to multiple bands.\n */\n public constructor(map: TileMap, options?: TileMapViewOptions) {\n this._map = map;\n this._cullable = options?.cullable ?? true;\n\n for (const layer of map.layers) {\n const node = new TileLayerNode(layer, { cullable: this._cullable });\n\n this._layerNodes.push(node);\n this._layerNodeById.set(layer.id, node);\n }\n\n for (const imageLayer of map.imageLayers) {\n const imageNode = new ImageLayerNode(imageLayer);\n\n this._imageLayerNodes.push(imageNode);\n this._imageLayerNodeById.set(imageLayer.id, imageNode);\n }\n\n if (options?.bands) {\n for (const [name, selectors] of Object.entries(options.bands)) {\n this._defineBand(name, selectors);\n }\n }\n\n for (const node of this._layerNodes) {\n if (!this._nodeBand.has(node)) {\n this._directLayerNodes.push(node);\n }\n }\n }\n\n /** The runtime map this view composes. Referenced, never owned. */\n public get map(): TileMap {\n return this._map;\n }\n\n /** All canonical tile-layer nodes, one per map tile layer, in map document order. */\n public get layers(): readonly TileLayerNode[] {\n return this._layerNodes;\n }\n\n /** The bands, in definition (insertion) order. */\n public get bands(): readonly TileMapBand[] {\n return this._bands;\n }\n\n /** Whether this view has been destroyed. */\n public get destroyed(): boolean {\n return this._destroyed;\n }\n\n /**\n * Render-only pixel-snap mode applied to every layer node this view owns (and\n * forwarded to every chunk drawable, current and rebuilt by\n * {@link refreshLayers}). Snaps tile chunk origins to the active render\n * target's device-pixel grid for crisp tiles; with integer tile pitch the grid\n * stays exact and adjacent chunks cannot drift apart. Purely visual - tile\n * data, layer offsets, chunk revisions, and culling are unchanged. Setting the\n * current value is a no-op; an invalid value throws and leaves the prior mode\n * unchanged.\n *\n * Defaults to `Geometry` because a tile grid is made of quads that share\n * their edges: left unsnapped, a boundary landing between two device pixels\n * is sampled across both, so the seams blur and shimmer as the view moves.\n * Set `None` to opt out.\n *\n * @default PixelSnapMode.Geometry\n * @stable\n */\n public get pixelSnapMode(): PixelSnapMode {\n return this._pixelSnapMode;\n }\n\n public set pixelSnapMode(mode: PixelSnapMode) {\n if (mode === this._pixelSnapMode) {\n return;\n }\n\n assertPixelSnapMode(mode);\n this._pixelSnapMode = mode;\n\n for (const node of this._layerNodes) {\n node.pixelSnapMode = mode;\n }\n\n for (const node of this._imageLayerNodes) {\n node.pixelSnapMode = mode;\n }\n }\n\n /**\n * The canonical layer node for the **tile** layer with the given **id**, or\n * `undefined`. Tile ids are authoritative and unique - this is the\n * unambiguous lookup. The returned node may be reparented into the caller's\n * own containers; the view still tracks it for refresh and destruction.\n */\n public getLayerNodeById(id: number): TileLayerNode | undefined {\n return this._layerNodeById.get(id);\n }\n\n /**\n * Every canonical tile-layer node whose layer has the given **name**, in map\n * document order. Layer names are not guaranteed unique, so this returns an\n * array (empty when no layer matches). Prefer {@link getLayerNodeById} when\n * you have the id.\n */\n public getLayerNodesByName(name: string): readonly TileLayerNode[] {\n return this._layerNodes.filter(node => node.layer.name === name);\n }\n\n /** All canonical image layer nodes, one per map image layer, in map document order. */\n public get imageLayerNodes(): readonly ImageLayerNode[] {\n return this._imageLayerNodes;\n }\n\n /**\n * The canonical image layer node for the image layer with the given **id**,\n * or `undefined`. Ids are authoritative and unique - this is the unambiguous\n * lookup. The returned node may be reparented into the caller's own\n * containers; the view still tracks it for refresh and destruction.\n */\n public getImageLayerNodeById(id: number): ImageLayerNode | undefined {\n return this._imageLayerNodeById.get(id);\n }\n\n /**\n * The canonical image layer node for the image layer with the given\n * **name**, or `undefined` if no image layer has that name. Prefer\n * {@link getImageLayerNodeById} when you have the id.\n * @throws If more than one image layer shares that name (reference such\n * layers by id instead).\n */\n public getImageLayerNodeByName(name: string): ImageLayerNode | undefined {\n const matches = this._map.imageLayers.filter(layer => layer.name === name);\n\n if (matches.length === 0) {\n return undefined;\n }\n\n if (matches.length > 1) {\n throw new Error(`TileMapView image layer name \"${name}\" is ambiguous ` + `(${matches.length} image layers share it); reference it by id instead.`);\n }\n\n return this._imageLayerNodeById.get(matches[0]!.id);\n }\n\n /**\n * The band registered under `name`.\n * @throws If no band with that name was defined.\n */\n public band(name: string): TileMapBand {\n const band = this._bandByName.get(name);\n\n if (!band) {\n throw new Error(\n `TileMapView has no band named \"${name}\". Defined bands: ${this._bands.length > 0 ? this._bands.map(b => `\"${b.name}\"`).join(', ') : '(none)'}.`,\n );\n }\n\n return band;\n }\n\n /** Whether a band with the given name was defined. */\n public hasBand(name: string): boolean {\n return this._bandByName.has(name);\n }\n\n /**\n * Rebuild the view after **structural** map changes (tile or image layers\n * added to or removed from the map). Ordinary tile edits and chunk\n * creation/removal do NOT need this - those are handled by chunk revisions\n * and {@link TileLayerNode.refresh} respectively.\n *\n * - Removed layers (tile or image): their generated node is detached and\n * destroyed.\n * - Unchanged layers: keep their existing node (stable identity).\n * - Added layers (tile or image): a new node is created and assigned to the\n * first band whose definition selects it (by a currently-unambiguous id or\n * name), otherwise owned directly by the view.\n * - Every band's children are re-ordered to the map's combined document\n * order ({@link import('./TileMap').TileMap.renderableLayers}).\n *\n * Application actors are never touched, and bands keep their placement in the\n * application scene graph.\n *\n * @throws If the view has been destroyed.\n */\n public refreshLayers(): this {\n if (this._destroyed) {\n throw new Error('Cannot refresh a destroyed TileMapView.');\n }\n\n const currentLayers = this._map.layers;\n const currentIds = new Set<number>();\n\n for (const layer of currentLayers) {\n currentIds.add(layer.id);\n }\n\n // 1. Remove nodes whose layer no longer exists.\n for (const node of [...this._layerNodes]) {\n if (!currentIds.has(node.layer.id)) {\n this._removeTileNode(node);\n }\n }\n\n const currentImageLayers = new Set(this._map.imageLayers);\n\n for (const node of [...this._imageLayerNodes]) {\n if (!currentImageLayers.has(node.layer)) {\n this._removeImageNode(node);\n }\n }\n\n // 2. Re-derive the doc-ordered node lists, creating + assigning new nodes.\n const newOrder: TileLayerNode[] = [];\n\n for (const layer of currentLayers) {\n let node = this._layerNodeById.get(layer.id);\n\n if (!node) {\n node = new TileLayerNode(layer, { cullable: this._cullable });\n // Unconditional: a node built after the view was set to `None` has to\n // inherit that too, not just a non-default mode.\n node.pixelSnapMode = this._pixelSnapMode;\n\n this._layerNodeById.set(layer.id, node);\n this._assignNewNode(node, layer);\n }\n\n newOrder.push(node);\n }\n\n this._layerNodes.length = 0;\n this._layerNodes.push(...newOrder);\n\n const newImageOrder: ImageLayerNode[] = [];\n\n for (const imageLayer of this._map.imageLayers) {\n let node = this._imageLayerNodes.find(candidate => candidate.layer === imageLayer);\n\n if (!node) {\n node = new ImageLayerNode(imageLayer);\n // Unconditional: a node built after the view was set to `None` has to\n // inherit that too, not just a non-default mode.\n node.pixelSnapMode = this._pixelSnapMode;\n\n this._imageLayerNodeById.set(imageLayer.id, node);\n this._assignNewNode(node, imageLayer);\n }\n\n newImageOrder.push(node);\n }\n\n this._imageLayerNodes.length = 0;\n this._imageLayerNodes.push(...newImageOrder);\n\n // 3. Re-order each band's children to the combined document order. Keyed\n // by layer instance: fallback-ordered maps may share an id across kinds.\n const documentIndex = new Map<TileLayer | ImageLayer, number>();\n\n for (const [index, layer] of this._map.renderableLayers.entries()) {\n documentIndex.set(layer, index);\n }\n\n for (const band of this._bands) {\n band._reorder(documentIndex);\n }\n\n // 4. Rebuild the unbanded set in doc order.\n this._directLayerNodes.length = 0;\n\n for (const node of newOrder) {\n if (!this._nodeBand.has(node)) {\n this._directLayerNodes.push(node);\n }\n }\n\n return this;\n }\n\n /**\n * Destroy the view: every band, generated tile-layer node, and generated\n * {@link ImageLayerNode} is destroyed (and detached from its application\n * parent), freeing cached chunk geometry. Banded nodes are destroyed by\n * their band; unbanded ones by the view directly. Idempotent. Application\n * actors, sibling content, the {@link TileMap}, its {@link TileLayer}s and\n * image layers, and Loader-owned textures all survive.\n */\n public destroy(): void {\n if (this._destroyed) {\n return;\n }\n\n this._destroyed = true;\n\n for (const band of this._bands) {\n band.destroy();\n }\n\n for (const node of this._directLayerNodes) {\n node.parent?.removeChild(node);\n node.destroy();\n }\n\n for (const node of this._imageLayerNodes) {\n if (this._nodeBand.has(node)) {\n continue; // Owned and already destroyed by its band.\n }\n\n node.parent?.removeChild(node);\n node.destroy();\n }\n\n this._bands.length = 0;\n this._bandByName.clear();\n this._bandDefs.length = 0;\n this._directLayerNodes.length = 0;\n this._layerNodes.length = 0;\n this._layerNodeById.clear();\n this._nodeBand.clear();\n this._imageLayerNodes.length = 0;\n this._imageLayerNodeById.clear();\n }\n\n // ── Internals ──────────────────────────────────────────────────────────\n\n /** Resolve one band definition into a {@link TileMapBand} and record it. */\n private _defineBand(name: string, selectors: TileMapBandDefinition): void {\n const members = new Set<TileLayer | ImageLayer>();\n\n for (const selector of selectors) {\n const layer = this._resolveSelector(name, selector);\n\n if (members.has(layer)) {\n throw new Error(`TileMapView band \"${name}\" lists layer ${layer.id} more than once.`);\n }\n\n const existing = this._nodeFor(layer);\n\n if (existing && this._nodeBand.has(existing)) {\n throw new Error(`TileMapView layer ${layer.id} is assigned to multiple bands ` + `(\"${this._nodeBand.get(existing)!.name}\" and \"${name}\").`);\n }\n\n members.add(layer);\n }\n\n // Order members by combined document order (membership selects; doc order\n // renders - tile and image members interleave).\n const orderedNodes: Array<TileLayerNode | ImageLayerNode> = [];\n\n for (const layer of this._map.renderableLayers) {\n if (members.has(layer)) {\n orderedNodes.push(this._nodeFor(layer)!);\n }\n }\n\n const band = new TileMapBand(name, orderedNodes);\n\n for (const node of orderedNodes) {\n this._nodeBand.set(node, band);\n }\n\n this._bands.push(band);\n this._bandByName.set(name, band);\n this._bandDefs.push({ name, selectors: Object.freeze([...selectors]) });\n }\n\n /**\n * Resolve a single selector to a tile or image layer instance, throwing on\n * unknown/ambiguous. Instances (not ids) disambiguate fallback-ordered maps\n * in which a tile layer and an image layer share an id.\n */\n private _resolveSelector(bandName: string, selector: TileLayerSelector): TileLayer | ImageLayer {\n if (typeof selector === 'number') {\n const tileLayer = this._map.getTileLayerById(selector);\n const imageLayer = this._map.imageLayers.find(layer => layer.id === selector);\n\n if (tileLayer && imageLayer) {\n throw new Error(\n `TileMapView band \"${bandName}\": layer id ${selector} is ambiguous ` +\n `(a tile layer and an image layer share it); reference it by a unique name instead.`,\n );\n }\n\n const layer = tileLayer ?? imageLayer;\n\n if (!layer) {\n throw new Error(`TileMapView band \"${bandName}\": no layer with id ${selector} in map \"${this._map.name}\".`);\n }\n\n return layer;\n }\n\n const matches: Array<TileLayer | ImageLayer> = [\n ...this._map.layers.filter(layer => layer.name === selector),\n ...this._map.imageLayers.filter(layer => layer.name === selector),\n ];\n\n if (matches.length === 0) {\n throw new Error(`TileMapView band \"${bandName}\": no layer named \"${selector}\" in map \"${this._map.name}\".`);\n }\n\n if (matches.length > 1) {\n throw new Error(\n `TileMapView band \"${bandName}\": layer name \"${selector}\" is ambiguous ` + `(${matches.length} layers share it); reference it by id instead.`,\n );\n }\n\n return matches[0]!;\n }\n\n /** The canonical node for a tile or image layer instance, if one exists. */\n private _nodeFor(layer: TileLayer | ImageLayer): TileLayerNode | ImageLayerNode | undefined {\n if (layer instanceof ImageLayer) {\n // Instance scan rather than the id map: image ids are not validated\n // unique, and fallback maps may collide with tile ids anyway.\n return this._imageLayerNodes.find(node => node.layer === layer);\n }\n\n return this._layerNodeById.get(layer.id);\n }\n\n /** Assign a freshly created node to the first band that selects its layer. */\n private _assignNewNode(node: TileLayerNode | ImageLayerNode, layer: TileLayer | ImageLayer): void {\n for (const def of this._bandDefs) {\n if (this._definitionSelects(def, layer)) {\n const band = this._bandByName.get(def.name)!;\n\n band._adopt(node);\n this._nodeBand.set(node, band);\n\n return;\n }\n }\n }\n\n /**\n * Whether a band definition selects the given layer - only by a selector\n * that is currently unambiguous (a unique name, or an id not shared across\n * kinds), mirroring {@link _resolveSelector}'s construction-time rules.\n */\n private _definitionSelects(def: ResolvedBandDef, layer: TileLayer | ImageLayer): boolean {\n for (const selector of def.selectors) {\n if (typeof selector === 'number') {\n if (selector === layer.id && !this._isCrossKindId(selector)) {\n return true;\n }\n } else if (selector === layer.name) {\n const sameName =\n this._map.layers.filter(other => other.name === selector).length + this._map.imageLayers.filter(other => other.name === selector).length;\n\n if (sameName === 1) {\n return true;\n }\n }\n }\n\n return false;\n }\n\n /** Whether an id currently belongs to both a tile layer and an image layer. */\n private _isCrossKindId(id: number): boolean {\n return this._map.getTileLayerById(id) !== undefined && this._map.imageLayers.some(layer => layer.id === id);\n }\n\n /** Detach + destroy a tile node, dropping it from bands and registries. */\n private _removeTileNode(node: TileLayerNode): void {\n this._releaseFromOwner(node);\n\n node.parent?.removeChild(node);\n this._layerNodeById.delete(node.layer.id);\n\n const orderIndex = this._layerNodes.indexOf(node);\n\n if (orderIndex !== -1) {\n this._layerNodes.splice(orderIndex, 1);\n }\n\n node.destroy();\n }\n\n /** Detach + destroy an image node, dropping it from bands and registries. */\n private _removeImageNode(node: ImageLayerNode): void {\n this._releaseFromOwner(node);\n\n node.parent?.removeChild(node);\n\n if (this._imageLayerNodeById.get(node.layer.id) === node) {\n this._imageLayerNodeById.delete(node.layer.id);\n }\n\n const orderIndex = this._imageLayerNodes.indexOf(node);\n\n if (orderIndex !== -1) {\n this._imageLayerNodes.splice(orderIndex, 1);\n }\n\n node.destroy();\n }\n\n /** Release a node from its band, or from the view's direct-ownership list. */\n private _releaseFromOwner(node: TileLayerNode | ImageLayerNode): void {\n const band = this._nodeBand.get(node);\n\n if (band) {\n band._release(node);\n this._nodeBand.delete(node);\n } else if (node instanceof TileLayerNode) {\n const directIndex = this._directLayerNodes.indexOf(node);\n\n if (directIndex !== -1) {\n this._directLayerNodes.splice(directIndex, 1);\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2GA,IAAa,cAAb,MAAyB;CACvB,AAAiB;CACjB,AAAiB;;CAGjB,AAAiB,cAA+B,CAAC;;CAEjD,AAAiB,iCAAiB,IAAI,IAA2B;;CAGjE,AAAiB,SAAwB,CAAC;;CAE1C,AAAiB,8BAAc,IAAI,IAAyB;;CAE5D,AAAiB,YAA+B,CAAC;;CAEjD,AAAiB,4BAAY,IAAI,IAAiD;;CAElF,AAAiB,oBAAqC,CAAC;;CAGvD,AAAiB,mBAAqC,CAAC;;CAEvD,AAAiB,sCAAsB,IAAI,IAA4B;CAEvE,AAAQ,aAAa;CACrB,AAAQ,iBAAgC,cAAc;;;;;;;CAQtD,AAAO,YAAY,KAAc,SAA8B;EAC7D,KAAK,OAAO;EACZ,KAAK,YAAY,SAAS,YAAY;EAEtC,KAAK,MAAM,SAAS,IAAI,QAAQ;GAC9B,MAAM,OAAO,IAAI,cAAc,OAAO,EAAE,UAAU,KAAK,UAAU,CAAC;GAElE,KAAK,YAAY,KAAK,IAAI;GAC1B,KAAK,eAAe,IAAI,MAAM,IAAI,IAAI;EACxC;EAEA,KAAK,MAAM,cAAc,IAAI,aAAa;GACxC,MAAM,YAAY,IAAI,eAAe,UAAU;GAE/C,KAAK,iBAAiB,KAAK,SAAS;GACpC,KAAK,oBAAoB,IAAI,WAAW,IAAI,SAAS;EACvD;EAEA,IAAI,SAAS,OACX,KAAK,MAAM,CAAC,MAAM,cAAc,OAAO,QAAQ,QAAQ,KAAK,GAC1D,KAAK,YAAY,MAAM,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AO;EACT;EAIJ,OAAO;CACT;;CAGA,AAAQ,eAAe,IAAqB;EAC1C,OAAO,KAAK,KAAK,iBAAiB,EAAE,MAAM,UAAa,KAAK,KAAK,YAAY,MAAK,UAAS,MAAM,OAAO,EAAE;CAC5G;;CAGA,AAAQ,gBAAgB,MAA2B;EACjD,KAAK,kBAAkB,IAAI;EAE3B,KAAK,QAAQ,YAAY,IAAI;EAC7B,KAAK,eAAe,OAAO,KAAK,MAAM,EAAE;EAExC,MAAM,aAAa,KAAK,YAAY,QAAQ,IAAI;EAEhD,IAAI,eAAe,IACjB,KAAK,YAAY,OAAO,YAAY,CAAC;EAGvC,KAAK,QAAQ;CACf;;CAGA,AAAQ,iBAAiB,MAA4B;EACnD,KAAK,kBAAkB,IAAI;EAE3B,KAAK,QAAQ,YAAY,IAAI;EAE7B,IAAI,KAAK,oBAAoB,IAAI,KAAK,MAAM,EAAE,MAAM,MAClD,KAAK,oBAAoB,OAAO,KAAK,MAAM,EAAE;EAG/C,MAAM,aAAa,KAAK,iBAAiB,QAAQ,IAAI;EAErD,IAAI,eAAe,IACjB,KAAK,iBAAiB,OAAO,YAAY,CAAC;EAG5C,KAAK,QAAQ;CACf;;CAGA,AAAQ,kBAAkB,MAA4C;EACpE,MAAM,OAAO,KAAK,UAAU,IAAI,IAAI;EAEpC,IAAI,MAAM;GACR,KAAK,SAAS,IAAI;GAClB,KAAK,UAAU,OAAO,IAAI;EAC5B,OAAO,IAAI,gBAAgB,eAAe;GACxC,MAAM,cAAc,KAAK,kBAAkB,QAAQ,IAAI;GAEvD,IAAI,gBAAgB,IAClB,KAAK,kBAAkB,OAAO,aAAa,CAAC;EAEhD;CACF;AACF"}
|
|
@@ -82,13 +82,10 @@ export interface WorkerSampledChunkSourceOptions {
|
|
|
82
82
|
* lifecycle hook, so nothing ties the two together automatically. Call it
|
|
83
83
|
* yourself alongside your own `ChunkStreamer.destroy()` call.
|
|
84
84
|
*
|
|
85
|
-
*
|
|
86
|
-
*
|
|
87
|
-
*
|
|
88
|
-
*
|
|
89
|
-
* config needed in Vite/webpack/etc.) but requires a Content-Security-Policy
|
|
90
|
-
* that permits `blob:` in `worker-src` (or `script-src` as a fallback) if
|
|
91
|
-
* your deployment sets one.
|
|
85
|
+
* `workerSource` runs through {@link import('@codexo/exojs').InlineWorker},
|
|
86
|
+
* so it needs no bundler support of its own but does need a
|
|
87
|
+
* Content-Security-Policy that permits `blob:` in `worker-src` if your
|
|
88
|
+
* deployment sets one; the constructor names that cause when it is refused.
|
|
92
89
|
* @advanced
|
|
93
90
|
*/
|
|
94
91
|
export declare const createWorkerSampledChunkSource: (layer: TileLayer, options: WorkerSampledChunkSourceOptions) => ChunkSource & {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"WorkerSampledChunkSource.d.ts","sourceRoot":"","sources":["../../src/WorkerSampledChunkSource.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"WorkerSampledChunkSource.d.ts","sourceRoot":"","sources":["../../src/WorkerSampledChunkSource.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAgB,WAAW,EAAE,MAAM,eAAe,CAAC;AAC/D,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAC7C,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAG5C;;;GAGG;AACH,MAAM,WAAW,+BAA+B;IAC9C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA+BG;IACH,YAAY,EAAE,MAAM,CAAC;IACrB;;;;;;;;;;;;OAYG;IACH,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB;;;;;;;OAOG;IACH,cAAc,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,YAAY,GAAG,IAAI,CAAC;CAC5E;AAiCD;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,eAAO,MAAM,8BAA8B,GAAI,OAAO,SAAS,EAAE,SAAS,+BAA+B,KAAG,WAAW,GAAG;IAAE,OAAO,IAAI,IAAI,CAAA;CA0F1I,CAAC"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { packTile } from "./types.js";
|
|
2
|
+
import { InlineWorker } from "@codexo/exojs";
|
|
2
3
|
|
|
3
4
|
//#region src/WorkerSampledChunkSource.ts
|
|
4
5
|
const isWorkerErrorMessage = (message) => "error" in message;
|
|
@@ -21,25 +22,19 @@ const isWorkerErrorMessage = (message) => "error" in message;
|
|
|
21
22
|
* lifecycle hook, so nothing ties the two together automatically. Call it
|
|
22
23
|
* yourself alongside your own `ChunkStreamer.destroy()` call.
|
|
23
24
|
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
*
|
|
28
|
-
* config needed in Vite/webpack/etc.) but requires a Content-Security-Policy
|
|
29
|
-
* that permits `blob:` in `worker-src` (or `script-src` as a fallback) if
|
|
30
|
-
* your deployment sets one.
|
|
25
|
+
* `workerSource` runs through {@link import('@codexo/exojs').InlineWorker},
|
|
26
|
+
* so it needs no bundler support of its own but does need a
|
|
27
|
+
* Content-Security-Policy that permits `blob:` in `worker-src` if your
|
|
28
|
+
* deployment sets one; the constructor names that cause when it is refused.
|
|
31
29
|
* @advanced
|
|
32
30
|
*/
|
|
33
31
|
const createWorkerSampledChunkSource = (layer, options) => {
|
|
34
32
|
const mapValueToTile = options.mapValueToTile.bind(options);
|
|
35
|
-
const
|
|
36
|
-
const
|
|
37
|
-
|
|
38
|
-
URL.revokeObjectURL(url);
|
|
39
|
-
if (options.initMessage !== void 0) worker.postMessage(options.initMessage);
|
|
33
|
+
const inline = new InlineWorker(options.workerSource, { name: "exojs-tilemap-chunk-sampler" });
|
|
34
|
+
const worker = inline.worker;
|
|
35
|
+
if (options.initMessage !== void 0) inline.postMessage(options.initMessage);
|
|
40
36
|
let requestCounter = 0;
|
|
41
37
|
const pending = /* @__PURE__ */ new Map();
|
|
42
|
-
let destroyed = false;
|
|
43
38
|
const composePayload = (values, request) => {
|
|
44
39
|
const { cx, cy, chunkWidth, chunkHeight } = request;
|
|
45
40
|
const startTx = cx * chunkWidth;
|
|
@@ -80,7 +75,7 @@ const createWorkerSampledChunkSource = (layer, options) => {
|
|
|
80
75
|
};
|
|
81
76
|
return {
|
|
82
77
|
getChunk(cx, cy) {
|
|
83
|
-
if (destroyed) return Promise.reject(/* @__PURE__ */ new Error("WorkerSampledChunkSource: getChunk() called after destroy()."));
|
|
78
|
+
if (inline.destroyed) return Promise.reject(/* @__PURE__ */ new Error("WorkerSampledChunkSource: getChunk() called after destroy()."));
|
|
84
79
|
const chunkWidth = layer.chunkWidth;
|
|
85
80
|
const chunkHeight = layer.chunkHeight;
|
|
86
81
|
const requestId = ++requestCounter;
|
|
@@ -100,16 +95,15 @@ const createWorkerSampledChunkSource = (layer, options) => {
|
|
|
100
95
|
chunkWidth,
|
|
101
96
|
chunkHeight
|
|
102
97
|
};
|
|
103
|
-
|
|
98
|
+
inline.postMessage(request);
|
|
104
99
|
});
|
|
105
100
|
},
|
|
106
101
|
destroy() {
|
|
107
|
-
if (destroyed) return;
|
|
108
|
-
destroyed = true;
|
|
102
|
+
if (inline.destroyed) return;
|
|
109
103
|
const error = /* @__PURE__ */ new Error("WorkerSampledChunkSource destroyed.");
|
|
110
104
|
for (const entry of pending.values()) entry.reject(error);
|
|
111
105
|
pending.clear();
|
|
112
|
-
|
|
106
|
+
inline.destroy();
|
|
113
107
|
}
|
|
114
108
|
};
|
|
115
109
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"WorkerSampledChunkSource.js","names":[],"sources":["../../src/WorkerSampledChunkSource.ts"],"sourcesContent":["import type { ChunkPayload, ChunkSource } from './ChunkSource';\nimport type { TileLayer } from './TileLayer';\nimport type { ResolvedTile } from './types';\nimport { packTile } from './types';\n\n/**\n * Options for {@link createWorkerSampledChunkSource}.\n * @advanced\n */\nexport interface WorkerSampledChunkSourceOptions {\n /**\n * Complete worker script source as a single self-contained string, Blob-URL'd\n * into a real `Worker` at construction time - the same technique\n * {@link import('@codexo/exojs').WorkletEffect} uses for AudioWorklet\n * processors. No separate worker asset is fetched and no bundler-specific\n * worker-import syntax is involved.\n *\n * Producing that string by hand-writing JavaScript into a template literal\n * works but gives up type checking, linting and shared code. Prefer a build\n * step that bundles a real module into a string: this repository's own\n * examples are authored as `*.worker.ts` and imported through a `?worker`\n * query, which is why they can `import` the sampling functions the main\n * thread uses instead of restating them.\n *\n * Must implement this request/response protocol:\n * - Request (received via `self.onmessage`):\n * `{ requestId: number; cx: number; cy: number; chunkWidth: number; chunkHeight: number }`.\n * - Response, success (send via `self.postMessage`, transferring the\n * buffer for a zero-copy handoff - `postMessage(response, [response.values.buffer])`):\n * `{ requestId: number; values: Float64Array }`, `values.length ===\n * chunkWidth * chunkHeight`, row-major (`localTy * chunkWidth + localTx`),\n * one sampled value per tile in the requested chunk. Compute each tile's\n * absolute coordinate as `cx * chunkWidth + localTx` /\n * `cy * chunkHeight + localTy`.\n * - Response, error (one request failed without crashing the worker):\n * `{ requestId: number; error: string }`.\n *\n * Your worker must reply to every request with exactly one success or\n * error message bearing the same `requestId`. A request left unanswered\n * leaves that chunk permanently unfetched - there is no timeout - since\n * `ChunkStreamer` tracks it as still in flight and never retries it.\n */\n workerSource: string;\n /**\n * Posted to the worker once, before any chunk request, when present.\n *\n * The transport for whatever the sampler needs to know that is not per-chunk\n * - a seed, a feature size, a cost knob. Without it those values would have\n * to be interpolated into {@link WorkerSampledChunkSourceOptions.workerSource}\n * as literals, which turns every parameter change into a source rebuild and a\n * new `Worker`.\n *\n * `postMessage` delivery is ordered, so the worker is guaranteed to see this\n * before the first request. Distinguish it from a chunk request by its own\n * shape; requests carry a `requestId`.\n */\n initMessage?: unknown;\n /**\n * Convert a sampled value (and its absolute tile coordinate) into a\n * resolved tile, or `null` for an empty cell. Always runs on the main\n * thread - a `ResolvedTile` references a `TileSet`/`Texture`, neither of\n * which can cross a `postMessage` boundary. Must be pure and\n * deterministic, same requirement as\n * {@link import('./SampledChunkSource').SampledChunkSourceOptions.mapValueToTile}.\n */\n mapValueToTile(value: number, tx: number, ty: number): ResolvedTile | null;\n}\n\ninterface WorkerRequestMessage {\n readonly requestId: number;\n readonly cx: number;\n readonly cy: number;\n readonly chunkWidth: number;\n readonly chunkHeight: number;\n}\n\ninterface WorkerSuccessMessage {\n readonly requestId: number;\n readonly values: Float64Array;\n}\n\ninterface WorkerErrorMessage {\n readonly requestId: number;\n readonly error: string;\n}\n\ntype WorkerResponseMessage = WorkerSuccessMessage | WorkerErrorMessage;\n\nconst isWorkerErrorMessage = (message: WorkerResponseMessage): message is WorkerErrorMessage => 'error' in message;\n\ninterface PendingRequest {\n readonly resolve: (payload: ChunkPayload | null) => void;\n readonly reject: (error: Error) => void;\n readonly cx: number;\n readonly cy: number;\n readonly chunkWidth: number;\n readonly chunkHeight: number;\n}\n\n/**\n * Build a {@link import('./ChunkStreamer').ChunkStreamer}-ready\n * {@link ChunkSource} that samples off the main thread via a Web Worker -\n * the async counterpart to\n * {@link import('./SampledChunkSource').createSampledChunkSource}, for\n * sampling functions expensive enough to want off-thread execution.\n *\n * Unlike the synchronous provider, sampling logic cannot be passed as a\n * live function - functions cannot cross a `postMessage` boundary. Instead\n * {@link WorkerSampledChunkSourceOptions.workerSource} is a self-contained\n * worker script string; see its documentation for the protocol.\n *\n * The returned value's `destroy()` MUST be called when done with it - the\n * underlying `Worker` is a real resource that leaks otherwise.\n * {@link import('./ChunkStreamer').ChunkStreamer} does not own the source it\n * is given and never calls this for you: `ChunkSource` itself has no\n * lifecycle hook, so nothing ties the two together automatically. Call it\n * yourself alongside your own `ChunkStreamer.destroy()` call.\n *\n * Implementation note: `workerSource` is Blob-URL'd into a real `Worker`\n * (`new Blob([workerSource])` → `URL.createObjectURL` → `new Worker(url)`) -\n * the same technique {@link import('@codexo/exojs').WorkletEffect} already\n * uses for AudioWorklet processors. This is bundler-agnostic (no special\n * config needed in Vite/webpack/etc.) but requires a Content-Security-Policy\n * that permits `blob:` in `worker-src` (or `script-src` as a fallback) if\n * your deployment sets one.\n * @advanced\n */\nexport const createWorkerSampledChunkSource = (layer: TileLayer, options: WorkerSampledChunkSourceOptions): ChunkSource & { destroy(): void } => {\n const mapValueToTile = options.mapValueToTile.bind(options);\n\n const blob = new Blob([options.workerSource], { type: 'application/javascript' });\n const url = URL.createObjectURL(blob);\n const worker = new Worker(url);\n URL.revokeObjectURL(url);\n\n if (options.initMessage !== undefined) {\n worker.postMessage(options.initMessage);\n }\n\n let requestCounter = 0;\n const pending = new Map<number, PendingRequest>();\n let destroyed = false;\n\n const composePayload = (values: Float64Array, request: PendingRequest): ChunkPayload | null => {\n const { cx, cy, chunkWidth, chunkHeight } = request;\n const startTx = cx * chunkWidth;\n const startTy = cy * chunkHeight;\n\n let out: Uint32Array | null = null;\n for (let ty = startTy; ty < startTy + chunkHeight; ty++) {\n for (let tx = startTx; tx < startTx + chunkWidth; tx++) {\n // Bounded-layer edge chunks may be smaller than a full chunk - same\n // clamp createSampledChunkSource applies, computed here (not asked\n // of the worker) since only this side knows the layer's bounds.\n if (layer.width !== undefined && layer.height !== undefined && (tx >= layer.width || ty >= layer.height)) continue;\n\n const localIndex = (ty - startTy) * chunkWidth + (tx - startTx);\n const value = values[localIndex];\n if (value === undefined) continue; // defensive: malformed/short values array\n const resolved = mapValueToTile(value, tx, ty);\n if (!resolved) continue;\n\n out ??= new Uint32Array(chunkWidth * chunkHeight);\n const tilesetIndex = layer.tilesets.indexOf(resolved.tileset);\n out[localIndex] = packTile(tilesetIndex, resolved.localTileId, resolved.transform);\n }\n }\n\n return out === null ? null : { width: chunkWidth, height: chunkHeight, tiles: out };\n };\n\n worker.onmessage = (event: MessageEvent<WorkerResponseMessage>): void => {\n const message = event.data;\n const entry = pending.get(message.requestId);\n if (!entry) return; // stale/unknown requestId (e.g. arrived after destroy())\n pending.delete(message.requestId);\n\n if (isWorkerErrorMessage(message)) {\n entry.reject(new Error(message.error));\n return;\n }\n\n entry.resolve(composePayload(message.values, entry));\n };\n\n worker.onerror = (event: ErrorEvent): void => {\n const error = new Error(`WorkerSampledChunkSource worker error: ${event.message}`);\n for (const entry of pending.values()) {\n entry.reject(error);\n }\n pending.clear();\n };\n\n return {\n getChunk(cx: number, cy: number): Promise<ChunkPayload | null> {\n if (destroyed) {\n return Promise.reject(new Error('WorkerSampledChunkSource: getChunk() called after destroy().'));\n }\n\n const chunkWidth = layer.chunkWidth;\n const chunkHeight = layer.chunkHeight;\n const requestId = ++requestCounter;\n\n return new Promise<ChunkPayload | null>((resolve, reject) => {\n pending.set(requestId, { resolve, reject, cx, cy, chunkWidth, chunkHeight });\n const request: WorkerRequestMessage = { requestId, cx, cy, chunkWidth, chunkHeight };\n worker.postMessage(request);\n });\n },\n\n destroy(): void {\n if (destroyed) return;\n destroyed = true;\n const error = new Error('WorkerSampledChunkSource destroyed.');\n for (const entry of pending.values()) {\n entry.reject(error);\n }\n pending.clear();\n worker.terminate();\n },\n };\n};\n"],"mappings":";;;AAwFA,MAAM,wBAAwB,YAAkE,WAAW;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuC3G,MAAa,kCAAkC,OAAkB,YAAgF;CAC/I,MAAM,iBAAiB,QAAQ,eAAe,KAAK,OAAO;CAE1D,MAAM,OAAO,IAAI,KAAK,CAAC,QAAQ,YAAY,GAAG,EAAE,MAAM,yBAAyB,CAAC;CAChF,MAAM,MAAM,IAAI,gBAAgB,IAAI;CACpC,MAAM,SAAS,IAAI,OAAO,GAAG;CAC7B,IAAI,gBAAgB,GAAG;CAEvB,IAAI,QAAQ,gBAAgB,QAC1B,OAAO,YAAY,QAAQ,WAAW;CAGxC,IAAI,iBAAiB;CACrB,MAAM,0BAAU,IAAI,IAA4B;CAChD,IAAI,YAAY;CAEhB,MAAM,kBAAkB,QAAsB,YAAiD;EAC7F,MAAM,EAAE,IAAI,IAAI,YAAY,gBAAgB;EAC5C,MAAM,UAAU,KAAK;EACrB,MAAM,UAAU,KA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M,YAAY,EAAE;GAEpB,OAAO,IAAI,SAA8B,SAAS,WAAW;IAC3D,QAAQ,IAAI,WAAW;KAAE;KAAS;KAAQ;KAAI;KAAI;KAAY;IAAY,CAAC;IAC3E,MAAM,UAAgC;KAAE;KAAW;KAAI;KAAI;KAAY;IAAY;IACnF,OAAO,YAAY,OAAO;GAC5B,CAAC;EACH;EAEA,UAAgB;GACd,IAAI,WAAW;GACf,YAAY;GACZ,MAAM,wBAAQ,IAAI,MAAM,qCAAqC;GAC7D,KAAK,MAAM,SAAS,QAAQ,OAAO,GACjC,MAAM,OAAO,KAAK;GAEpB,QAAQ,MAAM;GACd,OAAO,UAAU;EACnB;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"WorkerSampledChunkSource.js","names":[],"sources":["../../src/WorkerSampledChunkSource.ts"],"sourcesContent":["import { InlineWorker } from '@codexo/exojs';\n\nimport type { ChunkPayload, ChunkSource } from './ChunkSource';\nimport type { TileLayer } from './TileLayer';\nimport type { ResolvedTile } from './types';\nimport { packTile } from './types';\n\n/**\n * Options for {@link createWorkerSampledChunkSource}.\n * @advanced\n */\nexport interface WorkerSampledChunkSourceOptions {\n /**\n * Complete worker script source as a single self-contained string, Blob-URL'd\n * into a real `Worker` at construction time - the same technique\n * {@link import('@codexo/exojs').WorkletEffect} uses for AudioWorklet\n * processors. No separate worker asset is fetched and no bundler-specific\n * worker-import syntax is involved.\n *\n * Producing that string by hand-writing JavaScript into a template literal\n * works but gives up type checking, linting and shared code. Prefer a build\n * step that bundles a real module into a string: this repository's own\n * examples are authored as `*.worker.ts` and imported through a `?worker`\n * query, which is why they can `import` the sampling functions the main\n * thread uses instead of restating them.\n *\n * Must implement this request/response protocol:\n * - Request (received via `self.onmessage`):\n * `{ requestId: number; cx: number; cy: number; chunkWidth: number; chunkHeight: number }`.\n * - Response, success (send via `self.postMessage`, transferring the\n * buffer for a zero-copy handoff - `postMessage(response, [response.values.buffer])`):\n * `{ requestId: number; values: Float64Array }`, `values.length ===\n * chunkWidth * chunkHeight`, row-major (`localTy * chunkWidth + localTx`),\n * one sampled value per tile in the requested chunk. Compute each tile's\n * absolute coordinate as `cx * chunkWidth + localTx` /\n * `cy * chunkHeight + localTy`.\n * - Response, error (one request failed without crashing the worker):\n * `{ requestId: number; error: string }`.\n *\n * Your worker must reply to every request with exactly one success or\n * error message bearing the same `requestId`. A request left unanswered\n * leaves that chunk permanently unfetched - there is no timeout - since\n * `ChunkStreamer` tracks it as still in flight and never retries it.\n */\n workerSource: string;\n /**\n * Posted to the worker once, before any chunk request, when present.\n *\n * The transport for whatever the sampler needs to know that is not per-chunk\n * - a seed, a feature size, a cost knob. Without it those values would have\n * to be interpolated into {@link WorkerSampledChunkSourceOptions.workerSource}\n * as literals, which turns every parameter change into a source rebuild and a\n * new `Worker`.\n *\n * `postMessage` delivery is ordered, so the worker is guaranteed to see this\n * before the first request. Distinguish it from a chunk request by its own\n * shape; requests carry a `requestId`.\n */\n initMessage?: unknown;\n /**\n * Convert a sampled value (and its absolute tile coordinate) into a\n * resolved tile, or `null` for an empty cell. Always runs on the main\n * thread - a `ResolvedTile` references a `TileSet`/`Texture`, neither of\n * which can cross a `postMessage` boundary. Must be pure and\n * deterministic, same requirement as\n * {@link import('./SampledChunkSource').SampledChunkSourceOptions.mapValueToTile}.\n */\n mapValueToTile(value: number, tx: number, ty: number): ResolvedTile | null;\n}\n\ninterface WorkerRequestMessage {\n readonly requestId: number;\n readonly cx: number;\n readonly cy: number;\n readonly chunkWidth: number;\n readonly chunkHeight: number;\n}\n\ninterface WorkerSuccessMessage {\n readonly requestId: number;\n readonly values: Float64Array;\n}\n\ninterface WorkerErrorMessage {\n readonly requestId: number;\n readonly error: string;\n}\n\ntype WorkerResponseMessage = WorkerSuccessMessage | WorkerErrorMessage;\n\nconst isWorkerErrorMessage = (message: WorkerResponseMessage): message is WorkerErrorMessage => 'error' in message;\n\ninterface PendingRequest {\n readonly resolve: (payload: ChunkPayload | null) => void;\n readonly reject: (error: Error) => void;\n readonly cx: number;\n readonly cy: number;\n readonly chunkWidth: number;\n readonly chunkHeight: number;\n}\n\n/**\n * Build a {@link import('./ChunkStreamer').ChunkStreamer}-ready\n * {@link ChunkSource} that samples off the main thread via a Web Worker -\n * the async counterpart to\n * {@link import('./SampledChunkSource').createSampledChunkSource}, for\n * sampling functions expensive enough to want off-thread execution.\n *\n * Unlike the synchronous provider, sampling logic cannot be passed as a\n * live function - functions cannot cross a `postMessage` boundary. Instead\n * {@link WorkerSampledChunkSourceOptions.workerSource} is a self-contained\n * worker script string; see its documentation for the protocol.\n *\n * The returned value's `destroy()` MUST be called when done with it - the\n * underlying `Worker` is a real resource that leaks otherwise.\n * {@link import('./ChunkStreamer').ChunkStreamer} does not own the source it\n * is given and never calls this for you: `ChunkSource` itself has no\n * lifecycle hook, so nothing ties the two together automatically. Call it\n * yourself alongside your own `ChunkStreamer.destroy()` call.\n *\n * `workerSource` runs through {@link import('@codexo/exojs').InlineWorker},\n * so it needs no bundler support of its own but does need a\n * Content-Security-Policy that permits `blob:` in `worker-src` if your\n * deployment sets one; the constructor names that cause when it is refused.\n * @advanced\n */\nexport const createWorkerSampledChunkSource = (layer: TileLayer, options: WorkerSampledChunkSourceOptions): ChunkSource & { destroy(): void } => {\n const mapValueToTile = options.mapValueToTile.bind(options);\n\n const inline = new InlineWorker(options.workerSource, { name: 'exojs-tilemap-chunk-sampler' });\n const worker = inline.worker;\n\n if (options.initMessage !== undefined) {\n inline.postMessage(options.initMessage);\n }\n\n let requestCounter = 0;\n const pending = new Map<number, PendingRequest>();\n\n const composePayload = (values: Float64Array, request: PendingRequest): ChunkPayload | null => {\n const { cx, cy, chunkWidth, chunkHeight } = request;\n const startTx = cx * chunkWidth;\n const startTy = cy * chunkHeight;\n\n let out: Uint32Array | null = null;\n for (let ty = startTy; ty < startTy + chunkHeight; ty++) {\n for (let tx = startTx; tx < startTx + chunkWidth; tx++) {\n // Bounded-layer edge chunks may be smaller than a full chunk - same\n // clamp createSampledChunkSource applies, computed here (not asked\n // of the worker) since only this side knows the layer's bounds.\n if (layer.width !== undefined && layer.height !== undefined && (tx >= layer.width || ty >= layer.height)) continue;\n\n const localIndex = (ty - startTy) * chunkWidth + (tx - startTx);\n const value = values[localIndex];\n if (value === undefined) continue; // defensive: malformed/short values array\n const resolved = mapValueToTile(value, tx, ty);\n if (!resolved) continue;\n\n out ??= new Uint32Array(chunkWidth * chunkHeight);\n const tilesetIndex = layer.tilesets.indexOf(resolved.tileset);\n out[localIndex] = packTile(tilesetIndex, resolved.localTileId, resolved.transform);\n }\n }\n\n return out === null ? null : { width: chunkWidth, height: chunkHeight, tiles: out };\n };\n\n worker.onmessage = (event: MessageEvent<WorkerResponseMessage>): void => {\n const message = event.data;\n const entry = pending.get(message.requestId);\n if (!entry) return; // stale/unknown requestId (e.g. arrived after destroy())\n pending.delete(message.requestId);\n\n if (isWorkerErrorMessage(message)) {\n entry.reject(new Error(message.error));\n return;\n }\n\n entry.resolve(composePayload(message.values, entry));\n };\n\n worker.onerror = (event: ErrorEvent): void => {\n const error = new Error(`WorkerSampledChunkSource worker error: ${event.message}`);\n for (const entry of pending.values()) {\n entry.reject(error);\n }\n pending.clear();\n };\n\n return {\n getChunk(cx: number, cy: number): Promise<ChunkPayload | null> {\n if (inline.destroyed) {\n return Promise.reject(new Error('WorkerSampledChunkSource: getChunk() called after destroy().'));\n }\n\n const chunkWidth = layer.chunkWidth;\n const chunkHeight = layer.chunkHeight;\n const requestId = ++requestCounter;\n\n return new Promise<ChunkPayload | null>((resolve, reject) => {\n pending.set(requestId, { resolve, reject, cx, cy, chunkWidth, chunkHeight });\n const request: WorkerRequestMessage = { requestId, cx, cy, chunkWidth, chunkHeight };\n inline.postMessage(request);\n });\n },\n\n destroy(): void {\n if (inline.destroyed) return;\n const error = new Error('WorkerSampledChunkSource destroyed.');\n for (const entry of pending.values()) {\n entry.reject(error);\n }\n pending.clear();\n inline.destroy();\n },\n };\n};\n"],"mappings":";;;;AA0FA,MAAM,wBAAwB,YAAk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qB,OAAO,GAAG;GACjC,MAAM,OAAO,IAAI,MAAM,QAAQ,KAAK,CAAC;GACrC;EACF;EAEA,MAAM,QAAQ,eAAe,QAAQ,QAAQ,KAAK,CAAC;CACrD;CAEA,OAAO,WAAW,UAA4B;EAC5C,MAAM,wBAAQ,IAAI,MAAM,0CAA0C,MAAM,SAAS;EACjF,KAAK,MAAM,SAAS,QAAQ,OAAO,GACjC,MAAM,OAAO,KAAK;EAEpB,QAAQ,MAAM;CAChB;CAEA,OAAO;EACL,SAAS,IAAY,IAA0C;GAC7D,IAAI,OAAO,WACT,OAAO,QAAQ,uBAAO,IAAI,MAAM,8DAA8D,CAAC;GAGjG,MAAM,aAAa,MAAM;GACzB,MAAM,cAAc,MAAM;GAC1B,MAAM,YAAY,EAAE;GAEpB,OAAO,IAAI,SAA8B,SAAS,WAAW;IAC3D,QAAQ,IAAI,WAAW;KAAE;KAAS;KAAQ;KAAI;KAAI;KAAY;IAAY,CAAC;IAC3E,MAAM,UAAgC;KAAE;KAAW;KAAI;KAAI;KAAY;IAAY;IACnF,OAAO,YAAY,OAAO;GAC5B,CAAC;EACH;EAEA,UAAgB;GACd,IAAI,OAAO,WAAW;GACtB,MAAM,wBAAQ,IAAI,MAAM,qCAAqC;GAC7D,KAAK,MAAM,SAAS,QAAQ,OAAO,GACjC,MAAM,OAAO,KAAK;GAEpB,QAAQ,MAAM;GACd,OAAO,QAAQ;EACjB;CACF;AACF"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { TILE_DIAGONAL_BIT, TILE_ROW_MASK } from "../tileWord.js";
|
|
2
2
|
import tile_chunk_default from "./shaders/tile-chunk.frag.js";
|
|
3
3
|
import tile_chunk_default$1 from "./shaders/tile-chunk.vert.js";
|
|
4
|
-
import { AbstractWebGl2Renderer, BlendModes, BufferTypes, BufferUsage, RenderingPrimitives,
|
|
4
|
+
import { AbstractWebGl2Renderer, BlendModes, BufferTypes, BufferUsage, RenderingPrimitives, WebGl2RenderBuffer, WebGl2Shader, WebGl2VertexArrayObject, createWebGl2ShaderProgram, fillShaderSource, packedGroupChanged, uploadBufferRange, uploadBufferStore } from "@codexo/exojs/renderer-sdk";
|
|
5
5
|
|
|
6
6
|
//#region src/webgl2/WebGl2TileChunkRenderer.ts
|
|
7
7
|
const instanceStrideBytes = 32;
|
|
@@ -40,7 +40,7 @@ var WebGl2TileChunkRenderer = class extends AbstractWebGl2Renderer {
|
|
|
40
40
|
* tile chunks have no custom-material path to exclude.
|
|
41
41
|
* @internal
|
|
42
42
|
*/
|
|
43
|
-
|
|
43
|
+
supportsRetainedBatches = true;
|
|
44
44
|
_shader;
|
|
45
45
|
_batchSize;
|
|
46
46
|
_instanceData;
|
|
@@ -65,7 +65,7 @@ var WebGl2TileChunkRenderer = class extends AbstractWebGl2Renderer {
|
|
|
65
65
|
constructor(batchSize) {
|
|
66
66
|
super();
|
|
67
67
|
this._batchSize = batchSize;
|
|
68
|
-
this._shader = new
|
|
68
|
+
this._shader = new WebGl2Shader(tileVertexSource, tile_chunk_default);
|
|
69
69
|
this._instanceData = /* @__PURE__ */ new ArrayBuffer(batchSize * instanceStrideBytes);
|
|
70
70
|
this._instanceFloat32 = new Float32Array(this._instanceData);
|
|
71
71
|
this._instanceUint32 = new Uint32Array(this._instanceData);
|
|
@@ -274,7 +274,7 @@ var WebGl2TileChunkRenderer = class extends AbstractWebGl2Renderer {
|
|
|
274
274
|
this._vao = new WebGl2VertexArrayObject(RenderingPrimitives.TriangleStrip).addAttribute(this._instanceBuffer, this._shader.getAttribute("a_quadBounds"), gl.FLOAT, false, instanceStrideBytes, 0, false, 1).addAttribute(this._instanceBuffer, this._shader.getAttribute("a_uvBounds"), gl.UNSIGNED_SHORT, true, instanceStrideBytes, 16, false, 1).addAttribute(this._instanceBuffer, this._shader.getAttribute("a_color"), gl.UNSIGNED_BYTE, true, instanceStrideBytes, 24, false, 1).addAttribute(this._instanceBuffer, this._shader.getAttribute("a_tileWord"), gl.UNSIGNED_INT, false, instanceStrideBytes, 28, true, 1).connect(this._createVaoRuntime(this._connection));
|
|
275
275
|
}
|
|
276
276
|
onDisconnect() {
|
|
277
|
-
this._shader.
|
|
277
|
+
this._shader.destroy();
|
|
278
278
|
this._instanceBuffer?.destroy();
|
|
279
279
|
this._instanceBuffer = null;
|
|
280
280
|
this._vao?.destroy();
|
|
@@ -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,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,iBAAiBA,sBAAoB;CAAE,aAAa;CAAe,iBAAiB;AAAkB,CAAC;;;;;;;;;AAgBhI,IAAa,0BAAb,cAA6C,uBAA6E;;;;;;;;;;CAUxH,AAAgB,2BAA2B;CAE3C,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CAEjB,AAAiB,wBAAoC,IAAI,WAAW,CAAC,oBAAoB,CAAC;CAG1F,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c;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
|
+
{"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 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 = 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: 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): 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.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":";;;;;;AAoCA,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,iBAAiBA,sBAAoB;CAAE,aAAa;CAAe,iBAAiB;AAAkB,CAAC;;;;;;;;;AAgBhI,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,IAAI,WAAW,CAAC,CAAC,CAAC;CAGzE,AAAiB,kBAAyD,CAAC,IAAI;CAE/E,AAAQ,aAAa;CACrB,AAAQ,gBAAgB;CAMxB,AAAQ,kBAAkB;CAC1B,AAAQ,cAAc;CAItB,AAAQ,oBAAuC;CAC/C,AAAQ,kBAAkC;CAC1C,AAAQ,eAA4B;CACpC,AAAQ,iBAAiB;CACzB,AAAQ,mBAAmB;CAC3B,AAAiB,oCAAoB,IAAI,aAAa,CAAC;CAEvD,AAAQ,kBAA6C;CACrD,AAAQ,OAAuC;CAC/C,AAAQ,cAA6C;CAErD,AAAO,YAAY,WAAmB;EACpC,MAAM;EAEN,KAAK,aAAa;EAClB,KAAK,UAAU,IAAI,aAAa,kBAAkBC,kBAAkB;EACpE,KAAK,gCAAgB,IAAI,YAAY,YAAY,mBAAmB;EACpE,KAAK,mBAAmB,IAAI,aAAa,K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W,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;\
|
|
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;\\
|
|
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;\
|
|
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);\nv_color = vec4(a_color.rgb * 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;\\
|
|
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);\\nv_color = vec4(a_color.rgb * a_color.a, a_color.a);\\n}\";"],"mappings":";AAAA,yBAAe"}
|
|
@@ -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
|
-
|
|
40
|
+
supportsRetainedBatches = true;
|
|
41
41
|
_projectionData = new Float32Array(projectionByteLength / Float32Array.BYTES_PER_ELEMENT);
|
|
42
42
|
_writtenView = null;
|
|
43
43
|
_writtenViewUpdateId = -1;
|
|
@@ -104,7 +104,7 @@ var WebGpuTileChunkRenderer = class extends AbstractWebGpuRenderer {
|
|
|
104
104
|
this._device.queue.writeBuffer(this._indexBuffer, 0, quadIndices.buffer, quadIndices.byteOffset, quadIndices.byteLength);
|
|
105
105
|
}
|
|
106
106
|
onDisconnect() {
|
|
107
|
-
const coordinator = this._backend?.
|
|
107
|
+
const coordinator = this._backend?.passCoordinator ?? null;
|
|
108
108
|
if (coordinator !== null && this._passDraws !== null && this._passDraws === coordinator.activePass) coordinator.endPass();
|
|
109
109
|
this._instanceBuffer?.destroy();
|
|
110
110
|
this._indexBuffer?.destroy();
|
|
@@ -212,7 +212,7 @@ var WebGpuTileChunkRenderer = class extends AbstractWebGpuRenderer {
|
|
|
212
212
|
const projectionChanged = !this._hasWrittenProjection || this._writtenView !== view || this._writtenViewUpdateId !== view.updateId || viewportChanged || this._groupContentChanged(backend);
|
|
213
213
|
const scissor = backend.getScissorRect();
|
|
214
214
|
const maskClipsAll = scissor !== null && (scissor.width <= 0 || scissor.height <= 0);
|
|
215
|
-
const coordinator = backend.
|
|
215
|
+
const coordinator = backend.passCoordinator;
|
|
216
216
|
const texture = this._currentTexture;
|
|
217
217
|
const blendMode = this._currentBlendMode;
|
|
218
218
|
const indexBuffer = this._indexBuffer;
|
|
@@ -362,7 +362,7 @@ var WebGpuTileChunkRenderer = class extends AbstractWebGpuRenderer {
|
|
|
362
362
|
this.flush();
|
|
363
363
|
const scissor = backend.getScissorRect();
|
|
364
364
|
if (scissor !== null && (scissor.width <= 0 || scissor.height <= 0)) return;
|
|
365
|
-
const coordinator = backend.
|
|
365
|
+
const coordinator = backend.passCoordinator;
|
|
366
366
|
if (coordinator.passHasDraws) {
|
|
367
367
|
for (const texture of payload.textures) if (backend.textureUploadWouldMutate(texture)) {
|
|
368
368
|
coordinator.endPass();
|