@codexo/exojs-tilemap 0.19.1 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (157) hide show
  1. package/README.md +7 -163
  2. package/index.d.ts +1 -0
  3. package/index.js +1 -0
  4. package/package.json +12 -20
  5. package/dist/esm/ChunkSource.d.ts +0 -33
  6. package/dist/esm/ChunkSource.d.ts.map +0 -1
  7. package/dist/esm/ChunkStreamer.d.ts +0 -104
  8. package/dist/esm/ChunkStreamer.d.ts.map +0 -1
  9. package/dist/esm/ChunkStreamer.js +0 -229
  10. package/dist/esm/ChunkStreamer.js.map +0 -1
  11. package/dist/esm/ImageLayer.d.ts +0 -89
  12. package/dist/esm/ImageLayer.d.ts.map +0 -1
  13. package/dist/esm/ImageLayer.js +0 -74
  14. package/dist/esm/ImageLayer.js.map +0 -1
  15. package/dist/esm/ImageLayerNode.d.ts +0 -91
  16. package/dist/esm/ImageLayerNode.d.ts.map +0 -1
  17. package/dist/esm/ImageLayerNode.js +0 -210
  18. package/dist/esm/ImageLayerNode.js.map +0 -1
  19. package/dist/esm/MapObject.d.ts +0 -70
  20. package/dist/esm/MapObject.d.ts.map +0 -1
  21. package/dist/esm/MapObject.js +0 -34
  22. package/dist/esm/MapObject.js.map +0 -1
  23. package/dist/esm/MapObjectSpawner.d.ts +0 -133
  24. package/dist/esm/MapObjectSpawner.d.ts.map +0 -1
  25. package/dist/esm/MapObjectSpawner.js +0 -147
  26. package/dist/esm/MapObjectSpawner.js.map +0 -1
  27. package/dist/esm/MapSpawnSession.d.ts +0 -46
  28. package/dist/esm/MapSpawnSession.d.ts.map +0 -1
  29. package/dist/esm/MapSpawnSession.js +0 -88
  30. package/dist/esm/MapSpawnSession.js.map +0 -1
  31. package/dist/esm/MapWorld.d.ts +0 -134
  32. package/dist/esm/MapWorld.d.ts.map +0 -1
  33. package/dist/esm/MapWorld.js +0 -150
  34. package/dist/esm/MapWorld.js.map +0 -1
  35. package/dist/esm/MapWorldRuntime.d.ts +0 -180
  36. package/dist/esm/MapWorldRuntime.d.ts.map +0 -1
  37. package/dist/esm/MapWorldRuntime.js +0 -261
  38. package/dist/esm/MapWorldRuntime.js.map +0 -1
  39. package/dist/esm/ObjectLayer.d.ts +0 -379
  40. package/dist/esm/ObjectLayer.d.ts.map +0 -1
  41. package/dist/esm/ObjectLayer.js +0 -221
  42. package/dist/esm/ObjectLayer.js.map +0 -1
  43. package/dist/esm/SampledChunkSource.d.ts +0 -43
  44. package/dist/esm/SampledChunkSource.d.ts.map +0 -1
  45. package/dist/esm/SampledChunkSource.js +0 -48
  46. package/dist/esm/SampledChunkSource.js.map +0 -1
  47. package/dist/esm/TileAnimator.d.ts +0 -72
  48. package/dist/esm/TileAnimator.d.ts.map +0 -1
  49. package/dist/esm/TileAnimator.js +0 -158
  50. package/dist/esm/TileAnimator.js.map +0 -1
  51. package/dist/esm/TileChunk.d.ts +0 -103
  52. package/dist/esm/TileChunk.d.ts.map +0 -1
  53. package/dist/esm/TileChunk.js +0 -194
  54. package/dist/esm/TileChunk.js.map +0 -1
  55. package/dist/esm/TileChunkNode.d.ts +0 -2
  56. package/dist/esm/TileChunkNode.d.ts.map +0 -1
  57. package/dist/esm/TileChunkNode.js +0 -145
  58. package/dist/esm/TileChunkNode.js.map +0 -1
  59. package/dist/esm/TileLayer.d.ts +0 -286
  60. package/dist/esm/TileLayer.d.ts.map +0 -1
  61. package/dist/esm/TileLayer.js +0 -526
  62. package/dist/esm/TileLayer.js.map +0 -1
  63. package/dist/esm/TileLayerNode.d.ts +0 -129
  64. package/dist/esm/TileLayerNode.d.ts.map +0 -1
  65. package/dist/esm/TileLayerNode.js +0 -245
  66. package/dist/esm/TileLayerNode.js.map +0 -1
  67. package/dist/esm/TileMap.d.ts +0 -317
  68. package/dist/esm/TileMap.d.ts.map +0 -1
  69. package/dist/esm/TileMap.js +0 -406
  70. package/dist/esm/TileMap.js.map +0 -1
  71. package/dist/esm/TileMapBand.d.ts +0 -80
  72. package/dist/esm/TileMapBand.d.ts.map +0 -1
  73. package/dist/esm/TileMapBand.js +0 -155
  74. package/dist/esm/TileMapBand.js.map +0 -1
  75. package/dist/esm/TileMapNode.d.ts +0 -92
  76. package/dist/esm/TileMapNode.d.ts.map +0 -1
  77. package/dist/esm/TileMapNode.js +0 -134
  78. package/dist/esm/TileMapNode.js.map +0 -1
  79. package/dist/esm/TileMapView.d.ts +0 -248
  80. package/dist/esm/TileMapView.d.ts.map +0 -1
  81. package/dist/esm/TileMapView.js +0 -394
  82. package/dist/esm/TileMapView.js.map +0 -1
  83. package/dist/esm/TileProjection.d.ts +0 -59
  84. package/dist/esm/TileProjection.d.ts.map +0 -1
  85. package/dist/esm/TileProjection.js +0 -106
  86. package/dist/esm/TileProjection.js.map +0 -1
  87. package/dist/esm/TileSet.d.ts +0 -116
  88. package/dist/esm/TileSet.d.ts.map +0 -1
  89. package/dist/esm/TileSet.js +0 -168
  90. package/dist/esm/TileSet.js.map +0 -1
  91. package/dist/esm/WangSet.d.ts +0 -80
  92. package/dist/esm/WangSet.d.ts.map +0 -1
  93. package/dist/esm/WangSet.js +0 -73
  94. package/dist/esm/WangSet.js.map +0 -1
  95. package/dist/esm/WorkerSampledChunkSource.d.ts +0 -94
  96. package/dist/esm/WorkerSampledChunkSource.d.ts.map +0 -1
  97. package/dist/esm/WorkerSampledChunkSource.js +0 -113
  98. package/dist/esm/WorkerSampledChunkSource.js.map +0 -1
  99. package/dist/esm/autoTile.d.ts +0 -88
  100. package/dist/esm/autoTile.d.ts.map +0 -1
  101. package/dist/esm/autoTile.js +0 -173
  102. package/dist/esm/autoTile.js.map +0 -1
  103. package/dist/esm/chunkGeometry.d.ts +0 -2
  104. package/dist/esm/chunkGeometry.d.ts.map +0 -1
  105. package/dist/esm/chunkGeometry.js +0 -116
  106. package/dist/esm/chunkGeometry.js.map +0 -1
  107. package/dist/esm/index.d.ts +0 -2
  108. package/dist/esm/index.d.ts.map +0 -1
  109. package/dist/esm/index.js +0 -27
  110. package/dist/esm/nodeBounds.d.ts +0 -2
  111. package/dist/esm/nodeBounds.d.ts.map +0 -1
  112. package/dist/esm/nodeBounds.js +0 -40
  113. package/dist/esm/nodeBounds.js.map +0 -1
  114. package/dist/esm/pixelSnap.d.ts +0 -2
  115. package/dist/esm/pixelSnap.d.ts.map +0 -1
  116. package/dist/esm/pixelSnap.js +0 -21
  117. package/dist/esm/pixelSnap.js.map +0 -1
  118. package/dist/esm/projectObject.d.ts +0 -4
  119. package/dist/esm/projectObject.d.ts.map +0 -1
  120. package/dist/esm/projectObject.js +0 -87
  121. package/dist/esm/projectObject.js.map +0 -1
  122. package/dist/esm/public.d.ts +0 -48
  123. package/dist/esm/public.d.ts.map +0 -1
  124. package/dist/esm/tileCollision.d.ts +0 -190
  125. package/dist/esm/tileCollision.d.ts.map +0 -1
  126. package/dist/esm/tileCollision.js +0 -399
  127. package/dist/esm/tileCollision.js.map +0 -1
  128. package/dist/esm/tileWord.d.ts +0 -2
  129. package/dist/esm/tileWord.d.ts.map +0 -1
  130. package/dist/esm/tileWord.js +0 -16
  131. package/dist/esm/tileWord.js.map +0 -1
  132. package/dist/esm/tilemapExtension.d.ts +0 -20
  133. package/dist/esm/tilemapExtension.d.ts.map +0 -1
  134. package/dist/esm/tilemapExtension.js +0 -53
  135. package/dist/esm/tilemapExtension.js.map +0 -1
  136. package/dist/esm/tilemapSerializers.d.ts +0 -2
  137. package/dist/esm/tilemapSerializers.d.ts.map +0 -1
  138. package/dist/esm/tilemapSerializers.js +0 -54
  139. package/dist/esm/tilemapSerializers.js.map +0 -1
  140. package/dist/esm/types.d.ts +0 -231
  141. package/dist/esm/types.d.ts.map +0 -1
  142. package/dist/esm/types.js +0 -129
  143. package/dist/esm/types.js.map +0 -1
  144. package/dist/esm/webgl2/WebGl2TileChunkRenderer.d.ts +0 -2
  145. package/dist/esm/webgl2/WebGl2TileChunkRenderer.d.ts.map +0 -1
  146. package/dist/esm/webgl2/WebGl2TileChunkRenderer.js +0 -376
  147. package/dist/esm/webgl2/WebGl2TileChunkRenderer.js.map +0 -1
  148. package/dist/esm/webgl2/shaders/tile-chunk.frag.js +0 -6
  149. package/dist/esm/webgl2/shaders/tile-chunk.frag.js.map +0 -1
  150. package/dist/esm/webgl2/shaders/tile-chunk.vert.js +0 -6
  151. package/dist/esm/webgl2/shaders/tile-chunk.vert.js.map +0 -1
  152. package/dist/esm/webgpu/WebGpuTileChunkRenderer.d.ts +0 -2
  153. package/dist/esm/webgpu/WebGpuTileChunkRenderer.d.ts.map +0 -1
  154. package/dist/esm/webgpu/WebGpuTileChunkRenderer.js +0 -539
  155. package/dist/esm/webgpu/WebGpuTileChunkRenderer.js.map +0 -1
  156. package/dist/esm/webgpu/shaders/tile-chunk.wgsl.js +0 -6
  157. package/dist/esm/webgpu/shaders/tile-chunk.wgsl.js.map +0 -1
