Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(tilemap): a tile layer can be dug, blown up and rebuilt while the game runs

yhhecfed0c448a4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5c9291ff3..e6bf2942f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,10 +14,20 @@ published separately; it ships inside the editor.
## [Unreleased]
+### Added
+
+- **A tile layer can be dug, blown up and rebuilt while the game runs.** `createDestructibleTilemap` in `esengine/tilemap` gives a layer tiles with hardness that wear down over several blows, circular explosions with falloff that walls can shelter from, and placing and filling, with one list of what changed for drops and effects. The neighbouring autotiles re-resolve, `createNavGrid` or `syncNavGrid` keeps a navigation grid in step one cell at a time, and `toJSON` and `load` save only the cells that differ from the map it started as, refusing a damaged save whole. On a streamed world, `publishChunk` lays a player's changes over what the generator made, so a chunk let go and made again comes back as it was left.
+- **Solid tile ground can have colliders only where it is exposed.** `TilemapRuntime.setCollisionOutline` generates plain boxes for tiles with an open side, so solid ground costs no bodies and a tunnel below a surface leaves the surface's colliders alone. A destructible layer turns it on; `collisionOutline: false` keeps merged ground.
+
### Changed
+- **Editing a tile no longer replaces the colliders around it.** A tile edit used to destroy and remake every collider in its chunk, which ended a body's contact with the floor it stood on and woke what was asleep there. Now only the colliders whose shape changed are replaced.
- **A row of tiles being edited uploads a piece of itself.** One changed tile re-uploaded its whole row of chunks, over a megabyte when the row is full. A row that changes is now held in pieces of four chunks, so an edit uploads about an eighth of that, for up to seven more draws in that row until it has rested. A static map is drawn as before.
+### Fixed
+
+- **A tile's custom properties in an `.estileset` reach the game.** `getTileProperty` answered nothing on a layer painted from an `.estileset`; only Tiled maps carried them. Replacing a tileset blanks the properties of the old one.
+
## [0.100.0] - 2026-11-08
### Added
diff --git a/docs/astro/src/content/docs/gameplay/ai/navigation.mdx b/docs/astro/src/content/docs/gameplay/ai/navigation.mdx
index 4f91e9103..efc14ac49 100644
--- a/docs/astro/src/content/docs/gameplay/ai/navigation.mdx
+++ b/docs/astro/src/content/docs/gameplay/ai/navigation.mdx
@@ -44,7 +44,8 @@ export const setupNav = defineSystem([Res(Nav)], (nav) => {
To derive a grid from a painted tilemap instead of hand-authoring the mask, use
`navGridFromTilemapLayer` (which cells a layer's solid tiles block) or
`navGridFromTiles`. `grid.setWalkable(x, y, false)` closes a cell at any time — a
-door shuts, a tower goes up — and the next plan routes around it.
+door shuts, a tower goes up — and the next plan routes around it. A
+[destructible tilemap](/docs/world/tilemaps/#destructible-tilemaps) keeps a grid in step with what is dug and built by itself.
A route over a grid is **string-pulled** before it is handed back: A\* answers in
steps of one cell, and only the cells where the route actually has to turn survive.
diff --git a/docs/astro/src/content/docs/world/tilemaps.mdx b/docs/astro/src/content/docs/world/tilemaps.mdx
index 1f456bdfd..ca8de9168 100644
--- a/docs/astro/src/content/docs/world/tilemaps.mdx
+++ b/docs/astro/src/content/docs/world/tilemaps.mdx
@@ -351,6 +351,51 @@ queries](#tilemaps-api-reference) as any painted layer — `isTileSolid`,
`tileCollisionAt`, `tileCollisionAtWorld` — so nothing downstream needs to know the
cells came from the built-in palette.
+## Destructible tilemaps
+
+`setTile` changes a cell. A sandbox, mining or survival game needs more to follow it: tiles that take several blows, explosions, edges that re-tile, routes that
+change, and a save that remembers it all. `createDestructibleTilemap` opens any layer to that. The layer stays an ordinary layer.
+
+```typescript
+import { createDestructibleTilemap, peeringRetile } from 'esengine/tilemap';
+
+const ground = createDestructibleTilemap(app, layer, {
+ hardness: id => (id === BEDROCK ? Infinity : 3), // or a `hardness` property on the tile
+ replaceWith: id => (id === STONE ? RUBBLE : 0), // what a destroyed tile leaves
+ retile: peeringRetile(tileset), // neighbours re-resolve their edges
+});
+
+ground.dig(x, y, 1); // one blow: { damage, hardness, destroyed }
+ground.digAtWorld(wx, wy); // by world position; no power means any hardness
+ground.explode(wx, wy, 64, 10, { shielded: true }); // radius in world units, then force
+ground.set(x, y, BRICK); // build; also setMany and fillRect
+ground.subscribe(edits => { /* drops, dust, light: every change of one operation */ });
+```
+
+| What changes | How it follows |
+|---|---|
+| **Drawing** | The chunk's mesh is rebuilt. A row of chunks being edited is held in pieces of four, so a dug tile uploads one piece rather than the whole row; the row becomes one draw again 1800 collects after its last change. |
+| **Collision** | Only colliders whose shape actually changed are replaced, so a body resting on the rest sees no contact end and stays asleep. A destroyed floor wakes what stood on it. |
+| **Autotiles** | `retile` runs over the changed cells and their eight neighbours. `peeringRetile` answers edge and corner terrains; a Wang terrain paints corner colours, so a game using one gives its own function. |
+| **Navigation** | `ground.createNavGrid({ width, height })` places a grid where the layer is drawn and keeps it in step, one cell per change; agents plan again by themselves. `syncNavGrid(grid)` does the same for a grid you made. A tile blocks by the layer's collision, a sensor does not. |
+
+**Collision outline.** A destructible layer generates its plain boxes for exposed tiles only: a tile with a plain box on all four sides has none. Solid ground costs no bodies, and a tunnel dug
+below the surface leaves the surface's colliders alone. Nothing stops a body placed inside the ground, since the shell is all there is. Pass `collisionOutline: false`
+to keep merged ground, or call `TilemapRuntime.setCollisionOutline(layer, on)` for any layer. It applies to orthogonal layers; other orientations keep their merged boxes.
+
+**Saves.** `toJSON()` holds only the cells that differ from the map the layer started as, and the damage standing on any other, so its size follows what the player changed and not what the
+map holds. It is plain JSON for [`SaveManager`](/docs/scripting/save/). `load()` puts this session's changes back first, restores the save exactly without re-tiling, and refuses a damaged save whole, returning `false`.
+
+**Streamed worlds.** Pass `streamed: true` and publish chunks through the layer instead of `setChunkTiles`. What the generator made is laid under the player's changes,
+so a chunk let go and made again comes back as it was left, and a save loaded before a chunk arrives waits for it:
+
+```typescript
+ground.publishChunk(cx, cy, generatedTiles);
+ground.releaseChunk(cx, cy);
+```
+
+A chunk not yet published is not empty ground: nothing can be dug or written there.
+
## Object layers
Tiled **object layers** (spawn points, triggers, region shapes) load with the map. The
diff --git a/docs/astro/src/content/docs/zh-cn/gameplay/ai/navigation.mdx b/docs/astro/src/content/docs/zh-cn/gameplay/ai/navigation.mdx
index 47473cff7..88520df45 100644
--- a/docs/astro/src/content/docs/zh-cn/gameplay/ai/navigation.mdx
+++ b/docs/astro/src/content/docs/zh-cn/gameplay/ai/navigation.mdx
@@ -42,7 +42,7 @@ export const setupNav = defineSystem([Res(Nav)], (nav) => {
若想从已绘制的瓦片地图推导网格,而不是手写掩码,用 `navGridFromTilemapLayer`(把某图层的
实心瓦片视作阻挡)或 `navGridFromTiles`。`grid.setWalkable(x, y, false)` 随时可以关掉一格
-——门关上了、塔造起来了——下一次规划就会绕开它。
+——门关上了、塔造起来了——下一次规划就会绕开它。[可破坏瓦片地图](/docs/zh-cn/world/tilemaps/#可破坏瓦片地图)会让网格自动跟上挖掉和建起的东西。
格子上的路线在交出去之前会先**拉直**:A\* 是一格一步作答的,只有路线真正需要转弯的那些格
留了下来。抄近道只走搜索本身能走的线——线经过的每一格都容得下这个身体,而对角线要求它
diff --git a/docs/astro/src/content/docs/zh-cn/world/tilemaps.mdx b/docs/astro/src/content/docs/zh-cn/world/tilemaps.mdx
index 39a7a7e41..78d4eebb4 100644
--- a/docs/astro/src/content/docs/zh-cn/world/tilemaps.mdx
+++ b/docs/astro/src/content/docs/zh-cn/world/tilemaps.mdx
@@ -299,6 +299,49 @@ Tiled 地图享受同等待遇:在 **Tiled 瓦片碰撞编辑器** 里画的形
游戏代码通过与任意绘制层相同的[碰撞查询](#tilemaps-api-参考)读取碰撞层——`isTileSolid`、
`tileCollisionAt`、`tileCollisionAtWorld`——所以下游完全不必知道这些格子来自内置调色板。
+## 可破坏瓦片地图
+
+`setTile` 只改一格。沙盒、采矿、生存类游戏还需要后面跟着变的东西:要敲几下才碎的瓦片、爆炸、重新拼接的边缘、会变的路线,以及记得这一切的存档。`createDestructibleTilemap`
+能把任意图层开放给这些操作,图层本身仍是普通图层。
+
+```typescript
+import { createDestructibleTilemap, peeringRetile } from 'esengine/tilemap';
+
+const ground = createDestructibleTilemap(app, layer, {
+ hardness: id => (id === BEDROCK ? Infinity : 3), // 也可以写在瓦片的 `hardness` 属性上
+ replaceWith: id => (id === STONE ? RUBBLE : 0), // 瓦片碎掉后留下什么
+ retile: peeringRetile(tileset), // 邻居重新解析边缘
+});
+
+ground.dig(x, y, 1); // 敲一下:{ damage, hardness, destroyed }
+ground.digAtWorld(wx, wy); // 按世界坐标;不给力度就是敲碎任何硬度
+ground.explode(wx, wy, 64, 10, { shielded: true }); // 半径(世界单位),然后是力度
+ground.set(x, y, BRICK); // 建造;还有 setMany 和 fillRect
+ground.subscribe(edits => { /* 掉落物、尘土、光照:一次操作的全部改动 */ });
+```
+
+| 改动的是 | 如何跟上 |
+|---|---|
+| **绘制** | 重建该分块的网格。正在被改动的一行分块按每四块一段持有,挖一格只上传一段而不是整行;这一行最后一次改动的 1800 次收集之后,会变回一次绘制。 |
+| **碰撞** | 只替换形状真正变了的碰撞体,所以停在其余部分上的刚体不会收到接触结束,也继续睡眠。地板被毁时,站在上面的东西会被唤醒。 |
+| **自动拼接** | `retile` 会跑过改动的格子和它们的八个邻居。`peeringRetile` 负责边 / 角地形;Wang 地形绘制的是角颜色,所以用它的游戏要给自己的函数。 |
+| **导航** | `ground.createNavGrid({ width, height })` 把网格放在图层绘制的位置并保持同步,每次改动只翻对应的一格;代理会自己重新规划。`syncNavGrid(grid)` 对你自己建的网格做同样的事。瓦片是否阻挡看图层的碰撞,传感器不阻挡。 |
+
+**碰撞轮廓。** 可破坏图层只为露在外面的瓦片生成普通方块碰撞体:四边都被普通方块盖住的瓦片没有碰撞体。实心地面不占刚体,在地表下挖隧道也不会动到地表的碰撞体。因为只有这层壳,放进地面内部的刚体
+不会被挡住。传 `collisionOutline: false` 可以保留合并的实心碰撞体,也可以对任意图层调用 `TilemapRuntime.setCollisionOutline(layer, on)`。只对正交图层生效,其他朝向保持合并碰撞体。
+
+**存档。** `toJSON()` 只保存与图层初始地图不同的格子,以及其他格子上累积的伤害,所以大小取决于玩家改了多少,而不是地图有多大。它是普通 JSON,可以直接交给
+[`SaveManager`](/docs/zh-cn/scripting/save/)。`load()` 会先还原本次会话的改动,再原样恢复存档(不重新拼接);损坏的存档会被整份拒绝,返回 `false`。
+
+**流式世界。** 传 `streamed: true`,并通过它发布分块,而不是直接调用 `setChunkTiles`。生成器做出的内容垫在玩家的改动下面,所以分块放掉再重新生成后仍是离开时的样子,在分块到达前载入的存档也会等它:
+
+```typescript
+ground.publishChunk(cx, cy, generatedTiles);
+ground.releaseChunk(cx, cy);
+```
+
+还没发布的分块不是空地:那里挖不了也写不进去。
+
## 对象层
Tiled 的**对象层**(出生点、触发器、区域形状)随地图一起加载。现代的读法是
diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.json
index b8fa137da..3ff7150ac 100644
--- a/docs/astro/src/data/apiStability.generated.json
+++ b/docs/astro/src/data/apiStability.generated.json
@@ -3,10 +3,10 @@
"counts": {
"public": 115,
"beta": 176,
- "experimental": 2863,
+ "experimental": 2875,
"deprecated": 3
},
- "total": 3154,
+ "total": 3166,
"subsystems": [
{
"id": "mobile-controls",
diff --git a/sdk/etc/tilemap.api.md b/sdk/etc/tilemap.api.md
index 89a7e576d..7fef90a9a 100644
--- a/sdk/etc/tilemap.api.md
+++ b/sdk/etc/tilemap.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/tilemap
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 0 public · 5 beta · 141 experimental · 0 deprecated
+Symbols: 0 public · 5 beta · 153 experimental · 0 deprecated
## BuildNavGridOptions — interface @experimental
```
@@ -69,6 +69,47 @@ x: number
y: number
```
+## DestructibleTilemap — class @experimental
+```
+changedCells: number
+createNavGrid: (opts: TileNavGridOptions) => NavGrid
+damageAt: (x: number, y: number) => number
+dig: (x: number, y: number, power?: number) => TileHit | null
+digAtWorld: (worldX: number, worldY: number, power?: number) => TileHit | null
+dispose: () => void
+explode: (worldX: number, worldY: number, radius: number, power: number, opts?: TileExplosionOptions) => TileHit[]
+fillRect: (x: number, y: number, width: number, height: number, tile: number) => readonly TileEdit[]
+layer: number
+load: (data: DestructibleTilemapData) => boolean
+publishChunk: (chunkX: number, chunkY: number, tiles: Uint16Array) => void
+releaseChunk: (chunkX: number, chunkY: number) => void
+set: (x: number, y: number, tile: number) => boolean
+setMany: (cells: Iterable<{ x: number; y: number; tile: number; }>) => readonly TileEdit[]
+subscribe: (listener: (edits: readonly TileEdit[]) => void) => () => void
+syncNavGrid: (grid: NavGrid, opts?: TileNavSyncOptions) => () => void
+tileAt: (x: number, y: number) => number
+toJSON: () => DestructibleTilemapData
+worldToTile: (worldX: number, worldY: number) => { x: number; y: number; }
+static new (app: App, layer: Entity, options: DestructibleTilemapOptions): DestructibleTilemap
+static prototype: DestructibleTilemap
+```
+
+## DestructibleTilemapData — interface @experimental
+```
+chunks: { x: number; y: number; cells: number[]; damage?: number[]; }[]
+encoding: number[]
+version: 1
+```
+
+## DestructibleTilemapOptions — interface @experimental
+```
+collisionOutline: boolean | undefined
+hardness: number | ((tileId: number) => number) | undefined
+replaceWith: ((tileId: number) => number) | undefined
+retile: TileRetile | undefined
+streamed: boolean | undefined
+```
+
## LayerCollisionTable — interface @experimental
```
boxIds: ReadonlySet<number>
@@ -263,6 +304,26 @@ sensor: boolean
| { type: 'circle'; cx: number; cy: number; r: number }
```
+## TileEdit — interface @experimental
+```
+after: number
+before: number
+cause: TileEditCause
+x: number
+y: number
+```
+
+## TileEditCause — type @experimental
+```
+'set' | 'dig' | 'explode' | 'retile' | 'load'
+```
+
+## TileExplosionOptions — interface @experimental
+```
+falloff: number | undefined
+shielded: boolean | undefined
+```
+
## TileFlags — interface @experimental
```
flipD: boolean
@@ -285,6 +346,37 @@ tileHeight: number
tileWidth: number
```
+## TileHit — interface @experimental
+```
+damage: number
+destroyed: boolean
+hardness: number
+tile: number
+x: number
+y: number
+```
+
+## TileNavGridOptions — interface @experimental
+```
+height: number
+isBlocked: ((tileId: number) => boolean) | undefined
+tileX: number | undefined
+tileY: number | undefined
+width: number
+```
+
+## TileNavSyncOptions — interface @experimental
+```
+isBlocked: ((tileId: number) => boolean) | undefined
+tileX: number | undefined
+tileY: number | undefined
+```
+
+## TileRetile — type @experimental
+```
+(x: number, y: number, read: (x: number, y: number) => number) => number | undefined
+```
+
## TileStamp — interface @experimental
```
cells: number[]
@@ -455,6 +547,7 @@ static prototype: TilemapPlugin
dispose: () => void
install: (app: App) => void
resetLayers: () => void
+setCollisionOutline: (entity: number, outline: boolean) => void
setLayerTilesets: (entity: number, refs: readonly string[]) => void
static new (): TilemapRuntime
static prototype: TilemapRuntime
@@ -517,6 +610,7 @@ TileCollisionShape & {
animations: Map<number, { tileId: number; duration: number; }[]>
collidableTileIds: number[]
slots: TilesetModelSlot[]
+tileProperties: Map<number, Record<string, string>> | undefined
tileShapes: Map<number, ResolvedTileCollision>
```
@@ -606,6 +700,11 @@ tileTerrain: Map<number, number>
(material: CollisionMaterial): string
```
+## createDestructibleTilemap — function @experimental
+```
+(app: App, layer: Entity, options?: DestructibleTilemapOptions): DestructibleTilemap
+```
+
## createTileset — function @experimental
```
(texture: string, tileWidth?: number, tileHeight?: number, columns?: number): TilesetAsset
@@ -781,6 +880,11 @@ tileTerrain: Map<number, number>
(json: Record<string, unknown>, resolveExternal: (source: string) => Promise<string>): Promise<TiledMapData | null>
```
+## peeringRetile — function @experimental
+```
+(asset: TilesetAsset, firstId?: number): TileRetile
+```
+
## polygonLocalVerts — function @experimental
```
(norm: ReadonlyArray<readonly [number, number]>, tileW: number, tileH: number, flipH: boolean, flipV: boolean, flipD: boolean): { x: number; y: number; }[]
diff --git a/sdk/src/tilemap/chunkCodec.ts b/sdk/src/tilemap/chunkCodec.ts
index db41ac897..71e4e9675 100644
--- a/sdk/src/tilemap/chunkCodec.ts
+++ b/sdk/src/tilemap/chunkCodec.ts
@@ -42,8 +42,9 @@ const V1_HEADER_BYTES = 8;
* One cell from one encoding into another: the id it holds and the three flags
* it carries, at the positions this reader uses. -1 where the id does not FIT a
* narrowed mask — the only honest answers there are the tile or a refusal.
+ * `from` is `[chunkSize, idMask, flipH, flipV, flipD]`.
*/
-function recodeCell(word: number, from: number[]): number {
+export function recodeCell(word: number, from: readonly number[]): number {
const id = word & from[1]!;
if (id > TILE_ID_MASK) return -1;
let next = id;
diff --git a/sdk/src/tilemap/destructibleTilemap.ts b/sdk/src/tilemap/destructibleTilemap.ts
new file mode 100644
index 000000000..90979415c
--- /dev/null
+++ b/sdk/src/tilemap/destructibleTilemap.ts
@@ -0,0 +1,542 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file destructibleTilemap.ts
+ * @brief A tile layer a game can change while it runs: digging, explosions, placing, and all that has to follow them.
+ *
+ * @details Every change goes through one write, so the drawn tiles, the collision (which follows the native edit revision by itself), the neighbouring autotiles,
+ * the navigation grids and the save can never disagree about a cell. What a save stores is the difference from the map the layer started as, kept
+ * by chunk, so a large world costs what was changed in it rather than what it holds, and a chunk streamed out and made again comes back as it was left.
+ */
+import type { App } from '../app/app';
+import { NavGrid } from '../ai/nav/NavGrid';
+import { TilemapLayer, Transform, type TilemapLayerData } from '../ecs/component';
+import { log } from '../util/logger';
+import type { Entity } from '../types';
+import { CHUNK_SIZE, recodeCell } from './chunkCodec';
+import { buildTerrainIndices, resolveAutotileMatch, TERRAIN_NEIGHBORS } from './autotile';
+import { tileIdOf, TILE_FLIP_D, TILE_FLIP_H, TILE_FLIP_V, TILE_ID_MASK } from './tileBits';
+import { tileCellCenter, TilemapOrientation, type TileGridParams } from './tileGeometry';
+import { tileCollisionTable } from './tileQuery';
+import { Tilemaps, type TilemapToolkit } from './tilemapAPI';
+import { TilemapRuntimeState } from './tilemapPlugin';
+import type { TilesetAsset } from './tilesetAsset';
+
+/** What made a cell change. @experimental */
+export type TileEditCause = 'set' | 'dig' | 'explode' | 'retile' | 'load';
+
+/** One cell's change. `before` and `after` are raw cells: tile id and flip flags. @experimental */
+export interface TileEdit { x: number; y: number; before: number; after: number; cause: TileEditCause }
+
+/** What a blow did to one cell. @experimental */
+export interface TileHit {
+ x: number;
+ y: number;
+ /** The raw cell the blow landed on. */
+ tile: number;
+ /** Damage the cell has taken, after this blow. 0 once it is destroyed. */
+ damage: number;
+ hardness: number;
+ destroyed: boolean;
+}
+
+/** A cell's new look, or undefined to leave it. `read` answers any cell's raw value. @experimental */
+export type TileRetile = (x: number, y: number, read: (x: number, y: number) => number) => number | undefined;
+
+/** @experimental */
+export interface DestructibleTilemapOptions {
+ /**
+ * Damage a tile takes to destroy, by tile id; `Infinity` cannot be destroyed. Defaults to the tile's `hardness` property
+ * (from the `.estileset`, or Tiled), and 1 where it has none. Answers are remembered per tile id.
+ */
+ hardness?: number | ((tileId: number) => number);
+ /** The cell a destroyed tile leaves, by tile id: rubble, a back wall. Defaults to empty. */
+ replaceWith?: (tileId: number) => number;
+ /** Keeps edges right around every change. See {@link peeringRetile}. */
+ retile?: TileRetile;
+ /** Generate colliders for exposed tiles only (see `TilemapRuntime.setCollisionOutline`). Defaults to on. */
+ collisionOutline?: boolean;
+ /** The layer's chunks come from {@link DestructibleTilemap.publishChunk}, so a chunk not yet published is not empty ground: nothing is written to it. */
+ streamed?: boolean;
+}
+
+/** @experimental */
+export interface TileExplosionOptions {
+ /** How much weaker the rim is than the centre, 0 (flat) to 1 (nothing at the rim). Defaults to 1. */
+ falloff?: number;
+ /** Tiles on the way absorb the blast by their hardness, and one that cannot be destroyed stops it. Defaults to off. */
+ shielded?: boolean;
+}
+
+/** @experimental */
+export interface TileNavSyncOptions {
+ /** The tile the grid's top-left cell stands on. Defaults to (0, 0). */
+ tileX?: number;
+ tileY?: number;
+ /** Whether a tile id blocks. Defaults to the layer's collision (a sensor does not block), or any tile where it has none. */
+ isBlocked?: (tileId: number) => boolean;
+}
+
+/** @experimental */
+export interface TileNavGridOptions extends TileNavSyncOptions {
+ width: number;
+ height: number;
+}
+
+/** A layer's changes, as a save stores them. Plain JSON. @experimental */
+export interface DestructibleTilemapData {
+ version: 1;
+ /** `[chunkSize, idMask, flipH, flipV, flipD]` the cells were written under. A later engine recodes them. */
+ encoding: number[];
+ /** `cells` and `damage` are flat `[cellIndex, value, ...]` pairs. */
+ chunks: { x: number; y: number; cells: number[]; damage?: number[] }[];
+}
+
+interface CellChange { before: number | null; now: number }
+interface ChunkState { x: number; y: number; cells: Map<number, CellChange>; damage: Map<number, number> }
+interface NavBinding { grid: NavGrid; tileX: number; tileY: number; isBlocked: (tileId: number) => boolean }
+
+const chunkOf = (v: number): number => Math.floor(v / CHUNK_SIZE);
+const cellOf = (x: number, y: number): number =>
+ (y - chunkOf(y) * CHUNK_SIZE) * CHUNK_SIZE + (x - chunkOf(x) * CHUNK_SIZE);
+const ENCODING = [CHUNK_SIZE, TILE_ID_MASK, TILE_FLIP_H, TILE_FLIP_V, TILE_FLIP_D];
+
+/** One layer open to digging, explosions and building. Make one with {@link createDestructibleTilemap}. @experimental */
+export class DestructibleTilemap {
+ private readonly tiles_: TilemapToolkit;
+ private readonly chunks_ = new Map<string, ChunkState>();
+ private readonly hardness_ = new Map<number, number>();
+ private readonly listeners_ = new Set<(edits: readonly TileEdit[]) => void>();
+ private readonly navs_: NavBinding[] = [];
+ private readonly resident_: Set<string> | null;
+
+ /** @internal */
+ constructor(private readonly app: App, readonly layer: Entity, private readonly options: DestructibleTilemapOptions) {
+ this.tiles_ = app.getResource(Tilemaps);
+ this.resident_ = options.streamed ? new Set() : null;
+ if (options.collisionOutline !== false && app.hasResource(TilemapRuntimeState)) {
+ app.getResource(TilemapRuntimeState).setCollisionOutline(layer, true);
+ }
+ }
+
+ /** Told every operation's changes together, once it has finished. The returned function stops listening. */
+ subscribe(listener: (edits: readonly TileEdit[]) => void): () => void {
+ this.listeners_.add(listener);
+ return () => { this.listeners_.delete(listener); };
+ }
+
+ /** The raw cell, flip flags included. */
+ tileAt(x: number, y: number): number { return this.tiles_.getTile(this.layer, x, y); }
+
+ /** Damage the cell's tile has taken so far. */
+ damageAt(x: number, y: number): number {
+ return this.chunks_.get(`${chunkOf(x)},${chunkOf(y)}`)?.damage.get(cellOf(x, y)) ?? 0;
+ }
+
+ /** How many cells differ from the map the layer started as. */
+ get changedCells(): number {
+ let n = 0;
+ for (const chunk of this.chunks_.values()) n += chunk.cells.size;
+ return n;
+ }
+
+ /** The cell under a world position, through the layer's origin, rotation and grid. */
+ worldToTile(worldX: number, worldY: number): { x: number; y: number } {
+ const local = this.toLocal_(worldX, worldY), t = this.tiles_.worldToTile(this.layer, local.x, local.y, 0, 0);
+ return { x: Math.floor(t.x), y: Math.floor(t.y) };
+ }
+
+ /** Puts a raw cell down (0 clears it). Says whether anything changed. */
+ set(x: number, y: number, tile: number): boolean {
+ return this.setMany([{ x, y, tile }]).length > 0;
+ }
+
+ /** Changes many cells as one operation: autotiles settle and listeners hear once. Returns every change, autotile ones included. */
+ setMany(cells: Iterable<{ x: number; y: number; tile: number }>): readonly TileEdit[] {
+ const edits: TileEdit[] = [];
+ for (const { x, y, tile } of cells) this.write_(x, y, tile, 'set', edits);
+ return this.finish_(edits);
+ }
+
+ fillRect(x: number, y: number, width: number, height: number, tile: number): readonly TileEdit[] {
+ const edits: TileEdit[] = [];
+ for (let ty = y; ty < y + height; ty++) for (let tx = x; tx < x + width; tx++) this.write_(tx, ty, tile, 'set', edits);
+ return this.finish_(edits);
+ }
+
+ /** Lands a blow on one cell. Null when there is nothing to hit: an empty cell, or a tile that cannot be destroyed. */
+ dig(x: number, y: number, power = Infinity): TileHit | null {
+ const edits: TileEdit[] = [];
+ const hit = this.hit_(x, y, power, 'dig', edits);
+ this.finish_(edits);
+ return hit;
+ }
+
+ digAtWorld(worldX: number, worldY: number, power = Infinity): TileHit | null {
+ const t = this.worldToTile(worldX, worldY);
+ return this.dig(t.x, t.y, power);
+ }
+
+ /**
+ * Blasts a circle around a world position, `radius` in world units, measured from cell centres whatever the layer's orientation.
+ * Every cell it reached comes back, destroyed or only damaged.
+ */
+ explode(worldX: number, worldY: number, radius: number, power: number, opts: TileExplosionOptions = {}): TileHit[] {
+ if (!(radius > 0) || !(power > 0)) return [];
+ const falloff = Math.min(1, Math.max(0, opts.falloff ?? 1));
+ const centre = this.toLocal_(worldX, worldY), grid = this.grid_();
+ const corner = (dx: number, dy: number) => this.tiles_.worldToTile(this.layer, centre.x + dx, centre.y + dy, 0, 0);
+ const corners = [corner(-radius, -radius), corner(radius, -radius), corner(radius, radius), corner(-radius, radius)];
+ const x0 = Math.floor(Math.min(...corners.map(c => c.x))) - 1, x1 = Math.ceil(Math.max(...corners.map(c => c.x))) + 1;
+ const y0 = Math.floor(Math.min(...corners.map(c => c.y))) - 1, y1 = Math.ceil(Math.max(...corners.map(c => c.y))) + 1;
+ const origin = corner(0, 0), ox = Math.floor(origin.x), oy = Math.floor(origin.y);
+ // Every blow is worked out before any lands, so a cell's shelter is what stood when the blast began; the rays cross the same cells again and again.
+ const standing = new Map<string, number>();
+ const stood = (x: number, y: number): number => {
+ const key = `${x},${y}`;
+ let raw = standing.get(key);
+ if (raw === undefined) { raw = this.tileAt(x, y); standing.set(key, raw); }
+ return raw;
+ };
+ const blows: { x: number; y: number; amount: number }[] = [];
+ for (let y = y0; y <= y1; y++) for (let x = x0; x <= x1; x++) {
+ if (tileIdOf(stood(x, y)) === 0) continue;
+ const c = tileCellCenter(grid, x, y), distance = Math.hypot(c.x - centre.x, c.y - centre.y);
+ if (distance > radius) continue;
+ let amount = power * (1 - falloff * (distance / radius));
+ if (opts.shielded) amount -= this.shelter_(ox, oy, x, y, stood);
+ if (amount > 0) blows.push({ x, y, amount });
+ }
+ const edits: TileEdit[] = [], hits: TileHit[] = [];
+ for (const blow of blows) {
+ const hit = this.hit_(blow.x, blow.y, blow.amount, 'explode', edits);
+ if (hit) hits.push(hit);
+ }
+ this.finish_(edits);
+ return hits;
+ }
+
+ /**
+ * Keeps `grid` matching the layer from now on: it is brought up to date here, and each later change flips only its own cell,
+ * which is what sends agents to plan again. The returned function stops it.
+ */
+ syncNavGrid(grid: NavGrid, opts: TileNavSyncOptions = {}): () => void {
+ const binding: NavBinding = { grid, tileX: opts.tileX ?? 0, tileY: opts.tileY ?? 0, isBlocked: opts.isBlocked ?? this.defaultBlocked_() };
+ this.navs_.push(binding);
+ for (let gy = 0; gy < grid.height; gy++) for (let gx = 0; gx < grid.width; gx++) {
+ const x = binding.tileX + gx, y = binding.tileY + grid.height - 1 - gy;
+ grid.setWalkable(gx, gy, !binding.isBlocked(tileIdOf(this.tileAt(x, y))));
+ }
+ return () => { const i = this.navs_.indexOf(binding); if (i >= 0) this.navs_.splice(i, 1); };
+ }
+
+ /** A grid over a rectangle of this layer, already placed where the layer is drawn and kept in step. Needs an orthogonal, unrotated layer with square cells. */
+ createNavGrid(opts: TileNavGridOptions): NavGrid {
+ const data = this.data_(), rotated = this.rotation_() !== 0;
+ if (rotated || (data.orientation ?? 0) !== TilemapOrientation.Orthogonal || data.cellSize.x !== data.cellSize.y) {
+ throw new Error('createNavGrid needs an orthogonal, unrotated tile layer with square cells');
+ }
+ const tileX = opts.tileX ?? 0, tileY = opts.tileY ?? 0;
+ this.app.world.ensureTransformsComposed();
+ const at = this.app.world.get(this.layer, Transform).worldPosition;
+ const bottomLeft = tileCellCenter(this.grid_(), tileX, tileY + opts.height - 1);
+ const grid = new NavGrid({
+ width: opts.width, height: opts.height, cellSize: data.cellSize.x,
+ origin: { x: at.x + data.originOffset.x + bottomLeft.x, y: at.y + data.originOffset.y + bottomLeft.y, z: at.z },
+ });
+ this.syncNavGrid(grid, opts);
+ return grid;
+ }
+
+ /**
+ * Shows one chunk of a streamed layer: what the generator made, with this layer's changes laid over it. `tiles` is the chunk's whole
+ * row-major array and is not kept.
+ */
+ publishChunk(chunkX: number, chunkY: number, tiles: Uint16Array): void {
+ const merged = tiles.slice(), state = this.chunks_.get(`${chunkX},${chunkY}`);
+ for (const [cell, change] of state?.cells ?? []) {
+ change.before = tiles[cell] ?? 0;
+ if (change.before === change.now) state!.cells.delete(cell);
+ else merged[cell] = change.now;
+ }
+ if (state) this.prune_(state);
+ this.tiles_.setChunkTiles(this.layer, chunkX, chunkY, merged, CHUNK_SIZE, CHUNK_SIZE);
+ this.resident_?.add(`${chunkX},${chunkY}`);
+ for (let i = 0; i < merged.length; i++) {
+ this.syncNav_(chunkX * CHUNK_SIZE + (i % CHUNK_SIZE), chunkY * CHUNK_SIZE + Math.floor(i / CHUNK_SIZE), merged[i]!);
+ }
+ }
+
+ /** Lets one chunk go. Its changes are kept for when it is published again. */
+ releaseChunk(chunkX: number, chunkY: number): void {
+ this.resident_?.delete(`${chunkX},${chunkY}`);
+ this.tiles_.removeChunk(this.layer, chunkX, chunkY);
+ }
+
+ /** What a save stores: only the cells that changed and the damage standing on them. */
+ toJSON(): DestructibleTilemapData {
+ const chunks = [...this.chunks_.values()].sort((a, b) => a.y - b.y || a.x - b.x).map(({ x, y, cells, damage }) => {
+ const flat: number[] = [];
+ for (const cell of [...cells.keys()].sort((a, b) => a - b)) flat.push(cell, cells.get(cell)!.now);
+ const out: DestructibleTilemapData['chunks'][number] = { x, y, cells: flat };
+ if (damage.size > 0) {
+ out.damage = [];
+ for (const cell of [...damage.keys()].sort((a, b) => a - b)) out.damage.push(cell, damage.get(cell)!);
+ }
+ return out;
+ });
+ return { version: 1, encoding: ENCODING.slice(), chunks };
+ }
+
+ /**
+ * Replaces every change with a save's: what this session changed goes back first, so loading twice is loading once.
+ * A save that does not read is refused whole, with `false` and the layer untouched.
+ */
+ load(data: DestructibleTilemapData): boolean {
+ const decoded = decodeSave(data);
+ if (!decoded) {
+ log.error('tilemap', 'a destructible tilemap save was refused: it is damaged, or was written under an encoding that cannot hold its tiles.');
+ return false;
+ }
+ const edits: TileEdit[] = [];
+ for (const chunk of [...this.chunks_.values()]) {
+ if (!this.isResident_(chunk.x, chunk.y)) continue;
+ for (const [cell, change] of chunk.cells) {
+ if (change.before === null) continue;
+ this.write_(chunk.x * CHUNK_SIZE + (cell % CHUNK_SIZE), chunk.y * CHUNK_SIZE + Math.floor(cell / CHUNK_SIZE), change.before, 'load', edits);
+ }
+ }
+ this.chunks_.clear();
+ for (const { x, y, tile, damage } of decoded) {
+ if (tile !== undefined) {
+ if (this.isResident_(chunkOf(x), chunkOf(y))) this.write_(x, y, tile, 'load', edits);
+ else this.state_(chunkOf(x), chunkOf(y)).cells.set(cellOf(x, y), { before: null, now: tile });
+ }
+ if (damage !== undefined) this.state_(chunkOf(x), chunkOf(y)).damage.set(cellOf(x, y), damage);
+ }
+ // A save holds the settled autotiles already, so it is not settled again.
+ this.emit_(edits);
+ return true;
+ }
+
+ /** Stops the grids and listeners. The layer stays as it is. */
+ dispose(): void {
+ this.navs_.length = 0;
+ this.listeners_.clear();
+ }
+
+ private hit_(x: number, y: number, amount: number, cause: TileEditCause, edits: TileEdit[]): TileHit | null {
+ if (!(amount > 0) || !this.isResident_(chunkOf(x), chunkOf(y))) return null;
+ const tile = this.tileAt(x, y), id = tileIdOf(tile);
+ if (id === 0) return null;
+ const hardness = this.hardnessOf_(id, x, y);
+ if (hardness === Infinity) return null;
+ const state = this.chunks_.get(`${chunkOf(x)},${chunkOf(y)}`), cell = cellOf(x, y);
+ const damage = (state?.damage.get(cell) ?? 0) + amount;
+ if (damage < hardness) {
+ this.state_(chunkOf(x), chunkOf(y)).damage.set(cell, damage);
+ return { x, y, tile, damage, hardness, destroyed: false };
+ }
+ this.clearDamage_(x, y);
+ const left = this.options.replaceWith?.(id) ?? 0;
+ // A tile left as itself would never come down, and a hit would report one that did.
+ this.write_(x, y, tileIdOf(left) === id ? 0 : left, cause, edits);
+ return { x, y, tile, damage: 0, hardness, destroyed: true };
+ }
+
+ private write_(x: number, y: number, tile: number, cause: TileEditCause, edits: TileEdit[]): void {
+ if (!this.isResident_(chunkOf(x), chunkOf(y))) return;
+ const before = this.tileAt(x, y);
+ if (before === tile) return;
+ this.tiles_.setTile(this.layer, x, y, tile);
+ // A finite layer drops a write past its edge without a word.
+ if (tile !== 0 && this.tileAt(x, y) !== tile) return;
+ const state = this.state_(chunkOf(x), chunkOf(y)), cell = cellOf(x, y), change = state.cells.get(cell);
+ if (change) {
+ change.now = tile;
+ if (change.before === tile) state.cells.delete(cell);
+ } else {
+ state.cells.set(cell, { before, now: tile });
+ }
+ if (cause !== 'retile' && tileIdOf(before) !== tileIdOf(tile)) state.damage.delete(cell);
+ this.prune_(state);
+ this.syncNav_(x, y, tile);
+ edits.push({ x, y, before, after: tile, cause });
+ }
+
+ /** Settles the autotiles around what changed, then tells the listeners. */
+ private finish_(edits: TileEdit[]): readonly TileEdit[] {
+ const retile = this.options.retile;
+ if (retile && edits.length > 0) {
+ const seen = new Set<string>(), read = (x: number, y: number) => this.tileAt(x, y);
+ for (const { x, y } of edits.slice()) {
+ for (const n of [{ dx: 0, dy: 0 }, ...TERRAIN_NEIGHBORS]) {
+ const cx = x + n.dx, cy = y + n.dy, key = `${cx},${cy}`;
+ if (seen.has(key)) continue;
+ seen.add(key);
+ if (!this.neighbourhoodResident_(cx, cy) || tileIdOf(this.tileAt(cx, cy)) === 0) continue;
+ const next = retile(cx, cy, read);
+ if (next !== undefined) this.write_(cx, cy, next, 'retile', edits);
+ }
+ }
+ }
+ this.emit_(edits);
+ return edits;
+ }
+
+ private emit_(edits: readonly TileEdit[]): void {
+ if (edits.length > 0) for (const listener of [...this.listeners_]) listener(edits);
+ }
+
+ private syncNav_(x: number, y: number, tile: number): void {
+ for (const nav of this.navs_) {
+ const gx = x - nav.tileX, gy = nav.grid.height - 1 - (y - nav.tileY);
+ if (nav.grid.inBounds(gx, gy)) nav.grid.setWalkable(gx, gy, !nav.isBlocked(tileIdOf(tile)));
+ }
+ }
+
+ private defaultBlocked_(): (tileId: number) => boolean {
+ return (id) => {
+ if (id === 0) return false;
+ const table = tileCollisionTable(this.layer);
+ if (!table) return true;
+ return table.boxIds.has(id) || (table.shapes.has(id) && !table.shapes.get(id)!.sensor);
+ };
+ }
+
+ private hardnessOf_(id: number, x: number, y: number): number {
+ const fixed = this.options.hardness;
+ if (typeof fixed === 'number') return fixed;
+ let value = this.hardness_.get(id);
+ if (value === undefined) {
+ const authored = fixed ? fixed(id) : Number(this.tiles_.getTileProperty(this.layer, x, y, 'hardness') || NaN);
+ value = Number.isNaN(authored) ? 1 : authored;
+ this.hardness_.set(id, value);
+ }
+ return value;
+ }
+
+ /** What the tiles between the blast's centre and a cell absorb. A straight run over tile coordinates, the cell itself and the centre excluded. */
+ private shelter_(ox: number, oy: number, x: number, y: number, stood: (x: number, y: number) => number): number {
+ const steps = Math.max(Math.abs(x - ox), Math.abs(y - oy));
+ let absorbed = 0;
+ for (let i = 1; i < steps; i++) {
+ const tx = Math.round(ox + (x - ox) * i / steps), ty = Math.round(oy + (y - oy) * i / steps);
+ const id = tileIdOf(stood(tx, ty));
+ if (id !== 0) absorbed += this.hardnessOf_(id, tx, ty);
+ }
+ return absorbed;
+ }
+
+ private state_(x: number, y: number): ChunkState {
+ const key = `${x},${y}`;
+ let state = this.chunks_.get(key);
+ if (!state) { state = { x, y, cells: new Map(), damage: new Map() }; this.chunks_.set(key, state); }
+ return state;
+ }
+
+ private prune_(state: ChunkState): void {
+ if (state.cells.size === 0 && state.damage.size === 0) this.chunks_.delete(`${state.x},${state.y}`);
+ }
+
+ private clearDamage_(x: number, y: number): void {
+ const state = this.chunks_.get(`${chunkOf(x)},${chunkOf(y)}`);
+ if (state) { state.damage.delete(cellOf(x, y)); this.prune_(state); }
+ }
+
+ private isResident_(chunkX: number, chunkY: number): boolean {
+ return this.resident_ === null || this.resident_.has(`${chunkX},${chunkY}`);
+ }
+
+ /** A cell at the edge of what is loaded cannot tell its neighbours' terrain, so it keeps the look it was generated with. */
+ private neighbourhoodResident_(x: number, y: number): boolean {
+ if (this.resident_ === null) return true;
+ for (let dy = -1; dy <= 1; dy++) for (let dx = -1; dx <= 1; dx++) {
+ if (!this.isResident_(chunkOf(x + dx), chunkOf(y + dy))) return false;
+ }
+ return true;
+ }
+
+ private data_(): TilemapLayerData {
+ return this.app.world.get(this.layer, TilemapLayer) as TilemapLayerData;
+ }
+
+ private grid_(): TileGridParams {
+ const data = this.data_();
+ return {
+ orientation: data.orientation ?? 0, tileWidth: data.cellSize.x, tileHeight: data.cellSize.y,
+ hexSideLength: data.hexSideLength ?? 0, staggerAxisX: data.staggerAxis === 1, staggerIndexEven: data.staggerIndex === 1,
+ };
+ }
+
+ private rotation_(): number {
+ this.app.world.ensureTransformsComposed();
+ const q = this.app.world.get(this.layer, Transform).worldRotation;
+ return 2 * Math.atan2(q.z, q.w);
+ }
+
+ private toLocal_(worldX: number, worldY: number): { x: number; y: number } {
+ this.app.world.ensureTransformsComposed();
+ const transform = this.app.world.get(this.layer, Transform), offset = this.data_().originOffset;
+ const dx = worldX - transform.worldPosition.x, dy = worldY - transform.worldPosition.y;
+ const angle = this.rotation_(), c = Math.cos(angle), s = Math.sin(angle);
+ return { x: dx * c + dy * s - offset.x, y: -dx * s + dy * c - offset.y };
+ }
+}
+
+/** Every saved cell in tile coordinates, under this engine's encoding, or null when any of it does not read. */
+function decodeSave(data: DestructibleTilemapData): { x: number; y: number; tile?: number; damage?: number }[] | null {
+ if (data?.version !== 1 || !Array.isArray(data.encoding) || data.encoding.length !== 5 || !Array.isArray(data.chunks)) return null;
+ const side = data.encoding[0]!;
+ if (!Number.isInteger(side) || side <= 0 || !data.encoding.every(v => Number.isInteger(v) && v >= 0)) return null;
+ const out: { x: number; y: number; tile?: number; damage?: number }[] = [];
+ const read = (chunk: { x: number; y: number }, flat: number[], put: (at: { x: number; y: number }, value: number) => boolean): boolean => {
+ if (flat.length % 2 !== 0) return false;
+ for (let i = 0; i < flat.length; i += 2) {
+ const cell = flat[i]!;
+ if (!Number.isInteger(cell) || cell < 0 || cell >= side * side) return false;
+ if (!put({ x: chunk.x * side + (cell % side), y: chunk.y * side + Math.floor(cell / side) }, flat[i + 1]!)) return false;
+ }
+ return true;
+ };
+ for (const chunk of data.chunks) {
+ if (!Number.isInteger(chunk?.x) || !Number.isInteger(chunk?.y) || !Array.isArray(chunk.cells)) return null;
+ if (!read(chunk, chunk.cells, (at, raw) => {
+ if (!Number.isInteger(raw) || raw < 0 || raw > 0xffff) return false;
+ const tile = recodeCell(raw, data.encoding);
+ if (tile < 0) return false;
+ out.push({ ...at, tile });
+ return true;
+ })) return null;
+ if (chunk.damage !== undefined && (!Array.isArray(chunk.damage) || !read(chunk, chunk.damage, (at, damage) => {
+ if (!(damage > 0) || !Number.isFinite(damage)) return false;
+ out.push({ ...at, damage });
+ return true;
+ }))) return null;
+ }
+ return out;
+}
+
+/**
+ * Opens a tile layer to change at runtime. The layer stays an ordinary layer: draw, collision and queries read it as they always do.
+ * @experimental
+ */
+export function createDestructibleTilemap(app: App, layer: Entity, options: DestructibleTilemapOptions = {}): DestructibleTilemap {
+ return new DestructibleTilemap(app, layer, options);
+}
+
+/**
+ * Autotiling for a tileset's edge and corner terrains: a cell of a terrain takes the tile that matches which neighbours are still that terrain.
+ * Wang terrains paint corner colours rather than peering, so they are the game's to answer with its own {@link TileRetile}.
+ * @experimental
+ */
+export function peeringRetile(asset: TilesetAsset, firstId = 1): TileRetile {
+ const { sets, tileTerrain } = buildTerrainIndices(asset);
+ const setOf = (raw: number) => tileTerrain.get(tileIdOf(raw) - firstId + 1);
+ return (x, y, read) => {
+ const set = setOf(read(x, y)), index = set === undefined ? undefined : sets.get(set);
+ if (!index) return undefined;
+ const tileId = resolveAutotileMatch(index, TERRAIN_NEIGHBORS.map(n => setOf(read(x + n.dx, y + n.dy)) === set)).tileId;
+ return tileId === 0 ? undefined : tileId + firstId - 1;
+ };
+}
diff --git a/sdk/src/tilemap/index.ts b/sdk/src/tilemap/index.ts
index 4a16579e1..0d53fb0ad 100644
--- a/sdk/src/tilemap/index.ts
+++ b/sdk/src/tilemap/index.ts
@@ -16,6 +16,11 @@ export {
type TiledAnimFrame, type TilemapLoadOptions,
} from './tiledLoader';
export { tileCollisionOutlines, type TileCollisionPiece } from './tileCollisionOutline';
+export {
+ DestructibleTilemap, createDestructibleTilemap, peeringRetile,
+ type DestructibleTilemapOptions, type DestructibleTilemapData, type TileEdit, type TileEditCause, type TileHit,
+ type TileExplosionOptions, type TileNavSyncOptions, type TileNavGridOptions, type TileRetile,
+} from './destructibleTilemap';
export {
COLLISION_PALETTE_REF, COLLISION_BRUSHES, isCollisionPaletteRef, buildCollisionPaletteModel,
parseCollisionMaterial, collisionRefWithMaterial,
diff --git a/sdk/src/tilemap/tileQuery.ts b/sdk/src/tilemap/tileQuery.ts
index ac5baceb7..04b921d2c 100644
--- a/sdk/src/tilemap/tileQuery.ts
+++ b/sdk/src/tilemap/tileQuery.ts
@@ -40,6 +40,11 @@ export function _bindTileCollisionLookup(
lookup_ = lookups[lookups.length - 1]?.fn ?? null;
}
+/** @internal A layer's collision vocabulary, or null when it has none (yet). */
+export function tileCollisionTable(layer: number): LayerCollisionTable | null {
+ return lookup_?.(layer) ?? null;
+}
+
const PLAIN_BOX: ResolvedTileCollision = { shape: { type: 'box' } };
/**
diff --git a/sdk/src/tilemap/tiledLoader.ts b/sdk/src/tilemap/tiledLoader.ts
index d318d4b33..376eb00de 100644
--- a/sdk/src/tilemap/tiledLoader.ts
+++ b/sdk/src/tilemap/tiledLoader.ts
@@ -918,17 +918,75 @@ export function generateChunkCollision(
const grid = collisionGrid(tileW, tileH, layout), entities: Entity[] = [];
for (const chunk of chunks) {
const boxes = collisionBoxes(chunk.tiles, CHUNK_SIZE, CHUNK_SIZE, collisionIds, grid, chunk.x * CHUNK_SIZE, chunk.y * CHUNK_SIZE);
- for (const box of boxes) {
- const entity = world.spawn();
- world.insert(entity, Transform, { position: { x: originX + box.center.x, y: originY + box.center.y, z: 0 } });
- world.insert(entity, RigidBody2D, { bodyType: BodyType.Static });
- world.insert(entity, BoxCollider2D, { halfExtents: { x: box.halfExtents.x / pixelsPerUnit, y: box.halfExtents.y / pixelsPerUnit } });
- entities.push(entity);
- }
+ for (const box of boxes) entities.push(spawnCollisionBox(world, box, originX, originY, pixelsPerUnit));
}
return entities;
}
+function spawnCollisionBox(world: World, box: ReturnType<typeof collisionBoxes>[number], originX: number, originY: number, ppu: number): Entity {
+ const entity = world.spawn();
+ world.insert(entity, Transform, { position: { x: originX + box.center.x, y: originY + box.center.y, z: 0 } });
+ world.insert(entity, RigidBody2D, { bodyType: BodyType.Static });
+ world.insert(entity, BoxCollider2D, { halfExtents: { x: box.halfExtents.x / ppu, y: box.halfExtents.y / ppu } });
+ return entity;
+}
+
+/**
+ * The colliders one chunk should carry, by a key that names a collider's shape and place and nothing else. A rebuild keeps every collider whose key survives,
+ * so a body resting on one sees no contact end and nothing sleeping is woken. `boxTiles` is what the plain boxes merge over; the rich shapes always read `chunk.tiles`.
+ * @internal
+ */
+export function chunkColliderPlan(
+ chunk: { x: number; y: number; tiles: Uint16Array }, boxTiles: Uint16Array,
+ boxIds: ReadonlySet<number>, shapes: ReadonlyMap<number, ResolvedTileCollision>,
+ tileW: number, tileH: number, originX: number, originY: number, ppu: number, layout?: TileGridLayout,
+): Map<string, (world: World) => Entity> {
+ const plan = new Map<string, (world: World) => Entity>();
+ const grid = collisionGrid(tileW, tileH, layout), baseX = chunk.x * CHUNK_SIZE, baseY = chunk.y * CHUNK_SIZE;
+ if (boxIds.size > 0) {
+ for (const box of collisionBoxes(boxTiles, CHUNK_SIZE, CHUNK_SIZE, boxIds as Set<number>, grid, baseX, baseY)) {
+ plan.set(`b${box.center.x},${box.center.y},${box.halfExtents.x},${box.halfExtents.y}`,
+ world => spawnCollisionBox(world, box, originX, originY, ppu));
+ }
+ }
+ if (shapes.size > 0) {
+ for (let i = 0; i < chunk.tiles.length; i++) {
+ const raw = chunk.tiles[i]!, rc = shapes.get(tileIdOf(raw));
+ if (!rc) continue;
+ const gx = baseX + (i % CHUNK_SIZE), gy = baseY + Math.floor(i / CHUNK_SIZE);
+ plan.set(`s${i},${raw}`, world => spawnTileShape(world, rc, raw, gx, gy, tileW, tileH, originX, originY, ppu || 1, grid));
+ }
+ }
+ return plan;
+}
+
+/**
+ * A chunk's tiles with its buried plain boxes cleared: a box every side of which another plain box covers can never be touched from outside.
+ * `neighbour` answers the chunks around it, so a chunk edge reads the next chunk's tiles rather than counting as open ground.
+ * @internal
+ */
+export function exposedCollisionTiles(
+ chunk: { x: number; y: number; tiles: Uint16Array }, boxIds: ReadonlySet<number>,
+ neighbour: (chunkX: number, chunkY: number) => Uint16Array | undefined,
+): Uint16Array {
+ const out = chunk.tiles.slice();
+ const covers = (tiles: Uint16Array | undefined, index: number): boolean =>
+ tiles !== undefined && tiles.length > 0 && boxIds.has(tileIdOf(tiles[index]!));
+ const left = neighbour(chunk.x - 1, chunk.y), right = neighbour(chunk.x + 1, chunk.y);
+ const up = neighbour(chunk.x, chunk.y - 1), down = neighbour(chunk.x, chunk.y + 1);
+ const last = CHUNK_SIZE - 1;
+ for (let y = 0; y < CHUNK_SIZE; y++) for (let x = 0; x < CHUNK_SIZE; x++) {
+ const i = y * CHUNK_SIZE + x;
+ if (!boxIds.has(tileIdOf(chunk.tiles[i]!))) continue;
+ const buried = (x > 0 ? covers(chunk.tiles, i - 1) : covers(left, y * CHUNK_SIZE + last))
+ && (x < last ? covers(chunk.tiles, i + 1) : covers(right, y * CHUNK_SIZE))
+ && (y > 0 ? covers(chunk.tiles, i - CHUNK_SIZE) : covers(up, last * CHUNK_SIZE + x))
+ && (y < last ? covers(chunk.tiles, i + CHUNK_SIZE) : covers(down, x));
+ if (buried) out[i] = 0;
+ }
+ return out;
+}
+
/**
* Convert a tile's normalized polygon outline ([0,1], x right / y down) to entity-local
* vertices (origin = cell center, y up), applying the cell's flip flags so the collider
diff --git a/sdk/src/tilemap/tilemapPlugin.ts b/sdk/src/tilemap/tilemapPlugin.ts
index 4bc286aa9..a5a53272f 100644
--- a/sdk/src/tilemap/tilemapPlugin.ts
+++ b/sdk/src/tilemap/tilemapPlugin.ts
@@ -15,7 +15,7 @@ import { isCollisionPaletteRef, buildCollisionPaletteModel, parseCollisionMateri
import { _bindTileCollisionLookup, type LayerCollisionTable } from './tileQuery';
import type { ResolvedTileCollision } from './tilesetResolve';
import {
- generateChunkCollision, generateChunkTileShapes,
+ chunkColliderPlan, exposedCollisionTiles,
spawnObjectRegion, isCollisionObjectGroup, decodeTiledGid, tiledLayerComponent, tiledGridLayout,
} from './tiledLoader';
import { decodeTilemapChunks, type DecodedChunk } from './chunkCodec';
@@ -28,10 +28,11 @@ import { playModeOnly } from '../ecs/env';
import { log } from '../util/logger';
import type { Entity } from '../types';
import type { World } from '../ecs/world';
-import { usesStagger } from './tileGeometry';
+import { TilemapOrientation, usesStagger } from './tileGeometry';
interface CollisionInputs {
+ outline: boolean;
gridKey: string;
originX: number;
originY: number;
@@ -77,7 +78,11 @@ export class TilemapRuntime {
private sourceDerivedFrom_ = new Map<number, LoadedTilemapSource>();
/** tilemap entity → the static collider entities derived from its collidable tiles (play-mode only). */
private collisionEntities_ = new Map<number, Set<Entity>>();
- private collisionChunks_ = new Map<number, Map<string, { chunk: DecodedChunk; entities: Entity[] }>>();
+ private collisionChunks_ = new Map<number, Map<string, { chunk: DecodedChunk; colliders: Map<string, Entity> }>>();
+ /** Layers whose plain boxes are generated for exposed tiles only. */
+ private collisionOutlines_ = new Set<number>();
+ /** Layer → the `.estileset` property keys last pushed per tile, so a swap can blank the old ones. */
+ private appliedTileProperties_ = new Map<number, Map<number, Record<string, string>>>();
/** TilemapLayer entity → its baked collidable tile ids (out-of-band scene data; drives native collision). */
private nativeCollisionIds_ = new Map<number, number[]>();
/** TilemapLayer entity → per-tile rich collision shapes (global id → resolved
@@ -266,6 +271,8 @@ export class TilemapRuntime {
animatedLayers.delete(entity);
this.queryTableCache_.delete(entity);
this.derivedLayers_.delete(entity);
+ this.collisionOutlines_.delete(entity);
+ this.appliedTileProperties_.delete(entity);
}
}
@@ -378,6 +385,7 @@ export class TilemapRuntime {
animatedLayers.add(entity);
}
if (model.animations.size === 0) animatedLayers.delete(entity);
+ this.applyTileProperties_(TilemapAPI, entity, model.tileProperties ?? new Map());
if (model.collidableTileIds.length > 0) {
nativeCollisionIds.set(entity, model.collidableTileIds);
} else {
@@ -653,9 +661,20 @@ export class TilemapRuntime {
}
}
+ /** The native store has no way to forget a property, and an empty value reads the same as none. */
+ private applyTileProperties_(tiles: ReturnType<typeof createTilemapAPI>, entity: number, next: Map<number, Record<string, string>>): void {
+ for (const [tileId, props] of this.appliedTileProperties_.get(entity) ?? []) {
+ for (const key of Object.keys(props)) if (next.get(tileId)?.[key] === undefined) tiles.setTileProperty(entity, tileId, key, '');
+ }
+ for (const [tileId, props] of next) for (const [key, value] of Object.entries(props)) tiles.setTileProperty(entity, tileId, key, value);
+ if (next.size > 0) this.appliedTileProperties_.set(entity, next);
+ else this.appliedTileProperties_.delete(entity);
+ }
+
private syncLayerCollision_(world: World, entity: Entity, layer: TilemapLayerData, ppu: number, playMode: boolean): void {
if (!playMode || !this.toolkit_) return;
const ids = this.nativeCollisionIds_.get(entity), shapes = this.nativeTileShapes_.get(entity);
+ const outline = this.collisionOutlines_.has(entity) && (layer.orientation ?? 0) === TilemapOrientation.Orthogonal;
const hasBoxes = !!ids?.length, hasShapes = !!shapes?.size;
const current = this.collisionEntities_.get(entity);
if (!hasBoxes && !hasShapes) {
@@ -669,7 +688,7 @@ export class TilemapRuntime {
const gridKey = `${layer.orientation ?? 0}|${layer.hexSideLength ?? 0}|${layer.staggerAxis ?? 0}|${layer.staggerIndex ?? 0}`;
const originX = layer.originOffset?.x ?? 0, originY = layer.originOffset?.y ?? 0;
const previous = this.collisionInputs_.get(entity);
- const rebuild = !previous || previous.generation !== generation
+ const rebuild = !previous || previous.generation !== generation || previous.outline !== outline
|| previous.gridKey !== gridKey || previous.width !== layer.cellSize.x || previous.height !== layer.cellSize.y
|| previous.pixelsPerUnit !== ppu || previous.ids !== ids || previous.shapes !== shapes;
const sameContent = previous && generation !== undefined && revision !== undefined
@@ -691,31 +710,48 @@ export class TilemapRuntime {
}
const layout = { orientation: layer.orientation ?? 0, hexSideLength: layer.hexSideLength ?? 0,
staggerAxisX: layer.staggerAxis === 1, staggerIndexEven: layer.staggerIndex === 1 };
- const groups = this.collisionChunks_.get(entity) ?? new Map<string, { chunk: DecodedChunk; entities: Entity[] }>();
- const all = this.collisionEntities_.get(entity) ?? new Set<Entity>(), keys = new Set<string>();
- const remove = (group: { entities: Entity[] }) => {
- for (const collider of group.entities) { all.delete(collider); if (world.valid(collider)) world.despawn(collider); }
- };
- const boxIds = new Set(ids);
- for (const chunk of chunks) {
- const key = `${chunk.x},${chunk.y}`; keys.add(key);
+ const groups = this.collisionChunks_.get(entity) ?? new Map<string, { chunk: DecodedChunk; colliders: Map<string, Entity> }>();
+ const all = this.collisionEntities_.get(entity) ?? new Set<Entity>();
+ const remove = (collider: Entity) => { all.delete(collider); if (world.valid(collider)) world.despawn(collider); };
+ const live = new Map<string, DecodedChunk>(chunks.map(chunk => [`${chunk.x},${chunk.y}`, chunk]));
+ const dirty = new Set<string>();
+ for (const [key, chunk] of live) {
const old = groups.get(key);
if (old && (old.chunk.tiles === chunk.tiles || old.chunk.tiles.length === chunk.tiles.length
&& old.chunk.tiles.every((value, index) => value === chunk.tiles[index]))) continue;
- if (old) remove(old);
- const spawned: Entity[] = [];
- if (hasBoxes) for (const collider of generateChunkCollision(world, [chunk], boxIds, layer.cellSize.x, layer.cellSize.y,
- originX, originY, ppu, layout)) spawned.push(collider);
- if (hasShapes) for (const collider of generateChunkTileShapes(world, [chunk], shapes!, layer.cellSize.x, layer.cellSize.y,
- originX, originY, ppu, layout)) spawned.push(collider);
+ dirty.add(key);
+ }
+ for (const key of groups.keys()) if (!live.has(key)) dirty.add(key);
+ // Whether a chunk's edge tile is buried is the next chunk's answer too.
+ if (outline) for (const key of [...dirty]) {
+ const [x, y] = key.split(',').map(Number) as [number, number];
+ dirty.add(`${x - 1},${y}`); dirty.add(`${x + 1},${y}`); dirty.add(`${x},${y - 1}`); dirty.add(`${x},${y + 1}`);
+ }
+ const boxIds = new Set(hasBoxes ? ids : []), richShapes = hasShapes ? shapes! : new Map<number, ResolvedTileCollision>();
+ for (const key of dirty) {
+ const chunk = live.get(key), old = groups.get(key);
+ if (!chunk) {
+ if (old) { for (const collider of old.colliders.values()) remove(collider); groups.delete(key); }
+ continue;
+ }
+ const boxTiles = outline
+ ? exposedCollisionTiles(chunk, boxIds, (cx, cy) => live.get(`${cx},${cy}`)?.tiles) : chunk.tiles;
+ const plan = chunkColliderPlan(chunk, boxTiles, boxIds, richShapes, layer.cellSize.x, layer.cellSize.y, originX, originY, ppu, layout);
+ const colliders = new Map<string, Entity>(), spawned: Entity[] = [];
+ for (const [shape, collider] of old?.colliders ?? []) {
+ if (plan.has(shape)) colliders.set(shape, collider); else remove(collider);
+ }
+ for (const [shape, spawn] of plan) {
+ if (colliders.has(shape)) continue;
+ const collider = spawn(world);
+ colliders.set(shape, collider); spawned.push(collider); all.add(collider);
+ }
this.attachCollision_(world, entity, spawned);
- for (const collider of spawned) all.add(collider);
- groups.set(key, { chunk, entities: spawned });
+ groups.set(key, { chunk, colliders });
}
- for (const [key, old] of groups) if (!keys.has(key)) { remove(old); groups.delete(key); }
this.collisionChunks_.set(entity, groups);
this.collisionEntities_.set(entity, all);
- this.collisionInputs_.set(entity, { generation, revision, gridKey, originX, originY,
+ this.collisionInputs_.set(entity, { outline, generation, revision, gridKey, originX, originY,
width: layer.cellSize.x, height: layer.cellSize.y, pixelsPerUnit: ppu, ids, shapes, native });
}
@@ -742,7 +778,7 @@ export class TilemapRuntime {
this.derivedLayers_.delete(child);
this.nativeCollisionIds_.delete(child); this.nativeTileShapes_.delete(child);
this.collisionEntities_.delete(child); this.collisionInputs_.delete(child);
- this.collisionChunks_.delete(child);
+ this.collisionChunks_.delete(child); this.collisionOutlines_.delete(child);
this.appliedCellSize_.delete(child); this.appliedGrid_.delete(child);
// An owner despawn cascades to its children; only a component
// removal leaves them alive to clean up here.
@@ -762,6 +798,15 @@ export class TilemapRuntime {
this.applyTilesetRefs_?.(entity, refs);
}
+ /**
+ * Generates a layer's plain boxes for exposed tiles only, so ground dug far below a surface leaves the surface's colliders alone and solid ground costs no bodies.
+ * Nothing stops a body placed inside the ground, since the shell is all there is. Only orthogonal layers follow it.
+ */
+ setCollisionOutline(entity: number, outline: boolean): void {
+ if (outline) this.collisionOutlines_.add(entity);
+ else this.collisionOutlines_.delete(entity);
+ }
+
resetLayers(): void {
for (const entity of this.initializedLayers_) {
this.toolkit_?.destroyLayer(entity);
@@ -777,6 +822,8 @@ export class TilemapRuntime {
this.collisionEntities_.clear();
this.collisionInputs_.clear();
this.collisionChunks_.clear();
+ this.collisionOutlines_.clear();
+ this.appliedTileProperties_.clear();
this.nativeCollisionIds_.clear();
this.nativeTileShapes_.clear();
this.tilesetRefs_.clear();
diff --git a/sdk/src/tilemap/tilesetResolve.ts b/sdk/src/tilemap/tilesetResolve.ts
index 101412d68..afb84ac4f 100644
--- a/sdk/src/tilemap/tilesetResolve.ts
+++ b/sdk/src/tilemap/tilesetResolve.ts
@@ -76,6 +76,8 @@ export interface TilesetModel {
* separate from {@link collidableTileIds} so the fast merge path stays correctness-safe.
*/
tileShapes: Map<number, ResolvedTileCollision>;
+ /** Global tile id → its authored custom properties, as `getTileProperty` answers them. */
+ tileProperties?: Map<number, Record<string, string>>;
}
/** True for a tile the greedy box merge may fuse: a bare solid box, no modifiers. */
@@ -145,6 +147,7 @@ export function resolveTilesetModel(tilesets: ResolvedTileset[]): TilesetModel {
const animations = new Map<number, { tileId: number; duration: number }[]>();
const collidable: number[] = [];
const tileShapes = new Map<number, ResolvedTileCollision>();
+ const tileProperties = new Map<number, Record<string, string>>();
let firstId = 1;
for (const { asset, textureHandle, textureHeight } of tilesets) {
@@ -162,6 +165,7 @@ export function resolveTilesetModel(tilesets: ResolvedTileset[]): TilesetModel {
if (!Number.isInteger(localId) || localId <= 0) continue;
const globalId = firstId + localId - 1;
const tile = asset.tiles[localId];
+ if (tile.properties && Object.keys(tile.properties).length > 0) tileProperties.set(globalId, tile.properties);
if (tile.collision) {
// Plain solid boxes greedy-merge; everything richer spawns per-tile.
if (isPlainBox(tile.collision)) collidable.push(globalId);
@@ -182,5 +186,5 @@ export function resolveTilesetModel(tilesets: ResolvedTileset[]): TilesetModel {
}
collidable.sort((a, b) => a - b);
- return { slots, animations, collidableTileIds: collidable, tileShapes };
+ return { slots, animations, collidableTileIds: collidable, tileShapes, tileProperties };
}
diff --git a/sdk/tests/destructible-tilemap-wasm.test.ts b/sdk/tests/destructible-tilemap-wasm.test.ts
new file mode 100644
index 000000000..c47463e31
--- /dev/null
+++ b/sdk/tests/destructible-tilemap-wasm.test.ts
@@ -0,0 +1,614 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
+import { App } from '../src/app/app';
+import { Transform, TilemapLayer, Parent } from '../src/ecs/component';
+import { TilemapPlugin, TilemapRuntimeState } from '../src/tilemap/tilemapPlugin';
+import { Tilemaps } from '../src/tilemap/tilemapAPI';
+import { createDestructibleTilemap, peeringRetile, type DestructibleTilemapOptions } from '../src/tilemap/destructibleTilemap';
+import { CHUNK_SIZE } from '../src/tilemap/chunkCodec';
+import { TILE_FLIP_H } from '../src/tilemap/tileBits';
+import { tileCellCenter } from '../src/tilemap/tileGeometry';
+import { createTileset } from '../src/tilemap/tilesetAsset';
+import { resolveTilesetModel } from '../src/tilemap/tilesetResolve';
+import { Physics2DPlugin, Physics2DEvents } from '../src/physics/Physics2DPlugin';
+import { Physics2DRuntime } from '../src/physics/Physics2DRuntime';
+import { RigidBody2D, BoxCollider2D, BodyType } from '../src/physics/PhysicsComponents';
+import { NavPlugin } from '../src/ai/nav/NavPlugin';
+import { Nav } from '../src/ai/nav/Navigation';
+import { NavAgent } from '../src/ai/nav/NavAgent';
+import { navGridFromTilemapLayer } from '../src/tilemap/navGridFromTilemap';
+import type { ESEngineModule } from '../src/wasm';
+import type { PhysicsWasmModule } from '../src/physics/PhysicsModuleLoader';
+import { HAS_WASM, hasSideModule, loadSideModule, loadWasmModule } from './helpers/loadWasm';
+
+let core: ESEngineModule;
+const apps: App[] = [];
+afterEach(() => { for (const app of apps.splice(0)) app.quit(); vi.restoreAllMocks(); });
+
+function bare() {
+ core.setActiveContext(null);
+ const app = App.new(); apps.push(app); app.connectCpp(new core.Registry(), core, { ownedRegistry: true });
+ app.addPlugin(new TilemapPlugin());
+ const world = app.world, layer = world.spawn(), tiles = app.getResource(Tilemaps);
+ world.insert(layer, Transform); world.insert(layer, TilemapLayer, { cellSize: { x: 16, y: 16 } });
+ // Layers live in the core by entity id, and an id comes round again in the next world.
+ tiles.destroyLayer(layer);
+ tiles.initInfiniteLayer(layer, 16, 16);
+ const open = (options: DestructibleTilemapOptions = {}) => createDestructibleTilemap(app, layer, options);
+ return { app, world, layer, tiles, open };
+}
+
+async function withPhysics(gravity = -9.81) {
+ const scene = bare();
+ const module = await loadSideModule<PhysicsWasmModule>('physics');
+ scene.app.addPlugin(new Physics2DPlugin('', { gravity: { x: 0, y: gravity }, fixedTimestep: 1 / 60 }, async () => module));
+ await scene.app.getResource(Physics2DRuntime).initPromise;
+ scene.app.getResource(TilemapRuntimeState).setLayerTilesets(scene.layer, ['builtin:collision']);
+ const bodies = () => scene.world.getEntitiesWithComponents([RigidBody2D, Parent])
+ .filter(id => scene.world.get(id, Parent).entity === scene.layer);
+ return { ...scene, module, bodies };
+}
+
+describe.skipIf(!HAS_WASM)('destructible tilemap', () => {
+ beforeAll(async () => { core = await loadWasmModule(); });
+
+ describe('blows', () => {
+ it('wears a tile down and destroys it at its hardness', () => {
+ const { tiles, layer, open } = bare();
+ const map = open({ hardness: id => (id === 2 ? 10 : 1) });
+ tiles.setTile(layer, 1, 1, 2);
+ expect(map.dig(1, 1, 4)).toMatchObject({ damage: 4, hardness: 10, destroyed: false });
+ expect(map.damageAt(1, 1)).toBe(4);
+ expect(tiles.getTile(layer, 1, 1)).toBe(2);
+ expect(map.dig(1, 1, 6)).toMatchObject({ tile: 2, damage: 0, destroyed: true });
+ expect(tiles.getTile(layer, 1, 1)).toBe(0);
+ expect(map.damageAt(1, 1)).toBe(0);
+ expect(map.dig(1, 1, 6)).toBeNull();
+ });
+
+ it('refuses what cannot be destroyed, and a blow with no force', () => {
+ const { tiles, layer, open } = bare();
+ const map = open({ hardness: () => Infinity });
+ tiles.setTile(layer, 0, 0, 3);
+ expect(map.dig(0, 0)).toBeNull();
+ expect(tiles.getTile(layer, 0, 0)).toBe(3);
+ const soft = open({ hardness: 1 });
+ expect(soft.dig(0, 0, 0)).toBeNull();
+ expect(soft.dig(0, 0, Number.NaN)).toBeNull();
+ expect(soft.damageAt(0, 0)).toBe(0);
+ });
+
+ it('reads hardness from the tile property, and from an .estileset', async () => {
+ const { app, tiles, layer, open } = bare();
+ tiles.setTile(layer, 0, 0, 5);
+ tiles.setTileProperty(layer, 5, 'hardness', '7');
+ const map = open();
+ expect(map.dig(0, 0, 1)).toMatchObject({ hardness: 7 });
+ tiles.setTile(layer, 1, 0, 6);
+ expect(map.dig(1, 0, 1)).toMatchObject({ hardness: 1, destroyed: true });
+
+ const asset = createTileset('', 16, 16, 4);
+ asset.tiles[3] = { properties: { hardness: '9' } };
+ const model = resolveTilesetModel([{ asset, textureHandle: 1, textureHeight: 64 }]);
+ expect(model.tileProperties?.get(3)).toEqual({ hardness: '9' });
+ const runtime = app.getResource(TilemapRuntimeState) as unknown as {
+ applyTileProperties_(tiles: unknown, entity: number, next: Map<number, Record<string, string>>): void;
+ };
+ runtime.applyTileProperties_(tiles, layer, model.tileProperties!);
+ tiles.setTile(layer, 2, 0, 3);
+ expect(tiles.getTileProperty(layer, 2, 0, 'hardness')).toBe('9');
+ runtime.applyTileProperties_(tiles, layer, new Map());
+ expect(tiles.getTileProperty(layer, 2, 0, 'hardness')).toBe('');
+ });
+
+ it('forgets damage when another tile is put in the cell', () => {
+ const { tiles, layer, open } = bare();
+ tiles.setTile(layer, 0, 0, 1);
+ const map = open({ hardness: 10 });
+ map.dig(0, 0, 4);
+ map.set(0, 0, 1 | TILE_FLIP_H);
+ expect(map.damageAt(0, 0)).toBe(4);
+ map.set(0, 0, 2);
+ expect(map.damageAt(0, 0)).toBe(0);
+ });
+
+ it('leaves what replaceWith says, and never the same tile', () => {
+ const { tiles, layer, open } = bare();
+ const map = open({ replaceWith: id => (id === 1 ? 2 : id) });
+ tiles.setTile(layer, 0, 0, 1); tiles.setTile(layer, 1, 0, 3);
+ map.dig(0, 0); map.dig(1, 0);
+ expect(tiles.getTile(layer, 0, 0)).toBe(2);
+ expect(tiles.getTile(layer, 1, 0)).toBe(0);
+ });
+
+ it('takes a world position through the layer origin and rotation', () => {
+ const { world, tiles, layer, open } = bare();
+ world.update(layer, Transform, t => { t.position.x = 1000; t.position.y = 500; });
+ world.update(layer, TilemapLayer, l => { l.originOffset = { x: 32, y: 0 }; });
+ tiles.setTile(layer, 2, 3, 1);
+ const map = open();
+ expect(map.worldToTile(1000 + 32 + 2.5 * 16, 500 - 3.5 * 16)).toEqual({ x: 2, y: 3 });
+ expect(map.digAtWorld(1000 + 32 + 2.5 * 16, 500 - 3.5 * 16)?.destroyed).toBe(true);
+ world.update(layer, Transform, t => {
+ t.position.x = 0; t.position.y = 0;
+ t.rotation = { w: Math.SQRT1_2, x: 0, y: 0, z: Math.SQRT1_2 };
+ });
+ world.update(layer, TilemapLayer, l => { l.originOffset = { x: 0, y: 0 }; });
+ // A quarter turn counter-clockwise carries layer (x, y) to world (-y, x).
+ expect(map.worldToTile(3.5 * 16, 2.5 * 16)).toEqual({ x: 2, y: 3 });
+ });
+ });
+
+ describe('explosions', () => {
+ function field(size = 21) {
+ const scene = bare();
+ scene.tiles.fillRect(scene.layer, 0, 0, size, size, 1);
+ return scene;
+ }
+ const centre = { x: 10.5 * 16, y: -10.5 * 16 };
+
+ it('takes a circle and falls off toward the rim', () => {
+ const { tiles, layer, open } = field();
+ const map = open({ hardness: 100 });
+ const hits = map.explode(centre.x, centre.y, 5 * 16, 80);
+ const at = (x: number, y: number) => hits.find(h => h.x === x && h.y === y);
+ expect(at(10, 10)?.damage).toBeCloseTo(80);
+ expect(at(13, 10)?.damage).toBeCloseTo(32);
+ expect(at(15, 10)?.damage ?? 0).toBeCloseTo(0);
+ expect(at(14, 14)).toBeUndefined();
+ expect(hits.every(h => !h.destroyed)).toBe(true);
+ expect(tiles.getTile(layer, 10, 10)).toBe(1);
+ const flat = map.explode(centre.x, centre.y, 5 * 16, 20, { falloff: 0 });
+ expect(flat.find(h => h.x === 13 && h.y === 10)?.damage).toBeCloseTo(52);
+ });
+
+ it('destroys what its force beats and reports each cell once, together', () => {
+ const { tiles, layer, open } = field();
+ const map = open();
+ const heard: number[] = [];
+ map.subscribe(edits => heard.push(edits.length));
+ const hits = map.explode(centre.x, centre.y, 3 * 16, 1000);
+ expect(hits.length).toBeGreaterThan(20);
+ expect(hits.every(h => h.destroyed)).toBe(true);
+ expect(new Set(hits.map(h => `${h.x},${h.y}`)).size).toBe(hits.length);
+ expect(heard).toEqual([hits.length]);
+ for (const h of hits) expect(tiles.getTile(layer, h.x, h.y)).toBe(0);
+ expect(tiles.getTile(layer, 10, 14)).toBe(1);
+ });
+
+ it('stops at a wall that cannot be destroyed when shielded', () => {
+ const { tiles, layer, open } = field();
+ for (let y = 0; y < 21; y++) tiles.setTile(layer, 13, y, 9);
+ const hardness = (id: number) => (id === 9 ? Infinity : 1);
+ const open_ = open({ hardness });
+ open_.explode(centre.x, centre.y, 6 * 16, 1000, { falloff: 0 });
+ expect(tiles.getTile(layer, 12, 10)).toBe(0);
+ expect(tiles.getTile(layer, 13, 10)).toBe(9);
+ expect(tiles.getTile(layer, 14, 10)).toBe(0);
+
+ const { tiles: tiles2, layer: layer2, open: open2 } = field();
+ for (let y = 0; y < 21; y++) tiles2.setTile(layer2, 13, y, 9);
+ open2({ hardness }).explode(centre.x, centre.y, 6 * 16, 1000, { falloff: 0, shielded: true });
+ expect(tiles2.getTile(layer2, 12, 10)).toBe(0);
+ expect(tiles2.getTile(layer2, 14, 10)).toBe(1);
+ });
+
+ it.each([[1, 0, 0], [2, 0, 0], [3, 6, 1]])('measures from cell centres on a non-square grid (orientation %s)', (orientation, hexSideLength, staggerAxis) => {
+ const { world, tiles, layer, open } = field();
+ tiles.fillRect(layer, -30, -30, 90, 90, 1);
+ world.update(layer, TilemapLayer, l => { l.orientation = orientation!; l.hexSideLength = hexSideLength!; l.staggerAxis = staggerAxis!; });
+ tiles.setGridType(layer, orientation!); tiles.setHexParams(layer, hexSideLength!, staggerAxis === 1, false);
+ const map = open();
+ const grid = { orientation: orientation!, tileWidth: 16, tileHeight: 16, hexSideLength: hexSideLength!, staggerAxisX: staggerAxis === 1 };
+ const centreTile = tileCellCenter(grid, 10, 10);
+ // The geometry the blast measures with and the grid the engine picks with are one grid.
+ expect(map.worldToTile(centreTile.x, centreTile.y)).toEqual({ x: 10, y: 10 });
+ const hits = map.explode(centreTile.x, centreTile.y, 40, 1000);
+ expect(hits.some(h => h.x === 10 && h.y === 10)).toBe(true);
+ for (const h of hits) {
+ const c = tileCellCenter(grid, h.x, h.y);
+ expect(Math.hypot(c.x - centreTile.x, c.y - centreTile.y)).toBeLessThanOrEqual(40);
+ }
+ const reached = new Set(hits.map(h => `${h.x},${h.y}`));
+ for (let y = -5; y < 25; y++) for (let x = -5; x < 25; x++) {
+ const c = tileCellCenter(grid, x, y);
+ if (Math.hypot(c.x - centreTile.x, c.y - centreTile.y) < 39.9) expect(reached.has(`${x},${y}`)).toBe(true);
+ }
+ });
+ });
+
+ describe('autotile', () => {
+ const edgeSet = () => {
+ const asset = createTileset('', 16, 16, 16);
+ asset.terrains = [{ name: 'dirt', mode: 'edge' }];
+ for (let mask = 0; mask < 16; mask++) asset.tiles[mask + 1] = { terrain: { set: 0, mask } };
+ return asset;
+ };
+
+ it('re-resolves the neighbours of a dug cell', () => {
+ const { tiles, layer, open } = bare();
+ const map = open({ retile: peeringRetile(edgeSet()) });
+ map.fillRect(0, 0, 3, 3, 1);
+ const FULL = 16;
+ expect(tiles.getTile(layer, 1, 1)).toBe(FULL);
+ const edits: string[] = [];
+ map.subscribe(list => { for (const e of list) edits.push(`${e.x},${e.y}:${e.cause}`); });
+ map.dig(1, 1);
+ expect(tiles.getTile(layer, 1, 1)).toBe(0);
+ // The tile above the hole no longer has a tile south of it: mask 4 cleared.
+ expect(tiles.getTile(layer, 1, 0)).toBe(2 + 8 + 1);
+ expect(edits).toContain('1,1:dig');
+ expect(edits).toContain('1,0:retile');
+ });
+
+ it('offsets by firstId, and restores exactly from a save', () => {
+ const { tiles, layer, open } = bare();
+ const map = open({ retile: peeringRetile(edgeSet(), 101) });
+ map.fillRect(0, 0, 3, 1, 101);
+ expect(tiles.getTile(layer, 1, 0)).toBe(2 + 8 + 101);
+ const save = JSON.parse(JSON.stringify(map.toJSON()));
+ const { tiles: fresh, layer: layer2, open: open2 } = bare();
+ const retile = vi.fn(() => undefined);
+ expect(open2({ retile }).load(save)).toBe(true);
+ expect(fresh.getTile(layer2, 1, 0)).toBe(2 + 8 + 101);
+ expect(retile).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('saves', () => {
+ it('stores only what changed, and comes back through JSON', () => {
+ const { tiles, layer, open } = bare();
+ tiles.fillRect(layer, 0, 0, 40, 40, 1);
+ const map = open({ hardness: 10 });
+ map.dig(3, 3); map.dig(20, 20, 4); map.set(-5, -5, 2 | TILE_FLIP_H);
+ expect(map.changedCells).toBe(2);
+ const data = JSON.parse(JSON.stringify(map.toJSON()));
+ expect(JSON.stringify(data).length).toBeLessThan(200);
+
+ const next = bare();
+ next.tiles.fillRect(next.layer, 0, 0, 40, 40, 1);
+ const again = next.open({ hardness: 10 });
+ expect(again.load(data)).toBe(true);
+ expect(next.tiles.getTile(next.layer, 3, 3)).toBe(0);
+ expect(next.tiles.getTile(next.layer, -5, -5)).toBe(2 | TILE_FLIP_H);
+ expect(next.tiles.getTile(next.layer, 20, 20)).toBe(1);
+ expect(again.damageAt(20, 20)).toBe(4);
+ expect(again.dig(20, 20, 6)?.destroyed).toBe(true);
+ expect(JSON.stringify(again.toJSON()).length).toBeGreaterThan(0);
+ });
+
+ it('puts back what this session changed when a save loads, and forgets a cell returned to what it was', () => {
+ const { tiles, layer, open } = bare();
+ tiles.fillRect(layer, 0, 0, 4, 1, 1);
+ const map = open();
+ const empty = map.toJSON();
+ map.dig(0, 0); map.dig(1, 0);
+ expect(map.changedCells).toBe(2);
+ const dug = map.toJSON();
+ map.set(0, 0, 1);
+ expect(map.changedCells).toBe(1);
+ expect(map.load(empty)).toBe(true);
+ expect(map.changedCells).toBe(0);
+ expect(tiles.getTile(layer, 1, 0)).toBe(1);
+ for (let i = 0; i < 2; i++) {
+ expect(map.load(dug)).toBe(true);
+ expect(map.changedCells).toBe(2);
+ expect(tiles.getTile(layer, 0, 0)).toBe(0);
+ }
+ expect(map.toJSON()).toEqual(dug);
+ });
+
+ it.each([
+ ['another version', (d: any) => { d.version = 2; }],
+ ['no chunks', (d: any) => { delete d.chunks; }],
+ ['a cell off the chunk', (d: any) => { d.chunks[0].cells[0] = 9999; }],
+ ['a cell that is no tile', (d: any) => { d.chunks[0].cells[1] = 70000; }],
+ ['an odd pair list', (d: any) => { d.chunks[0].cells.push(1); }],
+ ['damage that is no number', (d: any) => { d.chunks[0].damage = [0, 'x']; }],
+ ['a tile the id mask cannot hold', (d: any) => { d.encoding[1] = 0xffff; d.chunks[0].cells[1] = 0x7fff; }],
+ ])('refuses %s whole and leaves the layer alone', (_name, spoil) => {
+ const { tiles, layer, open } = bare();
+ const map = open();
+ map.set(0, 0, 1); map.set(1, 0, 1);
+ const data = JSON.parse(JSON.stringify(map.toJSON()));
+ spoil(data);
+ map.set(2, 0, 3);
+ expect(map.load(data)).toBe(false);
+ expect(tiles.getTile(layer, 2, 0)).toBe(3);
+ expect(map.changedCells).toBe(3);
+ });
+
+ it('reads a save written under another encoding by what its cells mean', () => {
+ const { tiles, layer, open } = bare();
+ const map = open();
+ const flip = 0x8000, side = 8;
+ expect(map.load({ version: 1, encoding: [side, 0x0fff, flip, 0x4000, 0x2000],
+ chunks: [{ x: 3, y: -1, cells: [side + 2, 5 | flip] }] })).toBe(true);
+ expect(tiles.getTile(layer, 3 * side + 2, -side + 1)).toBe(5 | TILE_FLIP_H);
+ });
+
+ it('keeps a chunk as it was left through release and regeneration', () => {
+ const { tiles, layer, open } = bare();
+ const map = open({ streamed: true, hardness: 10 });
+ const generated = new Uint16Array(CHUNK_SIZE * CHUNK_SIZE).fill(1);
+ expect(map.dig(0, 0)).toBeNull();
+ expect(tiles.getTile(layer, 0, 0)).toBe(0);
+ map.publishChunk(0, 0, generated);
+ map.dig(2, 2); map.dig(3, 3, 4);
+ map.releaseChunk(0, 0);
+ expect(tiles.getTile(layer, 2, 2)).toBe(0);
+ expect(map.dig(5, 5)).toBeNull();
+ map.publishChunk(0, 0, generated);
+ expect(generated[2 * CHUNK_SIZE + 2]).toBe(1);
+ expect(tiles.getTile(layer, 2, 2)).toBe(0);
+ expect(tiles.getTile(layer, 1, 1)).toBe(1);
+ expect(map.damageAt(3, 3)).toBe(4);
+ });
+
+ it('holds a loaded save for a chunk not yet streamed in', () => {
+ const first = bare();
+ const a = first.open({ streamed: true });
+ const generated = new Uint16Array(CHUNK_SIZE * CHUNK_SIZE).fill(1);
+ a.publishChunk(0, 0, generated); a.dig(1, 1);
+ const save = JSON.parse(JSON.stringify(a.toJSON()));
+
+ const second = bare();
+ const b = second.open({ streamed: true });
+ expect(b.load(save)).toBe(true);
+ expect(second.tiles.getTile(second.layer, 2, 2)).toBe(0);
+ expect(b.toJSON()).toEqual(save);
+ b.publishChunk(0, 0, generated);
+ expect(second.tiles.getTile(second.layer, 1, 1)).toBe(0);
+ expect(second.tiles.getTile(second.layer, 2, 2)).toBe(1);
+ expect(b.toJSON()).toEqual(save);
+ });
+ });
+
+ describe.skipIf(!hasSideModule('physics'))('collision', () => {
+ it('keeps every collider a dig in the same chunk does not change', async () => {
+ const { app, world, tiles, layer, bodies, module } = await withPhysics();
+ for (let x = 0; x < 16; x++) tiles.setTile(layer, x, 3, 1);
+ tiles.setTile(layer, 14, 8, 1);
+ await app.tick(1 / 60);
+ const floor = bodies().find(id => world.get(id, Transform).position.y > -100)!;
+ const actor = world.spawn();
+ world.insert(actor, Transform, { position: { x: 40, y: -20, z: 0 } });
+ world.insert(actor, RigidBody2D, { bodyType: BodyType.Dynamic });
+ world.insert(actor, BoxCollider2D, { halfExtents: { x: 0.03, y: 0.03 } });
+ await app.stepFrames(300, 1 / 60);
+ expect(module._physics_isAwake(actor)).toBe(0);
+ tiles.setTile(layer, 14, 8, 0);
+ for (let i = 0; i < 3; i++) {
+ await app.tick(1 / 60);
+ const events = app.getResource(Physics2DEvents);
+ expect([...events.collisionEnters, ...events.collisionExits].filter(e => e.entityA === actor || e.entityB === actor)).toEqual([]);
+ }
+ expect(world.valid(floor)).toBe(true);
+ expect(module._physics_isAwake(actor)).toBe(0);
+ });
+
+ it('a dug floor drops what slept on it', async () => {
+ const { app, world, tiles, layer, open, module } = await withPhysics();
+ tiles.fillRect(layer, 0, 3, 16, 3, 1);
+ const map = open();
+ await app.tick(1 / 60);
+ const actor = world.spawn();
+ world.insert(actor, Transform, { position: { x: 40, y: -20, z: 0 } });
+ world.insert(actor, RigidBody2D, { bodyType: BodyType.Dynamic });
+ world.insert(actor, BoxCollider2D, { halfExtents: { x: 0.03, y: 0.03 } });
+ await app.stepFrames(300, 1 / 60);
+ expect(module._physics_isAwake(actor)).toBe(0);
+ const rest = world.get(actor, Transform).position.y;
+ map.explode(40, rest, 64, 1000, { falloff: 0 });
+ await app.stepFrames(30, 1 / 60);
+ expect(world.get(actor, Transform).position.y).toBeLessThan(rest - 20);
+ });
+
+ it('leaves buried ground with no bodies, and the surface alone when it is dug', async () => {
+ const { app, world, tiles, layer, open, bodies, module } = await withPhysics(0);
+ tiles.fillRect(layer, -16, -16, 48, 48, 1);
+ const map = open();
+ await app.tick(1 / 60);
+ // A 48x48 block over 9 chunks: the middle chunk holds no collider at all.
+ const inside = (id: number) => {
+ const p = world.get(id, Transform).position;
+ return p.x > 0 && p.x < 256 && p.y < 0 && p.y > -256;
+ };
+ expect(bodies().filter(inside)).toEqual([]);
+ const surface = new Set(bodies());
+ expect(surface.size).toBeLessThan(20);
+
+ map.dig(8, 8);
+ await app.tick(1 / 60);
+ const after = bodies();
+ for (const id of surface) expect(after).toContain(id);
+ expect(after.length - surface.size).toBe(4);
+ expect(module._physics_getBodyCount()).toBe(after.length);
+ });
+
+ it('rebuilds across a chunk edge when a neighbour is opened', async () => {
+ const { app, world, tiles, layer, open, bodies } = await withPhysics(0);
+ tiles.fillRect(layer, 0, 0, 48, 16, 1);
+ const map = open();
+ await app.tick(1 / 60);
+ const count = bodies().length;
+ // Column 16 is chunk 1's first; chunk 0's column 15 was buried behind it.
+ for (let y = 0; y < 16; y++) map.dig(16, y);
+ await app.tick(1 / 60);
+ const xs = bodies().map(id => world.get(id, Transform).position.x);
+ expect(xs.some(x => x > 15 * 16 && x < 16 * 16)).toBe(true);
+ expect(bodies().length).toBeGreaterThan(count);
+ tiles.fillRect(layer, 16, 0, 1, 16, 1);
+ await app.tick(1 / 60);
+ expect(bodies().length).toBe(count);
+ });
+
+ it('lets a body stand on outline ground as it stood on merged ground', async () => {
+ const { app, world, tiles, layer, open, bodies } = await withPhysics();
+ tiles.fillRect(layer, -32, 3, 64, 40, 1);
+ open();
+ await app.tick(1 / 60);
+ const actor = world.spawn();
+ world.insert(actor, Transform, { position: { x: 40, y: -20, z: 0 } });
+ world.insert(actor, RigidBody2D, { bodyType: BodyType.Dynamic });
+ world.insert(actor, BoxCollider2D, { halfExtents: { x: 0.03, y: 0.03 } });
+ await app.stepFrames(200, 1 / 60);
+ expect(world.get(actor, Transform).position.y).toBeGreaterThan(-52);
+ expect(bodies().length).toBeLessThan(25);
+ });
+
+ it('can be left with merged ground', async () => {
+ const { app, tiles, layer, open, bodies } = await withPhysics(0);
+ tiles.fillRect(layer, 0, 0, 16, 16, 1);
+ open({ collisionOutline: false });
+ await app.tick(1 / 60);
+ expect(bodies()).toHaveLength(1);
+ });
+
+ it('turning the outline on rebuilds a running layer', async () => {
+ const { app, tiles, layer, bodies } = await withPhysics(0);
+ tiles.fillRect(layer, 0, 0, 16, 16, 1);
+ await app.tick(1 / 60);
+ expect(bodies()).toHaveLength(1);
+ app.getResource(TilemapRuntimeState).setCollisionOutline(layer, true);
+ await app.tick(1 / 60);
+ expect(bodies().length).toBeGreaterThan(1);
+ });
+ });
+
+ describe('navigation', () => {
+ it('flips exactly the changed cell, and places the grid where the layer draws', () => {
+ const { world, tiles, layer, open } = bare();
+ world.update(layer, Transform, t => { t.position.x = 320; t.position.y = 160; });
+ tiles.fillRect(layer, 5, 0, 1, 10, 1);
+ const map = open();
+ const grid = map.createNavGrid({ width: 10, height: 10 });
+ const revision = () => grid.topologyRevision;
+ const wall = { x: 320 + 5.5 * 16, y: 160 - 4.5 * 16 };
+ const cell = grid.worldToCell(wall);
+ expect(cell).toEqual({ x: 5, y: 5 });
+ expect(grid.isWalkable(5, 5)).toBe(false);
+ const before = revision();
+ map.dig(5, 4);
+ expect(grid.isWalkable(5, 5)).toBe(true);
+ expect(revision()).toBe(before + 1);
+ let open_ = 0;
+ for (let y = 0; y < 10; y++) if (grid.isWalkable(5, y)) open_++;
+ expect(open_).toBe(1);
+ map.set(5, 4, 1);
+ expect(grid.isWalkable(5, 5)).toBe(false);
+ });
+
+ it('agrees with the existing builder on the same tiles', () => {
+ const { tiles, layer, open } = bare();
+ tiles.setTile(layer, 1, 2, 1); tiles.setTile(layer, 3, 0, 1);
+ const map = open();
+ const grid = map.createNavGrid({ width: 5, height: 4 });
+ const built = navGridFromTilemapLayer(layer, { width: 5, height: 4, cellSize: 16 });
+ expect([...grid.walkable]).toEqual([...built.walkable]);
+ });
+
+ it('honours a tile rectangle, a predicate, and stops when told', () => {
+ const { tiles, layer, open } = bare();
+ tiles.setTile(layer, 100, 200, 1); tiles.setTile(layer, 101, 200, 2);
+ const map = open();
+ const grid = map.createNavGrid({ tileX: 100, tileY: 200, width: 4, height: 1, isBlocked: id => id === 2 });
+ expect([...grid.walkable]).toEqual([1, 0, 1, 1]);
+ map.set(102, 200, 2);
+ map.set(50, 50, 2);
+ expect([...grid.walkable]).toEqual([1, 0, 0, 1]);
+ const other = map.createNavGrid({ tileX: 100, tileY: 200, width: 4, height: 1, isBlocked: id => id === 2 });
+ const stop = map.syncNavGrid(other);
+ stop();
+ map.set(103, 200, 2);
+ expect(grid.isWalkable(3, 0)).toBe(false);
+ });
+
+ it('does not block on a sensor tile, and does on a solid one, by the layer\'s collision', async () => {
+ const { app, open } = await withPhysics(0);
+ await app.tick(1 / 60);
+ const map = open();
+ const grid = map.createNavGrid({ width: 3, height: 1 });
+ const palette = await import('../src/tilemap/collisionPalette');
+ const brushes = palette.buildCollisionPaletteModel();
+ const solid = brushes.collidableTileIds[0]!;
+ const sensor = [...brushes.tileShapes].find(([, s]) => s.sensor)![0];
+ map.set(0, 0, solid); map.set(1, 0, sensor);
+ expect([...grid.walkable]).toEqual([0, 1, 1]);
+ });
+
+ it('restores the grid from a load and a streamed chunk', () => {
+ const { open } = bare();
+ const map = open({ streamed: true });
+ const grid = map.createNavGrid({ width: 2, height: 1 });
+ const generated = new Uint16Array(CHUNK_SIZE * CHUNK_SIZE).fill(1);
+ expect([...grid.walkable]).toEqual([1, 1]);
+ map.publishChunk(0, 0, generated);
+ expect([...grid.walkable]).toEqual([0, 0]);
+ map.dig(0, 0);
+ const save = map.toJSON();
+ expect([...grid.walkable]).toEqual([1, 0]);
+ map.set(0, 0, 1);
+ expect([...grid.walkable]).toEqual([0, 0]);
+ map.load(save);
+ expect([...grid.walkable]).toEqual([1, 0]);
+ map.releaseChunk(0, 0);
+ map.publishChunk(0, 0, generated);
+ expect([...grid.walkable]).toEqual([1, 0]);
+ });
+
+ it('walks an agent through the hole a dig made', async () => {
+ const { app, world, tiles, layer, open } = bare();
+ app.addPlugin(new NavPlugin());
+ tiles.fillRect(layer, 5, 0, 1, 11, 1);
+ const map = open();
+ const nav = app.getResource(Nav);
+ const grid = map.createNavGrid({ width: 11, height: 11 });
+ nav.setSurface(grid);
+ const agent = world.spawn();
+ world.insert(agent, Transform, { position: { x: 2.5 * 16, y: -5.5 * 16, z: 0 } });
+ const goal = { x: 8.5 * 16, y: -5.5 * 16 };
+ world.insert(agent, NavAgent, { speed: 400, radius: 0, arriveRadius: 2, hasTarget: true, targetX: goal.x, targetY: goal.y, targetZ: 0, repathInterval: 0 });
+ await app.stepFrames(60, 1 / 60);
+ expect(world.get(agent, NavAgent).arrived).toBeFalsy();
+ expect(world.get(agent, Transform).position.x).toBeLessThan(5 * 16);
+ map.dig(5, 5);
+ await app.stepFrames(60, 1 / 60);
+ expect(world.get(agent, NavAgent).arrived).toBe(true);
+ expect(world.get(agent, Transform).position.x).toBeGreaterThan(8 * 16);
+ });
+
+ it('refuses a grid the layer cannot be', () => {
+ const { world, layer, open } = bare();
+ world.update(layer, TilemapLayer, l => { l.cellSize = { x: 16, y: 24 }; });
+ expect(() => open().createNavGrid({ width: 2, height: 2 })).toThrow(/square/);
+ });
+ });
+
+ describe('edits', () => {
+ it('ignores a finite layer\'s outside, and records nothing for it', () => {
+ const { tiles, layer, open } = bare();
+ tiles.initLayer(layer, 4, 4, 16, 16);
+ const map = open();
+ expect(map.set(10, 10, 1)).toBe(false);
+ expect(map.changedCells).toBe(0);
+ expect(map.set(1, 1, 1)).toBe(true);
+ expect(map.changedCells).toBe(1);
+ });
+
+ it('hears one change for one operation, and nothing for no change', () => {
+ const { open } = bare();
+ const map = open();
+ const heard = vi.fn();
+ const stop = map.subscribe(heard);
+ expect(map.fillRect(0, 0, 2, 2, 1)).toHaveLength(4);
+ expect(heard).toHaveBeenCalledOnce();
+ expect(map.fillRect(0, 0, 2, 2, 1)).toHaveLength(0);
+ expect(heard).toHaveBeenCalledOnce();
+ stop();
+ map.set(9, 9, 1);
+ expect(heard).toHaveBeenCalledOnce();
+ });
+ });
+});
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index f68283a19..910fef3d5 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -4210,4 +4210,6 @@ export const NOTED = {
{"note": "A generated building stands on its ground, and generated roads keep foliage off them."},
"perf(tilemap): a row of tiles being edited uploads a piece of itself":
{"note": "A row of tiles being edited uploads a piece of itself."},
+ "feat(tilemap): a tile layer can be dug, blown up and rebuilt while the game runs":
+ {"note": "A tile layer can be dug, blown up and rebuilt while the game runs."},
};