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(sdk): run editor-authored .esfsm/.esbt at runtime + survive hot reload
esengine3ffa52434079
diff --git a/sdk/src/ai/bt/BtPlugin.ts b/sdk/src/ai/bt/BtPlugin.tsindex 378c13cc2..6dae41280 100644--- a/sdk/src/ai/bt/BtPlugin.ts+++ b/sdk/src/ai/bt/BtPlugin.ts@@ -20,6 +20,8 @@ import { defineResource } from '../../resource';import { Commands, type CommandsInstance } from '../../commands';import { playModeOnly } from '../../env';import type { AnyComponentDef, ComponentData } from '../../component';+import { Assets } from '../../asset/AssetPlugin';+import { resolveAssetKey } from '../../asset/resolveAssetKey';import { Blackboard } from '../fsm/Blackboard';import { aiRegistry, type AiContext } from '../fsm/AiContext';import { tickBt, createBtRunState, type BtRunState } from './BtRunner';@@ -58,6 +60,10 @@ export function stepBehaviorTrees(commands: CommandsInstance,dt: number,states: Map<Entity, BtAgentState>,+ // A `.esbt` asset registers under its resolved path; the agent holds the+ // authored ref, so resolve before lookup (falls back to the raw ref for+ // `registerBt` code names). Optional so tests need no realm.+ resolveKey?: (ref: string) => string,): void {if (dt <= 0) return;@@ -75,7 +81,7 @@ export function stepBehaviorTrees(for (const entity of world.getEntitiesWithComponents([BehaviorTreeAgent])) {const agent = world.get(entity, BehaviorTreeAgent);if (!agent.bt) continue;- const def = getBt(agent.bt);+ const def = getBt(resolveKey ? resolveKey(agent.bt) : agent.bt) ?? getBt(agent.bt);if (!def) continue;let st = states.get(entity);@@ -125,12 +131,15 @@ export class BtPlugin implements Plugin {app.world.onDespawn((entity: Entity) => states.delete(entity));app.insertResource(AiBt, new BehaviorTrees(states));+ const resolveKey = (ref: string): string =>+ resolveAssetKey(app.hasResource(Assets) ? app.getResource(Assets) : null, ref);+app.addSystemToSchedule(Schedule.Update,defineSystem([Res(Time), Commands(), GetWorld()],(time: TimeData, commands: CommandsInstance, world) => {- stepBehaviorTrees(world as AiWorldView, commands, time.delta, states);+ stepBehaviorTrees(world as AiWorldView, commands, time.delta, states, resolveKey);},{ name: 'BehaviorTreeSystem' },),diff --git a/sdk/src/ai/fsm/FsmPlugin.ts b/sdk/src/ai/fsm/FsmPlugin.tsindex 9b96ce314..cba4d4dae 100644--- a/sdk/src/ai/fsm/FsmPlugin.ts+++ b/sdk/src/ai/fsm/FsmPlugin.ts@@ -20,6 +20,8 @@ import { defineResource } from '../../resource';import { Commands, type CommandsInstance } from '../../commands';import { playModeOnly } from '../../env';import type { AnyComponentDef, ComponentData } from '../../component';+import { Assets } from '../../asset/AssetPlugin';+import { resolveAssetKey } from '../../asset/resolveAssetKey';import { Blackboard } from './Blackboard';import { createFsmRunState, stepFsm, type FsmRunState } from './FsmRunner';import { aiRegistry, type AiContext } from './AiContext';@@ -60,6 +62,11 @@ export function stepStateMachines(commands: CommandsInstance,dt: number,states: Map<Entity, AgentState>,+ // A `.esfsm` asset registers under its resolved path (the realm's ref resolver+ // maps a plain/`@uuid:` ref to that key); the agent still holds the authored+ // ref, so resolve before lookup. Falls back to the raw ref for `registerFsm`+ // code names, which are keyed verbatim. Optional so tests need no realm.+ resolveKey?: (ref: string) => string,): void {if (dt <= 0) return;@@ -77,7 +84,7 @@ export function stepStateMachines(for (const entity of world.getEntitiesWithComponents([StateMachineAgent])) {const agent = world.get(entity, StateMachineAgent);if (!agent.fsm) continue;- const fsm = getFsm(agent.fsm);+ const fsm = getFsm(resolveKey ? resolveKey(agent.fsm) : agent.fsm) ?? getFsm(agent.fsm);if (!fsm) continue;let st = states.get(entity);@@ -131,12 +138,15 @@ export class FsmPlugin implements Plugin {app.world.onDespawn((entity: Entity) => states.delete(entity));app.insertResource(AiFsm, new StateMachines(states));+ const resolveKey = (ref: string): string =>+ resolveAssetKey(app.hasResource(Assets) ? app.getResource(Assets) : null, ref);+app.addSystemToSchedule(Schedule.Update,defineSystem([Res(Time), Commands(), GetWorld()],(time: TimeData, commands: CommandsInstance, world) => {- stepStateMachines(world as FsmWorldView, commands, time.delta, states);+ stepStateMachines(world as FsmWorldView, commands, time.delta, states, resolveKey);},{ name: 'StateMachineSystem' },),diff --git a/sdk/src/app.ts b/sdk/src/app.tsindex 30c7d304c..20ce411a8 100644--- a/sdk/src/app.ts+++ b/sdk/src/app.ts@@ -23,6 +23,7 @@ import type { SceneConfig } from './sceneManager';import { SceneManager } from './sceneManager';import { sceneManagerPlugin } from './scenePlugin';import { getDefaultContext } from './context';+import { seedEngineComponents } from './component';import { cameraPlugin } from './camera/CameraPlugin';import { PhysicsRuntime } from './physics/PhysicsRuntime';import { SubsystemRegistry } from './subsystems';@@ -1002,6 +1003,10 @@ export interface WebAppOptions {}export function createWebApp(module: ESEngineModule, options?: WebAppOptions): App {+ // Restore any engine components a prior project hot-reload's clearUserComponents+ // wiped, so the scene about to load can still resolve them (no-op before the SDK+ // entry snapshots the baseline — e.g. in unit tests that never load it).+ seedEngineComponents();const app = App.new();if (options?.sideModules) app.setSideModules(options.sideModules);const cppRegistry = new module.Registry() as unknown as CppRegistry;diff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.tsindex 355e68587..cf86706f1 100644--- a/sdk/src/asset/Assets.ts+++ b/sdk/src/asset/Assets.ts@@ -494,6 +494,8 @@ export class Assets {const tilemapPaths = discovered.byType.get('tilemap') ?? new Set<string>();const tilesetPaths = discovered.byType.get('tileset') ?? new Set<string>();const timelinePaths = discovered.byType.get('timeline') ?? new Set<string>();+ const fsmPaths = discovered.byType.get('statemachine') ?? new Set<string>();+ const btPaths = discovered.byType.get('behaviortree') ?? new Set<string>();const spinePairs = discovered.spines;const textureHandles = new Map<string, number>();@@ -565,6 +567,11 @@ export class Assets {pushFireAndForget(tilesetPaths, p => this.loadTileset(p), 'tileset');pushFireAndForget(timelinePaths, p => this.loadTimeline(p), 'timeline');pushFireAndForget(audioPaths, p => this.loadAudio(p), 'audio');+ // FSM/BT loaders register the parsed definition into the shared AI store+ // under the asset path, so a StateMachineAgent/BehaviorTreeAgent whose+ // fsm/bt is that path resolves once the scene finishes preloading.+ pushFireAndForget(fsmPaths, p => this.loadTyped('statemachine', p), 'statemachine');+ pushFireAndForget(btPaths, p => this.loadTyped('behaviortree', p), 'behaviortree');const totalCount = tasks.length;onProgress?.(0, totalCount);diff --git a/sdk/src/asset/resolveAssetKey.ts b/sdk/src/asset/resolveAssetKey.tsnew file mode 100644index 000000000..fb46e12e2--- /dev/null+++ b/sdk/src/asset/resolveAssetKey.ts@@ -0,0 +1,23 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file resolveAssetKey.ts+ * @brief The single place a path-keyed runtime store maps an authored+ * component ref to the key it is registered under.+ *+ * A data asset (`.esfsm`, `.esbt`, `.estimeline`, `.estilemap`…) loads under its+ * RESOLVED path — the realm's ref resolver maps a plain path or `@uuid:` ref to+ * that key (in the play realm it gains the `estella://project/` origin). But the+ * component still holds the authored ref, and `resolveSceneAssetPaths` leaves+ * these path-keyed fields untouched (only texture/material/font become handles).+ * So the runtime plugin must resolve the ref the same way before the lookup, and+ * fall back to the raw value for keys registered verbatim (a `registerFsm`/+ * `registerBt` code name). See the FSM/BT/tilemap/timeline plugins.+ */++import type { AssetsData } from './AssetPlugin';++/** Resolve an authored asset ref to its runtime-store key (or the ref itself). */+export function resolveAssetKey(assets: AssetsData | null | undefined, ref: string): string {+ return (assets?.resolveRef(ref) ?? null) ?? ref;+}diff --git a/sdk/src/component.ts b/sdk/src/component.tsindex 17bcf7d37..0f2b12a5c 100644--- a/sdk/src/component.ts+++ b/sdk/src/component.ts@@ -300,6 +300,31 @@ export function unregisterComponent(name: string): void {userComponents().delete(name);}+// The engine's own `defineComponent`s (AI, animation, audio, physics joints, UI+// text, tilemap, timeline…) register at SDK module load into the per-app user+// registry. A hot reload only re-imports the PROJECT bundle — the cached `esengine`+// module does NOT re-run — so `clearUserComponents()` would drop these engine+// components with nothing to put them back. The SDK entry snapshots them once as a+// baseline; the hot-reload probe and app build re-seed it so engine components+// survive a reload (and the hot-swap fast path can match fingerprints).+let engineComponentBaseline_: Map<string, AnyComponentDef> | null = null;++/** Snapshot the currently-registered components as the engine baseline. Called+ * once from the SDK entry after all engine `defineComponent`s have run and before+ * any project bundle registers its own. */+export function markEngineComponentBaseline(): void {+ engineComponentBaseline_ = new Map(userComponents());+}++/** Re-add the engine baseline to a registry (only where missing), so a context+ * that has never re-run the SDK's module-level registrations still has them.+ * No-op until {@link markEngineComponentBaseline} has run (e.g. unit tests that+ * never load the SDK entry). */+export function seedEngineComponents(registry: Map<string, AnyComponentDef> = userComponents()): void {+ if (!engineComponentBaseline_) return;+ for (const [name, def] of engineComponentBaseline_) if (!registry.has(name)) registry.set(name, def);+}+function registerToEditor(name: string,defaults: Record<string, unknown>,diff --git a/sdk/src/hotReload.ts b/sdk/src/hotReload.tsindex 940e9cf3d..7208d38ab 100644--- a/sdk/src/hotReload.ts+++ b/sdk/src/hotReload.ts@@ -6,7 +6,7 @@* re-registrations in isolation so the editor can decide hot-swap vs reload.*/import { AppContext, getDefaultContext, setDefaultContext, type PendingSystemEntry } from './context';-import { getUserComponentFingerprint } from './component';+import { getUserComponentFingerprint, seedEngineComponents } from './component';export interface ProbedRegistrations {/** Digest of the user component schemas the bundle declared (shape, not values). */@@ -28,6 +28,11 @@ export interface ProbedRegistrations {export async function probeRegistrations(register: () => Promise<void>): Promise<ProbedRegistrations> {const live = getDefaultContext();const probe = new AppContext();+ // The re-imported bundle only re-runs the PROJECT's registrations (the cached+ // esengine module does not), so seed the engine baseline first — otherwise the+ // probe fingerprint would omit every SDK component and never match live, so the+ // hot-swap fast path could never engage.+ seedEngineComponents(probe.componentRegistry);setDefaultContext(probe);try {await register();diff --git a/sdk/src/index.ts b/sdk/src/index.tsindex e882c1b77..2fd380114 100644--- a/sdk/src/index.ts+++ b/sdk/src/index.ts@@ -6,12 +6,16 @@*/import { setPlatform, webAdapter } from './platform';-import { ensureBuiltinComponentsRegistered } from './component';+import { ensureBuiltinComponentsRegistered, markEngineComponentBaseline } from './component';setPlatform(webAdapter);// Register every engine component (COMPONENT_META) up front so a scene can never// silently drop a component that exists in the engine but lacks a typed const.ensureBuiltinComponentsRegistered();+// All engine `defineComponent`s have run by now (their modules are dependencies of+// this entry, evaluated before this statement); snapshot them so a project hot+// reload can't wipe them (see seedEngineComponents).+markEngineComponentBaseline();export * from './core';export * from './webAppFactory';diff --git a/sdk/src/index.wechat.ts b/sdk/src/index.wechat.tsindex 21ef3c037..81118711f 100644--- a/sdk/src/index.wechat.ts+++ b/sdk/src/index.wechat.ts@@ -7,7 +7,7 @@import { setPlatform } from './platform';import { wechatAdapter, initWeChatPlatform } from './platform/wechat';-import { ensureBuiltinComponentsRegistered } from './component';+import { ensureBuiltinComponentsRegistered, markEngineComponentBaseline } from './component';initWeChatPlatform();setPlatform(wechatAdapter);@@ -15,6 +15,7 @@ setPlatform(wechatAdapter);// Register every engine component (COMPONENT_META) so scenes never silently drop// a component that exists in the engine but lacks a typed const.ensureBuiltinComponentsRegistered();+markEngineComponentBaseline();export * from './core';export * from './webAppFactory';diff --git a/sdk/src/playRealmRuntime.ts b/sdk/src/playRealmRuntime.tsindex 741558b5b..599ee6f3b 100644--- a/sdk/src/playRealmRuntime.ts+++ b/sdk/src/playRealmRuntime.ts@@ -77,6 +77,11 @@ export function resolvePlayAssetRef(ref: string, manifest: Record<string, stringreturn url;}const base = (assetBaseUrl ?? '').replace(/\/$/, '');+ // Idempotent, like HttpBackend.resolveUrl: an already-resolved absolute URL or+ // base-prefixed path must not be prefixed again. Preload resolves a ref once to+ // bucket it by type, then the loader resolves it a second time — without this+ // guard a plain path would gain the base twice (estella://…/estella://…/404).+ if (ref.includes('://') || (base && ref.startsWith(`${base}/`))) return ref;return base ? `${base}/${ref.replace(/^\//, '')}` : ref;}diff --git a/sdk/src/tilemap/tilemapPlugin.ts b/sdk/src/tilemap/tilemapPlugin.tsindex 7bdc0936b..131674324 100644--- a/sdk/src/tilemap/tilemapPlugin.ts+++ b/sdk/src/tilemap/tilemapPlugin.ts@@ -12,7 +12,8 @@ import { getTilemapSource, getResolvedTileset } from './tilesetCache';import { resolveTilesetModel } from './tilesetResolve';import { generateLayerCollision, generateChunkCollision, generateChunkPolygonCollision } from './tiledLoader';import { decodeTilemapChunks } from './chunkCodec';-import { Assets, type AssetsData } from '../asset/AssetPlugin';+import { Assets } from '../asset/AssetPlugin';+import { resolveAssetKey } from '../asset/resolveAssetKey';import { Time } from '../resource';import { playModeOnly } from '../env';import { log } from '../logger';@@ -27,13 +28,6 @@ const GRID_TYPE_MAP: Record<string, number> = {staggered: 2,};-/** A `.estileset` ref → the resolved-tileset cache key (its project path). A `@uuid:`- * ref needs the Assets registry; an already-resolved path is used as-is. */-function resolveTilesetPath(assets: AssetsData | undefined, ref: string): string | null {- if (ref.startsWith('@uuid:')) return assets ? assets.resolveRef(ref) : null;- return ref;-}-export class TilemapPlugin implements Plugin {name = 'tilemap';@@ -177,8 +171,8 @@ export class TilemapPlugin implements Plugin {// derive its render table + animations + collision LIVE (once per load) —// replacing the copied columns and the baked collidableTileIds snapshot.if (tilesetRef && !liveResolved.has(entity)) {- const path = resolveTilesetPath(assets, tilesetRef);- const resolved = path ? getResolvedTileset(path) : undefined;+ const tilesetKey = resolveAssetKey(assets, tilesetRef);+ const resolved = getResolvedTileset(tilesetKey) ?? getResolvedTileset(tilesetRef);if (resolved) {const model = resolveTilesetModel([resolved]);TilemapAPI.setTilesets(entity, model.slots);@@ -193,14 +187,15 @@ export class TilemapPlugin implements Plugin {nativePolygonShapes.set(entity, model.polygonShapes);}liveResolved.add(entity);- } else if (path && assets && !requestedTilesetLoads.has(path)) {+ } else if (assets && !requestedTilesetLoads.has(tilesetKey)) {// 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);+ // nothing preloads it — kick the load off here (the loader+ // resolves the ref itself). Once it lands getResolvedTileset()+ // hits next frame and we resolve live.+ requestedTilesetLoads.add(tilesetKey);+ assets.load('tileset', tilesetRef).catch((e) => {+ log.warn('tilemap', `failed to load tileset asset '${tilesetRef}'`, e);});}}@@ -243,13 +238,10 @@ export class TilemapPlugin implements Plugin {const tilemap = world.tryGet(entity, Tilemap) as { source: string } | null;if (!tilemap?.source) continue;- // `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;+ // The loader keys the source cache by the RESOLVED path and+ // `resolveSceneAssetPaths` leaves `source` as the authored ref, so+ // resolve at lookup (see resolveAssetKey), falling back to the raw ref.+ const cached = getTilemapSource(resolveAssetKey(assets, tilemap.source)) ?? getTilemapSource(tilemap.source);if (!cached) continue;if (!sourceEntityKeys.has(entity)) {diff --git a/sdk/src/timeline/TimelinePlugin.ts b/sdk/src/timeline/TimelinePlugin.tsindex b4e1de069..af25f8aa5 100644--- a/sdk/src/timeline/TimelinePlugin.ts+++ b/sdk/src/timeline/TimelinePlugin.ts@@ -6,6 +6,8 @@ import { Res } from '../resource';import { Time, type TimeData } from '../resource';import { defineComponent, getComponent } from '../component';import { playModeOnly } from '../env';+import { Assets } from '../asset/AssetPlugin';+import { resolveAssetKey } from '../asset/resolveAssetKey';import { Audio, type AudioAPI } from '../audio/Audio';import { wrapModeFromName, TrackType, type TimelineAsset, type AnimFramesTrack } from './TimelineTypes';import { Timeline, TimelineApi } from './TimelineControl';@@ -97,6 +99,7 @@ export class TimelinePlugin implements Plugin {(time: TimeData) => {const tl = app.getResource(Timeline);const audio: AudioAPI | null = app.hasResource(Audio) ? app.getResource(Audio) : null;+ const assets = app.hasResource(Assets) ? app.getResource(Assets) : null;const deps: SampleDeps = {world,getComponent,@@ -106,7 +109,10 @@ export class TimelinePlugin implements Plugin {for (const entity of world.getEntitiesWithComponents([TimelinePlayer])) {const player = world.get(entity, TimelinePlayer) as TimelinePlayerData;if (!player.timeline) continue;- const asset = this.loadedAssets_.get(player.timeline);+ // The loader keys loadedAssets_/textureHandles_ by the RESOLVED+ // path; the component holds the authored ref (see resolveAssetKey).+ const timelineKey = resolveAssetKey(assets, player.timeline);+ const asset = this.loadedAssets_.get(timelineKey) ?? this.loadedAssets_.get(player.timeline);if (!asset) continue;const wrapMode = wrapModeFromName(player.wrapMode);@@ -118,7 +124,7 @@ export class TimelinePlugin implements Plugin {this.ensureAnimFrames(entity, asset);advanceTimelineTS(asset, entity, state, time.delta, { deps, audio });- this.processAnimFrames(world, entity, state.time, player.timeline);+ this.processAnimFrames(world, entity, state.time, timelineKey);// A clip that hit its end (Once) clears the component's play flag.if (!state.playing && player.playing) {diff --git a/sdk/tests/engine-component-baseline.test.ts b/sdk/tests/engine-component-baseline.test.tsnew file mode 100644index 000000000..2e3de46af--- /dev/null+++ b/sdk/tests/engine-component-baseline.test.ts@@ -0,0 +1,60 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * A project hot reload re-imports only the project bundle; the cached `esengine`+ * module does not re-run, so its module-level `defineComponent`s (AI, animation,+ * audio, joints, UI text, tilemap, timeline…) would be lost when the reload's+ * `clearUserComponents()` empties the registry. The SDK entry snapshots them as a+ * baseline that the app build and the hot-reload probe re-seed. Without this the+ * hot-swap probe fingerprint omits every engine component and never matches live,+ * so the destructive full reload always runs and comes back missing components.+ */+import { describe, it, expect } from 'vitest';+import {+ defineComponent, clearUserComponents, getComponent,+ getUserComponentFingerprint, markEngineComponentBaseline, seedEngineComponents,+} from '../src/component';+import { probeRegistrations } from '../src/hotReload';++describe('engine component baseline survives a hot reload', () => {+ it('re-seeds engine components after clearUserComponents wipes them', () => {+ defineComponent('EngineWidget', { n: 0 });+ markEngineComponentBaseline();+ expect(getComponent('EngineWidget')).toBeDefined();++ clearUserComponents(); // what the reload's full path does+ expect(getComponent('EngineWidget')).toBeUndefined();++ seedEngineComponents(); // what createWebApp does on the way back up+ expect(getComponent('EngineWidget')).toBeDefined();+ });++ it('re-seeds only the baseline, not project components registered later', () => {+ defineComponent('EngineWidget', { n: 0 });+ markEngineComponentBaseline();+ defineComponent('ProjectWidget', { m: 0 }); // after the baseline = project code++ clearUserComponents();+ seedEngineComponents();++ expect(getComponent('EngineWidget')).toBeDefined(); // engine restored+ expect(getComponent('ProjectWidget')).toBeUndefined(); // project comes back via the bundle+ });++ it('gives the hot-swap probe the engine baseline so its fingerprint can match live', async () => {+ defineComponent('EngineWidget', { n: 0 });+ markEngineComponentBaseline();++ // The probe re-imports the project bundle into a throwaway context; in reality+ // esengine is cached so only project components re-register there.+ const { fingerprint } = await probeRegistrations(async () => {+ defineComponent('ProjectWidget', { m: 0 });+ });++ // The seeded baseline means the probe no longer OMITS engine components.+ expect(fingerprint).toContain('EngineWidget');+ expect(fingerprint).toContain('ProjectWidget');+ // The live context (no project bundle re-run here) still carries the baseline.+ expect(getUserComponentFingerprint()).toContain('EngineWidget');+ });+});diff --git a/sdk/tests/play-realm-asset-ref.test.ts b/sdk/tests/play-realm-asset-ref.test.tsnew file mode 100644index 000000000..a7b73d85f--- /dev/null+++ b/sdk/tests/play-realm-asset-ref.test.ts@@ -0,0 +1,61 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * Regression for the enemy-ai "enemies never chase" bug: play-realm asset refs+ * are resolved once during preload (to bucket by type) and again by the loader,+ * so `resolvePlayAssetRef` must be idempotent or a plain path gains the origin+ * twice (estella://…/estella://…/404). And because a `.esfsm`/`.esbt` registers+ * under its resolved path while the agent still holds the authored ref, the FSM+ * step must resolve the ref before lookup.+ */+import { describe, it, expect, beforeEach } from 'vitest';+import { resolvePlayAssetRef } from '../src/playRealmRuntime';+import { registerFsm, getFsm, clearFsmStore, StateMachineAgent } from '../src/ai/fsm/StateMachineAgent';+import { stepStateMachines } from '../src/ai/fsm/FsmPlugin';++const BASE = 'estella://project';++describe('resolvePlayAssetRef idempotency', () => {+ it('prefixes a plain path exactly once', () => {+ const once = resolvePlayAssetRef('assets/ai/enemy.esfsm', {}, BASE);+ expect(once).toBe(`${BASE}/assets/ai/enemy.esfsm`);+ // Resolving the already-resolved URL again is a no-op (no double origin).+ expect(resolvePlayAssetRef(once, {}, BASE)).toBe(once);+ });++ it('passes any absolute URL through unchanged', () => {+ expect(resolvePlayAssetRef('estella://project/x.png', {}, BASE)).toBe('estella://project/x.png');+ expect(resolvePlayAssetRef('https://cdn/x.png', {}, BASE)).toBe('https://cdn/x.png');+ });++ it('maps @uuid: refs through the manifest', () => {+ const url = resolvePlayAssetRef('@uuid:ABC', { abc: `${BASE}/built/a.esfsm` }, BASE);+ expect(url).toBe(`${BASE}/built/a.esfsm`);+ });+});++describe('FSM step resolves the agent ref before lookup', () => {+ beforeEach(() => clearFsmStore());++ it('runs an FSM registered under the resolved key while the agent holds the raw ref', () => {+ const resolved = `${BASE}/assets/ai/enemy.esfsm`;+ // The loader registers under the resolved path (what preload keys it by).+ registerFsm(resolved, { initial: 'Idle', states: [{ name: 'Idle' }] });++ const store = new Map<number, Record<string, unknown>>([[1, { fsm: 'assets/ai/enemy.esfsm', current: '' }]]);+ const world = {+ getEntitiesWithComponents: () => [1],+ get: (_e: number, c: unknown) => (c === StateMachineAgent ? store.get(1) : undefined),+ set: (_e: number, _c: unknown, d: Record<string, unknown>) => store.set(1, d),+ has: () => false,+ };++ // Without a resolver the raw ref misses the resolved key → no state entered.+ stepStateMachines(world as never, null as never, 1 / 60, new Map());+ expect(store.get(1)!.current).toBe('');++ // With the realm resolver (raw → resolved), the agent finds its FSM.+ stepStateMachines(world as never, null as never, 1 / 60, new Map(), (ref) => resolvePlayAssetRef(ref, {}, BASE));+ expect(store.get(1)!.current).toBe('Idle');+ });+});diff --git a/sdk/tests/preload-ai-assets.test.ts b/sdk/tests/preload-ai-assets.test.tsnew file mode 100644index 000000000..272c05285--- /dev/null+++ b/sdk/tests/preload-ai-assets.test.ts@@ -0,0 +1,106 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * Regression: a scene that references .esfsm/.esbt brains through+ * StateMachineAgent.fsm / BehaviorTreeAgent.bt must have those assets loaded by+ * preloadSceneAssets, so getFsm/getBt resolve before the agents first tick.+ * Previously preloadSceneAssets dispatched a hardcoded type list that omitted+ * 'statemachine'/'behaviortree', so editor-authored AI assets never loaded and+ * the agents silently did nothing (the enemy-ai example: enemies never chased).+ *+ * The AI component defs are re-declared per test because the shared setup clears+ * the component registry (tests/setup.ts) — discovery only needs their+ * assetFields/discoverAssets, so this mirrors the real StateMachineAgent /+ * BehaviorTreeAgent metadata without depending on module-load order.+ */+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { Assets } from '../src/asset/Assets';+import { Catalog } from '../src/asset/Catalog';+import type { Backend } from '../src/asset/Backend';+import type { SceneData } from '../src/scene';+import { defineComponent } from '../src/component';+import { getFsm, clearFsmStore } from '../src/ai/fsm/StateMachineAgent';+import { getBt, clearBtStore } from '../src/ai/bt/BehaviorTreeAgent';++// The FSM/BT loaders don't touch the ResourceManager, but the shared LoadContext+// materializes it eagerly — stub it so the load path runs headless.+vi.mock('../src/resourceManager', () => ({+ requireResourceManager: () => ({}),+ evictTextureDimensions: vi.fn(),+}));++const FSM_PATH = 'assets/ai/enemy.esfsm';+const BT_PATH = 'assets/ai/enemy.esbt';++const FSM_JSON = JSON.stringify({+ initial: 'Patrol',+ states: [+ { name: 'Patrol', transitions: [{ to: 'Chase', condition: 'seesPlayer' }] },+ { name: 'Chase', onUpdate: 'chase', transitions: [{ to: 'Patrol', condition: 'lostPlayer' }] },+ ],+});+const BT_JSON = JSON.stringify({+ root: { type: 'selector', id: 'n0', children: [{ type: 'action', id: 'n1', name: 'patrol' }] },+});++function aiBackend(): Backend {+ return {+ fetch: vi.fn(async () => new ArrayBuffer(0)),+ fetchText: vi.fn(async (url: string) =>+ url.includes('.esfsm') ? FSM_JSON : url.includes('.esbt') ? BT_JSON : '{}'),+ resolveUrl: vi.fn((p: string) => p),+ resolvePath: vi.fn((p: string) => p),+ } as unknown as Backend;+}++const scene: SceneData = {+ name: 'ai', entities: [+ { id: 1, name: 'A', parent: null, children: [], components: [{ type: 'StateMachineAgent', data: { fsm: FSM_PATH, current: '' } }] },+ { id: 2, name: 'B', parent: null, children: [], components: [{ type: 'BehaviorTreeAgent', data: { bt: BT_PATH, status: 0 } }] },+ ],+};++describe('preloadSceneAssets — AI brains', () => {+ beforeEach(() => {+ clearFsmStore();+ clearBtStore();+ // Mirror the real SDK component metadata (the registry is cleared per test).+ defineComponent('StateMachineAgent', { fsm: '', current: '' }, {+ assetFields: [{ field: 'fsm', type: 'statemachine' }],+ discoverAssets: (d) => (typeof d.fsm === 'string' && d.fsm.endsWith('.esfsm') ? [{ type: 'statemachine', path: d.fsm }] : []),+ });+ defineComponent('BehaviorTreeAgent', { bt: '', status: 0 }, {+ assetFields: [{ field: 'bt', type: 'behaviortree' }],+ discoverAssets: (d) => (typeof d.bt === 'string' && d.bt.endsWith('.esbt') ? [{ type: 'behaviortree', path: d.bt }] : []),+ });+ });++ it('loads .esfsm / .esbt referenced by agents into the AI store', async () => {+ const assets = Assets.create({ backend: aiBackend(), catalog: Catalog.empty(), module: null as never });++ expect(getFsm(FSM_PATH)).toBeUndefined();+ expect(getBt(BT_PATH)).toBeUndefined();++ const result = await assets.preloadSceneAssets(scene, undefined, { skipSpine: true });++ expect(result.missing).toEqual([]);+ expect(getFsm(FSM_PATH)).toBeDefined();+ expect(getBt(BT_PATH)).toBeDefined();+ });++ it('keys the store by the resolved ref when a realm resolver is set', async () => {+ // Mirrors the play realm: the ref resolver prefixes the origin, so the+ // FSM/BT register under the resolved path — the key FsmPlugin/BtPlugin's+ // resolveKey reproduces from the agent's authored ref.+ const base = 'estella://project';+ const assets = Assets.create({ backend: aiBackend(), catalog: Catalog.empty(), module: null as never });+ assets.setAssetRefResolver((ref) => (ref.includes('://') ? ref : `${base}/${ref}`));++ const result = await assets.preloadSceneAssets(scene, undefined, { skipSpine: true });++ expect(result.missing).toEqual([]);+ expect(getFsm(`${base}/${FSM_PATH}`)).toBeDefined();+ expect(getBt(`${base}/${BT_PATH}`)).toBeDefined();+ expect(getFsm(FSM_PATH)).toBeUndefined(); // NOT keyed by the raw ref+ });+});diff --git a/sdk/tests/resolve-asset-key.test.ts b/sdk/tests/resolve-asset-key.test.tsnew file mode 100644index 000000000..77a4c67ab--- /dev/null+++ b/sdk/tests/resolve-asset-key.test.ts@@ -0,0 +1,28 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * The one primitive shared by every path-keyed runtime store (FSM, BT, tilemap,+ * timeline) to map an authored component ref to its resolved store key.+ */+import { describe, it, expect } from 'vitest';+import { resolveAssetKey } from '../src/asset/resolveAssetKey';+import type { AssetsData } from '../src/asset/AssetPlugin';++const assets = (fn: (ref: string) => string | null) =>+ ({ resolveRef: fn } as unknown as AssetsData);++describe('resolveAssetKey', () => {+ it('returns the resolver output when it resolves', () => {+ expect(resolveAssetKey(assets((r) => `estella://project/${r}`), 'a/b.esfsm'))+ .toBe('estella://project/a/b.esfsm');+ });++ it('falls back to the raw ref when the resolver returns null (code-registered name)', () => {+ expect(resolveAssetKey(assets(() => null), 'myCodeFsm')).toBe('myCodeFsm');+ });++ it('falls back to the raw ref when there is no Assets resource', () => {+ expect(resolveAssetKey(null, 'a/b.esbt')).toBe('a/b.esbt');+ expect(resolveAssetKey(undefined, 'a/b.esbt')).toBe('a/b.esbt');+ });+});