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): per-tile circle / one-way / sensor / material collision (SDK)

yhha5a63407d7db
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 7132bb633..2fb1ab45c 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1177 stable · 17 beta · 1 deprecated
+Symbols: 1179 stable · 17 beta · 1 deprecated
## ABI_LAYOUT_HASH — const
```
@@ -4970,6 +4970,16 @@ static prototype: ResMutInstance<any>
ImageBitmap | HTMLImageElement
```
+## ResolvedTileCollision — interface
+```
+density: number | undefined
+friction: number | undefined
+oneWay: { nx: number; ny: number; } | undefined
+restitution: number | undefined
+sensor: boolean | undefined
+shape: { type: "box"; } | { type: "polygon"; points: [number, number][]; } | { type: "circle"; cx: number; cy: number; r: number; }
+```
+
## ResourceDef — interface
```
_default: T
@@ -6219,6 +6229,13 @@ label: number
title: number
```
+## TileCollisionShape — type
+```
+| { type: 'box' }
+ | { type: 'polygon'; points: [number, number][] }
+ | { type: 'circle'; cx: number; cy: number; r: number }
+```
+
## TileFlags — interface
```
flipD: boolean
@@ -6354,8 +6371,16 @@ version: string
## TilesetCollision — type
```
-| { type: 'box' }
- | { type: 'polygon'; points: [number, number][] }
+TileCollisionShape & {
+ /** One-way (jump-through) platform: contacts from behind this normal pass through. */
+ oneWay?: { nx: number; ny: number };
+ /** Non-solid trigger volume (fires events, no physical response). */
+ sensor?: boolean;
+ /** Physics material overrides (absent = engine defaults). */
+ density?: number;
+ friction?: number;
+ restitution?: number;
+}
```
## TilesetTerrain — interface
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 8ce1a1ab6..fcdf952b6 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.node
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1176 stable · 19 beta · 1 deprecated
+Symbols: 1178 stable · 19 beta · 1 deprecated
## ANCHOR_AXES — const
```
@@ -4965,6 +4965,16 @@ static prototype: ResMutInstance<any>
ImageBitmap | HTMLImageElement
```
+## ResolvedTileCollision — interface
+```
+density: number | undefined
+friction: number | undefined
+oneWay: { nx: number; ny: number; } | undefined
+restitution: number | undefined
+sensor: boolean | undefined
+shape: { type: "box"; } | { type: "polygon"; points: [number, number][]; } | { type: "circle"; cx: number; cy: number; r: number; }
+```
+
## ResourceDef — interface
```
_default: T
@@ -6214,6 +6224,13 @@ label: number
title: number
```
+## TileCollisionShape — type
+```
+| { type: 'box' }
+ | { type: 'polygon'; points: [number, number][] }
+ | { type: 'circle'; cx: number; cy: number; r: number }
+```
+
## TileFlags — interface
```
flipD: boolean
@@ -6349,8 +6366,16 @@ version: string
## TilesetCollision — type
```
-| { type: 'box' }
- | { type: 'polygon'; points: [number, number][] }
+TileCollisionShape & {
+ /** One-way (jump-through) platform: contacts from behind this normal pass through. */
+ oneWay?: { nx: number; ny: number };
+ /** Non-solid trigger volume (fires events, no physical response). */
+ sensor?: boolean;
+ /** Physics material overrides (absent = engine defaults). */
+ density?: number;
+ friction?: number;
+ restitution?: number;
+}
```
## TilesetTerrain — interface
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.ts
index 5a7df1fbb..aa516472c 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -443,6 +443,8 @@ export {
type TilesetAsset,
type TilesetTile,
type TilesetCollision,
+ type TileCollisionShape,
+ type ResolvedTileCollision,
type TilesetAnimFrame,
type TerrainMode,
type TilesetTerrain,
diff --git a/sdk/src/tilemap/index.ts b/sdk/src/tilemap/index.ts
index 306e879dd..dfd26945f 100644
--- a/sdk/src/tilemap/index.ts
+++ b/sdk/src/tilemap/index.ts
@@ -7,7 +7,7 @@ export { TilemapPlugin, tilemapPlugin } from './tilemapPlugin';
export {
parseTmjJson, parseTmjWithExternals, loadTiledMap, loadTiledCollisionObjects,
generateTileCollision, generateLayerCollision, generateChunkCollision,
- generateChunkPolygonCollision, generateObjectCollision, isCollisionObjectGroup,
+ generateChunkPolygonCollision, generateChunkTileShapes, generateObjectCollision, isCollisionObjectGroup,
polygonLocalVerts, resolveRelativePath, packCollectionGrid,
type TiledMapData, type TiledLayerData, type TiledTilesetData,
type TiledCollectionTile, type CollectionGridTile,
@@ -26,12 +26,12 @@ export {
} from './tileStamp';
export {
TILESET_FORMAT_VERSION, parseTileset, serializeTileset, createTileset, collidableTileIds,
- type TilesetAsset, type TilesetTile, type TilesetCollision, type TilesetAnimFrame,
+ type TilesetAsset, type TilesetTile, type TilesetCollision, type TileCollisionShape, type TilesetAnimFrame,
type TerrainMode, type TilesetTerrain, type TilesetTileTerrain,
} from './tilesetAsset';
export {
resolveTilesetModel,
- type ResolvedTileset, type TilesetModel, type TilesetModelSlot,
+ type ResolvedTileset, type TilesetModel, type TilesetModelSlot, type ResolvedTileCollision,
} from './tilesetResolve';
export {
TB_N, TB_E, TB_S, TB_W, TB_NE, TB_SE, TB_SW, TB_NW, TERRAIN_NEIGHBORS,
diff --git a/sdk/src/tilemap/tiledLoader.ts b/sdk/src/tilemap/tiledLoader.ts
index e3e0ebcfc..71639b7f9 100644
--- a/sdk/src/tilemap/tiledLoader.ts
+++ b/sdk/src/tilemap/tiledLoader.ts
@@ -37,7 +37,8 @@ function uploadTiledLayerTiles(entity: Entity, layer: TiledLayerData): void {
}
}
}
-import { RigidBody, BoxCollider, CircleCollider, PolygonCollider, ChainCollider, BodyType } from '../physics/PhysicsComponents';
+import { RigidBody, BoxCollider, CircleCollider, PolygonCollider, ChainCollider, OneWayPlatform, BodyType } from '../physics/PhysicsComponents';
+import type { ResolvedTileCollision } from './tilesetResolve';
import { mergeCollisionTiles } from './collisionMerge';
import { CHUNK_SIZE } from './chunkCodec';
import { tileIdOf, tileFlagsOf } from './tileBits';
@@ -874,6 +875,94 @@ export function generateChunkPolygonCollision(
return entities;
}
+/** A one-way solid-side normal (world y-up; {0,1} = solid-top), reoriented by cell flips
+ * so a flipped platform's solid side follows the render. */
+function oneWayNormalWorld(nx: number, ny: number, fH: boolean, fV: boolean, fD: boolean): { x: number; y: number } {
+ let x = nx;
+ let y = ny;
+ if (fH) x = -x;
+ if (fV) y = -y;
+ if (fD) { const tmp = x; x = y; y = tmp; }
+ return { x, y };
+}
+
+/**
+ * Spawn one static collider per placed tile whose global id resolves to a RICH shape —
+ * polygon / circle, or a box carrying a one-way / sensor / material modifier — i.e. the
+ * tiles the plain-box greedy merge ({@link generateChunkCollision}) deliberately skips.
+ * Both run together over the same chunks. Flip flags reorient the shape (and the one-way
+ * normal) to match the rendered tile. Geometry is in physics units (÷ pixelsPerUnit).
+ */
+export function generateChunkTileShapes(
+ world: World,
+ chunks: { x: number; y: number; tiles: Uint16Array }[],
+ tileShapes: Map<number, ResolvedTileCollision>,
+ tileW: number,
+ tileH: number,
+ originX: number,
+ originY: number,
+ pixelsPerUnit: number = 1,
+): Entity[] {
+ const entities: Entity[] = [];
+ if (tileShapes.size === 0) return entities;
+ const ppu = pixelsPerUnit || 1;
+ 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 rc = tileShapes.get(tileIdOf(raw));
+ if (!rc) 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, RigidBody, { bodyType: BodyType.Static });
+
+ // Only the material/sensor fields the tile overrode; the rest keep component defaults.
+ const mat: { density?: number; friction?: number; restitution?: number; isSensor?: boolean } = {};
+ if (rc.density !== undefined) mat.density = rc.density;
+ if (rc.friction !== undefined) mat.friction = rc.friction;
+ if (rc.restitution !== undefined) mat.restitution = rc.restitution;
+ if (rc.sensor) mat.isSensor = true;
+
+ const s = rc.shape;
+ if (s.type === 'polygon') {
+ world.insert(entity, PolygonCollider, {
+ vertices: polygonLocalVerts(s.points, tileW, tileH, f.flipH, f.flipV, f.flipD)
+ .map((v) => ({ x: v.x / ppu, y: v.y / ppu })),
+ ...mat,
+ });
+ } else if (s.type === 'circle') {
+ // Reuse the polygon transform on the single centre point to apply flips; the
+ // radius is a tile-width fraction (assumes square-ish cells).
+ const c = polygonLocalVerts([[s.cx, s.cy]], tileW, tileH, f.flipH, f.flipV, f.flipD)[0];
+ world.insert(entity, CircleCollider, {
+ radius: (s.r * tileW) / ppu,
+ offset: { x: c.x / ppu, y: c.y / ppu },
+ ...mat,
+ });
+ } else {
+ world.insert(entity, BoxCollider, {
+ halfExtents: { x: (tileW * 0.5) / ppu, y: (tileH * 0.5) / ppu },
+ ...mat,
+ });
+ }
+
+ if (rc.oneWay) {
+ world.insert(entity, OneWayPlatform, {
+ normal: oneWayNormalWorld(rc.oneWay.nx, rc.oneWay.ny, f.flipH, f.flipV, f.flipD),
+ });
+ }
+ entities.push(entity);
+ }
+ }
+ return entities;
+}
+
export function loadTiledMap(
world: World,
mapData: TiledMapData,
diff --git a/sdk/src/tilemap/tilemapPlugin.ts b/sdk/src/tilemap/tilemapPlugin.ts
index 4d9a49be2..38f481b27 100644
--- a/sdk/src/tilemap/tilemapPlugin.ts
+++ b/sdk/src/tilemap/tilemapPlugin.ts
@@ -11,8 +11,9 @@ import { Tilemap } from './components';
import { registerSceneComponentCodec } from '../scene';
import { getTilemapSource, getResolvedTileset, type LoadedTilemapSource } from './tilesetCache';
import { resolveTilesetModel } from './tilesetResolve';
+import type { ResolvedTileCollision } from './tilesetResolve';
import {
- generateLayerCollision, generateChunkCollision, generateChunkPolygonCollision,
+ generateLayerCollision, generateChunkCollision, generateChunkTileShapes,
generateObjectCollision, isCollisionObjectGroup, decodeTiledGid,
} from './tiledLoader';
import { decodeTilemapChunks } from './chunkCodec';
@@ -53,8 +54,9 @@ export class TilemapPlugin implements Plugin {
private collisionEntities_ = new Map<number, Entity[]>();
/** 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 polygon collision outlines (global id → normalized points). */
- private nativePolygonShapes_ = new Map<number, Map<number, [number, number][]>>();
+ /** TilemapLayer entity → per-tile rich collision shapes (global id → resolved
+ * polygon/circle/box-with-modifier), spawned one collider each. */
+ private nativeTileShapes_ = new Map<number, Map<number, ResolvedTileCollision>>();
/** TilemapLayer entity → its `.estileset` refs, in firstId order (out-of-band; the
* whole list resolves live → multi-slot table/collision/anim). One entry = the
* common single-tileset layer. */
@@ -72,7 +74,7 @@ export class TilemapPlugin implements Plugin {
// teach the scene (de)serializer to carry them out-of-band instead of
// hardcoding TilemapLayer knowledge in scene.ts.
const nativeCollisionIds = this.nativeCollisionIds_;
- const nativePolygonShapes = this.nativePolygonShapes_;
+ const nativeTileShapes = this.nativeTileShapes_;
const tilesetRefs = this.tilesetRefs_;
const liveResolved = this.liveResolved_;
const requestedTilesetLoads = this.requestedTilesetLoads_;
@@ -171,7 +173,7 @@ export class TilemapPlugin implements Plugin {
initializedLayers.delete(entity);
appliedCellSize.delete(entity);
nativeCollisionIds.delete(entity);
- nativePolygonShapes.delete(entity);
+ nativeTileShapes.delete(entity);
tilesetRefs.delete(entity);
liveResolved.delete(entity);
const colliders = collisionEntities.get(entity);
@@ -246,21 +248,22 @@ export class TilemapPlugin implements Plugin {
if (model.collidableTileIds.length > 0) {
nativeCollisionIds.set(entity, model.collidableTileIds);
}
- if (model.polygonShapes.size > 0) {
- nativePolygonShapes.set(entity, model.polygonShapes);
+ if (model.tileShapes.size > 0) {
+ nativeTileShapes.set(entity, model.tileShapes);
}
liveResolved.add(entity);
}
}
// Native path: collidable tiles spawn static colliders once in play mode
- // — box tiles greedy-merged, polygon tiles one collider each — using the
- // live `.estileset` shapes when resolved, else the baked id set.
+ // — plain solid boxes greedy-merged, rich shapes (polygon/circle/one-way/
+ // material) one collider each — using the live `.estileset` shapes when
+ // resolved, else the baked id set.
const collIds = nativeCollisionIds.get(entity);
- const polyShapes = nativePolygonShapes.get(entity);
+ const tileShapes = nativeTileShapes.get(entity);
const hasBox = collIds != null && collIds.length > 0;
- const hasPoly = polyShapes != null && polyShapes.size > 0;
- if (playMode && (hasBox || hasPoly) && !collisionEntities.has(entity)) {
+ const hasShapes = tileShapes != null && tileShapes.size > 0;
+ if (playMode && (hasBox || hasShapes) && !collisionEntities.has(entity)) {
const chunks = decodeTilemapChunks(TilemapAPI.exportChunks(entity));
const tf = world.tryGet(entity, Transform) as { position: { x: number; y: number } } | null;
const ox = tf?.position.x ?? 0;
@@ -272,9 +275,9 @@ export class TilemapPlugin implements Plugin {
layerData.cellSize.x, layerData.cellSize.y, ox, oy, pixelsPerUnit,
));
}
- if (hasPoly) {
- spawned.push(...generateChunkPolygonCollision(
- world, chunks, polyShapes,
+ if (hasShapes) {
+ spawned.push(...generateChunkTileShapes(
+ world, chunks, tileShapes,
layerData.cellSize.x, layerData.cellSize.y, ox, oy, pixelsPerUnit,
));
}
@@ -557,7 +560,7 @@ export class TilemapPlugin implements Plugin {
// Collider entities die with the world on reset/teardown; just drop our bookkeeping.
this.collisionEntities_.clear();
this.nativeCollisionIds_.clear();
- this.nativePolygonShapes_.clear();
+ this.nativeTileShapes_.clear();
this.tilesetRefs_.clear();
this.liveResolved_.clear();
this.requestedTilesetLoads_.clear();
diff --git a/sdk/src/tilemap/tilesetAsset.ts b/sdk/src/tilemap/tilesetAsset.ts
index 3b27b89a9..aab7132c2 100644
--- a/sdk/src/tilemap/tilesetAsset.ts
+++ b/sdk/src/tilemap/tilesetAsset.ts
@@ -19,13 +19,32 @@
export const TILESET_FORMAT_VERSION = '1';
/**
- * A tile's collision shape. `box` = the full cell AABB (greedy-merged at runtime);
- * `polygon` = custom points in tile-local pixels (origin top-left, y-down like the atlas),
- * for slopes / partial tiles. Absence of `collision` on a tile = no collision.
+ * A tile's collision SHAPE, in tile-local pixels (origin top-left, y-down like the atlas).
+ * `box` = the full cell AABB (greedy-merged at runtime); `polygon` = custom points for
+ * slopes / partial tiles; `circle` = a disc centred at (cx, cy) with radius r.
*/
-export type TilesetCollision =
+export type TileCollisionShape =
| { type: 'box' }
- | { type: 'polygon'; points: [number, number][] };
+ | { type: 'polygon'; points: [number, number][] }
+ | { type: 'circle'; cx: number; cy: number; r: number };
+
+/**
+ * A tile's collision = a {@link TileCollisionShape} plus optional cross-cutting modifiers.
+ * Every modifier is optional and omitted when at its engine default, so existing
+ * `.estileset` files (plain `{type:'box'}` / `{type:'polygon'}`) round-trip byte-for-byte.
+ * `oneWay` is the solid-side normal in physics/world convention (y-up; `{0,1}` = solid-top,
+ * jump-through floor); flip flags reorient it at placement. Absence of `collision` = none.
+ */
+export type TilesetCollision = TileCollisionShape & {
+ /** One-way (jump-through) platform: contacts from behind this normal pass through. */
+ oneWay?: { nx: number; ny: number };
+ /** Non-solid trigger volume (fires events, no physical response). */
+ sensor?: boolean;
+ /** Physics material overrides (absent = engine defaults). */
+ density?: number;
+ friction?: number;
+ restitution?: number;
+};
/** One animation frame: show tile `tile` for `durationMs` milliseconds. */
export interface TilesetAnimFrame {
@@ -91,18 +110,50 @@ function nonNeg(v: unknown, fallback: number): number {
return typeof v === 'number' && Number.isFinite(v) && v >= 0 ? v : fallback;
}
+/** A one-way normal: `true` → solid-top (0,1); an {nx,ny}/{x,y} object → that unit normal. */
+function normalizeOneWay(raw: any): { nx: number; ny: number } | undefined {
+ if (raw === true) return { nx: 0, ny: 1 };
+ if (!raw || typeof raw !== 'object') return undefined;
+ const nx = Number.isFinite(raw.nx) ? raw.nx : (Number.isFinite(raw.x) ? raw.x : 0);
+ const ny = Number.isFinite(raw.ny) ? raw.ny : (Number.isFinite(raw.y) ? raw.y : 1);
+ const len = Math.hypot(nx, ny);
+ return len > 1e-6 ? { nx: nx / len, ny: ny / len } : { nx: 0, ny: 1 };
+}
+
function normalizeCollision(raw: any): TilesetCollision | undefined {
if (raw === true) return { type: 'box' }; // legacy / Tiled-style boolean flag
if (!raw || typeof raw !== 'object') return undefined;
+
+ // Shape first.
+ let shape: TileCollisionShape;
if (raw.type === 'polygon' && Array.isArray(raw.points)) {
const points = raw.points
.filter((p: any) => Array.isArray(p) && p.length >= 2
&& typeof p[0] === 'number' && typeof p[1] === 'number')
.map((p: any) => [p[0], p[1]] as [number, number]);
- return points.length >= 3 ? { type: 'polygon', points } : undefined;
+ if (points.length < 3) return undefined; // a polygon needs at least a triangle
+ shape = { type: 'polygon', points };
+ } else if (raw.type === 'circle' && Number.isFinite(raw.r) && raw.r > 0) {
+ shape = {
+ type: 'circle',
+ cx: Number.isFinite(raw.cx) ? raw.cx : 0,
+ cy: Number.isFinite(raw.cy) ? raw.cy : 0,
+ r: raw.r,
+ };
+ } else {
+ // Any other truthy collision (incl. `{type:'box'}` or a legacy `true`) = a full-cell box.
+ shape = { type: 'box' };
}
- // Any other truthy collision (incl. `{type:'box'}` or a legacy `true`) = a full-cell box.
- return { type: 'box' };
+
+ // Modifiers — attached only when present, so a plain box/polygon stays byte-identical.
+ const out: TilesetCollision = shape;
+ const oneWay = normalizeOneWay(raw.oneWay);
+ if (oneWay) out.oneWay = oneWay;
+ if (raw.sensor === true) out.sensor = true;
+ if (Number.isFinite(raw.density)) out.density = raw.density;
+ if (Number.isFinite(raw.friction)) out.friction = raw.friction;
+ if (Number.isFinite(raw.restitution)) out.restitution = raw.restitution;
+ return out;
}
/** Parse arbitrary JSON into a normalized {@link TilesetAsset} (tolerant of missing fields). */
diff --git a/sdk/src/tilemap/tilesetResolve.ts b/sdk/src/tilemap/tilesetResolve.ts
index 522562aa1..2e62c1047 100644
--- a/sdk/src/tilemap/tilesetResolve.ts
+++ b/sdk/src/tilemap/tilesetResolve.ts
@@ -16,7 +16,7 @@
* (`TilesetTable`/`tilemap_setTilesets`) and the Tiled GID convention — so a
* single TilemapLayer can mix tilesets and painted/imported maps converge.
*/
-import type { TilesetAsset } from './tilesetAsset';
+import type { TilesetAsset, TilesetCollision } from './tilesetAsset';
/** A `.estileset` parsed + its atlas texture loaded (handle resolved by the caller). */
export interface ResolvedTileset {
@@ -36,19 +36,66 @@ export interface TilesetModelSlot {
columns: number;
}
+/**
+ * A tile's collision resolved into normalized ([0,1], x right / y down) tile space, ready
+ * to spawn one collider per placed cell. Shapes that a plain-box greedy-merge can't
+ * represent — polygon, circle, or a box carrying one-way / sensor / material — land here.
+ */
+export interface ResolvedTileCollision {
+ shape:
+ | { type: 'box' }
+ | { type: 'polygon'; points: [number, number][] }
+ | { type: 'circle'; cx: number; cy: number; r: number };
+ /** Solid-side normal (world y-up; {0,1} = solid-top) of a one-way platform, if any. */
+ oneWay?: { nx: number; ny: number };
+ sensor?: boolean;
+ density?: number;
+ friction?: number;
+ restitution?: number;
+}
+
/** The runtime tileset model derived from `.estileset`(s) — global tile-id space. */
export interface TilesetModel {
/** Render table (sorted by firstId), fed to `tilemap_setTilesets`. */
slots: TilesetModelSlot[];
/** Animations keyed by GLOBAL tile id → frames (frame tile ids are global too). */
animations: Map<number, { tileId: number; duration: number }[]>;
- /** Global tile ids with a BOX collision shape (greedy-merged at runtime; sorted). */
+ /**
+ * Global tile ids that are a PLAIN solid box (default material, no one-way / sensor) —
+ * the only tiles a greedy rectangle merge may fuse. Sorted.
+ */
collidableTileIds: number[];
/**
- * Global tile id → polygon collision outline, points NORMALIZED to the tile
- * ([0,1], x right / y down). Emitted as one collider per placed tile (not merged).
+ * Global tile id → its resolved collision, for tiles that spawn ONE collider each
+ * (polygon / circle / a box with a one-way, sensor, or material modifier). Kept
+ * separate from {@link collidableTileIds} so the fast merge path stays correctness-safe.
*/
- polygonShapes: Map<number, [number, number][]>;
+ tileShapes: Map<number, ResolvedTileCollision>;
+}
+
+/** True for a tile the greedy box merge may fuse: a bare solid box, no modifiers. */
+function isPlainBox(c: TilesetCollision): boolean {
+ return c.type === 'box' && !c.oneWay && !c.sensor
+ && c.density === undefined && c.friction === undefined && c.restitution === undefined;
+}
+
+/** Resolve a tile's collision into normalized tile space (radius as a tile-width fraction). */
+function resolveTileCollision(c: TilesetCollision, tw: number, th: number): ResolvedTileCollision {
+ let shape: ResolvedTileCollision['shape'];
+ if (c.type === 'polygon') {
+ shape = { type: 'polygon', points: c.points.map(([px, py]) => [px / tw, py / th]) };
+ } else if (c.type === 'circle') {
+ shape = { type: 'circle', cx: c.cx / tw, cy: c.cy / th, r: c.r / tw };
+ } else {
+ shape = { type: 'box' };
+ }
+ const out: ResolvedTileCollision = { shape };
+ if (c.oneWay) out.oneWay = c.oneWay;
+ if (c.sensor) out.sensor = true;
+ if (c.density !== undefined) out.density = c.density;
+ if (c.friction !== undefined) out.friction = c.friction;
+ if (c.restitution !== undefined) out.restitution = c.restitution;
+ return out;
}
/**
@@ -80,7 +127,7 @@ export function resolveTilesetModel(tilesets: ResolvedTileset[]): TilesetModel {
const slots: TilesetModelSlot[] = [];
const animations = new Map<number, { tileId: number; duration: number }[]>();
const collidable: number[] = [];
- const polygonShapes = new Map<number, [number, number][]>();
+ const tileShapes = new Map<number, ResolvedTileCollision>();
let firstId = 1;
for (const { asset, textureHandle, textureHeight } of tilesets) {
@@ -94,10 +141,10 @@ 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.collision?.type === 'polygon') {
- polygonShapes.set(globalId, tile.collision.points.map(([px, py]) => [px / tw, py / th]));
- } else if (tile.collision) {
- collidable.push(globalId);
+ if (tile.collision) {
+ // Plain solid boxes greedy-merge; everything richer spawns per-tile.
+ if (isPlainBox(tile.collision)) collidable.push(globalId);
+ else tileShapes.set(globalId, resolveTileCollision(tile.collision, tw, th));
}
if (tile.animation && tile.animation.length > 0) {
animations.set(
@@ -114,5 +161,5 @@ export function resolveTilesetModel(tilesets: ResolvedTileset[]): TilesetModel {
}
collidable.sort((a, b) => a - b);
- return { slots, animations, collidableTileIds: collidable, polygonShapes };
+ return { slots, animations, collidableTileIds: collidable, tileShapes };
}
diff --git a/sdk/tests/tile-collision-schema.test.ts b/sdk/tests/tile-collision-schema.test.ts
new file mode 100644
index 000000000..2db140e75
--- /dev/null
+++ b/sdk/tests/tile-collision-schema.test.ts
@@ -0,0 +1,99 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * Phase 2 of unified collision: per-tile circle / one-way / sensor / material on the
+ * `.estileset`, and the resolve-time split between the plain-box merge set and the
+ * per-tile rich-shape bucket. Legacy files must round-trip byte-for-byte.
+ */
+import { describe, it, expect } from 'vitest';
+import { parseTileset, serializeTileset, type TilesetAsset } from '../src/tilemap/tilesetAsset';
+import { resolveTilesetModel, type ResolvedTileset } from '../src/tilemap/tilesetResolve';
+
+/** Round-trip a single tile's raw collision through parse+serialize. */
+function roundTripCollision(rawCollision: unknown): unknown {
+ const parsed = parseTileset({ texture: 't', tileWidth: 16, tileHeight: 16, columns: 4, tiles: { 1: { collision: rawCollision } } });
+ const out = serializeTileset(parsed) as { tiles: Record<string, { collision?: unknown }> };
+ return out.tiles['1']?.collision;
+}
+
+describe('tile collision schema — back-compat', () => {
+ it('legacy {type:box} round-trips byte-identically (no new keys)', () => {
+ expect(roundTripCollision({ type: 'box' })).toEqual({ type: 'box' });
+ });
+ it('legacy boolean true → {type:box}', () => {
+ expect(roundTripCollision(true)).toEqual({ type: 'box' });
+ });
+ it('polygon round-trips with only its points (no modifier keys)', () => {
+ const poly = { type: 'polygon', points: [[0, 16], [16, 16], [16, 0]] };
+ expect(roundTripCollision(poly)).toEqual(poly);
+ });
+ it('a bare box never gains one-way/sensor/material keys', () => {
+ const rt = roundTripCollision({ type: 'box' }) as Record<string, unknown>;
+ expect(Object.keys(rt)).toEqual(['type']);
+ });
+});
+
+describe('tile collision schema — new shapes + modifiers', () => {
+ it('circle parses with centre + radius', () => {
+ expect(roundTripCollision({ type: 'circle', cx: 8, cy: 8, r: 6 }))
+ .toEqual({ type: 'circle', cx: 8, cy: 8, r: 6 });
+ });
+ it('circle without a positive radius falls back to a box', () => {
+ expect(roundTripCollision({ type: 'circle', cx: 8, cy: 8, r: 0 })).toEqual({ type: 'box' });
+ });
+ it('oneWay:true becomes the solid-top unit normal', () => {
+ expect(roundTripCollision({ type: 'box', oneWay: true }))
+ .toEqual({ type: 'box', oneWay: { nx: 0, ny: 1 } });
+ });
+ it('oneWay {nx,ny} is normalized to a unit vector', () => {
+ const rt = roundTripCollision({ type: 'box', oneWay: { nx: 3, ny: 4 } }) as { oneWay: { nx: number; ny: number } };
+ expect(rt.oneWay.nx).toBeCloseTo(0.6, 6);
+ expect(rt.oneWay.ny).toBeCloseTo(0.8, 6);
+ });
+ it('sensor + material overrides carry through', () => {
+ expect(roundTripCollision({ type: 'box', sensor: true, friction: 0.1, restitution: 0.9, density: 2 }))
+ .toEqual({ type: 'box', sensor: true, friction: 0.1, restitution: 0.9, density: 2 });
+ });
+ it('a polygon can carry modifiers too', () => {
+ const rt = roundTripCollision({ type: 'polygon', points: [[0, 16], [16, 16], [16, 0]], oneWay: true }) as Record<string, unknown>;
+ expect(rt).toEqual({ type: 'polygon', points: [[0, 16], [16, 16], [16, 0]], oneWay: { nx: 0, ny: 1 } });
+ });
+});
+
+describe('resolveTilesetModel — merge fast-path vs per-tile bucket', () => {
+ const asset: TilesetAsset = parseTileset({
+ texture: 't', tileWidth: 16, tileHeight: 16, columns: 4, tileCount: 4,
+ tiles: {
+ 1: { collision: { type: 'box' } }, // plain box → merge
+ 2: { collision: { type: 'box', oneWay: true } }, // box + modifier → per-tile
+ 3: { collision: { type: 'circle', cx: 8, cy: 8, r: 8 } }, // circle → per-tile
+ 4: { collision: { type: 'polygon', points: [[0, 16], [16, 16], [16, 0]] } }, // polygon → per-tile
+ },
+ });
+
+ it('only the plain box lands in the greedy-merge set', () => {
+ const model = resolveTilesetModel([{ asset, textureHandle: 1 }]);
+ expect(model.collidableTileIds).toEqual([1]);
+ expect([...model.tileShapes.keys()].sort()).toEqual([2, 3, 4]);
+ });
+
+ it('modifier-bearing box, circle, and polygon are resolved into normalized shapes', () => {
+ const model = resolveTilesetModel([{ asset, textureHandle: 1 }]);
+ expect(model.tileShapes.get(2)!.shape.type).toBe('box');
+ expect(model.tileShapes.get(2)!.oneWay).toEqual({ nx: 0, ny: 1 });
+ const circle = model.tileShapes.get(3)!.shape as { type: 'circle'; cx: number; cy: number; r: number };
+ expect(circle).toEqual({ type: 'circle', cx: 0.5, cy: 0.5, r: 0.5 }); // 8/16, 8/16, 8/16
+ const poly = model.tileShapes.get(4)!.shape as { type: 'polygon'; points: [number, number][] };
+ expect(poly.points).toEqual([[0, 1], [1, 1], [1, 0]]); // normalized by tileW/H
+ });
+
+ it('re-keys shapes into the global id space across tilesets', () => {
+ const model = resolveTilesetModel([
+ { asset, textureHandle: 1 },
+ { asset, textureHandle: 2 },
+ ]);
+ // Second tileset starts at firstId 5 (first spans 4 tiles), so its tiles are 5..8.
+ expect(model.collidableTileIds).toEqual([1, 5]);
+ expect([...model.tileShapes.keys()].sort((a, b) => a - b)).toEqual([2, 3, 4, 6, 7, 8]);
+ });
+});
diff --git a/sdk/tests/tilemap-polygon-collision.test.ts b/sdk/tests/tilemap-polygon-collision.test.ts
index 5b9d402bd..06595781f 100644
--- a/sdk/tests/tilemap-polygon-collision.test.ts
+++ b/sdk/tests/tilemap-polygon-collision.test.ts
@@ -1,8 +1,8 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import { describe, it, expect, vi } from 'vitest';
-import { polygonLocalVerts, generateChunkPolygonCollision } from '../src/tilemap/tiledLoader';
-import { resolveTilesetModel } from '../src/tilemap/tilesetResolve';
+import { polygonLocalVerts, generateChunkPolygonCollision, generateChunkTileShapes } from '../src/tilemap/tiledLoader';
+import { resolveTilesetModel, type ResolvedTileCollision } from '../src/tilemap/tilesetResolve';
import { parseTileset } from '../src/tilemap/tilesetAsset';
import { encodeTile } from '../src/tilemap/tileBits';
import { CHUNK_SIZE } from '../src/tilemap/chunkCodec';
@@ -30,8 +30,8 @@ describe('resolveTilesetModel polygon shapes', () => {
});
const model = resolveTilesetModel([{ asset, textureHandle: 1 }]);
expect(model.collidableTileIds).toEqual([2]); // box only
- expect(model.polygonShapes.get(3)).toEqual([[0, 0], [1, 0], [1, 0.5]]); // normalized
- expect(model.polygonShapes.has(2)).toBe(false);
+ expect(model.tileShapes.get(3)?.shape).toEqual({ type: 'polygon', points: [[0, 0], [1, 0], [1, 0.5]] }); // normalized
+ expect(model.tileShapes.has(2)).toBe(false); // plain box → merge set, not tileShapes
});
it('re-keys polygon ids into the global id space across tilesets', () => {
@@ -44,8 +44,8 @@ describe('resolveTilesetModel polygon shapes', () => {
tiles: { 1: { collision: { type: 'polygon', points: [[0, 0], [16, 0], [0, 16]] } } },
});
const model = resolveTilesetModel([{ asset: a, textureHandle: 1 }, { asset: b, textureHandle: 2 }]);
- expect(model.polygonShapes.has(1)).toBe(true); // tileset a, local 1 → global 1
- expect(model.polygonShapes.has(5)).toBe(true); // tileset b, local 1 → global 1+4 = 5
+ expect(model.tileShapes.has(1)).toBe(true); // tileset a, local 1 → global 1
+ expect(model.tileShapes.has(5)).toBe(true); // tileset b, local 1 → global 1+4 = 5
});
});
@@ -101,3 +101,41 @@ describe('generateChunkPolygonCollision', () => {
expect(generateChunkPolygonCollision(world, [{ x: 0, y: 0, tiles }], shapes, 16, 16, 0, 0)).toHaveLength(0);
});
});
+
+describe('generateChunkTileShapes (rich per-tile shapes)', () => {
+ function spawnOne(shape: ResolvedTileCollision, flags?: { flipH?: boolean; flipV?: boolean; flipD?: boolean }) {
+ const { world, comps } = mockWorld();
+ const tiles = new Uint16Array(CHUNK_SIZE * CHUNK_SIZE);
+ tiles[0] = flags ? encodeTile(1, { flipH: !!flags.flipH, flipV: !!flags.flipV, flipD: !!flags.flipD }) : encodeTile(1);
+ const ents = generateChunkTileShapes(world, [{ x: 0, y: 0, tiles }], new Map([[1, shape]]), 16, 16, 0, 0);
+ return comps.get(ents[0] as number)!;
+ }
+
+ it('circle tile → CircleCollider (radius as tile-width fraction, centre offset)', () => {
+ const c = spawnOne({ shape: { type: 'circle', cx: 0.5, cy: 0.5, r: 0.5 } });
+ expect(c.get('CircleCollider').radius).toBeCloseTo(8); // 0.5 × 16
+ expect(c.get('CircleCollider').offset).toEqual({ x: 0, y: 0 }); // centred
+ expect(c.has('BoxCollider')).toBe(false);
+ });
+
+ it('box tile carries the material + sensor overrides it set', () => {
+ const c = spawnOne({ shape: { type: 'box' }, friction: 0.1, restitution: 0.9, density: 3, sensor: true });
+ expect(c.get('BoxCollider')).toMatchObject({ friction: 0.1, restitution: 0.9, density: 3, isSensor: true });
+ });
+
+ it('one-way box → OneWayPlatform with the solid-top normal', () => {
+ const c = spawnOne({ shape: { type: 'box' }, oneWay: { nx: 0, ny: 1 } });
+ expect(c.get('OneWayPlatform').normal).toEqual({ x: 0, y: 1 });
+ });
+
+ it('a vertically flipped cell flips the one-way normal', () => {
+ const c = spawnOne({ shape: { type: 'box' }, oneWay: { nx: 0, ny: 1 } }, { flipV: true });
+ expect(c.get('OneWayPlatform').normal).toEqual({ x: 0, y: -1 });
+ });
+
+ it('polygon tile → PolygonCollider (vertices from the flip-aware transform)', () => {
+ const c = spawnOne({ shape: { type: 'polygon', points: [[0, 1], [1, 1], [1, 0]] } });
+ expect(c.get('PolygonCollider').vertices).toHaveLength(3);
+ expect(c.has('OneWayPlatform')).toBe(false);
+ });
+});
diff --git a/sdk/tests/tileset-resolve.test.ts b/sdk/tests/tileset-resolve.test.ts
index f43990ead..d7a1fbbc2 100644
--- a/sdk/tests/tileset-resolve.test.ts
+++ b/sdk/tests/tileset-resolve.test.ts
@@ -24,7 +24,7 @@ describe('resolveTilesetModel', () => {
expect(m.slots).toEqual([{ firstId: 1, textureHandle: 100, columns: 4 }]);
// box tiles greedy-merge (collidableTileIds); polygon tiles carry their own shape.
expect(m.collidableTileIds).toEqual([2]);
- expect(m.polygonShapes.get(7)).toEqual([[0, 1], [1, 1], [0, 0]]); // normalized to the tile
+ expect(m.tileShapes.get(7)?.shape).toEqual({ type: 'polygon', points: [[0, 1], [1, 1], [0, 0]] }); // normalized
expect(m.animations.size).toBe(0);
});