package/README.md CHANGED
@@ -1,169 +1,13 @@
1
1
  # @codexo/exojs-tilemap
2
2
 
3
- Generic, format-independent tilemap runtime **and** WebGL2/WebGPU chunk renderer for [ExoJS](https://exoridus.github.io/ExoJS/). No Tiled (or any other on-disk format) vocabulary leaks into this package - adapters such as [`@codexo/exojs-tiled`](https://www.npmjs.com/package/@codexo/exojs-tiled) parse their format and hand this runtime fully resolved tiles.
3
+ Since ExoJS v0.20, import from @codexo/exojs/tilemap. This package is a compatibility shim for the 0.20 line; no independent feature development.
4
4
 
5
- ## Installation
5
+ Every export of this package is the very binding its Core entry exports, so code that still imports `@codexo/exojs-tilemap` shares one engine instance with code that already imports `@codexo/exojs/tilemap`. The package contains no implementation of its own and depends on nothing but its `@codexo/exojs` peer.
6
6
 
7
- ```sh
8
- npm install @codexo/exojs @codexo/exojs-tilemap
9
- ```
7
+ | Import | Replace with | Forwards |
8
+ | --- | --- | --- |
9
+ | `@codexo/exojs-tilemap` | `@codexo/exojs/tilemap` | everything |
10
10
 
11
- `@codexo/exojs` is a peer dependency, so install it explicitly. This package is itself a peer of the format adapters (`@codexo/exojs-tiled`, `@codexo/exojs-ldtk`) rather than something they pull in transitively — install it whether you use an adapter or build procedural / custom-format maps directly.
11
+ ## Migrating
12
12
 
13
- ## What this package provides
14
-
15
- **Runtime (data model)** — pure data, no scene graph:
16
-
17
- - `TileMap` — a finite, chunk-first map: dimensions, tile size, `tilesets`, ordered `layers`.
18
- - `TileLayer` — one tile layer; packed `Uint32Array` chunk storage, `visible` / `opacity` / `offsetX/Y`, queries, and revision tracking.
19
- - `TileSet` — a resolved tileset grid over a Core `TextureRegion` (Loader-owned texture).
20
- - `ResolvedTile` / `TileTransform` — value-typed tile references with `flipX` / `flipY` / `diagonal` orientation.
21
-
22
- **Worlds and level lifetime** — format-neutral, driven by whichever adapter loaded the data:
23
-
24
- - `MapWorld` / `MapLevel` — where levels sit: stable id, world bounds, neighbour graph, externality. Metadata only; no tiles, no textures.
25
- - `MapWorldRuntime` — explicit `loadLevel` / `unloadLevel`, one child `LoaderScope` per level, at most one live level per id. No camera policy: the game decides what to load.
26
- - `MapLevelRuntime` — one loaded level's map, scope and spawn session, with a single `destroy()` that tears all three down in a safe order.
27
-
28
- **Map object spawning**:
29
-
30
- - `MapObjectSpawner` — a local (never global) dispatch table from object class to a factory. Deterministic order, atomic rollback, `AbortSignal` cancellation.
31
- - `MapObjectDescriptor` — the format-neutral view of one authored object handed to a factory.
32
- - `MapSpawnSession` — owns what one spawn produced; constant-time lookup by stable source id, reverse-order teardown.
33
-
34
- **Scene / rendering (`@advanced`)**:
35
-
36
- - `TileMapNode` — convenience root that renders a whole `TileMap`.
37
- - `TileLayerNode` — renders one `TileLayer`; generated per layer by `TileMapView` (or construct directly).
38
- - `TileMapView` — groups a map's layers into independently placeable layer nodes and named `TileMapBand`s for actor interleaving (a helper, not a scene node).
39
- - `TileMapBand` — a `Container` of tile-layer nodes produced by `TileMapView`.
40
- - `tilemapExtension` — extension descriptor carrying the WebGL2/WebGPU renderer bindings.
41
-
42
- ## Usage — procedural map
43
-
44
- ```ts
45
- import { Application, Scene, type Texture, TextureRegion } from '@codexo/exojs';
46
- import { TileLayer, TileMap, TileMapNode, TileSet, tilemapExtension, TILE_TRANSFORM_IDENTITY } from '@codexo/exojs-tilemap';
47
-
48
- class WorldScene extends Scene {
49
- private atlas: Texture | null = null;
50
-
51
- public override async load(): Promise<void> {
52
- // A Loader-owned atlas texture: the tilemap runtime never destroys it.
53
- this.atlas = await this.loader.load('tiles.png');
54
- }
55
-
56
- public override init(): void {
57
- const atlas = this.atlas!;
58
- const terrain = new TileSet({
59
- name: 'terrain',
60
- texture: new TextureRegion(atlas, { x: 0, y: 0, width: atlas.width, height: atlas.height }),
61
- tileWidth: 16,
62
- tileHeight: 16,
63
- tileCount: 256,
64
- });
65
-
66
- const ground = new TileLayer({
67
- id: 1,
68
- name: 'ground',
69
- width: 64,
70
- height: 64,
71
- tileWidth: 16,
72
- tileHeight: 16,
73
- tilesets: [terrain],
74
- });
75
- ground.setTileAt(0, 0, { tileset: terrain, localTileId: 5, transform: TILE_TRANSFORM_IDENTITY });
76
-
77
- const map = new TileMap({
78
- name: 'world',
79
- width: 64,
80
- height: 64,
81
- tileWidth: 16,
82
- tileHeight: 16,
83
- tilesets: [terrain],
84
- layers: [ground],
85
- });
86
-
87
- // Render the whole map: a scene draws its root without a draw() override.
88
- this.addChild(new TileMapNode(map));
89
- }
90
- }
91
-
92
- const app = new Application({ extensions: [tilemapExtension] /* canvas, … */ });
93
-
94
- await app.start(WorldScene);
95
- ```
96
-
97
- ### Interleaving actors between layers — `TileMapView`
98
-
99
- `TileMapNode` owns **only** the map's layer nodes and renders them back-to-front — use it when nothing renders between layers. To draw application actors _between_ tile layers, create a `TileMapView`: it generates one `TileLayerNode` per map layer (stable identity, map document order) and groups them into named `TileMapBand`s that you parent yourself, as siblings of your own actor containers:
100
-
101
- ```ts
102
- const view = map.createView({
103
- bands: {
104
- ground: ['background', 'ground'],
105
- roof: ['roofs', 'foreground'],
106
- },
107
- });
108
-
109
- worldRoot.addChild(
110
- view.band('ground'),
111
- actors, // app-owned actor container — drawn between ground and roof
112
- view.band('roof'),
113
- );
114
- ```
115
-
116
- Or, without bands, place the generated per-layer nodes directly:
117
-
118
- ```ts
119
- const view = map.createView();
120
-
121
- worldRoot.addChild(view.getLayerNodeById(groundId)!, actors, view.getLayerNodeById(roofId)!);
122
- ```
123
-
124
- Actors are application-owned siblings. `TileMapView` never adopts or destroys actors.
125
-
126
- - A band definition **selects** layers (by id, or by unique layer name); rendering order within a band always follows map document order — definitions never reorder layers.
127
- - Layers not listed in any band stay reachable via `view.getLayerNodeById(id)` / `view.getLayerNodesByName(name)`; they are not auto-added to any band.
128
- - Destroying a view or a band destroys only the tile nodes it generated — never actors, the `TileMap`, its `TileLayer`s, or tileset textures.
129
- - There is no map-replacement API: to swap maps, destroy the old view and create a new view from the new map — the actor tree is untouched.
130
- - After layers are structurally added to or removed from the map, call `view.refreshLayers()`: unchanged layer nodes keep their identity and bands keep their placement in your scene graph.
131
-
132
- ## Isometric grids
133
-
134
- Supply a shared `TileProjection({ orientation: 'isometric', tileWidth, tileHeight, originX, originY })` to the map and each tile layer. Orthogonal is the default. `tileToPixel()` projects the cell's top diamond vertex; `pixelToTile()` inversely projects and floors both grid axes, including negative coordinates. Cell boundaries are half-open. `projection.logicalToPixel()` and `pixelToLogical()` preserve fractional coordinates. Isometric logical cells are squares of side `tileHeight`; display diamonds may have any positive integer width and height.
135
-
136
- Layer offsets are display translations. `TileLayer.logicalOffset` exposes the corresponding logical vector for simulation. A map's pixel dimensions describe the projected grid AABB, while `projection.getBounds()` also supplies its possibly negative origin. Scene-node bounds include isometric artwork overhangs and tileset offsets. Picking describes cells, not opaque pixels of tall artwork; apply inverse scene and camera transforms before calling the map/layer helpers.
137
-
138
- Isometric rendering splits resident storage chunks into diagonal draw sections, sorted across chunks by increasing `tx + ty`, then increasing `tx`. Only consecutive tiles with the same texture are batched, so tall tiles preserve painter order across texture and chunk boundaries. Geometry stays revision-cached. All sections share a layer-grid snap origin, including odd tile sizes. More draw sections and texture changes can cost more than orthogonal batching; no throughput improvement is promised.
139
-
140
- Object layers remain data-only. With a projection their objects use logical coordinates; `layer.getDisplayObject(object)` returns display geometry with the layer offset applied. Rectangles may become polygons and ellipses retain their exact affine shape. Tile/text dimensions stay in display pixels. Actors remain application-owned; bands interleave them between layers, not automatically among individual terrain tiles.
141
-
142
- ## Renderer model
143
-
144
- - **Chunk-first.** A `TileLayerNode` is a container of per-chunk `TileChunkNode` drawables (one per non-empty loaded chunk). The renderer batches tiles by `(shader, tileset texture)` and issues one instanced draw per batch — draw calls scale with _visible chunks × layers_, not total tile count.
145
- - **Revision-cached geometry.** Each chunk's quad geometry is built once and cached against the source chunk's `revision`. Unchanged chunks never rebuild; a camera pan rebuilds nothing — off-screen chunks are culled by their local bounds before any geometry is touched.
146
- - **Orientation.** `flipX` / `flipY` / `diagonal` are baked into the chunk geometry / resolved in the shader (all 8 combinations), with no per-tile matrix or per-frame cost.
147
- - **Multiple tilesets** with differing tile sizes are first-class; tiles taller than the map grid are bottom-left aligned (Tiled orthogonal convention).
148
- - **WebGL2 and WebGPU** share one CPU geometry builder and produce identical output (golden parity tested on both backends).
149
- - **Sampling.** Tile UVs are exact (no half-texel inset), which assumes **nearest** atlas filtering - the typical pixel-art case. Under linear or mipmap filtering, author tilesets with extruded tile margins to avoid neighbour bleed at tile edges; the tilemap renderer does not apply an extrusion-aware inset.
150
-
151
- ## Ownership & lifecycle
152
-
153
- - Tileset **textures are Loader-owned**. The runtime and renderer never destroy them.
154
- - A `MapWorldRuntime` owns the scope it creates under the one you give it, plus one child scope per loaded level - never the scope you passed in. A `MapLevelRuntime` owns the `TileMap` its provider returned, its spawn session, and its scope; `destroy()` releases them in that order.
155
- - `TileMapNode` / `TileMapView` / `TileMapBand` / `TileLayerNode` reference — but never own — the `TileMap`. Destroying a map node, view, or band frees only the tile nodes it generated (detaching them from their application parents) and their cached geometry; application actors, the `TileMap` data, its `TileLayer`s, and textures all survive. Free those via `TileMap.destroy()` and `Loader.destroy()` respectively.
156
- - A `TileMapNode` or `TileMapView` reflects the layer set at construction time. After layers are structurally added to or removed from the map call `node.refreshLayers()` / `view.refreshLayers()`; after tiles are written into previously-empty chunks call `layerNode.refresh()`. In-place edits to existing chunks are picked up automatically.
157
-
158
- ## Core compatibility
159
-
160
- This package follows the Core lockstep release line and declares the compatible `@codexo/exojs` minor as a peer dependency. Install matching package versions.
161
-
162
- ## Links
163
-
164
- - [API reference](https://exoridus.github.io/ExoJS/en/api/)
165
- - [`@codexo/exojs-tiled`](https://www.npmjs.com/package/@codexo/exojs-tiled) — load Tiled `.tmj` maps into this runtime
166
-
167
- ## License
168
-
169
- MIT
13
+ Change each import to the Core entry in the table, then remove this package with `npm uninstall @codexo/exojs-tilemap`. `@codexo/exojs` already contains the module; there is nothing else to install. The migration guide on the ExoJS site lists every renamed import.
package/index.d.ts ADDED
@@ -0,0 +1 @@
1
+ export * from '@codexo/exojs/tilemap';
package/index.js ADDED
@@ -0,0 +1 @@
1
+ export * from '@codexo/exojs/tilemap';
package/package.json CHANGED
@@ -1,46 +1,38 @@
1
1
  {
2
2
  "name": "@codexo/exojs-tilemap",
3
- "version": "0.19.1",
4
- "description": "Generic, format-independent tilemap runtime for ExoJS.",
3
+ "version": "0.20.0",
4
+ "description": "Compatibility shim that forwards to @codexo/exojs/tilemap. Since ExoJS v0.20, import from @codexo/exojs/tilemap.",
5
5
  "repository": {
6
6
  "type": "git",
7
7
  "url": "git+https://github.com/Exoridus/ExoJS.git",
8
- "directory": "packages/exojs-tilemap"
8
+ "directory": "packages/legacy/exojs-tilemap"
9
9
  },
10
10
  "type": "module",
11
11
  "sideEffects": false,
12
- "main": "./dist/esm/index.js",
13
- "module": "./dist/esm/index.js",
14
- "types": "./dist/esm/index.d.ts",
12
+ "main": "./index.js",
13
+ "types": "./index.d.ts",
15
14
  "exports": {
16
15
  ".": {
17
- "types": "./dist/esm/index.d.ts",
18
- "import": "./dist/esm/index.js",
19
- "default": "./dist/esm/index.js"
16
+ "types": "./index.d.ts",
17
+ "import": "./index.js",
18
+ "default": "./index.js"
20
19
  },
21
20
  "./package.json": "./package.json"
22
21
  },
23
22
  "files": [
24
- "dist/esm/",
23
+ "index.js",
24
+ "index.d.ts",
25
25
  "README.md",
26
26
  "LICENSE"
27
27
  ],
28
28
  "peerDependencies": {
29
- "@codexo/exojs": "0.19.x"
29
+ "@codexo/exojs": "0.20.x"
30
30
  },
31
31
  "devDependencies": {
32
- "@codexo/exojs": "0.19.1",
33
- "@codexo/exojs-config": "0.0.0"
32
+ "@codexo/exojs": "0.20.0"
34
33
  },
35
34
  "license": "MIT",
36
35
  "publishConfig": {
37
36
  "access": "public"
38
- },
39
- "scripts": {
40
- "build": "tsx ../../scripts/build-extension.ts",
41
- "build:dev": "tsx ../../scripts/build-extension.ts --dev",
42
- "typecheck": "exo-tsc --noEmit && exo-tsc --noEmit -p tsconfig.test.json",
43
- "lint": "eslint \"src/**/*.ts\" \"test/**/*.ts\"",
44
- "test": "vitest run --root ../.. --project=exojs-tilemap"
45
37
  }
46
38
  }
@@ -1,33 +0,0 @@
1
- /**
2
- * A chunk payload ready to install into a {@link import('./TileLayer').TileLayer}
3
- * via {@link import('./TileLayer').TileLayer._adoptChunk} - the same shape
4
- * {@link import('./TileChunk').TileChunk}'s constructor accepts as its
5
- * `source` parameter, named and exported so provider authors have a type to
6
- * import instead of matching an inline shape.
7
- * @advanced
8
- */
9
- export interface ChunkPayload {
10
- readonly width: number;
11
- readonly height: number;
12
- readonly tiles: Uint32Array;
13
- }
14
- /**
15
- * Supplies chunk data for one {@link import('./TileLayer').TileLayer} on
16
- * demand, keyed by signed chunk coordinates - the abstraction a
17
- * {@link import('./ChunkStreamer').ChunkStreamer} drives to implement chunk
18
- * streaming, and the seam a format adapter or a procedural generator
19
- * implements.
20
- *
21
- * `getChunk` may return synchronously (e.g. slicing already-parsed source
22
- * data) or a `Promise` (e.g. an expensive procedural-generation algorithm,
23
- * plausibly off the main thread) - {@link import('./ChunkStreamer').ChunkStreamer}
24
- * installs a synchronous result in the same tick it was requested, with
25
- * zero pop-in. Returning `null` (synchronously or via a resolved `Promise`)
26
- * means "no data for this coordinate" - e.g. outside a finite provider's
27
- * authored extent, even though the layer itself may be unbounded.
28
- * @advanced
29
- */
30
- export interface ChunkSource {
31
- getChunk(cx: number, cy: number): ChunkPayload | null | Promise<ChunkPayload | null>;
32
- }
33
- //# sourceMappingURL=ChunkSource.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"ChunkSource.d.ts","sourceRoot":"","sources":["../../src/ChunkSource.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,MAAM,WAAW,YAAY;IAC3B,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,KAAK,EAAE,WAAW,CAAC;CAC7B;AAED;;;;;;;;;;;;;;;GAeG;AACH,MAAM,WAAW,WAAW;IAC1B,QAAQ,CAAC,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,YAAY,GAAG,IAAI,GAAG,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC,CAAC;CACtF"}
@@ -1,104 +0,0 @@
1
- import { type View } from '@codexo/exojs';
2
- import type { ChunkSource } from './ChunkSource';
3
- import type { TileLayer } from './TileLayer';
4
- /**
5
- * Options for a {@link ChunkStreamer}. All optional.
6
- * @advanced
7
- */
8
- export interface ChunkStreamerOptions {
9
- /**
10
- * Chunks within this many chunk-units (Chebyshev distance to the visible
11
- * chunk range) of the view are loaded. Default `1`.
12
- */
13
- readonly loadRadius?: number;
14
- /**
15
- * Own-resident chunks beyond this many chunk-units of the view are
16
- * evicted. Must be `>= loadRadius` - the gap between the two is
17
- * deliberate hysteresis that prevents load/unload thrashing when the
18
- * view sits near a chunk boundary. Default `2`.
19
- */
20
- readonly unloadRadius?: number;
21
- /**
22
- * Maximum number of new chunk loads issued per {@link ChunkStreamer.update}
23
- * call, after the very first call (which loads the entire initial wanted
24
- * set unbudgeted, so the starting view never pops in). Default `8`.
25
- */
26
- readonly maxChunkLoadsPerFrame?: number;
27
- }
28
- /**
29
- * Drives {@link TileLayer._adoptChunk}/{@link TileLayer._evictChunk} calls
30
- * from a {@link View}'s position: chunks near the view are requested from a
31
- * {@link ChunkSource} and installed; chunks that scroll far enough away are
32
- * evicted. Works on both unbounded and bounded layers (a bounded-but-large
33
- * layer still benefits from not keeping every chunk resident at once) - for
34
- * a bounded layer, the wanted range is clamped to {@link TileLayer.chunkRange}.
35
- *
36
- * Touches only the {@link TileLayer} data layer -
37
- * {@link import('./TileLayerNode').TileLayerNode} reacts to
38
- * `_adoptChunk`/`_evictChunk` on its own via a structural listener, so this
39
- * class has no rendering dependency and no reference to any scene node.
40
- *
41
- * Tracks its own resident set (chunks *this instance* has loaded), never
42
- * touching chunks that predate its attachment or were installed by another
43
- * source.
44
- *
45
- * Tick it from your update loop, like {@link import('./TileAnimator').TileAnimator}:
46
- *
47
- * ```ts
48
- * const streamer = new ChunkStreamer(layer, mySource, view);
49
- * scene.systems.add({ update: () => streamer.update() });
50
- * ```
51
- *
52
- * @advanced
53
- */
54
- export declare class ChunkStreamer {
55
- private readonly _layer;
56
- private readonly _source;
57
- private readonly _view;
58
- private readonly _loadRadius;
59
- private readonly _unloadRadius;
60
- private readonly _maxChunkLoadsPerFrame;
61
- private readonly _resident;
62
- private readonly _inFlight;
63
- private _requestCounter;
64
- private _primed;
65
- private _destroyed;
66
- constructor(layer: TileLayer, source: ChunkSource, view: View, options?: ChunkStreamerOptions);
67
- /** Number of chunks this instance currently has resident in the layer. */
68
- get residentCount(): number;
69
- /**
70
- * Recompute the wanted chunk set from the view's current position; evict
71
- * own-resident chunks that fell outside `unloadRadius`, then request
72
- * chunks newly inside `loadRadius`. The very first call loads the entire
73
- * initial wanted set unbudgeted; every later call is capped at
74
- * {@link ChunkStreamerOptions.maxChunkLoadsPerFrame}. No-op once
75
- * {@link destroy}ed.
76
- */
77
- update(): void;
78
- /**
79
- * Evict every chunk this instance has loaded and stop responding to
80
- * {@link update}. Does not affect chunks predating attachment or
81
- * installed by another source. Idempotent.
82
- *
83
- * Does not destroy the {@link ChunkSource} passed to the constructor: this
84
- * class only reads from it and never took ownership. A source with its own
85
- * `destroy()` (e.g. {@link import('./WorkerSampledChunkSource').createWorkerSampledChunkSource}'s,
86
- * which tears down a real `Worker`) must be destroyed separately by
87
- * whoever created it.
88
- */
89
- destroy(): void;
90
- private _computeCoreRange;
91
- private _rangeDistance;
92
- private _unload;
93
- private _request;
94
- /**
95
- * Ignore-on-resolve: only the `_destroyed` and in-flight-token checks
96
- * guard installation - a chunk that scrolled out of the wanted set while
97
- * its request was in flight is still installed if it resolves (installing
98
- * it is cheap and self-correcting: the next {@link update} call's unload
99
- * pass evicts it again if it's genuinely no longer wanted). There is no
100
- * edit-persistence to protect, so discarding is never destructive.
101
- */
102
- private _onResolved;
103
- }
104
- //# sourceMappingURL=ChunkStreamer.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"ChunkStreamer.d.ts","sourceRoot":"","sources":["../../src/ChunkStreamer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAU,KAAK,IAAI,EAAE,MAAM,eAAe,CAAC;AAElD,OAAO,KAAK,EAAgB,WAAW,EAAE,MAAM,eAAe,CAAC;AAC/D,OAAO,KAAK,EAAc,SAAS,EAAE,MAAM,aAAa,CAAC;AAGzD;;;GAGG;AACH,MAAM,WAAW,oBAAoB;IACnC;;;OAGG;IACH,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;IAC7B;;;;;OAKG;IACH,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,CAAC;IAC/B;;;;OAIG;IACH,QAAQ,CAAC,qBAAqB,CAAC,EAAE,MAAM,CAAC;CACzC;AAWD;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,qBAAa,aAAa;IACxB,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAY;IACnC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAc;IACtC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAO;IAC7B,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAS;IACrC,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAS;IACvC,OAAO,CAAC,QAAQ,CAAC,sBAAsB,CAAS;IAEhD,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAmE;IAC7F,OAAO,CAAC,QAAQ,CAAC,SAAS,CAA6B;IACvD,OAAO,CAAC,eAAe,CAAK;IAC5B,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,UAAU,CAAS;IAE3B,YAAmB,KAAK,EAAE,SAAS,EAAE,MAAM,EAAE,WAAW,EAAE,IAAI,EAAE,IAAI,EAAE,OAAO,CAAC,EAAE,oBAAoB,EAWnG;IAED,0EAA0E;IAC1E,IAAW,aAAa,IAAI,MAAM,CAEjC;IAED;;;;;;;OAOG;IACI,MAAM,IAAI,IAAI,CA0CpB;IAED;;;;;;;;;;OAUG;IACI,OAAO,IAAI,IAAI,CASrB;IAED,OAAO,CAAC,iBAAiB;IAmDzB,OAAO,CAAC,cAAc;IAMtB,OAAO,CAAC,OAAO;IASf,OAAO,CAAC,QAAQ;IAqChB;;;;;;;OAOG;IACH,OAAO,CAAC,WAAW;CAUpB"}
@@ -1,229 +0,0 @@
1
- import { tileToChunkCoord } from "./types.js";
2
- import { logger } from "@codexo/exojs";
3
-
4
- //#region src/ChunkStreamer.ts
5
- const DEFAULT_LOAD_RADIUS = 1;
6
- const DEFAULT_UNLOAD_RADIUS = 2;
7
- const DEFAULT_MAX_CHUNK_LOADS_PER_FRAME = 8;
8
- const chunkKey = (cx, cy) => `${cx},${cy}`;
9
- const isThenable = (value) => value !== null && typeof value === "object" && typeof value.then === "function";
10
- /**
11
- * Drives {@link TileLayer._adoptChunk}/{@link TileLayer._evictChunk} calls
12
- * from a {@link View}'s position: chunks near the view are requested from a
13
- * {@link ChunkSource} and installed; chunks that scroll far enough away are
14
- * evicted. Works on both unbounded and bounded layers (a bounded-but-large
15
- * layer still benefits from not keeping every chunk resident at once) - for
16
- * a bounded layer, the wanted range is clamped to {@link TileLayer.chunkRange}.
17
- *
18
- * Touches only the {@link TileLayer} data layer -
19
- * {@link import('./TileLayerNode').TileLayerNode} reacts to
20
- * `_adoptChunk`/`_evictChunk` on its own via a structural listener, so this
21
- * class has no rendering dependency and no reference to any scene node.
22
- *
23
- * Tracks its own resident set (chunks *this instance* has loaded), never
24
- * touching chunks that predate its attachment or were installed by another
25
- * source.
26
- *
27
- * Tick it from your update loop, like {@link import('./TileAnimator').TileAnimator}:
28
- *
29
- * ```ts
30
- * const streamer = new ChunkStreamer(layer, mySource, view);
31
- * scene.systems.add({ update: () => streamer.update() });
32
- * ```
33
- *
34
- * @advanced
35
- */
36
- var ChunkStreamer = class {
37
- _layer;
38
- _source;
39
- _view;
40
- _loadRadius;
41
- _unloadRadius;
42
- _maxChunkLoadsPerFrame;
43
- _resident = /* @__PURE__ */ new Map();
44
- _inFlight = /* @__PURE__ */ new Map();
45
- _requestCounter = 0;
46
- _primed = false;
47
- _destroyed = false;
48
- constructor(layer, source, view, options) {
49
- this._layer = layer;
50
- this._source = source;
51
- this._view = view;
52
- this._loadRadius = options?.loadRadius ?? DEFAULT_LOAD_RADIUS;
53
- this._unloadRadius = options?.unloadRadius ?? DEFAULT_UNLOAD_RADIUS;
54
- this._maxChunkLoadsPerFrame = options?.maxChunkLoadsPerFrame ?? DEFAULT_MAX_CHUNK_LOADS_PER_FRAME;
55
- if (this._unloadRadius < this._loadRadius) throw new Error(`ChunkStreamer unloadRadius (${this._unloadRadius}) must be >= loadRadius (${this._loadRadius}).`);
56
- }
57
- /** Number of chunks this instance currently has resident in the layer. */
58
- get residentCount() {
59
- return this._resident.size;
60
- }
61
- /**
62
- * Recompute the wanted chunk set from the view's current position; evict
63
- * own-resident chunks that fell outside `unloadRadius`, then request
64
- * chunks newly inside `loadRadius`. The very first call loads the entire
65
- * initial wanted set unbudgeted; every later call is capped at
66
- * {@link ChunkStreamerOptions.maxChunkLoadsPerFrame}. No-op once
67
- * {@link destroy}ed.
68
- */
69
- update() {
70
- if (this._destroyed) return;
71
- const core = this._computeCoreRange();
72
- this._unload(core);
73
- const range = this._layer.chunkRange();
74
- let minCx = core.minCx - this._loadRadius;
75
- let minCy = core.minCy - this._loadRadius;
76
- let maxCx = core.maxCx + this._loadRadius;
77
- let maxCy = core.maxCy + this._loadRadius;
78
- if (range !== null) {
79
- minCx = Math.max(minCx, range.minCx);
80
- minCy = Math.max(minCy, range.minCy);
81
- maxCx = Math.min(maxCx, range.maxCx);
82
- maxCy = Math.min(maxCy, range.maxCy);
83
- }
84
- const toLoad = [];
85
- for (let cy = minCy; cy <= maxCy; cy++) for (let cx = minCx; cx <= maxCx; cx++) {
86
- const key = chunkKey(cx, cy);
87
- if (this._resident.has(key) || this._inFlight.has(key)) continue;
88
- toLoad.push({
89
- cx,
90
- cy
91
- });
92
- }
93
- if (!this._primed) {
94
- this._primed = true;
95
- for (const { cx, cy } of toLoad) this._request(cx, cy);
96
- return;
97
- }
98
- toLoad.sort((a, b) => this._rangeDistance(a.cx, a.cy, core) - this._rangeDistance(b.cx, b.cy, core));
99
- const budget = Math.min(this._maxChunkLoadsPerFrame, toLoad.length);
100
- for (const { cx, cy } of toLoad.slice(0, budget)) this._request(cx, cy);
101
- }
102
- /**
103
- * Evict every chunk this instance has loaded and stop responding to
104
- * {@link update}. Does not affect chunks predating attachment or
105
- * installed by another source. Idempotent.
106
- *
107
- * Does not destroy the {@link ChunkSource} passed to the constructor: this
108
- * class only reads from it and never took ownership. A source with its own
109
- * `destroy()` (e.g. {@link import('./WorkerSampledChunkSource').createWorkerSampledChunkSource}'s,
110
- * which tears down a real `Worker`) must be destroyed separately by
111
- * whoever created it.
112
- */
113
- destroy() {
114
- if (this._destroyed) return;
115
- this._destroyed = true;
116
- for (const { cx, cy } of this._resident.values()) this._layer._evictChunk(cx, cy);
117
- this._resident.clear();
118
- this._inFlight.clear();
119
- }
120
- _computeCoreRange() {
121
- const layer = this._layer;
122
- const view = this._view;
123
- const bounds = view.getBounds();
124
- const centerX = view.center.x;
125
- const centerY = view.center.y;
126
- const shiftX = centerX * (1 - layer.parallaxX);
127
- const shiftY = centerY * (1 - layer.parallaxY);
128
- const scale = layer.parallaxScale;
129
- let layerLeft = layer.offsetX + (bounds.left - shiftX - layer.offsetX) / scale;
130
- let layerTop = layer.offsetY + (bounds.top - shiftY - layer.offsetY) / scale;
131
- let layerRight = layer.offsetX + (bounds.right - shiftX - layer.offsetX) / scale;
132
- let layerBottom = layer.offsetY + (bounds.bottom - shiftY - layer.offsetY) / scale;
133
- if (layer.projection.orientation === "isometric") {
134
- let left = 0;
135
- let top = 0;
136
- let right = 0;
137
- let bottom = 0;
138
- for (const tileset of layer.tilesets) {
139
- left = Math.max(left, tileset.tileWidth - layer.tileWidth / 2 + tileset.offsetX);
140
- top = Math.max(top, layer.tileHeight + tileset.offsetY);
141
- right = Math.max(right, layer.tileWidth / 2 - tileset.offsetX);
142
- bottom = Math.max(bottom, tileset.tileHeight - layer.tileHeight - tileset.offsetY);
143
- }
144
- layerLeft -= left;
145
- layerTop -= top;
146
- layerRight += right;
147
- layerBottom += bottom;
148
- }
149
- const topLeftTile = layer.pixelToTile(layerLeft, layerTop);
150
- const bottomRightTile = layer.pixelToTile(layerRight, layerBottom);
151
- const topRightTile = layer.pixelToTile(layerRight, layerTop);
152
- const bottomLeftTile = layer.pixelToTile(layerLeft, layerBottom);
153
- const minTx = Math.min(topLeftTile.tx, topRightTile.tx, bottomLeftTile.tx, bottomRightTile.tx);
154
- const minTy = Math.min(topLeftTile.ty, topRightTile.ty, bottomLeftTile.ty, bottomRightTile.ty);
155
- const maxTx = Math.max(topLeftTile.tx, topRightTile.tx, bottomLeftTile.tx, bottomRightTile.tx);
156
- const maxTy = Math.max(topLeftTile.ty, topRightTile.ty, bottomLeftTile.ty, bottomRightTile.ty);
157
- const topLeftChunk = tileToChunkCoord(minTx, minTy, layer.chunkWidth, layer.chunkHeight);
158
- const bottomRightChunk = tileToChunkCoord(maxTx, maxTy, layer.chunkWidth, layer.chunkHeight);
159
- return {
160
- minCx: topLeftChunk.cx,
161
- minCy: topLeftChunk.cy,
162
- maxCx: bottomRightChunk.cx,
163
- maxCy: bottomRightChunk.cy
164
- };
165
- }
166
- _rangeDistance(cx, cy, range) {
167
- const dx = Math.max(range.minCx - cx, 0, cx - range.maxCx);
168
- const dy = Math.max(range.minCy - cy, 0, cy - range.maxCy);
169
- return Math.max(dx, dy);
170
- }
171
- _unload(core) {
172
- for (const [key, { cx, cy }] of this._resident) if (this._rangeDistance(cx, cy, core) > this._unloadRadius) {
173
- this._layer._evictChunk(cx, cy);
174
- this._resident.delete(key);
175
- }
176
- }
177
- _request(cx, cy) {
178
- const key = chunkKey(cx, cy);
179
- const token = ++this._requestCounter;
180
- this._inFlight.set(key, token);
181
- let result;
182
- try {
183
- result = this._source.getChunk(cx, cy);
184
- } catch (error) {
185
- this._inFlight.delete(key);
186
- logger.warn(`ChunkStreamer: source.getChunk(${cx}, ${cy}) threw synchronously.`, {
187
- source: "ChunkStreamer",
188
- error: error instanceof Error ? error : new Error(String(error))
189
- });
190
- return;
191
- }
192
- if (isThenable(result)) {
193
- result.then((payload) => {
194
- this._onResolved(key, cx, cy, token, payload);
195
- }, (error) => {
196
- this._inFlight.delete(key);
197
- logger.warn(`ChunkStreamer: source.getChunk(${cx}, ${cy}) rejected.`, {
198
- source: "ChunkStreamer",
199
- error: error instanceof Error ? error : new Error(String(error))
200
- });
201
- });
202
- return;
203
- }
204
- this._onResolved(key, cx, cy, token, result);
205
- }
206
- /**
207
- * Ignore-on-resolve: only the `_destroyed` and in-flight-token checks
208
- * guard installation - a chunk that scrolled out of the wanted set while
209
- * its request was in flight is still installed if it resolves (installing
210
- * it is cheap and self-correcting: the next {@link update} call's unload
211
- * pass evicts it again if it's genuinely no longer wanted). There is no
212
- * edit-persistence to protect, so discarding is never destructive.
213
- */
214
- _onResolved(key, cx, cy, token, payload) {
215
- if (this._destroyed) return;
216
- if (this._inFlight.get(key) !== token) return;
217
- this._inFlight.delete(key);
218
- if (payload === null) return;
219
- this._layer._adoptChunk(cx, cy, payload);
220
- this._resident.set(key, {
221
- cx,
222
- cy
223
- });
224
- }
225
- };
226
-
227
- //#endregion
228
- export { ChunkStreamer };
229
- //# sourceMappingURL=ChunkStreamer.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"ChunkStreamer.js","names":[],"sources":["../../src/ChunkStreamer.ts"],"sourcesContent":["import { logger, type View } from '@codexo/exojs';\n\nimport type { ChunkPayload, ChunkSource } from './ChunkSource';\nimport type { ChunkRange, TileLayer } from './TileLayer';\nimport { tileToChunkCoord } from './types';\n\n/**\n * Options for a {@link ChunkStreamer}. All optional.\n * @advanced\n */\nexport interface ChunkStreamerOptions {\n /**\n * Chunks within this many chunk-units (Chebyshev distance to the visible\n * chunk range) of the view are loaded. Default `1`.\n */\n readonly loadRadius?: number;\n /**\n * Own-resident chunks beyond this many chunk-units of the view are\n * evicted. Must be `>= loadRadius` - the gap between the two is\n * deliberate hysteresis that prevents load/unload thrashing when the\n * view sits near a chunk boundary. Default `2`.\n */\n readonly unloadRadius?: number;\n /**\n * Maximum number of new chunk loads issued per {@link ChunkStreamer.update}\n * call, after the very first call (which loads the entire initial wanted\n * set unbudgeted, so the starting view never pops in). Default `8`.\n */\n readonly maxChunkLoadsPerFrame?: number;\n}\n\nconst DEFAULT_LOAD_RADIUS = 1;\nconst DEFAULT_UNLOAD_RADIUS = 2;\nconst DEFAULT_MAX_CHUNK_LOADS_PER_FRAME = 8;\n\nconst chunkKey = (cx: number, cy: number): string => `${cx},${cy}`;\n\nconst isThenable = (value: unknown): value is Promise<ChunkPayload | null> =>\n value !== null && typeof value === 'object' && typeof (value as { then?: unknown }).then === 'function';\n\n/**\n * Drives {@link TileLayer._adoptChunk}/{@link TileLayer._evictChunk} calls\n * from a {@link View}'s position: chunks near the view are requested from a\n * {@link ChunkSource} and installed; chunks that scroll far enough away are\n * evicted. Works on both unbounded and bounded layers (a bounded-but-large\n * layer still benefits from not keeping every chunk resident at once) - for\n * a bounded layer, the wanted range is clamped to {@link TileLayer.chunkRange}.\n *\n * Touches only the {@link TileLayer} data layer -\n * {@link import('./TileLayerNode').TileLayerNode} reacts to\n * `_adoptChunk`/`_evictChunk` on its own via a structural listener, so this\n * class has no rendering dependency and no reference to any scene node.\n *\n * Tracks its own resident set (chunks *this instance* has loaded), never\n * touching chunks that predate its attachment or were installed by another\n * source.\n *\n * Tick it from your update loop, like {@link import('./TileAnimator').TileAnimator}:\n *\n * ```ts\n * const streamer = new ChunkStreamer(layer, mySource, view);\n * scene.systems.add({ update: () => streamer.update() });\n * ```\n *\n * @advanced\n */\nexport class ChunkStreamer {\n private readonly _layer: TileLayer;\n private readonly _source: ChunkSource;\n private readonly _view: View;\n private readonly _loadRadius: number;\n private readonly _unloadRadius: number;\n private readonly _maxChunkLoadsPerFrame: number;\n\n private readonly _resident = new Map<string, { readonly cx: number; readonly cy: number }>();\n private readonly _inFlight = new Map<string, number>();\n private _requestCounter = 0;\n private _primed = false;\n private _destroyed = false;\n\n public constructor(layer: TileLayer, source: ChunkSource, view: View, options?: ChunkStreamerOptions) {\n this._layer = layer;\n this._source = source;\n this._view = view;\n this._loadRadius = options?.loadRadius ?? DEFAULT_LOAD_RADIUS;\n this._unloadRadius = options?.unloadRadius ?? DEFAULT_UNLOAD_RADIUS;\n this._maxChunkLoadsPerFrame = options?.maxChunkLoadsPerFrame ?? DEFAULT_MAX_CHUNK_LOADS_PER_FRAME;\n\n if (this._unloadRadius < this._loadRadius) {\n throw new Error(`ChunkStreamer unloadRadius (${this._unloadRadius}) must be >= loadRadius (${this._loadRadius}).`);\n }\n }\n\n /** Number of chunks this instance currently has resident in the layer. */\n public get residentCount(): number {\n return this._resident.size;\n }\n\n /**\n * Recompute the wanted chunk set from the view's current position; evict\n * own-resident chunks that fell outside `unloadRadius`, then request\n * chunks newly inside `loadRadius`. The very first call loads the entire\n * initial wanted set unbudgeted; every later call is capped at\n * {@link ChunkStreamerOptions.maxChunkLoadsPerFrame}. No-op once\n * {@link destroy}ed.\n */\n public update(): void {\n if (this._destroyed) return;\n\n const core = this._computeCoreRange();\n\n this._unload(core);\n\n const range = this._layer.chunkRange();\n let minCx = core.minCx - this._loadRadius;\n let minCy = core.minCy - this._loadRadius;\n let maxCx = core.maxCx + this._loadRadius;\n let maxCy = core.maxCy + this._loadRadius;\n if (range !== null) {\n minCx = Math.max(minCx, range.minCx);\n minCy = Math.max(minCy, range.minCy);\n maxCx = Math.min(maxCx, range.maxCx);\n maxCy = Math.min(maxCy, range.maxCy);\n }\n\n const toLoad: Array<{ cx: number; cy: number }> = [];\n for (let cy = minCy; cy <= maxCy; cy++) {\n for (let cx = minCx; cx <= maxCx; cx++) {\n const key = chunkKey(cx, cy);\n if (this._resident.has(key) || this._inFlight.has(key)) continue;\n toLoad.push({ cx, cy });\n }\n }\n\n if (!this._primed) {\n this._primed = true;\n for (const { cx, cy } of toLoad) {\n this._request(cx, cy);\n }\n return;\n }\n\n toLoad.sort((a, b) => this._rangeDistance(a.cx, a.cy, core) - this._rangeDistance(b.cx, b.cy, core));\n\n const budget = Math.min(this._maxChunkLoadsPerFrame, toLoad.length);\n for (const { cx, cy } of toLoad.slice(0, budget)) {\n this._request(cx, cy);\n }\n }\n\n /**\n * Evict every chunk this instance has loaded and stop responding to\n * {@link update}. Does not affect chunks predating attachment or\n * installed by another source. Idempotent.\n *\n * Does not destroy the {@link ChunkSource} passed to the constructor: this\n * class only reads from it and never took ownership. A source with its own\n * `destroy()` (e.g. {@link import('./WorkerSampledChunkSource').createWorkerSampledChunkSource}'s,\n * which tears down a real `Worker`) must be destroyed separately by\n * whoever created it.\n */\n public destroy(): void {\n if (this._destroyed) return;\n this._destroyed = true;\n\n for (const { cx, cy } of this._resident.values()) {\n this._layer._evictChunk(cx, cy);\n }\n this._resident.clear();\n this._inFlight.clear();\n }\n\n private _computeCoreRange(): ChunkRange {\n const layer = this._layer;\n const view = this._view;\n const bounds = view.getBounds();\n const centerX = view.center.x;\n const centerY = view.center.y;\n\n const shiftX = centerX * (1 - layer.parallaxX);\n const shiftY = centerY * (1 - layer.parallaxY);\n const scale = layer.parallaxScale;\n\n let layerLeft = layer.offsetX + (bounds.left - shiftX - layer.offsetX) / scale;\n let layerTop = layer.offsetY + (bounds.top - shiftY - layer.offsetY) / scale;\n let layerRight = layer.offsetX + (bounds.right - shiftX - layer.offsetX) / scale;\n let layerBottom = layer.offsetY + (bounds.bottom - shiftY - layer.offsetY) / scale;\n if (layer.projection.orientation === 'isometric') {\n let left = 0;\n let top = 0;\n let right = 0;\n let bottom = 0;\n for (const tileset of layer.tilesets) {\n left = Math.max(left, tileset.tileWidth - layer.tileWidth / 2 + tileset.offsetX);\n top = Math.max(top, layer.tileHeight + tileset.offsetY);\n right = Math.max(right, layer.tileWidth / 2 - tileset.offsetX);\n bottom = Math.max(bottom, tileset.tileHeight - layer.tileHeight - tileset.offsetY);\n }\n layerLeft -= left;\n layerTop -= top;\n layerRight += right;\n layerBottom += bottom;\n }\n const topLeftTile = layer.pixelToTile(layerLeft, layerTop);\n const bottomRightTile = layer.pixelToTile(layerRight, layerBottom);\n\n const topRightTile = layer.pixelToTile(layerRight, layerTop);\n const bottomLeftTile = layer.pixelToTile(layerLeft, layerBottom);\n const minTx = Math.min(topLeftTile.tx, topRightTile.tx, bottomLeftTile.tx, bottomRightTile.tx);\n const minTy = Math.min(topLeftTile.ty, topRightTile.ty, bottomLeftTile.ty, bottomRightTile.ty);\n const maxTx = Math.max(topLeftTile.tx, topRightTile.tx, bottomLeftTile.tx, bottomRightTile.tx);\n const maxTy = Math.max(topLeftTile.ty, topRightTile.ty, bottomLeftTile.ty, bottomRightTile.ty);\n const topLeftChunk = tileToChunkCoord(minTx, minTy, layer.chunkWidth, layer.chunkHeight);\n const bottomRightChunk = tileToChunkCoord(maxTx, maxTy, layer.chunkWidth, layer.chunkHeight);\n\n return {\n minCx: topLeftChunk.cx,\n minCy: topLeftChunk.cy,\n maxCx: bottomRightChunk.cx,\n maxCy: bottomRightChunk.cy,\n };\n }\n\n private _rangeDistance(cx: number, cy: number, range: ChunkRange): number {\n const dx = Math.max(range.minCx - cx, 0, cx - range.maxCx);\n const dy = Math.max(range.minCy - cy, 0, cy - range.maxCy);\n return Math.max(dx, dy);\n }\n\n private _unload(core: ChunkRange): void {\n for (const [key, { cx, cy }] of this._resident) {\n if (this._rangeDistance(cx, cy, core) > this._unloadRadius) {\n this._layer._evictChunk(cx, cy);\n this._resident.delete(key);\n }\n }\n }\n\n private _request(cx: number, cy: number): void {\n const key = chunkKey(cx, cy);\n const token = ++this._requestCounter;\n this._inFlight.set(key, token);\n\n let result: ChunkPayload | null | Promise<ChunkPayload | null>;\n try {\n result = this._source.getChunk(cx, cy);\n } catch (error) {\n this._inFlight.delete(key);\n logger.warn(`ChunkStreamer: source.getChunk(${cx}, ${cy}) threw synchronously.`, {\n source: 'ChunkStreamer',\n error: error instanceof Error ? error : new Error(String(error)),\n });\n\n return;\n }\n\n if (isThenable(result)) {\n result.then(\n payload => {\n this._onResolved(key, cx, cy, token, payload);\n },\n (error: unknown) => {\n this._inFlight.delete(key);\n logger.warn(`ChunkStreamer: source.getChunk(${cx}, ${cy}) rejected.`, {\n source: 'ChunkStreamer',\n error: error instanceof Error ? error : new Error(String(error)),\n });\n },\n );\n return;\n }\n\n this._onResolved(key, cx, cy, token, result);\n }\n\n /**\n * Ignore-on-resolve: only the `_destroyed` and in-flight-token checks\n * guard installation - a chunk that scrolled out of the wanted set while\n * its request was in flight is still installed if it resolves (installing\n * it is cheap and self-correcting: the next {@link update} call's unload\n * pass evicts it again if it's genuinely no longer wanted). There is no\n * edit-persistence to protect, so discarding is never destructive.\n */\n private _onResolved(key: string, cx: number, cy: number, token: number, payload: ChunkPayload | null): void {\n if (this._destroyed) return;\n if (this._inFlight.get(key) !== token) return;\n this._inFlight.delete(key);\n\n if (payload === null) return;\n\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