@margoengine/tilemap 0.0.0-stage → 1.0.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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Scott Campbell
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,4 @@
1
+ Margo Engine
2
+ Copyright 2026 Scott Campbell
3
+
4
+ This product includes Margo Engine (https://margoengine.com) by Scott Campbell.
package/README.md CHANGED
@@ -1,3 +1,388 @@
1
- # Temporary Holding Version
1
+ # @margoengine/tilemap
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Import `margoengine/tilemap` from the `margoengine` package, or `@margoengine/tilemap` from this package alone; the two are the same module. Neither is on npm yet: the [Install](../../README.md#install) section lists the two routes that work today (run in a clone, or install local tarballs).
4
+
5
+ The 2D tile map format every other piece builds on: `TileMapData` holds the tile size, tilesets with per-tile properties, animation and collision shapes, tile layers as `Uint32Array` with Tiled's flip bits, object layers, parallax, offset, opacity and custom properties. The root entry has the types, small helpers and the `TileMap` renderer; auto-tiling and the Tiled importer are their own entries. `TileMap` draws orthogonal maps; `GridTileMap` of the `iso` entry draws isometric, staggered and hexagonal ones. (`@margoengine/tiles` is OGC 3D Tiles; this package is unrelated.)
6
+
7
+ ```ts
8
+ import {createTileLayer, encodeTile, FLIP_H, tileAt, validateTileMap, type TileMapData} from 'margoengine/tilemap';
9
+ const ground = createTileLayer('ground', 2, 2, Uint32Array.of(1, encodeTile(2, FLIP_H), 0, 1));
10
+ const map: TileMapData = {
11
+ width: 2, height: 2, tileWidth: 16, tileHeight: 16, layers: [ground],
12
+ tilesets: [{name: 'grass', firstGid: 1, tileWidth: 16, tileHeight: 16, tileCount: 2, columns: 2,
13
+ image: {source: 'grass.png', width: 32, height: 16}, tiles: [{id: 1, properties: {solid: true}}]}],
14
+ };
15
+ validateTileMap(map);
16
+ console.log(tileAt(ground, 1, 0)); // 2147483650: tile 2, mirrored left to right
17
+ ```
18
+
19
+ Layer values keep the low 28 bits for the global tile id (0 is empty) and the top bits for `FLIP_H`, `FLIP_V` and `FLIP_D`, exactly as Tiled stores them, so imported data is used as is. `decodeTile` and `encodeTile` split and join them; `tilesetForGid` and `tileDefForGid` find the tileset and the per-tile entry; `validateTileMap` throws a `TypeError` or `RangeError` that names the field.
20
+
21
+ ## Drawing a map
22
+
23
+ `TileMap` draws the tile layers with exact pixels: one instanced draw per visible 64 x 64 chunk per tileset, texels read with no filtering. Pass each tileset's atlas by name, as pixels, an `ImageBitmap`, a `GPUTexture` or a function.
24
+
25
+ ```ts
26
+ import {EngineKernel} from 'margoengine/core';
27
+ import {createTileLayer, TileMap, type TileMapData} from 'margoengine/tilemap';
28
+ const canvas = document.querySelector('canvas')!;
29
+ const engine = await EngineKernel.create(canvas, {backend: 'webgpu', exactSize: [320, 180]});
30
+ const map: TileMapData = {
31
+ width: 2, height: 1, tileWidth: 16, tileHeight: 16,
32
+ layers: [createTileLayer('ground', 2, 1, Uint32Array.of(1, 2))],
33
+ tilesets: [{name: 'grass', firstGid: 1, tileWidth: 16, tileHeight: 16, tileCount: 2, columns: 2}],
34
+ };
35
+ const image = await createImageBitmap(await (await fetch('grass.png')).blob());
36
+ const tiles = TileMap.attach(engine, {map, atlases: {grass: image}, camera: {x: 0, y: 0, zoom: 1}});
37
+ tiles.setTile('ground', 1, 0, 1); // only this cell's chunk goes up again
38
+ engine.render({delta: 1 / 60});
39
+ console.log(tiles.stats.draws); // 1
40
+ tiles.visible = false; // draws nothing and costs no draw calls, uploads or target clears
41
+ engine.render({delta: 1 / 60});
42
+ console.log(tiles.stats.draws); // 0
43
+ tiles.visible = true; // draws exactly as before
44
+ ```
45
+
46
+ | Option | Default | What it does |
47
+ | --- | --- | --- |
48
+ | `map` | required | The `TileMapData`. `setMap` swaps it |
49
+ | `atlases` | required | Tileset name to atlas. `setAtlas` swaps one |
50
+ | `camera` | `{x: 0, y: 0, zoom: 1}` | Map point at the top left and target pixels per map pixel, read each frame |
51
+ | `snap` | `true` | Rounds each layer's top left to a whole pixel, read each frame |
52
+ | `mapLayers` | every tile layer | Names of the tile layers to draw |
53
+ | `parallax` | `true` | Scrolls each layer by its own `parallax`; false when the camera carries it |
54
+ | `target` | the frame's colour target | Draw into this texture, or a function returning one |
55
+ | `clear` | the map's `backgroundColor`, else transparent | With `target`: colour to clear to, false draws over it |
56
+ | `order` | `10` | Frame-graph order |
57
+ | `layers` | `1` | Render-layer bits |
58
+ | `name` | `tilemap-1`, ... | Plugin name, unique per scene |
59
+
60
+ The `visible` property (default `true`) can be set at any time: a hidden map draws nothing, so with a `target` that target is not cleared either; setting it back to true draws the same pixels. It does not change the map's own layer `visible` flags.
61
+
62
+ ### Atlases and targets across a device restore
63
+
64
+ Pass a `GPUTexture` atlas as a function of the device: the map calls it once per device, so after a driver reset or
65
+ `rebootDevice()` the tiles come back by themselves.
66
+
67
+ ```ts
68
+ import {EngineKernel} from 'margoengine/core';
69
+ import {createTileLayer, TileMap} from 'margoengine/tilemap';
70
+ const engine = await EngineKernel.create(document.querySelector('canvas')!, {exactSize: [64, 32]});
71
+ const tiles = TileMap.attach(engine, {
72
+ map: {
73
+ width: 2, height: 1, tileWidth: 2, tileHeight: 2,
74
+ layers: [createTileLayer('ground', 2, 1, Uint32Array.of(1, 2))],
75
+ tilesets: [{name: 'grass', firstGid: 1, tileWidth: 2, tileHeight: 2, tileCount: 2, columns: 2}],
76
+ },
77
+ atlases: {
78
+ grass: (device: GPUDevice) => {
79
+ const texture = device.createTexture({
80
+ size: [4, 2], format: 'rgba8unorm', usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST,
81
+ });
82
+ device.queue.writeTexture({texture}, new Uint8Array(32).fill(255), {bytesPerRow: 16}, [4, 2]);
83
+ return texture;
84
+ },
85
+ },
86
+ });
87
+ engine.render({delta: 1 / 60});
88
+ console.log(tiles.stats.draws); // 1
89
+ ```
90
+
91
+ A plain `GPUTexture` (atlas, image or `target`) belongs to the device that made it. After a device restore the map
92
+ drops it, reports it once through `engine.onError` (`MargoError` `'state'`, help `borrowed-lost`) and skips what it
93
+ drew while the rest of the frame goes on, until `setAtlas`, `setImage` or `setTarget` hands in one made on
94
+ `engine.gpu`, for example from your own plugin's `onDeviceRestored(engine)`. `GridTileMap` and `ObjectTileMap` follow
95
+ the same rule.
96
+
97
+ To draw into a compositor layer of `margoengine/pixel`, pass `target: layer.target, camera: layer.camera, parallax: false, mapLayers: ['ground']`, with one `TileMap` per layer that scrolls on its own.
98
+
99
+ Tiles animate by their `animation` steps on the `time` clock (milliseconds; each frame adds its delta), which changes a small lookup and no cells. A tile larger than the cell sits on the cell's bottom left, as in Tiled. Layer `offset`, `opacity`, `tint`, `visible` and `parallax` and tileset `margin`, `spacing` and `tileOffset` are honoured. Overlapping oversize tiles of different tilesets draw tileset by tileset. Object layers are data only: draw tile objects with `margoengine/sprites`. Image collection tilesets (`columns: 0`) must be packed into one atlas first. After writing into `layer.data` yourself, call `invalidate(layer)`.
100
+
101
+ ## Isometric, staggered and hexagonal maps
102
+
103
+ `margoengine/tilemap/iso` places cells the way Tiled does for every `orientation`: isometric diamonds, staggered
104
+ diamonds whose rows (or columns) are pushed half a cell, and hexagons with flat sides of `hexSideLength`. `GridTileMap`
105
+ draws them with exact texels, the cells in view back to front so tiles taller than their cell (walls, trees) cover the
106
+ cells behind them. `margoengine/tilemap/hex` adds cube coordinates for distances, rings and lines.
107
+
108
+ ```ts
109
+ import { EngineKernel } from 'margoengine/core';
110
+ import { createTileLayer, type TileMapData } from 'margoengine/tilemap';
111
+ import { cellCenter, GridTileMap, pixelToCell } from 'margoengine/tilemap/iso';
112
+ import { hexDistance, hexRing } from 'margoengine/tilemap/hex';
113
+
114
+ const engine = await EngineKernel.create(document.querySelector('canvas')!, { exactSize: [160, 90] });
115
+ // Two 16 x 8 diamond tiles: grass and stone.
116
+ const data = new Uint8Array(32 * 8 * 4);
117
+ for (let y = 0; y < 8; y++)
118
+ for (let x = 0; x < 32; x++)
119
+ if (Math.abs((x % 16) + 0.5 - 8) / 8 + Math.abs(y + 0.5 - 4) / 4 <= 1)
120
+ data.set(x < 16 ? [70, 160, 60, 255] : [150, 150, 160, 255], (y * 32 + x) * 4);
121
+ const map: TileMapData = {
122
+ orientation: 'isometric', width: 8, height: 8, tileWidth: 16, tileHeight: 8,
123
+ layers: [createTileLayer('ground', 8, 8, new Uint32Array(64).map((_, i) => 1 + ((i >> 3) % 2)))],
124
+ tilesets: [{ name: 'floor', firstGid: 1, tileWidth: 16, tileHeight: 8, tileCount: 2, columns: 2 }],
125
+ };
126
+ GridTileMap.attach(engine, { map, atlases: { floor: { width: 32, height: 8, data } }, camera: { x: -16, y: -10, zoom: 1 } });
127
+ engine.start();
128
+
129
+ console.log(pixelToCell(map, ...cellCenter(map, 3, 5))); // [3, 5]
130
+ const hexes: TileMapData = { ...map, orientation: 'hexagonal', hexSideLength: 4, staggerAxis: 'y', staggerIndex: 'odd' };
131
+ console.log(hexDistance(hexes, [0, 0], [3, 2]), hexRing(hexes, 4, 4, 1).length); // 4 6
132
+ ```
133
+
134
+ | Function | What it gives |
135
+ | --- | --- |
136
+ | `cellBox(map, x, y)` | The cell's bounding box `{x, y, width, height}` in map pixels |
137
+ | `cellCenter`, `cellPolygon` | The cell's centre; its outline, 4 corners (6 for hexagons), clockwise from the top |
138
+ | `pixelToCell(map, px, py)` | The cell under a map pixel, for picking; cells outside the map are returned too |
139
+ | `cellNeighbors(map, x, y)` | The cells that share an edge: 4, or 6 on hexagonal maps |
140
+ | `mapPixelSize(map)`, `paintOrder(map)` | The box around all cells; every cell index back to front |
141
+ | `visibleCells(map, layer, [left, top, right, bottom])` | The cells whose boxes reach a view, in paint order |
142
+ | `cellToCube`, `cubeToCell`, `hexDistance`, `hexLine`, `hexRing`, `roundCube` (`/hex`) | Cube coordinates `q + r + s = 0` of hexagonal and staggered maps |
143
+
144
+ `GridTileMap` takes the options of `TileMap` (`map`, `atlases`, `camera`, `snap`, `mapLayers`, `parallax`, `target`,
145
+ `clear`, `order`, `layers`, `name`) and draws any orientation, `TileMap` included; `setMap`, `setAtlas`, `time`,
146
+ `stats` and `dispose` (or `using`) work the same. `TileMap` itself refuses a map that is not orthogonal.
147
+
148
+ - Tiles larger than the cell sit on the cell box's bottom left, as Tiled's format describes; flips work as on
149
+ orthogonal maps, and on hexagonal maps `FLIP_D` turns a tile 60 degrees clockwise and `HEX_ROTATE_120` 120.
150
+ - It writes the cells in view each frame (12 words each), so its cost follows the view, not the map; one draw per run
151
+ of tiles from one tileset in paint order. Cells are read every frame: writes into `layer.data` show on the next one.
152
+ - WebGPU only, exact texels on a single-sample target, like `TileMap`.
153
+
154
+ ## Pathfinding
155
+
156
+ `margoengine/tilemap/path` finds ways across a map: `findPath` gives a cheapest path from one cell to another by A*,
157
+ and `flowField` gives every cell its cost to the nearest goal and the next cell toward it, for many units heading to
158
+ the same places. Costs come from the map's tile properties with `tileCosts`, or from any array.
159
+
160
+ ```ts
161
+ import { createTileLayer, type TileMapData } from 'margoengine/tilemap';
162
+ import { findPath, flowField, followFlow, tileCosts } from 'margoengine/tilemap/path';
163
+
164
+ const map: TileMapData = {
165
+ width: 5, height: 3, tileWidth: 16, tileHeight: 16,
166
+ tilesets: [{ name: 'ground', firstGid: 1, tileWidth: 16, tileHeight: 16, tileCount: 3, columns: 3,
167
+ tiles: [{ id: 1, properties: { cost: 5 } }, { id: 2, properties: { solid: true } }] }],
168
+ // Grass (1), a swamp column (2) and one wall (3).
169
+ layers: [createTileLayer('ground', 5, 3, Uint32Array.of(1, 1, 2, 1, 1, 1, 3, 2, 1, 1, 1, 1, 1, 1, 1))],
170
+ };
171
+ const grid = tileCosts(map);
172
+ const path = findPath(grid, [0, 0], [4, 0]);
173
+ // Round the wall and down past the swamp: (0,0) (0,1) (0,2) (1,2) (2,2), then two corner steps up to (4,0).
174
+ console.log(path?.cells.length, path?.cost.toFixed(2)); // 7 6.83
175
+ const field = flowField(grid, [[4, 0]], { diagonal: 'never' });
176
+ console.log(followFlow(field, 0, 2).length); // 7
177
+ ```
178
+
179
+ | Piece | What it does |
180
+ | --- | --- |
181
+ | `findPath(grid, start, goal, options)` | `{cells, cost, searched, scanned}` from start to goal, both cells included, or null when there is no way; `searched` cells were expanded, `scanned` passed over by jumps |
182
+ | `flowField(grid, goals, options)` | `{width, height, distance, next}`: each cell's cost to the nearest goal and its next cell (`y * width + x`, -1 at goals and where none is reached) |
183
+ | `followFlow(field, x, y)` | The cells from (`x`, `y`) along a field to its goal |
184
+ | `tileCosts(map, {layers, property, solid, fallback, empty})` | A cost grid from tile properties: `solid: true` blocks (default property names `'solid'` and `'cost'`), a numeric `cost` sets the price, other tiles cost `fallback` (1), cells with no tile `empty` (`fallback`). A cell takes its highest layer cost |
185
+
186
+ A grid is `{width, height, cost, layout?}`; a step costs the cell it enters times its length, and a cost of 0, below 0
187
+ or Infinity blocks the cell. Options: `diagonal` (`'no-corners'` default: corner steps only when both cells beside them
188
+ are open; `'always'`; `'never'`), `maxCells` (1,000,000) and `jumpPoints` (false).
189
+
190
+ - On staggered and hexagonal maps (`layout` set, as `tileCosts` does) steps go to the cells that share an edge and
191
+ `diagonal` does not apply; orthogonal and isometric maps step along rows and columns.
192
+ - A* estimates with the octile (or hex) distance times the lowest cost on the grid, so paths are cheapest ones; equal
193
+ ones are broken by the order cells were found, the same every run.
194
+ - `jumpPoints: true` runs jump point search (Harabor and Grastien, "Online Graph Pruning for Pathfinding on Grid
195
+ Maps", AAAI 2011, https://doi.org/10.1609/aaai.v25i1.7994, with the no-corner-cutting rules of their "Improving Jump
196
+ Point Search", ICAPS 2014, https://doi.org/10.1609/icaps.v24i1.13633) where it is exact: an orthogonal or isometric
197
+ grid whose open cells all cost the same, with `diagonal: 'no-corners'`. Elsewhere `findPath` is plain A* and returns
198
+ the same result as without it. From each expanded cell the search runs straight and diagonally until a cell where a
199
+ cheapest path may turn, and queues only those. Costs equal plain A*'s (600 random walled grids in
200
+ `test/path.test.js`); where several paths tie the cells may differ. Across an open 200 x 200 grid it expands 3 cells
201
+ against plain A*'s 9,679 (scanning 40,479), and past a wall across the room 6 against 27,208 (scanning 40,449).
202
+
203
+ ```js
204
+ import { findPath } from 'margoengine/tilemap/path';
205
+ const width = 200, height = 200;
206
+ const cost = new Float64Array(width * height).fill(1);
207
+ for (let y = 11; y < height; y++) cost[y * width + 100] = Infinity; // a wall with a gap at the top
208
+ const grid = { width, height, cost };
209
+ const plain = findPath(grid, [10, 190], [190, 190])!;
210
+ const jump = findPath(grid, [10, 190], [190, 190], { jumpPoints: true })!;
211
+ console.log(plain.cost.toFixed(2), jump.cost.toFixed(2)); // 435.73 435.73
212
+ console.log(plain.searched, jump.searched); // 27208 6
213
+ ```
214
+
215
+ - Both run on the calling thread and allocate a few arrays of the grid's size per call.
216
+
217
+ ### Replanning as the map changes
218
+
219
+ `margoengine/tilemap/replan` keeps a search to one goal alive, for a unit that finds walls on its way or a map the
220
+ player edits. Change `grid.cost`, tell `update` which cells changed and ask for the path again: the cost is the one a
221
+ fresh `findPath` would give, and only the cells the change can matter to are expanded. It is D* Lite (Koenig and
222
+ Likhachev, "D* Lite", AAAI 2002, https://cdn.aaai.org/AAAI/2002/AAAI02-072.pdf, the optimized version).
223
+
224
+ ```js
225
+ import { findPath } from 'margoengine/tilemap/path';
226
+ import { PathReplanner } from 'margoengine/tilemap/replan';
227
+ const width = 200, height = 200;
228
+ const cost = new Float64Array(width * height).fill(1);
229
+ for (let y = 11; y < height; y++) cost[y * width + 100] = Infinity; // a wall with a gap at the top
230
+ const grid = { width, height, cost };
231
+ const plan = new PathReplanner(grid, [190, 190]);
232
+ const first = plan.findPath([10, 190])!;
233
+ console.log(first.cost.toFixed(2), first.searched); // 435.73 27046
234
+ const [x, y] = first.cells[5]; // a wall appears ahead of the unit
235
+ cost[y * width + x] = Infinity;
236
+ const next = plan.update([[x, y]]).findPath(first.cells[4])!;
237
+ console.log(next.searched, findPath(grid, first.cells[4], [190, 190])!.searched); // 92 27207
238
+ ```
239
+
240
+ | Piece | What it does |
241
+ | --- | --- |
242
+ | `new PathReplanner(grid, goal, {diagonal, maxCells, minCost})` | A replanner for one goal over a `CostGrid`, square or hexagonal. `maxCells` (1,000,000) limits one call, and the next call carries on. `minCost` (default the lowest cost at the start) is the lowest cost a cell will ever have; a change below it starts the search afresh |
243
+ | `update(cells)` | Names every cell whose cost changed since the last call, as `[x, y]` pairs |
244
+ | `findPath(start)` | `{cells, cost, searched, scanned}` from `start` to the goal, or null; `searched` counts the cells this call expanded |
245
+
246
+ - The first call costs about what A* costs. Later calls are cheap when the changes are near the unit; a change near the
247
+ goal that touches most cells' distances can cost more than a fresh search.
248
+ - It holds about 40 bytes a cell for as long as it lives. One goal each: use `flowField` for many units to one place on
249
+ a map that does not change.
250
+
251
+ ### Long paths on large maps
252
+
253
+ `margoengine/tilemap/hpa` cuts the grid into clusters and searches a small graph of the steps between them, then fills
254
+ in only the clusters the path crosses. Build it once and ask it many times. It follows HPA* (Botea, Mueller and
255
+ Schaeffer, "Near Optimal Hierarchical Path-Finding", Journal of Game Development 1(1), 2004,
256
+ https://webdocs.cs.ualberta.ca/~mmueller/ps/hpastar.pdf), with its own choice of transitions, which gives a bound.
257
+
258
+ ```js
259
+ import { findPath } from 'margoengine/tilemap/path';
260
+ import { PathHierarchy } from 'margoengine/tilemap/hpa';
261
+ const width = 200, height = 200;
262
+ const cost = new Float64Array(width * height).fill(1);
263
+ for (let y = 11; y < height; y++) cost[y * width + 100] = Infinity;
264
+ const grid = { width, height, cost };
265
+ const graph = new PathHierarchy(grid); // clusters of 16, detour 3
266
+ const full = findPath(grid, [10, 190], [190, 190])!;
267
+ const path = graph.findPath([10, 190], [190, 190])!;
268
+ console.log(path.cost.toFixed(2), path.searched, full.searched); // 435.73 4503 27208
269
+ cost[5 * width + 100] = Infinity; // a change rebuilds the clusters around it
270
+ graph.update([[100, 5]]);
271
+ console.log(graph.findPath([10, 190], [190, 190]) !== null); // true
272
+ ```
273
+
274
+ | Piece | What it does |
275
+ | --- | --- |
276
+ | `new PathHierarchy(grid, {diagonal, maxCells, cluster, detour})` | The graph of a `CostGrid`, square or hexagonal. `cluster` (16) is a cluster's side; `detour` (3) is how many steps a border crossing may lie from a transition, 0 for every crossing |
277
+ | `findPath(start, goal, {smooth})` | `{cells, cost, searched, scanned}` or null. `smooth` (true) searches the path again in short stretches and keeps what is cheaper |
278
+ | `update(cells)` | Names every changed cell; the clusters around them are rebuilt before the next query |
279
+ | `nodes` | The graph's nodes as cells, for drawing it and judging its size |
280
+
281
+ - A path is found whenever one exists.
282
+ - The cost is exactly the cheapest with `detour: 0`. Otherwise it is above the cheapest by at most
283
+ `(2 * detour + 1) * L * highest` for each cluster border a cheapest path crosses, where `highest` is the dearest open
284
+ cell and `L` is sqrt(2) with corner steps, 1 without them and on hexagonal and staggered maps. Typical paths are far
285
+ closer: 200 long queries on a 256 x 256 map with one cell in five walled cost 0.6% more in total than the cheapest
286
+ (the worst 3.5% more) and expanded 438,469 cells and nodes against A*'s 964,285.
287
+ - Building searches each cluster once from each of its nodes, so it costs more than one query; a larger `detour` makes
288
+ fewer nodes (on that map 9,382 at 0, 4,022 at 3).
289
+
290
+ ## Field of view and fog of war
291
+
292
+ `margoengine/tilemap/fov` works out which cells a viewer sees by shadowcasting, and `FogOfWar` keeps what is seen now
293
+ apart from what was seen before, for strategy maps and dungeon crawlers. Which tiles block sight comes from their
294
+ `opaque: true` property with `tileOpacity`, or from any array.
295
+
296
+ ```ts
297
+ import { createTileLayer, type TileMapData } from 'margoengine/tilemap';
298
+ import { FOG_EXPLORED, FogOfWar, fieldOfView, tileOpacity } from 'margoengine/tilemap/fov';
299
+
300
+ const map: TileMapData = {
301
+ width: 7, height: 5, tileWidth: 16, tileHeight: 16,
302
+ tilesets: [{ name: 'dungeon', firstGid: 1, tileWidth: 16, tileHeight: 16, tileCount: 2, columns: 2,
303
+ tiles: [{ id: 1, properties: { opaque: true } }] }],
304
+ // Floor (1) with one pillar (2) at (2, 2).
305
+ layers: [createTileLayer('ground', 7, 5, new Uint32Array(35).map((_, i) => (i === 16 ? 2 : 1)))],
306
+ };
307
+ const sight = tileOpacity(map);
308
+ const seen = fieldOfView(sight, 0, 2);
309
+ // The pillar's shadow widens behind it: (3, 2) to (6, 2), and (5, 1), (6, 1), (5, 3), (6, 3) at its edges.
310
+ console.log(seen.reduce((n, v) => n + v, 0)); // 27
311
+ const fog = new FogOfWar(sight);
312
+ fog.update([{ x: 0, y: 2, radius: 3 }]).update([{ x: 6, y: 2, radius: 3 }]);
313
+ console.log(fog.state(0, 2) === FOG_EXPLORED); // true
314
+ const { width, height, data } = fog.image(); // one RGBA pixel per cell, to stretch over the map as a fog texture
315
+ ```
316
+
317
+ | Piece | What it does |
318
+ | --- | --- |
319
+ | `fieldOfView(grid, x, y, {radius, into})` | A `width * height` mask, 1 where the viewer at (`x`, `y`) sees the cell; `into` adds the cells to a mask you pass, to join viewers |
320
+ | `FogOfWar(grid, explored?)` | `update(viewers)` refreshes `visible` from `{x, y, radius?}` viewers and adds it to `explored`; `state(x, y)` is `FOG_VISIBLE`, `FOG_EXPLORED` or `FOG_UNSEEN`; `image(colors)` gives RGBA per cell (default unseen black, explored black at alpha 128, visible clear) |
321
+ | `tileOpacity(map, {layers, property})` | A sight grid from tile properties: a cell blocks when any of its tiles has `opaque: true` (`property`, default `'opaque'`) |
322
+
323
+ A grid is `{width, height, opaque, orientation?}`. Sight lines leave the centre of the viewer's cell and walls are whole
324
+ squares: a cell is seen when a fan of sight lines wider than a point reaches it, blocking cells that are reached are
325
+ seen too, and two walls that touch at a corner close the gap between them. `radius` (default Infinity) keeps the cells
326
+ whose centre is within it.
327
+
328
+ - Orthogonal and isometric maps only; staggered and hexagonal grids are refused.
329
+ - Sight is not symmetric: a cell seen from here may not see back, because sight starts at a centre and ends anywhere in
330
+ a cell.
331
+ - `FogOfWar` reads `grid.opaque` on every `update`, so changing it (an opened door) counts on the next one. Save
332
+ `explored` and pass it back to the constructor to restore a game.
333
+
334
+ ## Auto-tiling
335
+
336
+ `margoengine/tilemap/autotile` picks the tile for each cell from its neighbours with rule sets written as data: 16 tiles for the four edge neighbours (`cardinal`), or 47 for all eight (`blob`; corners count only when both edges beside them are filled). Terrain sets match the terrain at a tile's four corners instead. Both are deterministic.
337
+
338
+ ```ts
339
+ import {autotileGrid, BLOB_MASKS} from 'margoengine/tilemap/autotile';
340
+ const filled = [1, 1, 0, 1, 1, 1, 0, 1, 1]; // 3 x 3, 1 = ground
341
+ const tiles = BLOB_MASKS.map((_, i) => i); // tile id for each of the 47 cases
342
+ const cells = autotileGrid(filled, 3, 3, {mode: 'blob', tiles}, {firstGid: 1});
343
+ console.log(cells.length); // 9 global tile values, 0 where nothing is drawn
344
+ ```
345
+
346
+ `autotile(layer, rules)` does the same on a `TileLayer`; `resolveTerrain(vertices, width, height, set)` and `verticesFromCells` handle corner terrain.
347
+
348
+ ## Tiled import
349
+
350
+ `margoengine/tilemap/tiled` reads a Tiled map saved as JSON (`.tmj`, or `.json`) into `TileMapData`. It takes the text, UTF-8 bytes or the parsed object. Tile layers may be CSV (an array), base64, or base64 with zlib or gzip compression; infinite maps are joined into one layer per Tiled layer; group layers pass their offset, opacity, visibility and parallax to their children. An external tileset (`.tsj`) is loaded through `options.resolve`, which receives the path written in the map. Image layers, text and object templates are skipped with a call to `onWarning`. Isometric, staggered and hexagonal maps keep their `orientation`, `staggerAxis`, `staggerIndex` and `hexSideLength`, and hexagonal ones keep Tiled's 120 degree turn bit (`HEX_ROTATE_120`); oblique maps and infinite maps that are not orthogonal are refused.
351
+
352
+ ```ts
353
+ import { parseTiled } from 'margoengine/tilemap/tiled';
354
+ const map = await parseTiled({
355
+ orientation: 'orthogonal', width: 2, height: 1, tilewidth: 16, tileheight: 16,
356
+ tilesets: [{ firstgid: 1, name: 'grass', tilewidth: 16, tileheight: 16, tilecount: 2, columns: 2, image: 'grass.png', imagewidth: 32, imageheight: 16 }],
357
+ layers: [{ type: 'tilelayer', name: 'ground', width: 2, height: 1, data: [1, 2] }],
358
+ });
359
+ console.log(map.layers[0].type); // 'tile'
360
+ ```
361
+
362
+ Bad input throws a `MapImportError` with a `code` (`syntax`, `truncated`, `missing`, `unsupported`, `limit` or `aborted`) and a message that names the fix; a compressed layer cannot expand past its declared size, and a layer past 16,777,216 cells is refused. `fromTMX(map)` converts what `parseTMX` of `margoengine/loaders` returns into the same `TileMapData`. Pass `signal` to stop an import.
363
+
364
+ ## LDtk import
365
+
366
+ `margoengine/tilemap/ldtk` reads an LDtk project saved as JSON (`.ldtk`). It takes the text, UTF-8 bytes or the parsed object and returns each level of every world as a `TileMapData` with its entities, IntGrid values and fields.
367
+
368
+ ```ts
369
+ import { parseLDtk } from 'margoengine/tilemap/ldtk';
370
+ const project = parseLDtk({
371
+ jsonVersion: '1.5.3',
372
+ defs: { tilesets: [{ uid: 1, identifier: 'Grass', relPath: 'grass.png', pxWid: 32, pxHei: 16, tileGridSize: 16, __cWid: 2, __cHei: 1 }] },
373
+ levels: [{ identifier: 'Start', pxWid: 32, pxHei: 16, layerInstances: [
374
+ { __identifier: 'Ground', __type: 'Tiles', __gridSize: 16, __tilesetDefUid: 1, gridTiles: [{ px: [16, 0], t: 1, f: 0 }] },
375
+ ] }],
376
+ });
377
+ console.log(project.levels[0].map.layers[0].type); // 'tile'
378
+ ```
379
+
380
+ Layers come back to front, with `__opacity`, `visible` and the total pixel offset. A cell holds one tile, so tiles LDtk rules stack on one cell become extra layers named `Ground#2`, `Ground#3`. When layers have different grids the map's tile size is their common divisor. Entity layers become object layers, and `entities` lists each one with its pivot, tags and fields. `.ldtkl` separate level files are refused with a `MapImportError` (the same codes as Tiled); off-grid tiles and tiles with their own alpha go through `onWarning`. Pass `signal` to stop an import.
381
+
382
+ Apache-2.0. Optional, tree-shakable package; core peer: ^1.0.0.
383
+
384
+ Build and unit tests: npm test --workspace @margoengine/tilemap
385
+
386
+ ## Film time
387
+
388
+ `TileMap`, `GridTileMap` and `ObjectTileMap` move their tile animation clock (`time`, in milliseconds) with `advanceTime(delta)` in the frame update, so `seek` from `@margoengine/cutscene/seek` starts a film scene on the tile frames a continuous run shows.