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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
fix(tilemap): physics-align collision, preload .estileset, resolve refs in play
yhhd891740694cd
diff --git a/sdk/src/component.ts b/sdk/src/component.tsindex 434916638..17bcf7d37 100644--- a/sdk/src/component.ts+++ b/sdk/src/component.ts@@ -645,7 +645,18 @@ export const SpineAnimation = defineBuiltin<SpineAnimationData>('SpineAnimation');export const TilemapLayer = defineBuiltin<TilemapLayerData>('TilemapLayer',- metaDefaults<TilemapLayerData>('TilemapLayer')+ metaDefaults<TilemapLayerData>('TilemapLayer'),+ {+ // The `.estileset` reference is carried out-of-band (see tilemapPlugin's scene+ // codec), but it's a real asset dependency: surface it here so the scene asset+ // preloader loads it up front. Then the tilemap sync derives the render table,+ // collision AND animation live from the tileset on the FIRST frame — no lazy-load+ // gap, no baked `collidableTileIds` snapshot needed. This is the single-source model.+ discoverAssets: (data) => {+ const ref = data.tilesetAsset;+ return typeof ref === 'string' && ref ? [{ type: 'tileset', path: ref }] : [];+ },+ },);// =============================================================================diff --git a/sdk/src/runtimeLoader.ts b/sdk/src/runtimeLoader.tsindex 4c53c122d..1574f6f32 100644--- a/sdk/src/runtimeLoader.ts+++ b/sdk/src/runtimeLoader.ts@@ -16,6 +16,7 @@ import { PhysicsPlugin, type PhysicsPluginConfig } from './physics/PhysicsPluginimport { SpinePlugin } from './spine/SpinePlugin';import type { App } from './app';import { Assets as AssetsClass } from './asset/Assets';+import { Assets as AssetsResource } from './asset/AssetPlugin';import { initBuiltinAssetFields } from './asset/AssetFieldRegistry';import type { TextureImportSettings } from './asset/loaders/TextureLoader';import { SceneManager, type SceneConfig } from './sceneManager';@@ -177,6 +178,12 @@ export async function loadRuntimeScene(options: LoadRuntimeSceneOptions): Promis// loader implementation, shared with the editor — driven by this realm's// provider. Spine stays a two-phase load+apply below (skipSpine).const sceneAssets = createSceneAssets(app, module, source, sceneData);+ // Expose the realm's Assets (with its manifest ref-resolver) as the app resource+ // so plugins that resolve `@uuid:` refs at runtime — the tilemap plugin looks up+ // its `Tilemap.source` / `.estileset` refs each frame — find the SAME resolver the+ // preload keyed the caches with. Without this the shipping runtime app has no+ // Assets resource, so those refs resolve to nothing and tilemaps never render.+ app.insertResource(AssetsResource, sceneAssets);const assetResult = await sceneAssets.preloadSceneAssets(sceneData, undefined, { skipSpine: true });sceneAssets.resolveSceneAssetPaths(sceneData, assetResult);applyTextureMetadata(sceneData, assetResult.textureHandles, source.resolveRef ?? ((ref) => ref));diff --git a/sdk/src/tilemap/tiledLoader.ts b/sdk/src/tilemap/tiledLoader.tsindex bf86ef091..ba085c0a8 100644--- a/sdk/src/tilemap/tiledLoader.ts+++ b/sdk/src/tilemap/tiledLoader.ts@@ -334,8 +334,18 @@ export function parseTmjJson(json: Record<string, unknown>): TiledMapData | null}export function resolveRelativePath(basePath: string, relativePath: string): string {- const lastSlash = basePath.lastIndexOf('/');- const baseDir = lastSlash >= 0 ? basePath.substring(0, lastSlash + 1) : '';+ // Preserve a URL scheme+authority (e.g. "estella://project", "http://host")+ // before normalizing: the "//" after the scheme must survive, but the segment+ // walk below drops empty parts — which would collapse "estella://" to+ // "estella:/" and break the fetch. The editor Play realm resolves assets to+ // absolute estella:// URLs, so a Tiled map's relative tileset image ("../x.png")+ // is joined against such a base.+ const schemeMatch = /^([a-z][a-z0-9+.-]*:\/\/[^/]*)(\/.*|)$/i.exec(basePath);+ const prefix = schemeMatch ? schemeMatch[1] : '';+ const pathPart = schemeMatch ? schemeMatch[2] : basePath;++ const lastSlash = pathPart.lastIndexOf('/');+ const baseDir = lastSlash >= 0 ? pathPart.substring(0, lastSlash + 1) : '';const parts = (baseDir + relativePath).split('/');const resolved: string[] = [];for (const part of parts) {@@ -345,7 +355,7 @@ export function resolveRelativePath(basePath: string, relativePath: string): strresolved.push(part);}}- return resolved.join('/');+ return prefix ? `${prefix}/${resolved.join('/')}` : resolved.join('/');}export async function parseTiledMap(@@ -553,13 +563,9 @@ 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. Tiles are stored top-down (row 0 = top) while the- * world is y-up, so rows flip within `flipHeight` tile-rows of pixel height; each merged- * rect becomes one static `BoxCollider` body placed relative to (originX, originY) — the- * tilemap entity's world origin.- *- * @param flipHeight Tile-rows used for the y-flip (defaults to the grid height; the Tiled- * path passes the MAP height so a sub-sized layer flips against the map box).+ * 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+ * `BoxCollider` body placed relative to (originX, originY) — the tilemap entity's origin.*/export function generateLayerCollision(world: World,@@ -571,25 +577,31 @@ export function generateLayerCollision(collisionIds: Set<number>,originX: number,originY: number,- flipHeight: number = gridHeight,+ pixelsPerUnit: number = 1,): Entity[] {const merged = mergeCollisionTiles(tiles, gridWidth, gridHeight, collisionIds);const entities: Entity[] = [];- const pixelH = flipHeight * tileH;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 + (pixelH - rect.row * tileH) - mergedH * 0.5;+ const worldY = originY - rect.row * tileH - mergedH * 0.5;const entity = world.spawn();world.insert(entity, Transform, {position: { x: worldX, y: worldY, z: 0 },});world.insert(entity, RigidBody, { 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, BoxCollider, {- halfExtents: { x: mergedW * 0.5, y: mergedH * 0.5 },+ halfExtents: { x: mergedW * 0.5 / pixelsPerUnit, y: mergedH * 0.5 / pixelsPerUnit },});entities.push(entity);}@@ -607,7 +619,7 @@ export function generateTileCollision(return generateLayerCollision(world, layer.tiles, layer.width, layer.height,mapData.tileWidth, mapData.tileHeight, collisionIds,- originX, originY, mapData.height,+ originX, originY,);}@@ -629,6 +641,7 @@ export function generateChunkCollision(tileH: number,originX: number,originY: number,+ pixelsPerUnit: number = 1,): Entity[] {const entities: Entity[] = [];for (const chunk of chunks) {@@ -649,8 +662,9 @@ export function generateChunkCollision(},});world.insert(entity, RigidBody, { bodyType: BodyType.Static });+ // halfExtents in physics units (metres); divide the pixel size by ppu.world.insert(entity, BoxCollider, {- halfExtents: { x: rect.width * tileW * 0.5, y: rect.height * tileH * 0.5 },+ halfExtents: { x: rect.width * tileW * 0.5 / pixelsPerUnit, y: rect.height * tileH * 0.5 / pixelsPerUnit },});entities.push(entity);}diff --git a/sdk/src/tilemap/tilemapPlugin.ts b/sdk/src/tilemap/tilemapPlugin.tsindex dbc9895d9..7bdc0936b 100644--- a/sdk/src/tilemap/tilemapPlugin.ts+++ b/sdk/src/tilemap/tilemapPlugin.ts@@ -2,7 +2,7 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamimport type { App, Plugin } from '../app';import type { ESEngineModule } from '../wasm';-import { Transform, TilemapLayer, type TilemapLayerData } from '../component';+import { Transform, TilemapLayer, Canvas, type TilemapLayerData } from '../component';import { Schedule } from '../system';import type { SystemDef } from '../system';import { initTilemapAPI, shutdownTilemapAPI, TilemapAPI } from './tilemapAPI';@@ -15,6 +15,7 @@ import { decodeTilemapChunks } from './chunkCodec';import { Assets, type AssetsData } from '../asset/AssetPlugin';import { Time } from '../resource';import { playModeOnly } from '../env';+import { log } from '../logger';import type { Entity } from '../types';const SYNTHETIC_KEY_BASE = 0x40000000;@@ -49,6 +50,8 @@ export class TilemapPlugin implements Plugin {private tilesetRefs_ = new Map<number, string>();/** Entities whose `.estileset` has been resolved+applied (so we do it once per load). */private liveResolved_ = new Set<number>();+ /** Resolved `.estileset` paths a load has already been kicked off for (de-dupes the lazy load). */+ private requestedTilesetLoads_ = new Set<string>();build(app: App): void {const module = app.wasmModule as ESEngineModule;@@ -61,6 +64,7 @@ export class TilemapPlugin implements Plugin {const nativePolygonShapes = this.nativePolygonShapes_;const tilesetRefs = this.tilesetRefs_;const liveResolved = this.liveResolved_;+ const requestedTilesetLoads = this.requestedTilesetLoads_;registerSceneComponentCodec('TilemapLayer', {exportData: (entity, data) => {const blob = TilemapAPI.exportChunks(entity);@@ -112,6 +116,13 @@ export class TilemapPlugin implements Plugin {// next Play regenerates from the current tiles.const playMode = playModeOnly();const assets = app.getResource(Assets);+ // Physics half-extents are metres; tile sizes are pixels. Divide by the+ // scene's pixelsPerUnit (Canvas, default 100) when spawning tile colliders.+ let pixelsPerUnit = 100;+ for (const ce of world.getEntitiesWithComponents([Canvas])) {+ const c = world.tryGet(ce, Canvas) as { pixelsPerUnit?: number } | null;+ if (c?.pixelsPerUnit) { pixelsPerUnit = c.pixelsPerUnit; break; }+ }if (!playMode && collisionEntities.size > 0) {for (const [, ents] of collisionEntities) {for (const e of ents) world.despawn(e);@@ -182,6 +193,15 @@ export class TilemapPlugin implements Plugin {nativePolygonShapes.set(entity, model.polygonShapes);}liveResolved.add(entity);+ } else if (path && assets && !requestedTilesetLoads.has(path)) {+ // The `.estileset` is referenced but not loaded. It's an+ // out-of-band ref (invisible to scene asset discovery), so+ // nothing preloads it — kick the load off here. Once it lands+ // getResolvedTileset() hits next frame and we resolve live.+ requestedTilesetLoads.add(path);+ assets.load('tileset', path).catch((e) => {+ log.warn('tilemap', `failed to load tileset asset '${path}'`, e);+ });}}@@ -201,7 +221,7 @@ export class TilemapPlugin implements Plugin {if (hasBox) {spawned.push(...generateChunkCollision(world, chunks, new Set(collIds),- layerData.cellSize.x, layerData.cellSize.y, ox, oy,+ layerData.cellSize.x, layerData.cellSize.y, ox, oy, pixelsPerUnit,));}if (hasPoly) {@@ -223,7 +243,13 @@ export class TilemapPlugin implements Plugin {const tilemap = world.tryGet(entity, Tilemap) as { source: string } | null;if (!tilemap?.source) continue;- const cached = getTilemapSource(tilemap.source);+ // `source` may be a `@uuid:` ref (how the editor serializes asset+ // fields) or a plain path. The loader keys the source cache by the+ // RESOLVED path (Assets.resolveRef → path), and `resolveSceneAssetPaths`+ // does NOT rewrite tilemap fields, so resolve here too or a `@uuid:`+ // scene would never find its cached source.+ const sourcePath = resolveTilesetPath(assets, tilemap.source);+ const cached = sourcePath ? getTilemapSource(sourcePath) : undefined;if (!cached) continue;if (!sourceEntityKeys.has(entity)) {@@ -314,7 +340,7 @@ export class TilemapPlugin implements Plugin {if (layer.infinite || layer.tiles.length === 0) continue;spawned.push(...generateLayerCollision(world, layer.tiles, layer.width, layer.height,- cached.tileWidth, cached.tileHeight, ids, ox, oy,+ cached.tileWidth, cached.tileHeight, ids, ox, oy, pixelsPerUnit,));}collisionEntities.set(entity, spawned);@@ -364,6 +390,7 @@ export class TilemapPlugin implements Plugin {this.nativePolygonShapes_.clear();this.tilesetRefs_.clear();this.liveResolved_.clear();+ this.requestedTilesetLoads_.clear();}cleanup(): void {diff --git a/sdk/tests/tilemap.test.ts b/sdk/tests/tilemap.test.tsindex 140fbd531..468bfd89c 100644--- a/sdk/tests/tilemap.test.ts+++ b/sdk/tests/tilemap.test.ts@@ -212,6 +212,15 @@ describe('resolveRelativePath', () => {it('should handle base path without directory', () => {expect(resolveRelativePath('level1.tmj', 'tileset.png')).toBe('tileset.png');});++ it('should preserve a URL scheme+authority in the base (editor Play realm)', () => {+ // The "//" after the scheme must survive; otherwise the fetch breaks+ // ("estella://" collapsing to "estella:/" produced a 404 in play mode).+ expect(resolveRelativePath('estella://project/assets/maps/level.tmj', '../textures/tileset.png'))+ .toBe('estella://project/assets/textures/tileset.png');+ expect(resolveRelativePath('http://127.0.0.1:5173/assets/maps/level.tmj', '../textures/props.png'))+ .toBe('http://127.0.0.1:5173/assets/textures/props.png');+ });});describe('TilemapAPI', () => {@@ -1029,27 +1038,28 @@ describe('generateLayerCollision (B2-1 runtime tile collision)', () => {expect(ents).toHaveLength(1);const e = store.get(ents[0])!;- expect(e.Transform.position).toEqual({ x: 16, y: 16, z: 0 });+ // y-DOWN (matches the renderer): row 0 top edge at origin y=0, centre below.+ expect(e.Transform.position).toEqual({ x: 16, y: -16, z: 0 });expect(e.BoxCollider.halfExtents).toEqual({ x: 16, y: 16 });expect(e.RigidBody.bodyType).toBe(BodyType.Static);});- it('flips rows to y-up so the bottom row sits at low world-Y', () => {+ it('places rows y-down so lower rows sit at more-negative world-Y', () => {const { world, store } = createMockWorld();// 1 column × 3 rows, only the BOTTOM row (row index 2, stored last) is collidable.const tiles = new Uint16Array([0, 0, 1]);const ents = generateLayerCollision(world, tiles, 1, 3, 10, 10, new Set([1]), 0, 0);expect(ents).toHaveLength(1);- // pixelH=30; row2 → worldY = (30 - 20) - 5 = 5 (near the bottom of a y-up world).- expect(store.get(ents[0])!.Transform.position).toEqual({ x: 5, y: 5, z: 0 });+ // row2 → worldY = -(2*10) - 5 = -25 (matches renderer `origin - ty*th - hh`).+ expect(store.get(ents[0])!.Transform.position).toEqual({ x: 5, y: -25, z: 0 });});it('offsets colliders by the tilemap entity world origin', () => {const { world, store } = createMockWorld();const tiles = new Uint16Array([1, 1, 1, 1]);const ents = generateLayerCollision(world, tiles, 2, 2, 16, 16, new Set([1]), 100, 200);- expect(store.get(ents[0])!.Transform.position).toEqual({ x: 116, y: 216, z: 0 });+ expect(store.get(ents[0])!.Transform.position).toEqual({ x: 116, y: 184, z: 0 });});it('ignores non-collidable and empty tiles', () => {diff --git a/tools/asset-meta.js b/tools/asset-meta.jsindex cffd0c4cf..1b47bfe35 100644--- a/tools/asset-meta.js+++ b/tools/asset-meta.js@@ -78,6 +78,7 @@ const EXT_TO_TYPE = Object.freeze({// Tilemap'.tmx': 'tilemap','.tmj': 'tilemap',+ '.estileset': 'tileset',// Spine (skel / atlas — .png pair handled by the texture entry)'.skel': 'spine','.atlas': 'spine',@@ -111,6 +112,7 @@ function getImporterDefaults(type) {case 'bitmapFont':case 'font':case 'tilemap':+ case 'tileset':return {};default:return {};