@margoengine/tilemap 0.0.0-stage → 0.1.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,294 @@
1
- # Temporary Holding Version
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.
1
+ # @margoengine/tilemap
2
+
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}` from start to goal, both cells included, or null when there is no way |
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'`) and `maxCells` (1,000,000).
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
+ - Both run on the calling thread and allocate a few arrays of the grid's size per call.
195
+
196
+ ## Field of view and fog of war
197
+
198
+ `margoengine/tilemap/fov` works out which cells a viewer sees by shadowcasting, and `FogOfWar` keeps what is seen now
199
+ apart from what was seen before, for strategy maps and dungeon crawlers. Which tiles block sight comes from their
200
+ `opaque: true` property with `tileOpacity`, or from any array.
201
+
202
+ ```ts
203
+ import { createTileLayer, type TileMapData } from 'margoengine/tilemap';
204
+ import { FOG_EXPLORED, FogOfWar, fieldOfView, tileOpacity } from 'margoengine/tilemap/fov';
205
+
206
+ const map: TileMapData = {
207
+ width: 7, height: 5, tileWidth: 16, tileHeight: 16,
208
+ tilesets: [{ name: 'dungeon', firstGid: 1, tileWidth: 16, tileHeight: 16, tileCount: 2, columns: 2,
209
+ tiles: [{ id: 1, properties: { opaque: true } }] }],
210
+ // Floor (1) with one pillar (2) at (2, 2).
211
+ layers: [createTileLayer('ground', 7, 5, new Uint32Array(35).map((_, i) => (i === 16 ? 2 : 1)))],
212
+ };
213
+ const sight = tileOpacity(map);
214
+ const seen = fieldOfView(sight, 0, 2);
215
+ // The pillar's shadow widens behind it: (3, 2) to (6, 2), and (5, 1), (6, 1), (5, 3), (6, 3) at its edges.
216
+ console.log(seen.reduce((n, v) => n + v, 0)); // 27
217
+ const fog = new FogOfWar(sight);
218
+ fog.update([{ x: 0, y: 2, radius: 3 }]).update([{ x: 6, y: 2, radius: 3 }]);
219
+ console.log(fog.state(0, 2) === FOG_EXPLORED); // true
220
+ const { width, height, data } = fog.image(); // one RGBA pixel per cell, to stretch over the map as a fog texture
221
+ ```
222
+
223
+ | Piece | What it does |
224
+ | --- | --- |
225
+ | `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 |
226
+ | `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) |
227
+ | `tileOpacity(map, {layers, property})` | A sight grid from tile properties: a cell blocks when any of its tiles has `opaque: true` (`property`, default `'opaque'`) |
228
+
229
+ A grid is `{width, height, opaque, orientation?}`. Sight lines leave the centre of the viewer's cell and walls are whole
230
+ squares: a cell is seen when a fan of sight lines wider than a point reaches it, blocking cells that are reached are
231
+ seen too, and two walls that touch at a corner close the gap between them. `radius` (default Infinity) keeps the cells
232
+ whose centre is within it.
233
+
234
+ - Orthogonal and isometric maps only; staggered and hexagonal grids are refused.
235
+ - Sight is not symmetric: a cell seen from here may not see back, because sight starts at a centre and ends anywhere in
236
+ a cell.
237
+ - `FogOfWar` reads `grid.opaque` on every `update`, so changing it (an opened door) counts on the next one. Save
238
+ `explored` and pass it back to the constructor to restore a game.
239
+
240
+ ## Auto-tiling
241
+
242
+ `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.
243
+
244
+ ```ts
245
+ import {autotileGrid, BLOB_MASKS} from 'margoengine/tilemap/autotile';
246
+ const filled = [1, 1, 0, 1, 1, 1, 0, 1, 1]; // 3 x 3, 1 = ground
247
+ const tiles = BLOB_MASKS.map((_, i) => i); // tile id for each of the 47 cases
248
+ const cells = autotileGrid(filled, 3, 3, {mode: 'blob', tiles}, {firstGid: 1});
249
+ console.log(cells.length); // 9 global tile values, 0 where nothing is drawn
250
+ ```
251
+
252
+ `autotile(layer, rules)` does the same on a `TileLayer`; `resolveTerrain(vertices, width, height, set)` and `verticesFromCells` handle corner terrain.
253
+
254
+ ## Tiled import
255
+
256
+ `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.
257
+
258
+ ```ts
259
+ import { parseTiled } from 'margoengine/tilemap/tiled';
260
+ const map = await parseTiled({
261
+ orientation: 'orthogonal', width: 2, height: 1, tilewidth: 16, tileheight: 16,
262
+ tilesets: [{ firstgid: 1, name: 'grass', tilewidth: 16, tileheight: 16, tilecount: 2, columns: 2, image: 'grass.png', imagewidth: 32, imageheight: 16 }],
263
+ layers: [{ type: 'tilelayer', name: 'ground', width: 2, height: 1, data: [1, 2] }],
264
+ });
265
+ console.log(map.layers[0].type); // 'tile'
266
+ ```
267
+
268
+ 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.
269
+
270
+ ## LDtk import
271
+
272
+ `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.
273
+
274
+ ```ts
275
+ import { parseLDtk } from 'margoengine/tilemap/ldtk';
276
+ const project = parseLDtk({
277
+ jsonVersion: '1.5.3',
278
+ defs: { tilesets: [{ uid: 1, identifier: 'Grass', relPath: 'grass.png', pxWid: 32, pxHei: 16, tileGridSize: 16, __cWid: 2, __cHei: 1 }] },
279
+ levels: [{ identifier: 'Start', pxWid: 32, pxHei: 16, layerInstances: [
280
+ { __identifier: 'Ground', __type: 'Tiles', __gridSize: 16, __tilesetDefUid: 1, gridTiles: [{ px: [16, 0], t: 1, f: 0 }] },
281
+ ] }],
282
+ });
283
+ console.log(project.levels[0].map.layers[0].type); // 'tile'
284
+ ```
285
+
286
+ 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.
287
+
288
+ Apache-2.0. Optional, tree-shakable package; core peer: ^1.0.0.
289
+
290
+ Build and unit tests: npm test --workspace @margoengine/tilemap
291
+
292
+ ## Film time
293
+
294
+ `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.
@@ -0,0 +1,105 @@
1
+ import { type TileLayer, type Properties } from './index.js';
2
+ /** Tiled Wang colour metadata. Array index plus one is the colour id; zero means no terrain. */
3
+ export interface WangColor {
4
+ readonly name: string;
5
+ readonly color: string;
6
+ readonly tile: number;
7
+ readonly probability: number;
8
+ readonly properties?: Properties;
9
+ }
10
+ /** Edge/corner colours clockwise: N, NE, E, SE, S, SW, W, NW. */
11
+ export interface WangTile {
12
+ readonly tile: number;
13
+ readonly colors: readonly [number, number, number, number, number, number, number, number];
14
+ readonly weight?: number;
15
+ /** Global-id flip bits carried by older Tiled Wang entries. Default zero. */
16
+ readonly flags?: number;
17
+ }
18
+ /** Imported Wang rules, including multi-colour edge, corner and mixed sets. */
19
+ export interface WangRuleSet {
20
+ readonly mode: 'wang';
21
+ readonly name: string;
22
+ readonly type: 'edge' | 'corner' | 'mixed';
23
+ readonly colors: readonly WangColor[];
24
+ readonly tiles: readonly WangTile[];
25
+ readonly properties?: Properties;
26
+ }
27
+ /** Shared lattice values make neighbouring Wang cells agree on edges and corners. */
28
+ export interface WangGrid {
29
+ /** (width + 1) * (height + 1) corner colours. Missing means unconstrained. -1 is a wildcard. */
30
+ readonly vertices?: ArrayLike<number>;
31
+ /** width * (height + 1) horizontal edges, row-major. */
32
+ readonly horizontal?: ArrayLike<number>;
33
+ /** (width + 1) * height vertical edges, row-major. */
34
+ readonly vertical?: ArrayLike<number>;
35
+ }
36
+ /** Match imported Wang rules against a shared lattice, with seeded weighted variants. Unmatched cells are zero. */
37
+ export declare function resolveWang(grid: WangGrid, width: number, height: number, set: WangRuleSet, options?: TerrainOptions): Uint32Array;
38
+ /** The 47 distinct blob masks, ascending. Bits: N 1, NE 2, E 4, SE 8, S 16, SW 32, W 64, NW 128. */
39
+ export declare const BLOB_MASKS: readonly number[];
40
+ /** Bitmask of the four edge neighbours: N 1, E 2, S 4, W 8. Any truthy argument counts as filled. */
41
+ export declare function cardinalMask(n: unknown, e: unknown, s: unknown, w: unknown): number;
42
+ /**
43
+ * Bitmask of all eight neighbours for blob tiling, reduced: a corner only counts when both edges beside it are
44
+ * filled, so the 256 raw cases collapse to the 47 values in `BLOB_MASKS`. Bits: N 1, NE 2, E 4, SE 8, S 16, SW 32, W 64, NW 128.
45
+ */
46
+ export declare function blobMask(n: unknown, ne: unknown, e: unknown, se: unknown, s: unknown, sw: unknown, w: unknown, nw: unknown): number;
47
+ /** Position of a reduced blob mask in `BLOB_MASKS` (0..46). Throws a RangeError for a mask that is not reduced. */
48
+ export declare function blobIndex(mask: number): number;
49
+ /**
50
+ * Tile choices as data. `cardinal`: 16 tiles indexed by `cardinalMask`. `blob`: 47 tiles in `BLOB_MASKS` order.
51
+ * `tiles` hold tile ids local to the tileset.
52
+ */
53
+ export interface AutotileRuleSet {
54
+ readonly mode: 'cardinal' | 'blob';
55
+ readonly tiles: readonly number[];
56
+ }
57
+ /** Options of `autotileGrid` and `autotile`. */
58
+ export interface AutotileOptions {
59
+ /** Global id of the tileset's first tile, added to each rule tile. Default 1. */
60
+ readonly firstGid?: number;
61
+ /** Whether cells beyond the map edge count as filled (the terrain continues off the map). Default false. */
62
+ readonly outside?: boolean;
63
+ }
64
+ /**
65
+ * Pick a tile for every filled cell of a `width x height` grid from the filled neighbours. Returns global tile
66
+ * values, 0 where the grid is empty. The same input always gives the same output.
67
+ */
68
+ export declare function autotileGrid(filled: ArrayLike<unknown>, width: number, height: number, rules: AutotileRuleSet, options?: AutotileOptions): Uint32Array;
69
+ /**
70
+ * Auto-tile a tile layer: cells that `matches` (default: any tile) get the tile their neighbours call for, other
71
+ * cells are copied unchanged. Returns a new layer.
72
+ */
73
+ export declare function autotile(layer: TileLayer, rules: AutotileRuleSet, options?: AutotileOptions & {
74
+ readonly matches?: (value: number) => boolean;
75
+ }): TileLayer;
76
+ /** A tile for terrain matching: terrain ids at its corners, top left, top right, bottom right, bottom left. */
77
+ export interface TerrainTile {
78
+ /** Tile id local to the tileset. */
79
+ readonly tile: number;
80
+ readonly corners: readonly [number, number, number, number];
81
+ /** Chance weight among tiles with the same corners. Default 1. */
82
+ readonly weight?: number;
83
+ }
84
+ /** Tiles tagged by the terrain at their corners. */
85
+ export interface TerrainSet {
86
+ readonly tiles: readonly TerrainTile[];
87
+ }
88
+ /** Options of `resolveTerrain`. */
89
+ export interface TerrainOptions {
90
+ /** Global id of the tileset's first tile. Default 1. */
91
+ readonly firstGid?: number;
92
+ /** Changes which of several matching tiles is picked; the same seed always gives the same map. Default 0. */
93
+ readonly seed?: number;
94
+ }
95
+ /**
96
+ * Pick the tile whose four corners equal the terrain at the four corners of each cell. `vertices` is the
97
+ * `(width + 1) x (height + 1)` grid of corner terrain ids. Cells no tile matches stay 0. Several matches are
98
+ * chosen by weight with a hash of the cell and seed, so the result is deterministic.
99
+ */
100
+ export declare function resolveTerrain(vertices: ArrayLike<number>, width: number, height: number, set: TerrainSet, options?: TerrainOptions): Uint32Array;
101
+ /**
102
+ * Corner terrain from painted cells: each corner takes the highest terrain id among the cells that touch it, so
103
+ * 0 (nothing) loses to any terrain. Returns the `(width + 1) x (height + 1)` grid for `resolveTerrain`.
104
+ */
105
+ export declare function verticesFromCells(cells: ArrayLike<number>, width: number, height: number): Uint8Array;