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.

fix(tilemap): derive collision from each layer grid

yhh0b89111a8b13
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6612e5803..ea4babac1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,8 @@ published separately; it ships inside the editor.
### Fixed
+- **Tile collision follows painted and imported layer layouts.** Static boxes, rich shapes and legacy polygon helpers share layout-aware cell placement. Projected box merging preserves the authored union without filling holes. Tiled runtime collision belongs to each derived layer and follows its transform, layout edits and lifetime through the same path as painted layers. Origin-offset edits move existing bodies without re-exporting tiles, and direct Tiled loads retain their grid metadata.
+
- **Staggered and hexagonal picking follows cell polygons.** Core queries identify the containing diamond or hexagon instead of its rectangular partition, including negative coordinates and either stagger axis/index. Drawing and coordinate queries share native grid geometry, while editor outlines use the same effective hex side limit along the stagger axis. Shared edges resolve to a touching cell; rotation and translation preserve cell ownership. Picking examines at most three neighboring stagger lines without reading tile contents.
- **Rotated tile layers share one frame for drawing, picking and collision previews.** World Z rotation, including parent rotation, applies to tile vertices, visible chunk selection, editor grids, brush ghosts and world-to-tile queries. Collision previews rotate cached local geometry and keep large shapes visible when their bounds overlap the viewport. Generated tile one-way platforms rotate their solid side with the physics body; ordinary one-way platforms retain world-space normals unless `localSpace` is enabled. Static-parent rotation needs no repeated normal submissions, and rebuilt shapes restore their pre-solve behavior.
diff --git a/sdk/etc/tilemap.api.md b/sdk/etc/tilemap.api.md
index ff0ddf476..d379cef6e 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 · 137 experimental · 0 deprecated
+Symbols: 0 public · 5 beta · 138 experimental · 0 deprecated
## BuildNavGridOptions — interface @experimental
```
@@ -256,6 +256,11 @@ flipH: boolean
flipV: boolean
```
+## TileGridLayout — type @experimental
+```
+Omit<TileGridParams, 'tileWidth' | 'tileHeight'>
+```
+
## TileGridParams — interface @experimental
```
hexSideLength: number | undefined
@@ -623,27 +628,27 @@ tileTerrain: Map<number, number>
## generateChunkCollision — function @experimental
```
-(world: World, chunks: { x: number; y: number; tiles: Uint16Array; }[], collisionIds: Set<number>, tileW: number, tileH: number, originX: number, originY: number, pixelsPerUnit?: number): Entity[]
+(world: World, chunks: { x: number; y: number; tiles: Uint16Array; }[], collisionIds: Set<number>, tileW: number, tileH: number, originX: number, originY: number, pixelsPerUnit?: number, layout?: TileGridLayout): Entity[]
```
## generateChunkPolygonCollision — function @experimental
```
-(world: World, chunks: { x: number; y: number; tiles: Uint16Array; }[], polygonShapes: Map<number, readonly [number, number][]>, tileW: number, tileH: number, originX: number, originY: number, pixelsPerUnit?: number): Entity[]
+(world: World, chunks: { x: number; y: number; tiles: Uint16Array; }[], polygonShapes: Map<number, readonly [number, number][]>, tileW: number, tileH: number, originX: number, originY: number, pixelsPerUnit?: number, layout?: TileGridLayout): Entity[]
```
## generateChunkTileShapes — function @experimental
```
-(world: World, chunks: { x: number; y: number; tiles: Uint16Array; }[], tileShapes: Map<number, ResolvedTileCollision>, tileW: number, tileH: number, originX: number, originY: number, pixelsPerUnit?: number): Entity[]
+(world: World, chunks: { x: number; y: number; tiles: Uint16Array; }[], tileShapes: Map<number, ResolvedTileCollision>, tileW: number, tileH: number, originX: number, originY: number, pixelsPerUnit?: number, layout?: TileGridLayout): Entity[]
```
## generateLayerCollision — function @experimental
```
-(world: World, tiles: ArrayLike<number>, gridWidth: number, gridHeight: number, tileW: number, tileH: number, collisionIds: Set<number>, originX: number, originY: number, pixelsPerUnit?: number): Entity[]
+(world: World, tiles: ArrayLike<number>, gridWidth: number, gridHeight: number, tileW: number, tileH: number, collisionIds: Set<number>, originX: number, originY: number, pixelsPerUnit?: number, layout?: TileGridLayout): Entity[]
```
## generateLayerTileShapes — function @experimental
```
-(world: World, tiles: ArrayLike<number>, gridWidth: number, gridHeight: number, tileShapes: Map<number, ResolvedTileCollision>, tileW: number, tileH: number, originX: number, originY: number, pixelsPerUnit?: number): Entity[]
+(world: World, tiles: ArrayLike<number>, gridWidth: number, gridHeight: number, tileShapes: Map<number, ResolvedTileCollision>, tileW: number, tileH: number, originX: number, originY: number, pixelsPerUnit?: number, layout?: TileGridLayout): Entity[]
```
## generateObjectCollision — function @experimental
@@ -853,7 +858,7 @@ tileTerrain: Map<number, number>
## tileCollisionOutlines — function @experimental
```
-(chunks: DecodedChunk[], model: TilesetModel, tileW: number, tileH: number, originX: number, originY: number): TileCollisionPiece[]
+(chunks: DecodedChunk[], model: TilesetModel, tileW: number, tileH: number, originX: number, originY: number, layout?: TileGridLayout): TileCollisionPiece[]
```
## tileFlagsOf — function @experimental
diff --git a/sdk/src/tilemap/collisionBoxes.ts b/sdk/src/tilemap/collisionBoxes.ts
new file mode 100644
index 000000000..52f7e18ed
--- /dev/null
+++ b/sdk/src/tilemap/collisionBoxes.ts
@@ -0,0 +1,51 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file collisionBoxes.ts
+ * @brief Shared box placement and exact merging for runtime collision and previews.
+ */
+import { mergeCollisionTiles } from './collisionMerge';
+import { tileIdOf } from './tileBits';
+import { tileCellCenter, TilemapOrientation, type TileGridLayout, type TileGridParams } from './tileGeometry';
+
+interface CollisionBox {
+ center: { x: number; y: number };
+ halfExtents: { x: number; y: number };
+}
+
+export function collisionGrid(tw: number, th: number, layout?: TileGridLayout): TileGridParams {
+ return { ...layout, orientation: layout?.orientation ?? 0, tileWidth: tw, tileHeight: th };
+}
+
+export function collisionBoxes(
+ tiles: ArrayLike<number>, width: number, height: number, ids: Set<number>,
+ grid: TileGridParams, baseX = 0, baseY = 0,
+): CollisionBox[] {
+ const boxes: CollisionBox[] = [];
+ const append = (x: number, y: number, w: number, h: number) => {
+ const start = tileCellCenter(grid, baseX + x, baseY + y);
+ boxes.push({ center: { x: start.x + (w - 1) * grid.tileWidth * .5,
+ y: start.y - (h - 1) * grid.tileHeight * .5 },
+ halfExtents: { x: w * grid.tileWidth * .5, y: h * grid.tileHeight * .5 } });
+ };
+ if (grid.orientation === TilemapOrientation.Orthogonal) {
+ for (const rect of mergeCollisionTiles(tiles, width, height, ids)) append(rect.col, rect.row, rect.width, rect.height);
+ return boxes;
+ }
+ // Merge only where projected tile boxes touch along a world axis.
+ const iso = grid.orientation === TilemapOrientation.Isometric;
+ const dx = iso || !grid.staggerAxisX ? 1 : 0, dy = iso || grid.staggerAxisX ? 1 : 0;
+ const vertical = dy === 1;
+ const solid = (x: number, y: number) => {
+ if (x < 0 || y < 0 || x >= width || y >= height) return false;
+ const id = tileIdOf(tiles[y * width + x] ?? 0);
+ return id !== 0 && ids.has(id);
+ };
+ for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) {
+ if (!solid(x, y) || solid(x - dx, y - dy)) continue;
+ let count = 1;
+ while (solid(x + count * dx, y + count * dy)) count++;
+ append(x, y, vertical ? 1 : count, vertical ? count : 1);
+ }
+ return boxes;
+}
diff --git a/sdk/src/tilemap/index.ts b/sdk/src/tilemap/index.ts
index 73f10f0fc..b78164f33 100644
--- a/sdk/src/tilemap/index.ts
+++ b/sdk/src/tilemap/index.ts
@@ -23,7 +23,7 @@ export {
} from './collisionPalette';
export {
tileCellCenter, tileCellOutline, isNonOrthogonal, usesStagger, isHexOrientation, TilemapOrientation, TilemapStaggerAxis, TilemapStaggerIndex,
- type TileGridParams, type Vec2Like,
+ type TileGridParams, type TileGridLayout, type Vec2Like,
} from './tileGeometry';
export { mergeCollisionTiles, type MergedRect } from './collisionMerge';
export { decodeTilemapChunks, CHUNK_SIZE, type DecodedChunk } from './chunkCodec';
diff --git a/sdk/src/tilemap/tileCollisionOutline.ts b/sdk/src/tilemap/tileCollisionOutline.ts
index b94b69232..a06b7b60a 100644
--- a/sdk/src/tilemap/tileCollisionOutline.ts
+++ b/sdk/src/tilemap/tileCollisionOutline.ts
@@ -18,7 +18,8 @@ import type { Vec2 } from '../types';
import type { DecodedChunk } from './chunkCodec';
import { CHUNK_SIZE } from './chunkCodec';
import { tileIdOf, tileFlagsOf } from './tileBits';
-import { mergeCollisionTiles } from './collisionMerge';
+import { collisionBoxes, collisionGrid } from './collisionBoxes';
+import { tileCellCenter, type TileGridLayout } from './tileGeometry';
import { tileColliderShape, oneWayNormalWorld } from './tiledLoader';
import { collider2DOutline, shapeCenter } from '../physics/ColliderShape2D';
import type { Collider2DShape } from '../physics/ColliderShape2D';
@@ -58,6 +59,7 @@ export function tileCollisionOutlines(
tileH: number,
originX: number,
originY: number,
+ layout?: TileGridLayout,
): TileCollisionPiece[] {
const pieces: TileCollisionPiece[] = [];
const boxIds = new Set(model.collidableTileIds);
@@ -65,6 +67,7 @@ export function tileCollisionOutlines(
const hasBoxes = boxIds.size > 0;
const hasShapes = shapes.size > 0;
if (!hasBoxes && !hasShapes) return pieces;
+ const grid = collisionGrid(tileW, tileH, layout);
for (const chunk of chunks) {
const baseX = chunk.x * CHUNK_SIZE;
@@ -73,16 +76,11 @@ export function tileCollisionOutlines(
// Plain solid boxes: greedy-merge per chunk (matching generateChunkCollision), one
// outline per merged rectangle — so a solid platform reads as a few big rects.
if (hasBoxes) {
- for (const rect of mergeCollisionTiles(chunk.tiles, CHUNK_SIZE, CHUNK_SIZE, boxIds)) {
- const x0 = baseX + rect.col;
- const y0 = baseY + rect.row;
- const x1 = x0 + rect.width - 1;
- const y1 = y0 + rect.height - 1;
- const cx = originX + ((x0 + x1 + 1) / 2) * tileW;
- const cy = originY - ((y0 + y1 + 1) / 2) * tileH;
+ for (const box of collisionBoxes(chunk.tiles, CHUNK_SIZE, CHUNK_SIZE, boxIds, grid, baseX, baseY)) {
+ const cx = originX + box.center.x, cy = originY + box.center.y;
const shape: Collider2DShape = {
kind: 'box',
- halfExtents: { x: rect.width * tileW * 0.5, y: rect.height * tileH * 0.5 },
+ halfExtents: box.halfExtents,
offset: { x: 0, y: 0 },
};
const o = outlineAt(shape, { x: cx, y: cy });
@@ -99,7 +97,8 @@ export function tileCollisionOutlines(
if (!rc) continue;
const gx = baseX + (i % CHUNK_SIZE);
const gy = baseY + Math.floor(i / CHUNK_SIZE);
- const cellCenter = { x: originX + (gx + 0.5) * tileW, y: originY - (gy + 0.5) * tileH };
+ const local = tileCellCenter(grid, gx, gy);
+ const cellCenter = { x: originX + local.x, y: originY + local.y };
const f = tileFlagsOf(raw);
const shape = tileColliderShape(rc, tileW, tileH, f.flipH, f.flipV, f.flipD);
const o = outlineAt(shape, cellCenter);
diff --git a/sdk/src/tilemap/tileGeometry.ts b/sdk/src/tilemap/tileGeometry.ts
index cea448a1e..cf77f5a85 100644
--- a/sdk/src/tilemap/tileGeometry.ts
+++ b/sdk/src/tilemap/tileGeometry.ts
@@ -40,6 +40,9 @@ export interface Vec2Like {
y: number;
}
+/** Layout without cell dimensions, for consumers that already receive tile width/height. */
+export type TileGridLayout = Omit<TileGridParams, 'tileWidth' | 'tileHeight'>;
+
/** The effective hex side length: the authored value, or the regular-hex fallback (th/2). */
function hexSide(p: TileGridParams): number {
const side = p.hexSideLength && p.hexSideLength > 0 ? p.hexSideLength : p.tileHeight * 0.5;
diff --git a/sdk/src/tilemap/tiledLoader.ts b/sdk/src/tilemap/tiledLoader.ts
index 0aef77a53..d318d4b33 100644
--- a/sdk/src/tilemap/tiledLoader.ts
+++ b/sdk/src/tilemap/tiledLoader.ts
@@ -40,7 +40,8 @@ function uploadTiledLayerTiles(entity: Entity, layer: TiledLayerData): void {
import { RigidBody2D, BoxCollider2D, CircleCollider2D, PolygonCollider2D, ChainCollider2D, OneWayPlatform2D, BodyType } from '../physics/PhysicsComponents';
import type { Collider2DShape } from '../physics/ColliderShape2D';
import type { ResolvedTileCollision } from './tilesetResolve';
-import { mergeCollisionTiles } from './collisionMerge';
+import { collisionBoxes, collisionGrid } from './collisionBoxes';
+import { tileCellCenter, TilemapOrientation, type TileGridLayout, type TileGridParams } from './tileGeometry';
import { CHUNK_SIZE } from './chunkCodec';
import { tileIdOf, tileFlagsOf } from './tileBits';
import { log } from '../util/logger';
@@ -156,6 +157,16 @@ export interface TiledMapData {
tileProperties: Map<number, Map<string, string>>;
}
+export function tiledGridLayout(map: {
+ orientation?: string; hexSideLength?: number; staggerAxis?: string; staggerIndex?: string;
+}): TileGridLayout {
+ const orientations: Record<string, number> = { orthogonal: TilemapOrientation.Orthogonal,
+ isometric: TilemapOrientation.Isometric, staggered: TilemapOrientation.Staggered, hexagonal: TilemapOrientation.Hexagonal };
+ return { orientation: orientations[map.orientation ?? 'orthogonal'] ?? 0,
+ hexSideLength: map.hexSideLength ?? 0, staggerAxisX: map.staggerAxis === 'x',
+ staggerIndexEven: map.staggerIndex === 'even' };
+}
+
const TILED_FLIP_H = 0x80000000;
const TILED_FLIP_V = 0x40000000;
const TILED_FLIP_D = 0x20000000;
@@ -844,12 +855,8 @@ export function loadTiledCollisionObjects(
}
/**
- * @brief Greedy-merge a tile grid's collidable cells into static box colliders.
- *
- * Grid-agnostic core shared by the Tiled-import (`generateTileCollision`) and the runtime
- * asset (`TilemapSyncSystem`) paths. Row 0 (top of the grid) maps to the highest world-Y
- * and rows descend (y-down), matching the renderer; each merged rect becomes one static
- * `BoxCollider2D` body placed relative to (originX, originY) — the tilemap entity's origin.
+ * Static boxes in layer pixels, relative to the supplied origin; extents use physics units.
+ * Layout defaults to orthogonal. Merging preserves the union of projected tile boxes.
*/
export function generateLayerCollision(
world: World,
@@ -862,31 +869,15 @@ export function generateLayerCollision(
originX: number,
originY: number,
pixelsPerUnit: number = 1,
+ layout?: TileGridLayout,
): Entity[] {
- const merged = mergeCollisionTiles(tiles, gridWidth, gridHeight, collisionIds);
- const entities: Entity[] = [];
-
- for (const rect of merged) {
- const mergedW = rect.width * tileW;
- const mergedH = rect.height * tileH;
- // y-DOWN, matching the renderer (`worldY = origin - row*tileH - hh`,
- // TilemapRenderPlugin.cpp) and generateChunkCollision — so colliders land
- // exactly on the visible tiles. (Was y-up/flipped, which put them a full
- // map-height off; never caught because no example ran tilemap physics in play.)
- const worldX = originX + rect.col * tileW + mergedW * 0.5;
- const worldY = originY - rect.row * tileH - mergedH * 0.5;
+ const grid = collisionGrid(tileW, tileH, layout), entities: Entity[] = [];
+ for (const box of collisionBoxes(tiles, gridWidth, gridHeight, collisionIds, grid)) {
const entity = world.spawn();
- world.insert(entity, Transform, {
- position: { x: worldX, y: worldY, z: 0 },
- });
+ world.insert(entity, Transform, { position: { x: originX + box.center.x, y: originY + box.center.y, z: 0 } });
world.insert(entity, RigidBody2D, { bodyType: BodyType.Static });
- // Position is in pixels (physics scales it by pixelsPerUnit); halfExtents are
- // PHYSICS units (metres), so divide the pixel size — otherwise a tile collider
- // is pixelsPerUnit× too big (the default 100 → 100× oversized).
- world.insert(entity, BoxCollider2D, {
- halfExtents: { x: mergedW * 0.5 / pixelsPerUnit, y: mergedH * 0.5 / pixelsPerUnit },
- });
+ world.insert(entity, BoxCollider2D, { halfExtents: { x: box.halfExtents.x / pixelsPerUnit, y: box.halfExtents.y / pixelsPerUnit } });
entities.push(entity);
}
return entities;
@@ -904,18 +895,13 @@ export function generateTileCollision(
world, layer.tiles, layer.width, layer.height,
mapData.tileWidth, mapData.tileHeight, collisionIds,
originX, originY,
+ 1, tiledGridLayout(mapData),
);
}
/**
- * @brief Build static box colliders for an INFINITE (chunked) tilemap layer from its
- * collidable tiles — the native scene-`TilemapLayer` path.
- *
- * Each chunk's collidable tiles are greedy-merged independently (no cross-chunk merge); a
- * merged rect (x0,y0)-(x1,y1) maps to a world AABB by the SAME orthogonal convention
- * `worldToTile` uses (tile tx covers world-x [origin.x+tx·tw, origin.x+(tx+1)·tw); world-y
- * grows downward as ty rises), so colliders line up exactly with what the painter placed.
- * (Isometric/staggered collision is not derived here.)
+ * Static boxes from native chunks, with layout-aware placement and exact per-chunk merging.
+ * Positions use layer pixels; extents are divided by pixelsPerUnit for physics.
*/
export function generateChunkCollision(
world: World,
@@ -926,30 +912,17 @@ export function generateChunkCollision(
originX: number,
originY: number,
pixelsPerUnit: number = 1,
+ layout?: TileGridLayout,
): Entity[] {
- const entities: Entity[] = [];
+
+ const grid = collisionGrid(tileW, tileH, layout), entities: Entity[] = [];
for (const chunk of chunks) {
- const merged = mergeCollisionTiles(chunk.tiles, CHUNK_SIZE, CHUNK_SIZE, collisionIds);
- const baseX = chunk.x * CHUNK_SIZE;
- const baseY = chunk.y * CHUNK_SIZE;
- for (const rect of merged) {
- const x0 = baseX + rect.col;
- const y0 = baseY + rect.row;
- const x1 = x0 + rect.width - 1;
- const y1 = y0 + rect.height - 1;
+ 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 + ((x0 + x1 + 1) / 2) * tileW,
- y: originY - ((y0 + y1 + 1) / 2) * tileH,
- z: 0,
- },
- });
+ world.insert(entity, Transform, { position: { x: originX + box.center.x, y: originY + box.center.y, z: 0 } });
world.insert(entity, RigidBody2D, { bodyType: BodyType.Static });
- // halfExtents in physics units (metres); divide the pixel size by ppu.
- world.insert(entity, BoxCollider2D, {
- halfExtents: { x: rect.width * tileW * 0.5 / pixelsPerUnit, y: rect.height * tileH * 0.5 / pixelsPerUnit },
- });
+ world.insert(entity, BoxCollider2D, { halfExtents: { x: box.halfExtents.x / pixelsPerUnit, y: box.halfExtents.y / pixelsPerUnit } });
entities.push(entity);
}
}
@@ -1023,35 +996,12 @@ export function generateChunkPolygonCollision(
originX: number,
originY: number,
pixelsPerUnit: number = 1,
+ layout?: TileGridLayout,
): Entity[] {
- const entities: Entity[] = [];
- if (polygonShapes.size === 0) return entities;
- for (const chunk of chunks) {
- const baseX = chunk.x * CHUNK_SIZE;
- const baseY = chunk.y * CHUNK_SIZE;
- for (let i = 0; i < chunk.tiles.length; i++) {
- const raw = chunk.tiles[i];
- const id = tileIdOf(raw);
- const shape = polygonShapes.get(id);
- if (!shape) continue;
- const gx = baseX + (i % CHUNK_SIZE);
- const gy = baseY + Math.floor(i / CHUNK_SIZE);
- const f = tileFlagsOf(raw);
- const entity = world.spawn();
- world.insert(entity, Transform, {
- position: { x: originX + (gx + 0.5) * tileW, y: originY - (gy + 0.5) * tileH, z: 0 },
- });
- world.insert(entity, RigidBody2D, { bodyType: BodyType.Static });
- // PolygonCollider2D vertices are physics units (uploaded unscaled, like
- // BoxCollider2D.halfExtents) — divide the pixel-space outline by ppu.
- world.insert(entity, PolygonCollider2D, {
- vertices: polygonLocalVerts(shape, tileW, tileH, f.flipH, f.flipV, f.flipD)
- .map((v) => ({ x: v.x / pixelsPerUnit, y: v.y / pixelsPerUnit })),
- });
- entities.push(entity);
- }
- }
- return entities;
+
+ const shapes = new Map<number, ResolvedTileCollision>();
+ for (const [id, points] of polygonShapes) shapes.set(id, { shape: { type: "polygon", points: Array.from(points) } });
+ return generateChunkTileShapes(world, chunks, shapes, tileW, tileH, originX, originY, pixelsPerUnit, layout);
}
/** A one-way solid-side normal (layer y-up; {0,1} = solid-top), reoriented by cell flips
@@ -1082,11 +1032,13 @@ function spawnTileShape(
originX: number,
originY: number,
ppu: number,
+ grid: TileGridParams,
): Entity {
const f = tileFlagsOf(raw);
+ const center = tileCellCenter(grid, gx, gy);
const entity = world.spawn();
world.insert(entity, Transform, {
- position: { x: originX + (gx + 0.5) * tileW, y: originY - (gy + 0.5) * tileH, z: 0 },
+ position: { x: originX + center.x, y: originY + center.y, z: 0 },
});
world.insert(entity, RigidBody2D, { bodyType: BodyType.Static });
@@ -1144,10 +1096,12 @@ export function generateChunkTileShapes(
originX: number,
originY: number,
pixelsPerUnit: number = 1,
+ layout?: TileGridLayout,
): Entity[] {
const entities: Entity[] = [];
if (tileShapes.size === 0) return entities;
const ppu = pixelsPerUnit || 1;
+ const grid = collisionGrid(tileW, tileH, layout);
for (const chunk of chunks) {
const baseX = chunk.x * CHUNK_SIZE;
const baseY = chunk.y * CHUNK_SIZE;
@@ -1157,7 +1111,7 @@ export function generateChunkTileShapes(
if (!rc) continue;
const gx = baseX + (i % CHUNK_SIZE);
const gy = baseY + Math.floor(i / CHUNK_SIZE);
- entities.push(spawnTileShape(world, rc, raw, gx, gy, tileW, tileH, originX, originY, ppu));
+ entities.push(spawnTileShape(world, rc, raw, gx, gy, tileW, tileH, originX, originY, ppu, grid));
}
}
return entities;
@@ -1179,10 +1133,12 @@ export function generateLayerTileShapes(
originX: number,
originY: number,
pixelsPerUnit: number = 1,
+ layout?: TileGridLayout,
): Entity[] {
const entities: Entity[] = [];
if (tileShapes.size === 0) return entities;
const ppu = pixelsPerUnit || 1;
+ const grid = collisionGrid(tileW, tileH, layout);
const count = Math.min(tiles.length, gridWidth * gridHeight);
for (let i = 0; i < count; i++) {
const raw = tiles[i];
@@ -1190,7 +1146,7 @@ export function generateLayerTileShapes(
if (!rc) continue;
entities.push(spawnTileShape(
world, rc, raw, i % gridWidth, Math.floor(i / gridWidth),
- tileW, tileH, originX, originY, ppu,
+ tileW, tileH, originX, originY, ppu, grid,
));
}
return entities;
@@ -1199,8 +1155,12 @@ export function generateLayerTileShapes(
/** The TilemapLayer a Tiled layer becomes: its lattice, and what Tiled says about drawing it. */
export function tiledLayerComponent(
layer: TiledLayerData, tileWidth: number, tileHeight: number, renderLayer: number,
-): Pick<TilemapLayerData, 'cellSize' | 'renderLayer' | 'visible' | 'opacity' | 'tintColor' | 'parallaxFactor'> {
+ layout?: TileGridLayout,
+): Pick<TilemapLayerData, 'cellSize' | 'renderLayer' | 'visible' | 'opacity' | 'tintColor' | 'parallaxFactor'
+ | 'orientation' | 'hexSideLength' | 'staggerAxis' | 'staggerIndex'> {
return {
+ orientation: layout?.orientation ?? 0, hexSideLength: layout?.hexSideLength ?? 0,
+ staggerAxis: layout?.staggerAxisX ? 1 : 0, staggerIndex: layout?.staggerIndexEven ? 1 : 0,
cellSize: { x: tileWidth, y: tileHeight },
renderLayer,
visible: layer.visible,
@@ -1218,6 +1178,7 @@ export function loadTiledMap(
): Entity[] {
const entities: Entity[] = [];
const firstTileset = mapData.tilesets[0];
+ const layout = tiledGridLayout(mapData);
let layerIndex = 0;
for (const layer of mapData.layers) {
@@ -1232,13 +1193,15 @@ export function loadTiledMap(
const columns = firstTileset?.columns ?? 1;
world.insert(entity, TilemapLayer, {
- ...tiledLayerComponent(layer, mapData.tileWidth, mapData.tileHeight, layerIndex),
+ ...tiledLayerComponent(layer, mapData.tileWidth, mapData.tileHeight, layerIndex, layout),
tileset: textureHandle,
tilesetColumns: columns,
});
TilemapAPI.initInfiniteLayer(entity, mapData.tileWidth, mapData.tileHeight);
TilemapAPI.setOriginEntity(entity, entity);
+ TilemapAPI.setGridType(entity, layout.orientation);
+ TilemapAPI.setHexParams(entity, layout.hexSideLength ?? 0, !!layout.staggerAxisX, !!layout.staggerIndexEven);
uploadTiledLayerTiles(entity, layer);
entities.push(entity);
@@ -1262,7 +1225,7 @@ export function loadTiledMap(
entities.push(...(layer.infinite
? generateChunkCollision(
world, layer.chunks, tileCollisionIds,
- mapData.tileWidth, mapData.tileHeight, 0, 0)
+ mapData.tileWidth, mapData.tileHeight, 0, 0, 1, layout)
: generateTileCollision(world, layer, mapData, tileCollisionIds, 0, 0)));
}
}
@@ -1272,10 +1235,10 @@ export function loadTiledMap(
entities.push(...(layer.infinite
? generateChunkTileShapes(
world, layer.chunks, mapData.tileShapes,
- mapData.tileWidth, mapData.tileHeight, 0, 0)
+ mapData.tileWidth, mapData.tileHeight, 0, 0, 1, layout)
: generateLayerTileShapes(
world, layer.tiles, layer.width, layer.height, mapData.tileShapes,
- mapData.tileWidth, mapData.tileHeight, 0, 0)));
+ mapData.tileWidth, mapData.tileHeight, 0, 0, 1, layout)));
}
}
diff --git a/sdk/src/tilemap/tilemapPlugin.ts b/sdk/src/tilemap/tilemapPlugin.ts
index ccdd9f81a..d9c724b67 100644
--- a/sdk/src/tilemap/tilemapPlugin.ts
+++ b/sdk/src/tilemap/tilemapPlugin.ts
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import type { App, Plugin } from '../app/app';
-import { engineApi } from '../ecs/bridge/engineApi';
+import { engineApi, worldEngineApi } from '../ecs/bridge/engineApi';
import { Transform, TilemapLayer, Sprite, Canvas, RuntimeOnly, Marker, type TilemapLayerData } from '../ecs/component';
import { Schedule } from '../ecs/system';
import { defineResource } from '../ecs/resource';
@@ -15,8 +15,8 @@ import { isCollisionPaletteRef, buildCollisionPaletteModel, parseCollisionMateri
import { _bindTileCollisionLookup, type LayerCollisionTable } from './tileQuery';
import type { ResolvedTileCollision } from './tilesetResolve';
import {
- generateLayerCollision, generateLayerTileShapes, generateChunkCollision, generateChunkTileShapes,
- spawnObjectRegion, isCollisionObjectGroup, decodeTiledGid, tiledLayerComponent,
+ generateChunkCollision, generateChunkTileShapes,
+ spawnObjectRegion, isCollisionObjectGroup, decodeTiledGid, tiledLayerComponent, tiledGridLayout,
} from './tiledLoader';
import { decodeTilemapChunks } from './chunkCodec';
import { Assets, type AssetsData } from '../asset/AssetPlugin';
@@ -27,17 +27,13 @@ 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';
-const GRID_TYPE_MAP: Record<string, number> = {
- orthogonal: 0,
- isometric: 1,
- staggered: 2,
- hexagonal: 3,
-};
-const GRID_STAGGERED = 2;
-const GRID_HEXAGONAL = 3;
interface CollisionInputs {
+ gridKey: string;
+ originX: number;
+ originY: number;
generation: number;
revision: number;
width: number;
@@ -70,6 +66,7 @@ export class TilemapRuntime {
private animatedLayers_ = new Set<number>();
/** Tilemap(source) entity → the RuntimeOnly child layer entities derived from its `.tmj`. */
private sourceLayerEntities_ = new Map<number, Entity[]>();
+ private derivedLayers_ = new Set<number>();
/** Tilemap(source) entity → the cached source OBJECT its children were derived
* from. Identity is the change detector: a `source` field edit resolves to a
* different object, a hot reload re-registers a fresh one, an invalidation
@@ -270,6 +267,7 @@ export class TilemapRuntime {
// and a wrong one after id reuse) and leaks its query table.
animatedLayers.delete(entity);
this.queryTableCache_.delete(entity);
+ this.derivedLayers_.delete(entity);
const colliders = collisionEntities.get(entity);
if (colliders) {
for (const e of colliders) world.despawn(e);
@@ -293,7 +291,7 @@ export class TilemapRuntime {
const refs = tilesetRefs.get(entity);
// A layer needs either a copied texture (legacy) or .estileset ref(s).
- if (!layerData.tileset && (!refs || refs.length === 0)) {
+ if (!this.derivedLayers_.has(entity) && !layerData.tileset && (!refs || refs.length === 0)) {
for (const collider of collisionEntities.get(entity) ?? []) world.despawn(collider);
collisionEntities.delete(entity);
collisionInputs.delete(entity);
@@ -403,49 +401,7 @@ export class TilemapRuntime {
}
}
- // Rebuild native collision when its content or geometry changes;
- // merge solid boxes and preserve individual rich shapes.
- const collIds = nativeCollisionIds.get(entity);
- const tileShapes = nativeTileShapes.get(entity);
- const hasBox = collIds != null && collIds.length > 0;
- const hasShapes = tileShapes != null && tileShapes.size > 0;
- const revision = playMode && (hasBox || hasShapes)
- ? engine.tilemap_getEditRevision?.(entity) ?? 0
- : 0;
- const generation = playMode && (hasBox || hasShapes)
- ? engine.tilemap_getGeneration?.(entity) ?? 0
- : 0;
- const previous = collisionInputs.get(entity);
- const changed = !previous || previous.generation !== generation || previous.revision !== revision
- || previous.width !== layerData.cellSize.x || previous.height !== layerData.cellSize.y
- || previous.pixelsPerUnit !== pixelsPerUnit
- || previous.ids !== collIds || previous.shapes !== tileShapes;
- if (playMode && collisionEntities.has(entity) && (changed || (!hasBox && !hasShapes))) {
- for (const collider of collisionEntities.get(entity)!) world.despawn(collider);
- collisionEntities.delete(entity);
- collisionInputs.delete(entity);
- }
- if (playMode && (hasBox || hasShapes) && !collisionEntities.has(entity)) {
- const chunks = decodeTilemapChunks(TilemapAPI.exportChunks(entity));
- const spawned: Entity[] = [];
- if (hasBox) {
- spawned.push(...generateChunkCollision(
- world, chunks, new Set(collIds),
- layerData.cellSize.x, layerData.cellSize.y, 0, 0, pixelsPerUnit,
- ));
- }
- if (hasShapes) {
- spawned.push(...generateChunkTileShapes(
- world, chunks, tileShapes,
- layerData.cellSize.x, layerData.cellSize.y, 0, 0, pixelsPerUnit,
- ));
- }
- this.attachCollision_(world, entity, spawned);
- collisionEntities.set(entity, spawned);
- collisionInputs.set(entity, { generation, revision, width: layerData.cellSize.x,
- height: layerData.cellSize.y, pixelsPerUnit,
- ids: collIds, shapes: tileShapes });
- }
+ this.syncLayerCollision_(world, entity, layerData, pixelsPerUnit, playMode);
}
const tilemapEntities = world.getEntitiesWithComponents(
@@ -471,7 +427,7 @@ export class TilemapRuntime {
if (!sourceLayerEntities.has(entity)) {
const children: Entity[] = [];
- const gridType = GRID_TYPE_MAP[cached.orientation ?? 'orthogonal'] ?? 0;
+ const layout = tiledGridLayout(cached), gridType = layout.orientation;
for (let i = 0; i < cached.layers.length; i++) {
const layer = cached.layers[i];
@@ -484,7 +440,7 @@ export class TilemapRuntime {
const child = world.spawn(layer.name || `TiledLayer_${i}`);
world.insert(child, Transform, { position: { x: 0, y: 0, z: 0 } });
world.insert(child, TilemapLayer,
- tiledLayerComponent(layer, cached.tileWidth, cached.tileHeight, i));
+ tiledLayerComponent(layer, cached.tileWidth, cached.tileHeight, i, layout));
world.insert(child, RuntimeOnly, {});
world.setParent(child, entity);
@@ -513,7 +469,7 @@ export class TilemapRuntime {
}
// Staggered + hexagonal both read the stagger axis/index (the
// half-cell shift). Staggered iso ignores the side length.
- if (gridType === GRID_STAGGERED || gridType === GRID_HEXAGONAL) {
+ if (usesStagger(gridType)) {
TilemapAPI.setHexParams(
child, cached.hexSideLength ?? 0,
cached.staggerAxis === 'x', cached.staggerIndex === 'even',
@@ -572,6 +528,11 @@ export class TilemapRuntime {
children.push(child);
initializedLayers.add(child);
+ this.derivedLayers_.add(child);
+ appliedCellSize.set(child, { x: cached.tileWidth, y: cached.tileHeight });
+ if (cached.collisionTileIds?.length) nativeCollisionIds.set(child, cached.collisionTileIds);
+ if (cached.tileShapes?.size) nativeTileShapes.set(child, cached.tileShapes);
+ this.syncLayerCollision_(world, child, world.get(child, TilemapLayer), pixelsPerUnit, playMode);
}
// Tile (GID) objects — a positioned tile rendered as a Sprite,
@@ -666,61 +627,7 @@ export class TilemapRuntime {
this.sourceDerivedFrom_.set(entity, cached);
}
- // Object-group colliders (solid + sensor) are derived as RuntimeOnly region
- // entities above (edit+play, gizmo-visible); only TILE collision spawns
- // here, play-mode only.
- const hasTileCollision = !!(cached.collisionTileIds && cached.collisionTileIds.length > 0);
- const hasTileShapes = !!(cached.tileShapes && cached.tileShapes.size > 0);
- if (
- playMode
- && !collisionEntities.has(entity)
- && (hasTileCollision || hasTileShapes)
- ) {
- const spawned: Entity[] = [];
- if (hasTileCollision || hasTileShapes) {
- const ids = new Set(cached.collisionTileIds);
- for (const layer of cached.layers) {
- if (layer.infinite) {
- // Infinite Tiled layers are re-chunked to CHUNK_SIZE at
- // parse, so they ride the SAME chunk generators the
- // painted path uses.
- if (layer.chunks.length === 0) continue;
- if (hasTileCollision) {
- spawned.push(...generateChunkCollision(
- world, layer.chunks, ids,
- cached.tileWidth, cached.tileHeight, 0, 0, pixelsPerUnit,
- ));
- }
- if (hasTileShapes) {
- spawned.push(...generateChunkTileShapes(
- world, layer.chunks, cached.tileShapes!,
- cached.tileWidth, cached.tileHeight, 0, 0, pixelsPerUnit,
- ));
- }
- continue;
- }
- if (layer.tiles.length === 0) continue;
- if (hasTileCollision) {
- spawned.push(...generateLayerCollision(
- world, layer.tiles, layer.width, layer.height,
- cached.tileWidth, cached.tileHeight, ids, 0, 0, pixelsPerUnit,
- ));
- }
- // Rich Tiled tile-collision (shapes / one-way / sensor /
- // material) spawns through the same per-tile core as the
- // painted `.estileset` path.
- if (hasTileShapes) {
- spawned.push(...generateLayerTileShapes(
- world, layer.tiles, layer.width, layer.height,
- cached.tileShapes!, cached.tileWidth, cached.tileHeight,
- 0, 0, pixelsPerUnit,
- ));
- }
- }
- }
- this.attachCollision_(world, entity, spawned);
- collisionEntities.set(entity, spawned);
- }
+
}
for (const entity of [...sourceLayerEntities.keys()]) {
@@ -747,6 +654,51 @@ export class TilemapRuntime {
}
}
+ 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 hasBoxes = !!ids?.length, hasShapes = !!shapes?.size;
+ const current = this.collisionEntities_.get(entity);
+ if (!hasBoxes && !hasShapes) {
+ for (const collider of current ?? []) if (world.valid(collider)) world.despawn(collider);
+ this.collisionEntities_.delete(entity); this.collisionInputs_.delete(entity);
+ return;
+ }
+ const engine = worldEngineApi(world), tiles = this.toolkit_;
+ if (!engine) return;
+ const generation = engine.tilemap_getGeneration?.(entity) ?? 0;
+ const revision = engine.tilemap_getEditRevision?.(entity) ?? 0;
+ 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 changed = !previous || previous.generation !== generation || previous.revision !== revision
+ || previous.gridKey !== gridKey || previous.width !== layer.cellSize.x || previous.height !== layer.cellSize.y
+ || previous.pixelsPerUnit !== ppu || previous.ids !== ids || previous.shapes !== shapes;
+ if (current && changed) {
+ for (const collider of current) if (world.valid(collider)) world.despawn(collider);
+ this.collisionEntities_.delete(entity); this.collisionInputs_.delete(entity);
+ } else if (current && previous && (previous.originX !== originX || previous.originY !== originY)) {
+ const dx = originX - previous.originX, dy = originY - previous.originY;
+ for (const collider of current) world.update(collider, Transform, value => {
+ value.position.x += dx; value.position.y += dy;
+ });
+ previous.originX = originX; previous.originY = originY;
+ }
+ if (this.collisionEntities_.has(entity)) return;
+ const layout = { orientation: layer.orientation ?? 0, hexSideLength: layer.hexSideLength ?? 0,
+ staggerAxisX: layer.staggerAxis === 1, staggerIndexEven: layer.staggerIndex === 1 };
+ const chunks = decodeTilemapChunks(tiles.exportChunks(entity));
+ const spawned: Entity[] = [];
+ if (hasBoxes) spawned.push(...generateChunkCollision(world, chunks, new Set(ids), layer.cellSize.x, layer.cellSize.y,
+ originX, originY, ppu, layout));
+ if (hasShapes) spawned.push(...generateChunkTileShapes(world, chunks, shapes!, layer.cellSize.x, layer.cellSize.y,
+ originX, originY, ppu, layout));
+ this.attachCollision_(world, entity, spawned);
+ this.collisionEntities_.set(entity, spawned);
+ this.collisionInputs_.set(entity, { generation, revision, gridKey, originX, originY,
+ width: layer.cellSize.x, height: layer.cellSize.y, pixelsPerUnit: ppu, ids, shapes });
+ }
+
/** Drop ONE tilemap entity's derived artifacts (child layer entities +
* play-mode colliders + bookkeeping) so the sync can re-derive — or not,
* if its source is gone. Fires when the Tilemap component disappears AND
@@ -762,18 +714,16 @@ export class TilemapRuntime {
}
this.animatedLayers_.delete(child);
this.derivedQueryTables_.delete(child);
+ this.derivedLayers_.delete(child);
+ this.nativeCollisionIds_.delete(child); this.nativeTileShapes_.delete(child);
+ this.collisionEntities_.delete(child); this.collisionInputs_.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.
if (world.valid(child)) world.despawn(child);
}
this.sourceLayerEntities_.delete(entity);
this.sourceDerivedFrom_.delete(entity);
-
- const colliders = this.collisionEntities_.get(entity);
- if (colliders) {
- for (const e of colliders) if (world.valid(e)) world.despawn(e);
- this.collisionEntities_.delete(entity);
- }
}
/**
@@ -795,6 +745,7 @@ export class TilemapRuntime {
this.appliedGrid_.clear();
this.animatedLayers_.clear();
this.sourceLayerEntities_.clear();
+ this.derivedLayers_.clear();
this.sourceDerivedFrom_.clear();
// Collider entities die with the world on reset/teardown; just drop our bookkeeping.
this.collisionEntities_.clear();
diff --git a/sdk/tests/collision-grid-geometry.test.ts b/sdk/tests/collision-grid-geometry.test.ts
new file mode 100644
index 000000000..b3eeaceb0
--- /dev/null
+++ b/sdk/tests/collision-grid-geometry.test.ts
@@ -0,0 +1,32 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { describe, expect, it } from 'vitest';
+import { collisionBoxes } from '../src/tilemap/collisionBoxes';
+import { tileCellCenter, type TileGridParams } from '../src/tilemap/tileGeometry';
+
+const grids: TileGridParams[] = [];
+for (const orientation of [0, 1, 2, 3]) for (const staggerAxisX of [false, true]) {
+ for (const staggerIndexEven of [false, true]) grids.push({ orientation, staggerAxisX, staggerIndexEven,
+ tileWidth: 16, tileHeight: 24, hexSideLength: 6 });
+}
+describe('projected collision box merging', () => {
+ it.each(grids)('preserves the exact union of authored boxes: %j', grid => {
+ const cells = new Uint16Array([1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1]);
+ const boxes = collisionBoxes(cells, 4, 4, new Set([1]), grid, -32, -48);
+ const originals = [...cells].flatMap((id, i) => id ? [tileCellCenter(grid, -32 + i % 4, -48 + Math.floor(i / 4))] : []);
+ const minX = Math.min(...originals.map(p => p.x)) - 10, maxX = Math.max(...originals.map(p => p.x)) + 10;
+ const minY = Math.min(...originals.map(p => p.y)) - 14, maxY = Math.max(...originals.map(p => p.y)) + 14;
+ for (let y = minY; y <= maxY; y += 2.3) for (let x = minX; x <= maxX; x += 2.7) {
+ const expected = originals.some(p => Math.abs(x - p.x) <= 8 && Math.abs(y - p.y) <= 12);
+ const actual = boxes.some(box => Math.abs(x - box.center.x) <= box.halfExtents.x && Math.abs(y - box.center.y) <= box.halfExtents.y);
+ expect(actual).toBe(expected);
+ }
+ });
+ it.each(grids)('keeps dense chunk body counts bounded: %j', grid => {
+ const cells = new Uint16Array(256).fill(1);
+ const boxes = collisionBoxes(cells, 16, 16, new Set([1]), grid);
+ expect(boxes.length).toBeGreaterThan(0);
+ expect(boxes.length).toBeLessThanOrEqual(32);
+ if (grid.orientation === 0) expect(boxes).toHaveLength(1);
+ });
+});
diff --git a/sdk/tests/tiled-layer-drawing.test.ts b/sdk/tests/tiled-layer-drawing.test.ts
index f152cf399..6561b2b4d 100644
--- a/sdk/tests/tiled-layer-drawing.test.ts
+++ b/sdk/tests/tiled-layer-drawing.test.ts
@@ -69,6 +69,7 @@ describe('a Tiled layer draws the way Tiled says', () => {
it('hands the layer component all of it', async () => {
const [, water] = await loadedLayers();
expect(tiledLayerComponent(water, 16, 12, 1)).toEqual({
+ orientation: 0, hexSideLength: 0, staggerAxis: 0, staggerIndex: 0,
cellSize: { x: 16, y: 12 },
renderLayer: 1,
visible: false,
diff --git a/sdk/tests/tilemap-grid-collision-wasm.test.ts b/sdk/tests/tilemap-grid-collision-wasm.test.ts
new file mode 100644
index 000000000..a7de8133a
--- /dev/null
+++ b/sdk/tests/tilemap-grid-collision-wasm.test.ts
@@ -0,0 +1,131 @@
+// 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, RuntimeOnly } from '../src/ecs/component';
+import { Tilemap } from '../src/tilemap/components';
+import { TilemapPlugin, TilemapRuntimeState } from '../src/tilemap/tilemapPlugin';
+import { Tilemaps } from '../src/tilemap/tilemapAPI';
+import { tileCellCenter } from '../src/tilemap/tileGeometry';
+import { Physics2DPlugin } from '../src/physics/Physics2DPlugin';
+import { Physics2DRuntime } from '../src/physics/Physics2DRuntime';
+import { Physics2D } from '../src/physics/Physics2D';
+import { RigidBody2D, BoxCollider2D, BodyType } from '../src/physics/PhysicsComponents';
+import type { PhysicsWasmModule } from '../src/physics/PhysicsModuleLoader';
+import { Assets } from '../src/asset/Assets';
+import { Assets as AssetsResource } from '../src/asset/AssetPlugin';
+import { registerTilemapSupport } from '../src/tilemap/tilemapSupport';
+import type { ESEngineModule, CppResourceManager } from '../src/wasm';
+import { HAS_WASM, hasSideModule, loadSideModule, loadWasmModule } from './helpers/loadWasm';
+import { initResourceManager, shutdownResourceManager } from '../src/wasm/resourceManager';
+
+let core: ESEngineModule;
+const apps: App[] = [], cleanup: Array<() => void> = [];
+afterEach(() => { for (const app of apps.splice(0)) app.quit(); for (const fn of cleanup.splice(0).reverse()) fn(); shutdownResourceManager(); vi.restoreAllMocks(); });
+function scene() {
+ core.setActiveContext(null);
+ const app = App.new(); apps.push(app);
+ app.connectCpp(new core.Registry(), core, { ownedRegistry: true }); app.addPlugin(new TilemapPlugin());
+ return { app, world: app.world, tiles: app.getResource(Tilemaps), runtime: app.getResource(TilemapRuntimeState) };
+}
+function generated(app: App, layer: number) {
+ return (app.getResource(TilemapRuntimeState) as unknown as { collisionEntities_: Map<number, number[]> }).collisionEntities_.get(layer)!;
+}
+describe.skipIf(!HAS_WASM)('projected tile collision ownership', () => {
+ beforeAll(async () => { core = await loadWasmModule(); });
+ it.each([0, 1, 2, 3])('updates layout %s and shifts origin without replacing stable colliders', async orientation => {
+ const { app, world, tiles, runtime } = scene(), layer = world.spawn();
+ world.insert(layer, Transform); world.insert(layer, TilemapLayer, { cellSize: { x: 16, y: 24 }, orientation, hexSideLength: 6 });
+ runtime.setLayerTilesets(layer, ['builtin:collision']); tiles.initInfiniteLayer(layer, 16, 24); tiles.setTile(layer, 3, 2, 1);
+ await app.tick(1 / 60);
+ const original = [...generated(app, layer)], expected = tileCellCenter({ orientation, tileWidth: 16, tileHeight: 24, hexSideLength: 6 }, 3, 2);
+ expect(original).toHaveLength(1);
+ expect(world.get(original[0], Transform).position).toMatchObject(expected);
+ const exported = vi.spyOn(tiles, 'exportChunks');
+ world.update(layer, TilemapLayer, value => { value.originOffset = { x: 7, y: -3 }; });
+ await app.stepFrames(3, 1 / 60);
+ expect(generated(app, layer)).toEqual(original); expect(exported).not.toHaveBeenCalled();
+ expect(world.get(original[0], Transform).position).toMatchObject({ x: expected.x + 7, y: expected.y - 3 });
+ world.update(layer, TilemapLayer, value => { value.orientation = (orientation + 1) % 4; });
+ await app.tick(1 / 60);
+ expect(generated(app, layer)).not.toEqual(original); expect(exported).toHaveBeenCalledOnce();
+ expect(world.valid(original[0])).toBe(false);
+ const next = tileCellCenter({ orientation: (orientation + 1) % 4, tileWidth: 16, tileHeight: 24, hexSideLength: 6 }, 3, 2);
+ expect(world.get(generated(app, layer)[0], Transform).position).toMatchObject({ x: next.x + 7, y: next.y - 3 });
+ });
+
+ it.each([false, true])('derives imported colliders under their actual layer (infinite=%s)', async infinite => {
+ registerTilemapSupport();
+ const { app, world, tiles } = scene();
+ // Collision-only fixture: image loading fails before any GPU allocation.
+ initResourceManager({ acquireTextureByPath: () => 0, invalidateTexturePath: () => false,
+ releaseTexture: () => {} } as unknown as CppResourceManager);
+ const document = JSON.stringify({ orientation: 'hexagonal', hexsidelength: 6, staggeraxis: 'x', staggerindex: 'even',
+ width: 4, height: 3, tilewidth: 16, tileheight: 24, infinite,
+ tilesets: [{ firstgid: 1, name: 'collision', image: '', columns: 1, tilecount: 1,
+ tiles: [{ id: 0, properties: [{ name: 'collision', value: true }] }] }],
+ layers: [{ type: 'tilelayer', name: 'ground', width: 4, height: 3,
+ ...(infinite ? { chunks: [{ x: 3, y: 2, width: 1, height: 1, data: [1] }] }
+ : { data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1] }) }] });
+ const assets = Assets.create({ module: core, backend: { fetchText: async () => document,
+ fetchBinary: async () => { throw Error('Collision-only fixture has no texture'); }, resolveUrl: path => path } });
+ cleanup.push(() => assets.releaseAll()); app.insertResource(AssetsResource, assets);
+ const held = await assets.acquireTyped('tilemap', 'collision.tmj'); cleanup.push(() => held.release());
+ const owner = world.spawn(); world.insert(owner, Transform); world.insert(owner, Tilemap, { source: 'collision.tmj' });
+ await app.stepFrames(3, 1 / 60);
+ const layer = world.getEntitiesWithComponents([TilemapLayer]).find(id => world.has(id, RuntimeOnly))!;
+ expect(layer).toBeDefined();
+ const component = world.get(layer, TilemapLayer);
+ expect(component.orientation).toBe(3); expect(component.staggerAxis).toBe(1); expect(component.staggerIndex).toBe(1);
+ const colliders = [...generated(app, layer)]; expect(colliders).toHaveLength(1);
+ expect(world.get(colliders[0], Parent).entity).toBe(layer);
+ const exported = vi.spyOn(tiles, 'exportChunks');
+ world.update(layer, Transform, value => { value.position.x = 40; }); await app.stepFrames(2, 1 / 60);
+ world.ensureTransformsComposed();
+ expect(generated(app, layer)).toEqual(colliders); expect(exported).not.toHaveBeenCalled();
+ const center = tileCellCenter({ orientation: 3, tileWidth: 16, tileHeight: 24, hexSideLength: 6, staggerAxisX: true, staggerIndexEven: true }, 3, 2);
+ expect(world.get(colliders[0], Transform).worldPosition.x).toBeCloseTo(center.x + 40, 4);
+ const anchor = tiles.tileToWorld(layer, 3, 2, 0, 0);
+ expect(anchor.x + 8).toBeCloseTo(center.x, 4); expect(anchor.y - 12).toBeCloseTo(center.y, 4);
+ world.update(layer, TilemapLayer, value => { value.originOffset = { x: 7, y: -3 }; });
+ await app.stepFrames(2, 1 / 60); world.ensureTransformsComposed();
+ expect(generated(app, layer)).toEqual(colliders); expect(exported).not.toHaveBeenCalled();
+ expect(world.get(colliders[0], Transform).worldPosition.x).toBeCloseTo(center.x + 47, 4);
+ world.update(layer, TilemapLayer, value => { value.orientation = 1; }); await app.tick(1 / 60);
+ expect(generated(app, layer)).not.toEqual(colliders); expect(world.valid(colliders[0])).toBe(false);
+ const replacement = generated(app, layer)[0];
+ world.remove(owner, Tilemap); await app.tick(1 / 60);
+ expect(world.valid(layer)).toBe(false); expect(world.valid(replacement)).toBe(false);
+ });
+});
+
+describe.skipIf(!HAS_WASM || !hasSideModule('physics'))('projected tile collision in Box2D', () => {
+ beforeAll(async () => { core = await loadWasmModule(); });
+ it.each([0, 1, 2, 3])('lands a body on the rendered layout %s tile under parent rotation', async orientation => {
+ const { app, world, tiles, runtime } = scene(), angle = .37, nx = -Math.sin(angle), ny = Math.cos(angle);
+ const module = await loadSideModule<PhysicsWasmModule>('physics');
+ app.addPlugin(new Physics2DPlugin('', { gravity: { x: -nx * 9.81, y: -ny * 9.81 } }, async () => module));
+ await app.getResource(Physics2DRuntime).initPromise;
+ const parent = world.spawn(), layer = world.spawn();
+ const rotation = { x: 0, y: 0, z: Math.sin(angle / 2), w: Math.cos(angle / 2) };
+ world.insert(parent, Transform, { position: { x: 20, y: -35, z: 0 }, rotation });
+ world.insert(layer, Transform); world.setParent(layer, parent);
+ world.insert(layer, TilemapLayer, { cellSize: { x: 16, y: 24 }, orientation, hexSideLength: 6, originOffset: { x: 3, y: -2 } });
+ runtime.setLayerTilesets(layer, ['builtin:collision']); tiles.initInfiniteLayer(layer, 16, 24); tiles.setTile(layer, 3, 2, 1);
+ await app.stepFrames(3, 1 / 60);
+ const local = tileCellCenter({ orientation, tileWidth: 16, tileHeight: 24, hexSideLength: 6 }, 3, 2);
+ const center = { x: 20 + Math.cos(angle) * (local.x + 3) - Math.sin(angle) * (local.y - 2),
+ y: -35 + Math.sin(angle) * (local.x + 3) + Math.cos(angle) * (local.y - 2) };
+ const hit = app.getResource(Physics2D).raycast({ x: center.x + nx * 40, y: center.y + ny * 40 }, { x: -nx, y: -ny }, 80)
+ .find(value => value.entity === generated(app, layer)[0]);
+ expect(hit).toBeDefined(); expect(hit!.point.x).toBeCloseTo(center.x + nx * 12, 2); expect(hit!.point.y).toBeCloseTo(center.y + ny * 12, 2);
+ const actor = world.spawn();
+ world.insert(actor, Transform, { position: { x: center.x + nx * 40, y: center.y + ny * 40, z: 0 }, rotation });
+ world.insert(actor, RigidBody2D, { bodyType: BodyType.Dynamic, fixedRotation: true });
+ world.insert(actor, BoxCollider2D, { halfExtents: { x: .02, y: .02 } });
+ await app.stepFrames(120, 1 / 60);
+ const position = world.get(actor, Transform).worldPosition;
+ const distance = (position.x - center.x) * nx + (position.y - center.y) * ny;
+ expect(distance).toBeGreaterThan(12); expect(distance).toBeLessThan(20);
+ });
+});
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 8716e6df3..65594139f 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -28,6 +28,8 @@ export const NOTES_FLOOR = 'v0.65.0';
* the reader recognises anyway.
*/
export const NOTED = {
+ 'fix(tilemap): derive collision from each layer grid':
+ { note: 'Tile collision follows painted and imported layer layouts.' },
'fix(tilemap): share exact staggered and hex grid geometry':
{ note: 'Staggered and hexagonal picking follows cell polygons.' },
'test(editor): cover staggered polygon picking through transforms':