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): the runtime belongs to one app, and so does the toolkit
esengine579c66e3b3c0
diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.jsonindex fefa22e37..5f57d557f 100644--- a/docs/astro/src/data/apiStability.generated.json+++ b/docs/astro/src/data/apiStability.generated.json@@ -3,10 +3,10 @@"counts": {"public": 113,"beta": 89,- "experimental": 1640,+ "experimental": 1639,"deprecated": 3},- "total": 1842,+ "total": 1841,"subsystems": [{"id": "ecs",diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 9b3101c3b..37edb7a55 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: 113 public · 82 beta · 1503 experimental · 3 deprecated+Symbols: 113 public · 82 beta · 1502 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -627,11 +627,6 @@ static new (): AppContextstatic prototype: AppContext```-## ApplyTilesetRefs — type @experimental-```-(entity: number, refs: readonly string[]) => void-```-## ArrayDataSource — class @experimental```append: (items: readonly T[]) => void@@ -8292,7 +8287,7 @@ visible: boolean## TilemapLiveSync — const @experimental```-{ _bind(fn: ApplyTilesetRefs | null): void; setLayerTilesets(entity: number, refs: readonly string[]): void; }+{ setLayerTilesets(app: App, entity: number, refs: readonly string[]): void; }```## TilemapOrientation — enum @beta@@ -8306,9 +8301,8 @@ Staggered = 2## TilemapPlugin — class @experimental```build: (app: App) => void-cleanup: () => void+cleanup: (app?: App) => voidname: string-resetLayers: () => voidstatic new (): TilemapPluginstatic prototype: TilemapPlugin```diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex b346db868..ac700ab6f 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.native<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 113 public · 87 beta · 1522 experimental · 3 deprecated+Symbols: 113 public · 87 beta · 1521 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -627,11 +627,6 @@ static new (): AppContextstatic prototype: AppContext```-## ApplyTilesetRefs — type @experimental-```-(entity: number, refs: readonly string[]) => void-```-## ArrayDataSource — class @experimental```append: (items: readonly T[]) => void@@ -8485,7 +8480,7 @@ visible: boolean## TilemapLiveSync — const @experimental```-{ _bind(fn: ApplyTilesetRefs | null): void; setLayerTilesets(entity: number, refs: readonly string[]): void; }+{ setLayerTilesets(app: App, entity: number, refs: readonly string[]): void; }```## TilemapOrientation — enum @beta@@ -8499,9 +8494,8 @@ Staggered = 2## TilemapPlugin — class @experimental```build: (app: App) => void-cleanup: () => void+cleanup: (app?: App) => voidname: string-resetLayers: () => voidstatic new (): TilemapPluginstatic prototype: TilemapPlugin```diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 30d114063..cae643246 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: 113 public · 84 beta · 1502 experimental · 3 deprecated+Symbols: 113 public · 84 beta · 1501 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -622,11 +622,6 @@ static new (): AppContextstatic prototype: AppContext```-## ApplyTilesetRefs — type @experimental-```-(entity: number, refs: readonly string[]) => void-```-## ArrayDataSource — class @experimental```append: (items: readonly T[]) => void@@ -8287,7 +8282,7 @@ visible: boolean## TilemapLiveSync — const @experimental```-{ _bind(fn: ApplyTilesetRefs | null): void; setLayerTilesets(entity: number, refs: readonly string[]): void; }+{ setLayerTilesets(app: App, entity: number, refs: readonly string[]): void; }```## TilemapOrientation — enum @beta@@ -8301,9 +8296,8 @@ Staggered = 2## TilemapPlugin — class @experimental```build: (app: App) => void-cleanup: () => void+cleanup: (app?: App) => voidname: string-resetLayers: () => voidstatic new (): TilemapPluginstatic prototype: TilemapPlugin```diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 336440055..8388e26d0 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -1,7 +1,7 @@# API surface — esengine/minigame<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 113 public · 82 beta · 1524 experimental · 3 deprecated+Symbols: 113 public · 82 beta · 1523 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -622,11 +622,6 @@ static new (): AppContextstatic prototype: AppContext```-## ApplyTilesetRefs — type @experimental-```-(entity: number, refs: readonly string[]) => void-```-## ArrayDataSource — class @experimental```append: (items: readonly T[]) => void@@ -8533,7 +8528,7 @@ visible: boolean## TilemapLiveSync — const @experimental```-{ _bind(fn: ApplyTilesetRefs | null): void; setLayerTilesets(entity: number, refs: readonly string[]): void; }+{ setLayerTilesets(app: App, entity: number, refs: readonly string[]): void; }```## TilemapOrientation — enum @beta@@ -8547,9 +8542,8 @@ Staggered = 2## TilemapPlugin — class @experimental```build: (app: App) => void-cleanup: () => void+cleanup: (app?: App) => voidname: string-resetLayers: () => voidstatic new (): TilemapPluginstatic prototype: TilemapPlugin```diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 6e274ed81..58c2b6b5c 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -1,7 +1,7 @@# API surface — esengine/wechat<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 113 public · 82 beta · 1514 experimental · 3 deprecated+Symbols: 113 public · 82 beta · 1513 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -622,11 +622,6 @@ static new (): AppContextstatic prototype: AppContext```-## ApplyTilesetRefs — type @experimental-```-(entity: number, refs: readonly string[]) => void-```-## ArrayDataSource — class @experimental```append: (items: readonly T[]) => void@@ -8294,7 +8289,7 @@ visible: boolean## TilemapLiveSync — const @experimental```-{ _bind(fn: ApplyTilesetRefs | null): void; setLayerTilesets(entity: number, refs: readonly string[]): void; }+{ setLayerTilesets(app: App, entity: number, refs: readonly string[]): void; }```## TilemapOrientation — enum @beta@@ -8308,9 +8303,8 @@ Staggered = 2## TilemapPlugin — class @experimental```build: (app: App) => void-cleanup: () => void+cleanup: (app?: App) => voidname: string-resetLayers: () => voidstatic new (): TilemapPluginstatic prototype: TilemapPlugin```diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex f21c71935..8b43861bf 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -637,7 +637,6 @@ export {type TerrainIndices,type WangIndex,type WangIndices,- type ApplyTilesetRefs,} from './tilemap';// =============================================================================diff --git a/sdk/src/tilemap/index.ts b/sdk/src/tilemap/index.tsindex 5f9bb1fbf..2b6f618ea 100644--- a/sdk/src/tilemap/index.ts+++ b/sdk/src/tilemap/index.ts@@ -2,8 +2,8 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamexport { Tilemap, TilemapLayer, type TilemapData, type TilemapLayerData } from './components';export { TilemapAPI, Tilemaps, initTilemapAPI, shutdownTilemapAPI } from './tilemapAPI';-export { TilemapLiveSync, type ApplyTilesetRefs } from './tilemapLiveSync';-export { TilemapPlugin, tilemapPlugin } from './tilemapPlugin';+export { TilemapLiveSync } from './tilemapLiveSync';+export { TilemapPlugin, tilemapPlugin, TilemapRuntime, TilemapRuntimeState } from './tilemapPlugin';export {parseTmjJson, parseTmjWithExternals, loadTiledMap, loadTiledCollisionObjects,generateTileCollision, generateLayerCollision, generateChunkCollision,diff --git a/sdk/src/tilemap/tilemapAPI.ts b/sdk/src/tilemap/tilemapAPI.tsindex c32efcfe1..6a66d4143 100644--- a/sdk/src/tilemap/tilemapAPI.ts+++ b/sdk/src/tilemap/tilemapAPI.ts@@ -103,32 +103,40 @@ export function shutdownTilemapAPI(): void {*/export const TILESET_SLOT_STRIDE = 6;-export const TilemapAPI = {+/**+ * The tilemap toolkit over ONE engine core.+ *+ * A factory rather than a singleton: an editor world and a play world are two+ * apps with two cores, and a module-level `module_` answered both with whichever+ * initialised last — so one app's reads went to the other's engine.+ */+function tilemapAPI(moduleOf: () => TilemapModule | null) {+ return {initLayer(entity: number, width: number, height: number,tileWidth: number, tileHeight: number): void {- module_?.tilemap_initLayer(entity, width, height, tileWidth, tileHeight);+ moduleOf()?.tilemap_initLayer(entity, width, height, tileWidth, tileHeight);},destroyLayer(entity: number): void {- module_?.tilemap_destroyLayer(entity);+ moduleOf()?.tilemap_destroyLayer(entity);},setTile(entity: number, x: number, y: number, tileId: number): void {- module_?.tilemap_setTile(entity, x, y, tileId);+ moduleOf()?.tilemap_setTile(entity, x, y, tileId);},getTile(entity: number, x: number, y: number): number {- if (!module_) return 0;- return module_.tilemap_getTile(entity, x, y);+ if (!moduleOf()) return 0;+ return moduleOf()!.tilemap_getTile(entity, x, y);},fillRect(entity: number, x: number, y: number,w: number, h: number, tileId: number): void {- module_?.tilemap_fillRect(entity, x, y, w, h, tileId);+ moduleOf()?.tilemap_fillRect(entity, x, y, w, h, tileId);},setTiles(entity: number, tiles: Uint16Array): void {- const m = module_;+ const m = moduleOf();if (!m) return;const bytes = tiles.byteLength;withMalloc(m, bytes, ptr => {@@ -147,7 +155,7 @@ export const TilemapAPI = {firstId: number; textureHandle: number; columns: number;margin?: number; spacing?: number; extrude?: number;}[]): void {- const m = module_;+ const m = moduleOf();if (!m) return;const STRIDE = TILESET_SLOT_STRIDE;const packed = new Uint32Array(slots.length * STRIDE);@@ -166,34 +174,34 @@ export const TilemapAPI = {},hasLayer(entity: number): boolean {- if (!module_) return false;- return module_.tilemap_hasLayer(entity);+ if (!moduleOf()) return false;+ return moduleOf()!.tilemap_hasLayer(entity);},setRenderProps(entity: number, textureHandle: number, tilesetColumns: number,uvTileW: number, uvTileH: number,sortLayer: number, depth: number,parallaxX: number, parallaxY: number): void {- module_?.tilemap_setRenderProps(entity, textureHandle, tilesetColumns,+ moduleOf()?.tilemap_setRenderProps(entity, textureHandle, tilesetColumns,uvTileW, uvTileH, sortLayer, depth, parallaxX, parallaxY);},setTint(entity: number, r: number, g: number, b: number, a: number,opacity: number): void {- module_?.tilemap_setTint(entity, r, g, b, a, opacity);+ moduleOf()?.tilemap_setTint(entity, r, g, b, a, opacity);},setVisible(entity: number, visible: boolean): void {- module_?.tilemap_setVisible(entity, visible);+ moduleOf()?.tilemap_setVisible(entity, visible);},setOriginEntity(layerKey: number, originEntity: number): void {- module_?.tilemap_setOriginEntity(layerKey, originEntity);+ moduleOf()?.tilemap_setOriginEntity(layerKey, originEntity);},setTileAnimation(entity: number, tileId: number,frames: { tileId: number; duration: number }[]): void {- const m = module_;+ const m = moduleOf();if (!m || frames.length === 0) return;const buf = new Uint32Array(frames.length * 2);for (let i = 0; i < frames.length; i++) {@@ -209,44 +217,45 @@ export const TilemapAPI = {/** Drop every tile animation on the layer (a tileset swap re-adds the new set's). */clearTileAnimations(entity: number): void {- module_?.tilemap_clearTileAnimations(entity);+ moduleOf()?.tilemap_clearTileAnimations(entity);},advanceAnimations(entity: number, dtMs: number): void {- module_?.tilemap_advanceAnimations(entity, dtMs);+ moduleOf()?.tilemap_advanceAnimations(entity, dtMs);},setTileProperty(entity: number, tileId: number,key: string, value: string): void {- module_?.tilemap_setTileProperty(entity, tileId, key, value);+ moduleOf()?.tilemap_setTileProperty(entity, tileId, key, value);},getTileProperty(entity: number, x: number, y: number, key: string): string {- if (!module_) return '';- return module_.tilemap_getTileProperty(entity, x, y, key);+ if (!moduleOf()) return '';+ return moduleOf()!.tilemap_getTileProperty(entity, x, y, key);},flipTile(entity: number, x: number, y: number,flipH: boolean, flipV: boolean, flipD: boolean): void {- module_?.tilemap_flipTile(entity, x, y, flipH, flipV, flipD);+ moduleOf()?.tilemap_flipTile(entity, x, y, flipH, flipV, flipD);},rotateTile(entity: number, x: number, y: number, degrees: number): void {- module_?.tilemap_rotateTile(entity, x, y, degrees);+ moduleOf()?.tilemap_rotateTile(entity, x, y, degrees);},initInfiniteLayer(entity: number, tileWidth: number, tileHeight: number): void {// Prefer the idempotent binding so a second call doesn't wipe tiles.- if (module_?.tilemap_initInfinite) {- module_.tilemap_initInfinite(entity, tileWidth, tileHeight);+ const m = moduleOf();+ if (m?.tilemap_initInfinite) {+ m.tilemap_initInfinite(entity, tileWidth, tileHeight);return;}- module_?.tilemap_initInfiniteLayer(entity, tileWidth, tileHeight);+ moduleOf()?.tilemap_initInfiniteLayer(entity, tileWidth, tileHeight);},setChunkTiles(entity: number, chunkX: number, chunkY: number,tiles: Uint16Array, width: number, height: number): void {- const m = module_;+ const m = moduleOf();if (!m) return;const bytes = tiles.byteLength;withMalloc(m, bytes, ptr => {@@ -256,43 +265,64 @@ export const TilemapAPI = {},setGridType(entity: number, type: number): void {- module_?.tilemap_setGridType(entity, type);+ moduleOf()?.tilemap_setGridType(entity, type);},/** Hexagonal-grid layout inputs (Tiled hexsidelength/staggeraxis/staggerindex);* only read when the layer's grid type is Hexagonal (3). */setHexParams(entity: number, sideLength: number, staggerAxisX: boolean, staggerIndexEven: boolean): void {- module_?.tilemap_setHexParams(entity, sideLength, staggerAxisX ? 1 : 0, staggerIndexEven ? 1 : 0);+ moduleOf()?.tilemap_setHexParams(entity, sideLength, staggerAxisX ? 1 : 0, staggerIndexEven ? 1 : 0);},tileToWorld(entity: number, tx: number, ty: number,originX: number, originY: number): { x: number; y: number } {- if (!module_) return { x: 0, y: 0 };- const ptr = module_.tilemap_tileToWorld(entity, tx, ty, originX, originY);- const floats = new Float32Array(module_.HEAPU8.buffer, ptr, 2);+ if (!moduleOf()) return { x: 0, y: 0 };+ const m0 = moduleOf()!;+ const ptr = m0.tilemap_tileToWorld(entity, tx, ty, originX, originY);+ const floats = new Float32Array(m0.HEAPU8.buffer, ptr, 2);return { x: floats[0], y: floats[1] };},worldToTile(entity: number, wx: number, wy: number,originX: number, originY: number): { x: number; y: number } {- if (!module_) return { x: 0, y: 0 };- const ptr = module_.tilemap_worldToTile(entity, wx, wy, originX, originY);- const floats = new Float32Array(module_.HEAPU8.buffer, ptr, 2);+ if (!moduleOf()) return { x: 0, y: 0 };+ const m0 = moduleOf()!;+ const ptr = m0.tilemap_worldToTile(entity, wx, wy, originX, originY);+ const floats = new Float32Array(m0.HEAPU8.buffer, ptr, 2);return { x: floats[0], y: floats[1] };},exportChunks(entity: number): string {- return module_?.tilemap_exportChunks?.(entity) ?? '';+ return moduleOf()?.tilemap_exportChunks?.(entity) ?? '';},importChunks(entity: number, encoded: string): boolean {- return module_?.tilemap_importChunks?.(entity, encoded) ?? false;+ return moduleOf()?.tilemap_importChunks?.(entity, encoded) ?? false;},-};+ };+}++/** The tilemap toolkit's shape, however it was bound. */+export type TilemapToolkit = ReturnType<typeof tilemapAPI>;++/**+ * The host/tooling seam: the editor's tile tools and tests reach the core that+ * {@link initTilemapAPI} bound, where no App is in scope. Game code reads+ * `Res(Tilemaps)`, which is its own app's.+ */+export const TilemapAPI: TilemapToolkit = tilemapAPI(() => module_);++/** @internal One toolkit per App, over that app's core. */+export function createTilemapAPI(engine: NonNullable<EngineApi>): TilemapToolkit {+ const own = new TilemapBridge();+ own.connect(engine);+ const module = own.module as unknown as TilemapModule;+ return tilemapAPI(() => module);+}/*** The canonical game-code accessor: `Res(Tilemaps)`, same shape as every other- * subsystem resource. Wraps the {@link TilemapAPI} singleton — see its doc for- * when direct use is appropriate.+ * subsystem resource. The tilemap plugin inserts its app's own toolkit; the+ * default is the host seam above, for a world with no tilemap plugin built.*/-export const Tilemaps = defineResource<typeof TilemapAPI>(TilemapAPI, 'Tilemaps');+export const Tilemaps = defineResource<TilemapToolkit>(TilemapAPI, 'Tilemaps');diff --git a/sdk/src/tilemap/tilemapLiveSync.ts b/sdk/src/tilemap/tilemapLiveSync.tsindex d49e6f194..902a6905c 100644--- a/sdk/src/tilemap/tilemapLiveSync.ts+++ b/sdk/src/tilemap/tilemapLiveSync.ts@@ -6,31 +6,22 @@** `tilesetAssets` is out-of-band — NOT a C++ ABI field — so the editor's reconciler* drops it when it projects a component change to the World, and the scene codec's- * `importData` (which owns `tilesetRefs_`) only runs on a FULL scene load. That- * leaves no path for "the editor added a tileset to this layer" to reach the running- * tilemap plugin, so the sync would keep rendering from the stale ref list.+ * `importData` only runs on a FULL scene load. That leaves no path for "the editor+ * added a tileset to this layer" to reach the running tilemap plugin, so the sync+ * would keep rendering from the stale ref list. This is that path.*- * This singleton is that path: the active {@link TilemapPlugin} binds its ref-apply- * in `build()` (and clears it in `cleanup()`); the editor pushes a ref-list change- * through {@link TilemapLiveSync.setLayerTilesets}, the plugin updates `tilesetRefs_`- * and clears `liveResolved_`, and the next sync re-resolves the multi-slot render- * table + animations + collision LIVE. It is the exact analog of- * `TilemapAPI.importChunks` for painted tiles — an out-of-band field pushed straight- * to the runtime, bypassing the reconciler. Unbound (no runtime) = a no-op.+ * It takes the App to push into. A module-level "active runtime" pointer answered+ * whichever plugin built last, so an editor world and a play world in one process+ * could not both be driven.*/--/** Apply a layer's `.estileset` refs to the running plugin (empty = clear). */-export type ApplyTilesetRefs = (entity: number, refs: readonly string[]) => void;--let apply: ApplyTilesetRefs | null = null;+import type { App } from '../app/app';+import { TilemapRuntimeState } from './tilemapPlugin';export const TilemapLiveSync = {- /** The active TilemapPlugin registers its ref-apply (build) / clears it (cleanup). */- _bind(fn: ApplyTilesetRefs | null): void {- apply = fn;- },- /** Push a layer's `.estileset` refs to the runtime so the next sync re-resolves. */- setLayerTilesets(entity: number, refs: readonly string[]): void {- apply?.(entity, refs);+ /** Push a layer's `.estileset` refs to `app`'s runtime so its next sync+ * re-resolves. A no-op for an app with no tilemap runtime. */+ setLayerTilesets(app: App, entity: number, refs: readonly string[]): void {+ if (!app.hasResource(TilemapRuntimeState)) return;+ app.getResource(TilemapRuntimeState).setLayerTilesets(entity, refs);},};diff --git a/sdk/src/tilemap/tilemapPlugin.ts b/sdk/src/tilemap/tilemapPlugin.tsindex 71695b2fd..2ccebb860 100644--- a/sdk/src/tilemap/tilemapPlugin.ts+++ b/sdk/src/tilemap/tilemapPlugin.ts@@ -4,9 +4,9 @@ import type { App, Plugin } from '../app/app';import { engineApi } 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';import type { SystemDef } from '../ecs/system';-import { initTilemapAPI, shutdownTilemapAPI, TilemapAPI } from './tilemapAPI';-import { TilemapLiveSync } from './tilemapLiveSync';+import { initTilemapAPI, shutdownTilemapAPI, TilemapAPI, createTilemapAPI, Tilemaps } from './tilemapAPI';import { Tilemap } from './components';import { registerSceneComponentCodec } from '../scene/scene';import { tilemapSource, resolvedTileset, type LoadedTilemapSource } from './tilesetCache';@@ -35,9 +35,15 @@ const GRID_TYPE_MAP: Record<string, number> = {const GRID_STAGGERED = 2;const GRID_HEXAGONAL = 3;-export class TilemapPlugin implements Plugin {- name = 'tilemap';-+/**+ * One app's tilemap runtime: every derived layer, collider, animation and+ * resolved tileset it is holding.+ *+ * All of it is entity-keyed, so it belongs to one World. Two apps count their+ * entities from 1, and a shared instance cannot tell them apart.+ */+export class TilemapRuntime {+ private applyTilesetRefs_: ((entity: number, refs: readonly string[]) => void) | null = null;private initializedLayers_ = new Set<number>();/** TilemapLayer entity → the tile size last pushed to its C++ layer (`w*K+h`).* The renderer + worldToTile read the C++ `tile_width`; the component `cellSize`@@ -82,7 +88,7 @@ export class TilemapPlugin implements Plugin {table: LayerCollisionTable;}>();- build(app: App): void {+ install(app: App): void {// Whichever core is present (the wasm module on the web, the native host's// bindings on a device). A core built without ES_ENABLE_TILEMAP answers// none of these, and says so once instead of throwing on the first tile.@@ -92,6 +98,9 @@ export class TilemapPlugin implements Plugin {return;}initTilemapAPI(engine);+ // And this app's own toolkit over its own core: `Res(Tilemaps)` must not+ // answer with whichever engine initialised the module seam last.+ app.insertResource(Tilemaps, createTilemapAPI(engine));// Tile chunks live in a C++ blob, not the component's field record, so// teach the scene (de)serializer to carry them out-of-band instead of@@ -112,7 +121,7 @@ export class TilemapPlugin implements Plugin {else tilesetRefs.delete(entity);liveResolved.delete(entity);};- TilemapLiveSync._bind(applyTilesetRefs);+ this.applyTilesetRefs_ = applyTilesetRefs;// Tile-collision queries (tileCollisionAt / isTileSolid): resolve a layer to// its collision vocabulary — a derived Tiled child's table, or a painted@@ -701,6 +710,16 @@ export class TilemapPlugin implements Plugin {}}+ /**+ * The editor's out-of-band push: a layer's `.estileset` ref list changed.+ * Reached through THIS app's runtime, so an editor world and a play world+ * cannot answer for each other — which a module-level "active plugin"+ * pointer decided by whoever built last.+ */+ setLayerTilesets(entity: number, refs: readonly string[]): void {+ this.applyTilesetRefs_?.(entity, refs);+ }+resetLayers(): void {for (const entity of this.initializedLayers_) {TilemapAPI.destroyLayer(entity);@@ -721,12 +740,33 @@ export class TilemapPlugin implements Plugin {this.queryTableCache_.clear();}- cleanup(): void {+ dispose(): void {this.resetLayers();- TilemapLiveSync._bind(null);+ this.applyTilesetRefs_ = null;_bindTileCollisionLookup(null);shutdownTilemapAPI();}}+/** @internal One per App, created by the plugin's build. */+export const TilemapRuntimeState = defineResource<TilemapRuntime>(null!, 'TilemapRuntime');++/**+ * Installs the tilemap runtime into an app. Stateless on purpose: what it+ * installs is per app, and this object is a singleton that several apps share.+ */+export class TilemapPlugin implements Plugin {+ name = 'tilemap';++ build(app: App): void {+ const runtime = new TilemapRuntime();+ app.insertResource(TilemapRuntimeState, runtime);+ runtime.install(app);+ }++ cleanup(app?: App): void {+ if (app?.hasResource(TilemapRuntimeState)) app.getResource(TilemapRuntimeState).dispose();+ }+}+export const tilemapPlugin = new TilemapPlugin();diff --git a/sdk/tests/tilemap-live-sync.test.ts b/sdk/tests/tilemap-live-sync.test.tsindex de1ad1a35..ee37ae2d1 100644--- a/sdk/tests/tilemap-live-sync.test.ts+++ b/sdk/tests/tilemap-live-sync.test.ts@@ -1,53 +1,56 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team/**- * @file TilemapLiveSync forwarding contract — the editor→runtime channel for a- * layer's `.estileset` ref list. The plugin binds its ref-apply in build()- * and clears it in cleanup(); the editor pushes ref-list changes through- * setLayerTilesets. Guards that pushes reach the bound plugin, that an- * unbound channel is inert (no runtime), and that cleanup stops delivery.+ * @file tilemap-live-sync.test.ts+ * @brief The editor→runtime channel for a layer's `.estileset` ref list, and+ * which app it reaches.+ *+ * @details An editor world beside a play world is two Apps. The push names the+ * one it is for, so neither the caller nor the runtime has to work out+ * which of them a pointer happens to be aimed at.*/-import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { describe, it, expect } from 'vitest';+import { App } from '../src/app/app';import { TilemapLiveSync } from '../src/tilemap/tilemapLiveSync';+import { TilemapRuntime, TilemapRuntimeState } from '../src/tilemap/tilemapPlugin';-describe('TilemapLiveSync', () => {- beforeEach(() => TilemapLiveSync._bind(null));- afterEach(() => TilemapLiveSync._bind(null));+/** An app carrying a runtime whose applies are observable. */+function appWithRuntime(): { app: App; seen: Array<{ entity: number; refs: string[] }> } {+ const app = App.new();+ const runtime = new TilemapRuntime();+ const seen: Array<{ entity: number; refs: string[] }> = [];+ (runtime as unknown as { applyTilesetRefs_: (e: number, r: readonly string[]) => void })+ .applyTilesetRefs_ = (entity, refs) => seen.push({ entity, refs: [...refs] });+ app.insertResource(TilemapRuntimeState, runtime);+ return { app, seen };+}- it('forwards setLayerTilesets to the bound apply fn', () => {- const calls: Array<{ entity: number; refs: string[] }> = [];- TilemapLiveSync._bind((entity, refs) => calls.push({ entity, refs: [...refs] }));- TilemapLiveSync.setLayerTilesets(7, ['@uuid:a', '@uuid:b']);- expect(calls).toEqual([{ entity: 7, refs: ['@uuid:a', '@uuid:b'] }]);- });+describe('a live tileset push names the app it is for', () => {+ it('reaches that app\'s runtime, and only that one', () => {+ // Deliberately the same entity id in both: two Apps always have them.+ const edit = appWithRuntime();+ const play = appWithRuntime();- it('is a no-op when unbound (no runtime plugin has built)', () => {- expect(() => TilemapLiveSync.setLayerTilesets(1, ['@uuid:x'])).not.toThrow();- });+ TilemapLiveSync.setLayerTilesets(edit.app, 10, ['@uuid:a', '@uuid:b']);- it('an empty list still forwards (clears a layer to zero tilesets)', () => {- let seen: readonly string[] | null = null;- TilemapLiveSync._bind((_e, refs) => { seen = refs; });- TilemapLiveSync.setLayerTilesets(3, []);- expect(seen).toEqual([]);- });+ expect(edit.seen).toEqual([{ entity: 10, refs: ['@uuid:a', '@uuid:b'] }]);+ expect(play.seen, 'the other realm was driven too').toEqual([]);+ });- it('cleanup (unbind) stops delivery — a later push is inert', () => {- let count = 0;- TilemapLiveSync._bind(() => { count++; });- TilemapLiveSync.setLayerTilesets(1, ['@uuid:a']);- TilemapLiveSync._bind(null); // plugin.cleanup()- TilemapLiveSync.setLayerTilesets(1, ['@uuid:a']);- expect(count).toBe(1);- });+ it('an empty list still forwards — that is how a layer is cleared', () => {+ const { app, seen } = appWithRuntime();+ TilemapLiveSync.setLayerTilesets(app, 3, []);+ expect(seen).toEqual([{ entity: 3, refs: [] }]);+ });- it('rebinding points delivery at the newest plugin (world rebuild)', () => {- const a: number[] = [];- const b: number[] = [];- TilemapLiveSync._bind((e) => a.push(e));- TilemapLiveSync._bind((e) => b.push(e)); // a second build() replaces the binding- TilemapLiveSync.setLayerTilesets(5, ['@uuid:a']);- expect(a).toEqual([]);- expect(b).toEqual([5]);- });+ it('an app with no tilemap runtime is a no-op, not a throw', () => {+ expect(() => TilemapLiveSync.setLayerTilesets(App.new(), 1, ['@uuid:x'])).not.toThrow();+ });++ it('a disposed runtime stops delivering', () => {+ const { app, seen } = appWithRuntime();+ app.getResource(TilemapRuntimeState).dispose();+ TilemapLiveSync.setLayerTilesets(app, 1, ['@uuid:a']);+ expect(seen).toEqual([]);+ });});diff --git a/sdk/tests/tilemap-realm-assets.test.ts b/sdk/tests/tilemap-realm-assets.test.tsindex 5c5510124..66ed81823 100644--- a/sdk/tests/tilemap-realm-assets.test.ts+++ b/sdk/tests/tilemap-realm-assets.test.ts@@ -150,3 +150,53 @@ describe('a tilemap era owns the textures it resolved', () => {expect(pool.liveTextures(), 'a composed texture nothing can name was left behind').toBe(0);});});++describe('a tilemap runtime belongs to one app', () => {+ it('two apps with the same entity ids do not share derived state', async () => {+ // The plugin object is a shared singleton and every one of these+ // collections is entity-keyed. Two apps both count entities from 1.+ const { tilemapPlugin, TilemapRuntimeState } = await import('../src/tilemap/tilemapPlugin');+ const { App } = await import('../src/app/app');++ // Through the real installer, and the SAME plugin object both times —+ // which is what `DefaultPlugins` hands every app.+ const a = App.new();+ const b = App.new();+ tilemapPlugin.build(a);+ tilemapPlugin.build(b);+ expect(a.getResource(TilemapRuntimeState), 'one plugin object, one runtime for both apps')+ .not.toBe(b.getResource(TilemapRuntimeState));++ const layersOf = (app: typeof a): Set<number> =>+ (app.getResource(TilemapRuntimeState) as unknown as { initializedLayers_: Set<number> })+ .initializedLayers_;+ layersOf(a).add(1);+ expect(layersOf(b).has(1), 'one app\'s layer showed up in the other').toBe(false);++ // And a teardown is one app's: B keeps what it had.+ layersOf(b).add(1);+ a.getResource(TilemapRuntimeState).dispose();+ expect(layersOf(a).size).toBe(0);+ expect(layersOf(b).has(1), 'one app\'s cleanup emptied the other').toBe(true);+ });+});++describe('the tilemap toolkit reads its own app\'s core', () => {+ it('two apps with two engines answer for themselves', async () => {+ // `Res(Tilemaps)` was one static object over a module-level `module_`,+ // so the app that initialised last answered for both — an editor world+ // reading tiles out of the play world's engine.+ const { createTilemapAPI, Tilemaps } = await import('../src/tilemap/tilemapAPI');+ const { App } = await import('../src/app/app');+ const core = (answer: number) =>+ ({ tilemap_getTile: vi.fn(() => answer), tilemap_initLayer: vi.fn() }) as never;++ const a = App.new();+ const b = App.new();+ a.insertResource(Tilemaps, createTilemapAPI(core(111)));+ b.insertResource(Tilemaps, createTilemapAPI(core(222)));++ expect(a.getResource(Tilemaps).getTile(1, 0, 0)).toBe(111);+ expect(b.getResource(Tilemaps).getTile(1, 0, 0), 'both apps read one engine').toBe(222);+ });+});diff --git a/tools/check-tilemap-realm.mjs b/tools/check-tilemap-realm.mjsnew file mode 100644index 000000000..6f67c40fa--- /dev/null+++ b/tools/check-tilemap-realm.mjs@@ -0,0 +1,99 @@+#!/usr/bin/env node+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file check-tilemap-realm.mjs — tilemap answers for one app, and owns what it took.+ *+ * The tilemap subsystem was the last place four retired shapes still lived: a+ * module-global asset cache, a loader taking textures with no receipt, a+ * module-level "active runtime" pointer, and a shared plugin object holding+ * World-local state. Each of them is cheaper to write back than to do right, so+ * each is refused by name:+ *+ * 1. No module-level cache of a loaded map or resolved tileset. The realm's+ * slot table is where the current era of a ref-bound asset lives.+ * 2. The tilemap/tileset loaders acquire (a receipt) or compose (an owned+ * texture) — never `loadTexture`, which hands back nothing to release.+ * 3. No module-level mutable "active" binding in the tilemap sources: an+ * editor world and a play world are two apps, and a pointer answers one.+ * 4. `TilemapPlugin` holds no state. What it installs is per app.+ *+ * Run: node tools/check-tilemap-realm.mjs (exit 1 on violation)+ */+import { readFileSync, existsSync, readdirSync } from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');+const DIR = path.join(ROOT, 'sdk/src/tilemap');+const LOADERS = [+ 'sdk/src/asset/loaders/TilemapAssetLoader.ts',+ 'sdk/src/asset/loaders/TilesetAssetLoader.ts',+];++const missing = [...LOADERS, 'sdk/src/tilemap/tilemapPlugin.ts'].filter(+ (f) => !existsSync(path.join(ROOT, f)));+if (missing.length) {+ console.error(`check-tilemap-realm is stale: ${missing.join(', ')} does not exist.`);+ process.exit(1);+}++/** Comments out, line numbers intact. */+const stripComments = (text) =>+ text+ .replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, ' '))+ .replace(/\/\/[^\n]*/g, '');++const findings = [];+const at = (code, index) => code.slice(0, index).split('\n').length;++// --- 1 + 3. no module-level asset cache, no module-level "active" binding ---+const RETIRED = [+ [/^const \w*(?:[Cc]ache|Store)\w* = new Map</m, 'a module-level asset cache — the realm\'s slot table holds the current era'],+ [/^let (?:apply|active)\w*\s*[:=]/m, 'a module-level "active runtime" pointer — an editor world and a play world are two apps'],+];+let scanned = 0;+for (const name of readdirSync(DIR).filter((f) => f.endsWith('.ts'))) {+ const code = stripComments(readFileSync(path.join(DIR, name), 'utf8'));+ scanned++;+ for (const [pattern, why] of RETIRED) {+ const hit = pattern.exec(code);+ if (hit) findings.push(`sdk/src/tilemap/${name}:${at(code, hit.index)} ${why}.`);+ }+}+if (scanned < 8) {+ console.error(`check-tilemap-realm: read only ${scanned} tilemap source(s) — the guard is looking in the wrong place.`);+ process.exit(1);+}++// --- 2. the loaders take a receipt, or compose something they own -----------+for (const file of LOADERS) {+ const code = stripComments(readFileSync(path.join(ROOT, file), 'utf8'));+ const loose = /\bctx\.(?:loadTexture|createTextureFromPixels)\s*\(/.exec(code);+ if (loose) {+ findings.push(`${file}:${at(code, loose.index)} takes a texture with no owner (${loose[0].trim()}) — acquireTexture for one that has a path, createOwnedTexture for one this composes.`);+ }+ if (!/\bdependencies\.add\s*\(/.test(code)) {+ findings.push(`${file} puts nothing in its era's dependencies — whatever it resolved is pinned for the life of the app.`);+ }+}++// --- 4. the plugin is an installer, not a holder ----------------------------+const plugin = stripComments(readFileSync(path.join(ROOT, 'sdk/src/tilemap/tilemapPlugin.ts'), 'utf8'));+const cls = /export class TilemapPlugin implements Plugin \{([\s\S]*?)\n\}/.exec(plugin);+if (!cls) {+ console.error('check-tilemap-realm: cannot read TilemapPlugin — this guard parses its body.');+ process.exit(1);+}+const field = /^\s{4}(?:private |readonly |private readonly )*(\w+)\s*[:=]/m.exec(cls[1].replace(/^\s*name = 'tilemap';$/m, ''));+if (field && field[1] !== 'name') {+ findings.push(`sdk/src/tilemap/tilemapPlugin.ts TilemapPlugin holds \`${field[1]}\` — one plugin object installs into many apps, and every collection here is World-local.`);+}++if (findings.length === 0) {+ console.log(`check-tilemap-realm: ${scanned} tilemap source(s) hold no module-level asset state, both loaders own what they take, and the plugin holds nothing.`);+ process.exit(0);+}+for (const f of findings) console.error(f);+console.error('\nA tilemap belongs to the app that loaded it, and an era owns what it resolved.');+process.exit(1);diff --git a/tools/gates.mjs b/tools/gates.mjsindex a5252dff0..e5fc78031 100644--- a/tools/gates.mjs+++ b/tools/gates.mjs@@ -114,6 +114,10 @@ export const GATES = [// A scene that unloads and a load that failed halfway own the same things;// two implementations of giving them back is how one came to miss four steps.{ id: 'scene-teardown', run: 'node tools/check-scene-teardown.mjs' },+ // The subsystem that held all four retired shapes at once: a module-global+ // asset cache, an ownerless texture, an "active runtime" pointer, and+ // World-local state on a plugin object several Apps share.+ { id: 'tilemap-realm', run: 'node tools/check-tilemap-realm.mjs' },// …and that each of them can be reached on a device, where the registry is// assembled from ptr accessors rather than from embind.{ id: 'native-components', run: 'node tools/check-native-components.mjs' },