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(export): every project scene ships as a switchable SceneManager target

yhh2310ccc30c85
diff --git a/desktop/electron/exportGame.ts b/desktop/electron/exportGame.ts
index ad1c147d3..61dfac3af 100644
--- a/desktop/electron/exportGame.ts
+++ b/desktop/electron/exportGame.ts
@@ -21,7 +21,7 @@
*/
import type { BuildOptions } from 'esbuild';
import { loadEsbuild } from './esbuildRuntime';
-import { writeFile, mkdir, cp } from 'node:fs/promises';
+import { writeFile, mkdir, cp, readdir } from 'node:fs/promises';
import { existsSync } from 'node:fs';
import path from 'node:path';
import { cookAssets } from './cookAssets';
@@ -33,6 +33,46 @@ import { ESENGINE_EXTERNAL } from './esengineResolve';
export type ExportPlatform = 'web' | 'desktop' | 'wechat' | 'playable';
+/** A switchable scene the export ships: SceneManager name + project-relative path. */
+export interface ExportScene {
+ name: string;
+ path: string;
+}
+
+/**
+ * Every scene the shipped game can switch to: all `.esscene` under the
+ * project's scenes dir plus the entry scene wherever it lives. Names are the
+ * scenes-dir-relative path without extension ('main', 'levels/boss') — the
+ * stable ids game code passes to `SceneManager.switchTo`; a scene outside the
+ * scenes dir is named by its project-relative path. The entry always sorts
+ * first. Cook reachability runs from ALL of these roots, so every scene's
+ * assets ship (playable stays entry-only: a size-capped single file).
+ */
+export async function discoverProjectScenes(root: string, entryScene: string, scenesDir?: string): Promise<ExportScene[]> {
+ const dir = (scenesDir ?? path.dirname(entryScene)).replace(/\\/g, '/');
+ const sceneName = (projectPath: string): string => {
+ const p = projectPath.replace(/\\/g, '/');
+ const rel = p.startsWith(`${dir}/`) ? p.slice(dir.length + 1) : p;
+ return rel.replace(/\.esscene$/i, '');
+ };
+ const scenes: ExportScene[] = [{ name: sceneName(entryScene), path: entryScene.replace(/\\/g, '/') }];
+ const absDir = path.join(root, dir);
+ if (existsSync(absDir)) {
+ const walk = async (sub: string): Promise<void> => {
+ for (const entry of await readdir(path.join(absDir, sub), { withFileTypes: true })) {
+ const rel = sub ? `${sub}/${entry.name}` : entry.name;
+ if (entry.isDirectory()) await walk(rel);
+ else if (/\.esscene$/i.test(entry.name)) {
+ const projectPath = `${dir}/${rel}`;
+ if (projectPath !== scenes[0].path) scenes.push({ name: sceneName(projectPath), path: projectPath });
+ }
+ }
+ };
+ await walk('');
+ }
+ return scenes;
+}
+
export interface ExportGameResult {
ok: boolean;
platform: ExportPlatform;
@@ -201,6 +241,9 @@ async function stageDesktopApp(absOut: string, title: string, appId?: string, pr
export async function exportGame(opts: {
root: string;
entryScene: string;
+ /** Project-relative scenes dir (manifest layout); default the entry's dir.
+ * Every `.esscene` under it ships as a switchable scene. */
+ scenesDir?: string;
gameHostEntry: string;
/** Project-relative startup entry (e.g. src/main.ts) → bundled to scripts.mjs. */
scriptsEntry?: string;
@@ -237,12 +280,14 @@ export async function exportGame(opts: {
const platform = opts.platform ?? 'web';
const title = opts.title ?? 'Game';
const progress = opts.onProgress ?? (() => {});
+ const scenes = await discoverProjectScenes(opts.root, opts.entryScene, opts.scenesDir);
// WeChat has no import maps + a different module/asset model → its own pipeline.
if (platform === 'wechat') {
return exportWeChat({
root: opts.root,
entryScene: opts.entryScene,
+ scenes,
scriptsEntry: opts.scriptsEntry,
sdkDir: opts.sdkDistDir,
wasmDir: opts.wasmDir,
@@ -295,9 +340,10 @@ export async function exportGame(opts: {
logLevel: 'silent',
};
- // 1. Cook reachable assets + manifest (the entry scene file is staged too).
+ // 1. Cook reachable assets + manifest, from EVERY shippable scene as a root
+ // (the scene files themselves are staged too).
progress({ phase: 'Cooking assets' });
- const cook = await cookAssets(opts.root, { entryScenes: [opts.entryScene], outDir: payloadDir, contentAddressed: opts.contentAddressed ?? true, compressTextures: opts.compressTextures, atlasTextures: opts.atlasTextures });
+ const cook = await cookAssets(opts.root, { entryScenes: scenes.map((s) => s.path), outDir: payloadDir, contentAddressed: opts.contentAddressed ?? true, compressTextures: opts.compressTextures, atlasTextures: opts.atlasTextures });
warnings.push(...cook.warnings);
progress({ phase: 'Cooking assets', detail: `${cook.included.length} reachable` });
@@ -337,7 +383,7 @@ export async function exportGame(opts: {
await writeFile(
path.join(payloadDir, 'game.config.json'),
JSON.stringify(
- { entryScene: opts.entryScene, ...(opts.ySortLayers ? { ySortLayers: opts.ySortLayers } : {}) },
+ { entryScene: opts.entryScene, scenes, ...(opts.ySortLayers ? { ySortLayers: opts.ySortLayers } : {}) },
null, 2,
) + '\n',
);
diff --git a/desktop/electron/exportWeChat.ts b/desktop/electron/exportWeChat.ts
index f776b05a0..1223a5aa1 100644
--- a/desktop/electron/exportWeChat.ts
+++ b/desktop/electron/exportWeChat.ts
@@ -26,6 +26,7 @@ import { writeFile, mkdir, cp, readFile, rename, stat, rm } from 'node:fs/promis
import { existsSync } from 'node:fs';
import path from 'node:path';
import { cookAssets } from './cookAssets';
+import type { ExportScene } from './exportGame';
import type { OnExportProgress } from './exportProgress';
import { esengineAlias } from './esengineResolve';
import {
@@ -114,7 +115,9 @@ function projectConfigJson(title: string, appid: string, includeSuffixes: string
miniprogramRoot: './',
projectname: title,
appid, // set in Project Settings → Packaging → WeChat (else fill in devtools)
- setting: { es6: false, minified: false },
+ // bigPackageSizeSupport: devtools preview of a >4MB main package (upload
+ // still enforces the limit — move heavy content to subpackages/ to ship).
+ setting: { es6: false, minified: false, bigPackageSizeSupport: true },
compileType: 'game',
...(includeSuffixes.length > 0
? { packOptions: { include: includeSuffixes.map((value) => ({ type: 'suffix', value })) } }
@@ -142,18 +145,19 @@ bundle.boot(engineFactory, sideModuleFactories);
}
/** The export-time mirror of the runtime's physics/spine self-gating: which
- * optional modules the scene needs. A needed module absent from the wechat
- * wasm dir is a HARD error — the package would otherwise ship silently broken
- * (same contract as the playable exporter's collectSideModules). */
+ * optional modules ANY shipped scene needs (a dynamically switched scene must
+ * find its modules present). A needed module absent from the wechat wasm dir
+ * is a HARD error — the package would otherwise ship silently broken (same
+ * contract as the playable exporter's collectSideModules). */
async function scanWeChatSideModules(
- sceneData: unknown,
+ sceneDatas: unknown[],
cookEntries: CookManifest['entries'],
absOut: string,
wasmDir: string,
errors: string[],
): Promise<Array<{ id: string; file: string }>> {
const ids = new Set<string>();
- if (sceneData && sceneUsesPhysics(sceneData as Parameters<typeof sceneUsesPhysics>[0])) ids.add('physics');
+ if (sceneDatas.some((s) => s && sceneUsesPhysics(s as Parameters<typeof sceneUsesPhysics>[0]))) ids.add('physics');
// Spine: the skeleton carries the version. Skeleton + atlas share the authored
// meta type `spine`, so discriminate by extension — `.skel` is a binary
// skeleton, `.json` a JSON one; the `.atlas` sibling is not a skeleton.
@@ -238,6 +242,9 @@ async function buildAddressableManifest(absOut: string): Promise<string> {
export async function exportWeChat(opts: {
root: string;
entryScene: string;
+ /** Every switchable scene to ship (name + project-relative path, entry
+ * included) — discovered by exportGame. Absent: the entry scene only. */
+ scenes?: ExportScene[];
scriptsEntry?: string;
sdkDir: string;
wasmDir: string;
@@ -281,43 +288,65 @@ export async function exportWeChat(opts: {
await mkdir(absOut, { recursive: true });
- // 1. Cook reachable assets (paths preserved) + the flat manifest. KTX2
- // textures are fine here: the scan below sees the staged .ktx2 files and
- // ships the Basis transcoder side module with them.
+ // Every switchable scene ships; the exporter's caller (exportGame) discovers
+ // them from the project's scenes dir. Absent (tests / direct calls): entry only.
+ const scenes: ExportScene[] = opts.scenes ?? [
+ { name: path.basename(opts.entryScene).replace(/\.[^.]+$/, ''), path: opts.entryScene.replace(/\\/g, '/') },
+ ];
+ const sceneName = scenes.find((s) => s.path === opts.entryScene.replace(/\\/g, '/'))?.name ?? scenes[0].name;
+
+ // 1. Cook reachable assets from every scene root (paths preserved) + the flat
+ // manifest. KTX2 textures are fine here: the scan below sees the staged
+ // .ktx2 files and ships the Basis transcoder side module with them.
progress({ phase: 'Cooking assets' });
- const cook = await cookAssets(opts.root, { entryScenes: [opts.entryScene], outDir: absOut, contentAddressed: opts.contentAddressed, compressTextures: opts.compressTextures, atlasTextures: opts.atlasTextures });
+ const cook = await cookAssets(opts.root, { entryScenes: scenes.map((s) => s.path), outDir: absOut, contentAddressed: opts.contentAddressed, compressTextures: opts.compressTextures, atlasTextures: opts.atlasTextures });
warnings.push(...cook.warnings);
- // 1a. WeChat's code-package suffix whitelist has no `ktx2` — the packer
- // drops such files and fs reads are denied regardless of packOptions.
- // Re-stage KTX2 containers under the whitelisted `.bin` with a
- // truth-keeping compound suffix; the runtime's KTX2 detection
- // (isKtx2Path) accepts both spellings.
+ // 1a. Restage for WeChat's code-package suffix whitelist (it has no `ktx2`
+ // or `esscene`; the packer drops such files and fs reads are denied
+ // regardless of packOptions):
+ // *.ktx2 → *.ktx2.bin (whitelisted; isKtx2Path accepts both)
+ // assets/…/<x>.esscene → scenes/<name>.json, @uuid: refs stripped to the
+ // bare uuids the WeChat resolver keys by; the
+ // manifest entry follows, so scene refs resolve
+ // to the readable file.
+ progress({ phase: 'Transforming scenes' });
const flatManifestPath = path.join(absOut, 'assets.manifest.json');
+ let cookEntries: CookManifest['entries'] = [];
+ const sceneRawByName = new Map<string, unknown>();
try {
const flat = JSON.parse(await readFile(flatManifestPath, 'utf8')) as CookManifest;
- let renamed = 0;
for (const e of flat.entries) {
- if (!e.path.toLowerCase().endsWith('.ktx2')) continue;
- await rename(path.join(absOut, e.path), path.join(absOut, `${e.path}.bin`));
- e.path = `${e.path}.bin`;
- renamed++;
+ if (e.path.toLowerCase().endsWith('.ktx2')) {
+ await rename(path.join(absOut, e.path), path.join(absOut, `${e.path}.bin`));
+ e.path = `${e.path}.bin`;
+ continue;
+ }
+ const scene = scenes.find((s) => s.path === e.path);
+ if (scene) {
+ const staged = path.join(absOut, e.path);
+ const raw = JSON.parse(await readFile(staged, 'utf8'));
+ sceneRawByName.set(scene.name, raw);
+ const outPath = `scenes/${scene.name}.json`;
+ await mkdir(path.dirname(path.join(absOut, outPath)), { recursive: true });
+ await writeFile(path.join(absOut, outPath), JSON.stringify(stripUuidRefs(raw)) + '\n');
+ await rm(staged, { force: true });
+ e.path = outPath;
+ }
}
- if (renamed > 0) await writeFile(flatManifestPath, JSON.stringify(flat, null, 2));
- } catch { /* no cook manifest — surfaces in step 2 */ }
+ await writeFile(flatManifestPath, JSON.stringify(flat, null, 2));
+ cookEntries = flat.entries;
+ } catch (err) {
+ errors.push(`scene transform: ${err instanceof Error ? err.message : String(err)}`);
+ }
- // 1b. Scan the scene for the optional modules it needs (physics/spine), so the
- // generated entry requires exactly those — the export-time half of the
- // runtime's self-gating. Read the cook manifest + scene once and reuse below.
- let cookEntries: CookManifest['entries'] = [];
- let sceneRaw: unknown = null;
- try {
- cookEntries = (JSON.parse(await readFile(path.join(absOut, 'assets.manifest.json'), 'utf8')) as CookManifest).entries;
- } catch { /* surfaces in step 2 */ }
- try {
- sceneRaw = JSON.parse(await readFile(path.join(absOut, opts.entryScene), 'utf8'));
- } catch { /* surfaces in step 3 */ }
- const sideModules = await scanWeChatSideModules(sceneRaw, cookEntries, absOut, opts.wasmDir, errors);
+ // 1b. Scan every scene for the optional modules it needs (physics/spine), so
+ // the generated entry requires exactly those — the export-time half of
+ // the runtime's self-gating. A dynamically switched scene must find its
+ // modules present, so the union over ALL shipped scenes counts.
+ const sideModules = await scanWeChatSideModules([...sceneRawByName.values()], cookEntries, absOut, opts.wasmDir, errors);
+ const sceneRaw = sceneRawByName.get(sceneName) ?? null;
+ if (!sceneRaw) errors.push(`entry scene "${opts.entryScene}" was not staged by the cook`);
// 2. Flat manifest → AddressableManifest (asset-manifest.json); drop the web one.
progress({ phase: 'Building manifest' });
@@ -328,17 +357,6 @@ export async function exportWeChat(opts: {
errors.push(`manifest: ${err instanceof Error ? err.message : String(err)}`);
}
- // 3. Entry scene → scenes/<name>.json with @uuid: refs stripped to bare uuids.
- progress({ phase: 'Transforming scene' });
- const sceneName = path.basename(opts.entryScene).replace(/\.[^.]+$/, '');
- try {
- const raw = sceneRaw ?? JSON.parse(await readFile(path.join(absOut, opts.entryScene), 'utf8'));
- await mkdir(path.join(absOut, 'scenes'), { recursive: true });
- await writeFile(path.join(absOut, 'scenes', `${sceneName}.json`), JSON.stringify(stripUuidRefs(raw)) + '\n');
- } catch (err) {
- errors.push(`scene transform: ${err instanceof Error ? err.message : String(err)}`);
- }
-
// 4. game-bundle.js — wechat SDK (esengine aliased) + project scripts + boot(),
// one esengine instance so the project's defineComponent/defineSystem run.
const scriptsAbs = opts.scriptsEntry ? path.join(opts.root, opts.scriptsEntry) : null;
@@ -350,7 +368,7 @@ export async function exportWeChat(opts: {
`import { initWeChatRuntime } from 'esengine';\n` +
(scriptsAbs && existsSync(scriptsAbs) ? `import ${JSON.stringify(scriptsAbs)};\n` : '') +
`export function boot(engineFactory, sideModuleFactories) {\n` +
- ` return initWeChatRuntime({ engineFactory, engineWasmPath: ${JSON.stringify(engineWasmPath)}, sideModuleFactories, sceneNames: ${JSON.stringify([sceneName])}, firstScene: ${JSON.stringify(sceneName)}${opts.ySortLayers ? `, ySortLayers: ${opts.ySortLayers >>> 0}` : ''} });\n` +
+ ` return initWeChatRuntime({ engineFactory, engineWasmPath: ${JSON.stringify(engineWasmPath)}, sideModuleFactories, sceneNames: ${JSON.stringify(scenes.map((s) => s.name))}, firstScene: ${JSON.stringify(sceneName)}${opts.ySortLayers ? `, ySortLayers: ${opts.ySortLayers >>> 0}` : ''} });\n` +
`}\n`;
progress({ phase: 'Bundling game' });
try {
diff --git a/desktop/electron/main.ts b/desktop/electron/main.ts
index 85d315e5d..7c1996478 100644
--- a/desktop/electron/main.ts
+++ b/desktop/electron/main.ts
@@ -34,7 +34,7 @@ import { buildPlayRealm } from './buildPlayRealm';
import { syncSdkTypes } from './syncSdkTypes';
import { installCrashCapture, logsDir } from './resilience';
import { checkForUpdate } from './updateCheck';
-import { resolveScripts } from '../src/project/format';
+import { resolveLayout, resolveScripts } from '../src/project/format';
import type { WorkspaceState } from '../src/project/format';
// Enable WebGPU in the renderer so the viewport's WebGPU backend (Settings →
@@ -532,6 +532,7 @@ ipcMain.handle(
return exportGame({
root,
entryScene,
+ scenesDir: resolveLayout(manifest).scenes,
ySortLayers,
gameHostEntry: path.join(HOSTS_DIR, 'gameHost.js'),
playableHostEntry: path.join(HOSTS_DIR, 'playableHost.js'),
diff --git a/desktop/src/gameHost.ts b/desktop/src/gameHost.ts
index 27625fbe6..431cb3537 100644
--- a/desktop/src/gameHost.ts
+++ b/desktop/src/gameHost.ts
@@ -16,6 +16,8 @@ import type { CatalogData, CookedAtlasInfo, ESEngineModule, SceneData } from 'es
interface GameConfig {
entryScene: string;
+ /** Every switchable scene (SceneManager name + cooked path); includes the entry. */
+ scenes?: Array<{ name: string; path: string }>;
/** Bitmask of render layers (0..31) that y-sort within the layer. */
ySortLayers?: number;
}
@@ -119,11 +121,20 @@ async function boot(): Promise<void> {
// physics.wasm sits next to esengine.wasm; the runtime loads it when the scene
// uses physics. (Runtime-spawned bodies still need a build-time enable flag —
// a follow-up that cooks features.physics into game.config.json.)
+ // The entry scene boots eagerly (already fetched); every other shipped scene
+ // registers lazily by path, so SceneManager.switchTo('name') fetches it on
+ // first use — the same registration shape the WeChat runtime uses.
+ const sceneList = cfg.scenes ?? [];
+ const entryName = sceneList.find((s) => s.path === cfg.entryScene)?.name;
await initPlayRealmRuntime({
app,
module,
canvas,
sceneData,
+ entrySceneName: entryName,
+ extraScenes: sceneList
+ .filter((s) => s.path !== cfg.entryScene)
+ .map((s) => ({ name: s.name, path: `./${s.path}` })),
assetManifest,
assetPathMap: pathMap,
catalogData: catalog,
diff --git a/desktop/tests/export-game.test.ts b/desktop/tests/export-game.test.ts
index c85b8827b..4670f3c4e 100644
--- a/desktop/tests/export-game.test.ts
+++ b/desktop/tests/export-game.test.ts
@@ -131,6 +131,34 @@ describe('exportGame', () => {
expect(existsSync(path.join(out2, 'game.js'))).toBe(true);
}, 60_000);
+ it('ships every scene in the scenes dir, listed in game.config.json', async () => {
+ const LV2SCN = '77777777-7777-7777-7777-777777777777';
+ writeFileSync(
+ path.join(root, 'scenes', 'level2.esscene'),
+ JSON.stringify({ version: '1.0', name: 'Level2', entities: [] }),
+ );
+ writeFileSync(path.join(root, 'scenes', 'level2.esscene.meta'), meta(LV2SCN, 'scene'));
+ const outMulti = path.join(root, 'dist-game-multi');
+ const res = await exportGame({
+ root,
+ entryScene: 'scenes/main.esscene',
+ gameHostEntry: GAME_HOST,
+ scriptsEntry: 'src/main.ts',
+ sdkDistDir: path.join(root, '_sdk'),
+ wasmDir: path.join(root, '_wasm'),
+ outDir: outMulti,
+ title: 'My Game',
+ });
+ expect(res.ok).toBe(true);
+ // Both scenes staged (web serves .esscene as-is) and listed for the host's
+ // SceneManager registration — entry eager, the rest lazy by path.
+ expect(existsSync(path.join(outMulti, 'scenes/level2.esscene'))).toBe(true);
+ const cfg = JSON.parse(readFileSync(path.join(outMulti, 'game.config.json'), 'utf8'));
+ expect(cfg.scenes).toContainEqual({ name: 'main', path: 'scenes/main.esscene' });
+ expect(cfg.scenes).toContainEqual({ name: 'level2', path: 'scenes/level2.esscene' });
+ expect(cfg.scenes[0]).toEqual({ name: 'main', path: 'scenes/main.esscene' }); // entry first
+ }, 60_000);
+
it('fails when the wasm runtime is missing — the build cannot boot without it', async () => {
const out3 = path.join(root, 'dist-game-nowasm');
const res = await exportGame({
diff --git a/desktop/tests/export-wechat.test.ts b/desktop/tests/export-wechat.test.ts
index e54806cfb..aef658a5b 100644
--- a/desktop/tests/export-wechat.test.ts
+++ b/desktop/tests/export-wechat.test.ts
@@ -162,11 +162,14 @@ describe('exportGame (wechat)', () => {
const SPINESCN = 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee';
writeFileSync(path.join(root, 'assets', 'boy.json'), JSON.stringify({ skeleton: { spine: '4.2.22' } }));
writeFileSync(path.join(root, 'assets', 'boy.json.meta'), meta(SPINE, 'spine'));
+ // Own scenes dir: scene discovery walks the entry's dir, and this test's
+ // scene must not leak into the other exports (nor theirs into this one).
+ mkdirSync(path.join(root, 'scenes-spine'), { recursive: true });
writeFileSync(
- path.join(root, 'scenes', 'spine.esscene'),
+ path.join(root, 'scenes-spine', 'spine.esscene'),
JSON.stringify({ version: '1.0', name: 'Spine', entities: [{ id: 0, components: [{ type: 'SpineSkeleton', data: { skeleton: `@uuid:${SPINE}` } }] }] }),
);
- writeFileSync(path.join(root, 'scenes', 'spine.esscene.meta'), meta(SPINESCN, 'scene'));
+ writeFileSync(path.join(root, 'scenes-spine', 'spine.esscene.meta'), meta(SPINESCN, 'scene'));
const wxDir = path.join(root, '_wxwasm-spine');
mkdirSync(wxDir, { recursive: true });
writeFileSync(path.join(wxDir, 'esengine.js'), 'module.exports = () => Promise.resolve({});');
@@ -177,7 +180,7 @@ describe('exportGame (wechat)', () => {
const outSpine = path.join(root, 'dist-wechat-spine');
const res = await exportGame({
root,
- entryScene: 'scenes/spine.esscene',
+ entryScene: 'scenes-spine/spine.esscene',
gameHostEntry: 'unused-for-wechat',
scriptsEntry: 'src/main.ts',
sdkDistDir: path.join(root, '_sdk'),
@@ -189,10 +192,11 @@ describe('exportGame (wechat)', () => {
const entry = readFileSync(path.join(outSpine, 'game.js'), 'utf8');
expect(entry).toContain("\"spine:4.2\": asFactory(require('./wasm/spine42.js'))");
expect(existsSync(path.join(outSpine, 'wasm', 'spine42.wasm'))).toBe(true);
+ // Scenes restage as scenes/<name>.json, so no .esscene ships — and native
+ // types stay out of the include list; it exists for the custom ones.
const spcfg = JSON.parse(readFileSync(path.join(outSpine, 'project.config.json'), 'utf8'));
- expect(spcfg.packOptions.include).toContainEqual({ type: 'suffix', value: '.esscene' });
- // Native types stay out of the include list — it exists for the custom ones.
- expect(spcfg.packOptions.include).not.toContainEqual({ type: 'suffix', value: '.json' });
+ expect(spcfg.packOptions?.include ?? []).not.toContainEqual({ type: 'suffix', value: '.esscene' });
+ expect(spcfg.packOptions?.include ?? []).not.toContainEqual({ type: 'suffix', value: '.json' });
// The manifest keeps the real addressable type, not a 'binary' downgrade.
const manifest = JSON.parse(readFileSync(path.join(outSpine, 'asset-manifest.json'), 'utf8'));
expect(manifest.groups.main.assets[SPINE].type).toBe('spine');
@@ -202,7 +206,7 @@ describe('exportGame (wechat)', () => {
const outBroken = path.join(root, 'dist-wechat-spine-missing');
const res = await exportGame({
root,
- entryScene: 'scenes/spine.esscene',
+ entryScene: 'scenes-spine/spine.esscene',
gameHostEntry: 'unused-for-wechat',
scriptsEntry: 'src/main.ts',
sdkDistDir: path.join(root, '_sdk'),
@@ -219,11 +223,12 @@ describe('exportGame (wechat)', () => {
const KTXSCN = 'abababab-abab-abab-abab-abababababab';
writeFileSync(path.join(root, 'assets', 'pre.ktx2'), 'KTX2BYTES');
writeFileSync(path.join(root, 'assets', 'pre.ktx2.meta'), meta(KTX, 'texture'));
+ mkdirSync(path.join(root, 'scenes-ktx2'), { recursive: true });
writeFileSync(
- path.join(root, 'scenes', 'ktx2.esscene'),
+ path.join(root, 'scenes-ktx2', 'ktx2.esscene'),
JSON.stringify({ version: '1.0', name: 'Ktx', entities: [{ id: 0, components: [{ type: 'Sprite', data: { texture: `@uuid:${KTX}` } }] }] }),
);
- writeFileSync(path.join(root, 'scenes', 'ktx2.esscene.meta'), meta(KTXSCN, 'scene'));
+ writeFileSync(path.join(root, 'scenes-ktx2', 'ktx2.esscene.meta'), meta(KTXSCN, 'scene'));
const wxDir = path.join(root, '_wxwasm-basis');
mkdirSync(wxDir, { recursive: true });
writeFileSync(path.join(wxDir, 'esengine.js'), 'module.exports = () => Promise.resolve({});');
@@ -234,7 +239,7 @@ describe('exportGame (wechat)', () => {
const outKtx = path.join(root, 'dist-wechat-ktx2');
const res = await exportGame({
root,
- entryScene: 'scenes/ktx2.esscene',
+ entryScene: 'scenes-ktx2/ktx2.esscene',
gameHostEntry: 'unused-for-wechat',
scriptsEntry: 'src/main.ts',
sdkDistDir: path.join(root, '_sdk'),
@@ -262,7 +267,7 @@ describe('exportGame (wechat)', () => {
const outNoBasis = path.join(root, 'dist-wechat-ktx2-missing');
const res = await exportGame({
root,
- entryScene: 'scenes/ktx2.esscene',
+ entryScene: 'scenes-ktx2/ktx2.esscene',
gameHostEntry: 'unused-for-wechat',
scriptsEntry: 'src/main.ts',
sdkDistDir: path.join(root, '_sdk'),
@@ -296,7 +301,60 @@ describe('exportGame (wechat)', () => {
// the runtime's ManifestModel + catalog resolve path refs through it.
expect(tex.path).toMatch(/^assets\/[0-9a-f]{16}\.png$/);
expect(tex.address).toBe('assets/hero.png');
- // Scenes keep their logical path and carry no address.
- expect(manifest.groups.main.assets[SCN].address).toBeUndefined();
+ // The scene restaged to scenes/<name>.json keeps its logical path as the
+ // address, so scene refs resolve to the WeChat-readable file.
+ expect(manifest.groups.main.assets[SCN].path).toBe('scenes/main.json');
+ expect(manifest.groups.main.assets[SCN].address).toBe('scenes/main.esscene');
+ }, 60_000);
+
+ it('ships every scene in the scenes dir as a switchable SceneManager target', async () => {
+ const LV2TEX = '99999999-9999-9999-9999-999999999999';
+ const LV2SCN = '88888888-8888-8888-8888-888888888888';
+ mkdirSync(path.join(root, 'scenes-multi'), { recursive: true });
+ writeFileSync(
+ path.join(root, 'scenes-multi', 'main.esscene'),
+ JSON.stringify({ version: '1.0', name: 'Main', entities: [{ id: 0, components: [{ type: 'Sprite', data: { texture: `@uuid:${TEX}` } }] }] }),
+ );
+ writeFileSync(path.join(root, 'scenes-multi', 'main.esscene.meta'), meta('12121212-1212-1212-1212-121212121212', 'scene'));
+ writeFileSync(path.join(root, 'assets', 'lv2.png'), 'PNG3DATA');
+ writeFileSync(path.join(root, 'assets', 'lv2.png.meta'), meta(LV2TEX, 'texture'));
+ writeFileSync(
+ path.join(root, 'scenes-multi', 'level2.esscene'),
+ JSON.stringify({ version: '1.0', name: 'Level2', entities: [{ id: 0, components: [{ type: 'Sprite', data: { texture: `@uuid:${LV2TEX}` } }] }] }),
+ );
+ writeFileSync(path.join(root, 'scenes-multi', 'level2.esscene.meta'), meta(LV2SCN, 'scene'));
+
+ const outMulti = path.join(root, 'dist-wechat-multi');
+ const res = await exportGame({
+ root,
+ entryScene: 'scenes-multi/main.esscene',
+ gameHostEntry: 'unused-for-wechat',
+ scriptsEntry: 'src/main.ts',
+ sdkDistDir: path.join(root, '_sdk'),
+ wasmDir: path.join(root, '_wxwasm'),
+ outDir: outMulti,
+ platform: 'wechat',
+ });
+ expect(res.ok).toBe(true);
+
+ // Both scenes transformed; the staged .esscene sources (not in WeChat's
+ // suffix whitelist) are gone, their manifest entries following the move.
+ expect(existsSync(path.join(outMulti, 'scenes', 'main.json'))).toBe(true);
+ expect(existsSync(path.join(outMulti, 'scenes', 'level2.json'))).toBe(true);
+ expect(existsSync(path.join(outMulti, 'scenes-multi', 'main.esscene'))).toBe(false);
+ expect(existsSync(path.join(outMulti, 'scenes-multi', 'level2.esscene'))).toBe(false);
+ const manifest = JSON.parse(readFileSync(path.join(outMulti, 'asset-manifest.json'), 'utf8'));
+ expect(manifest.groups.main.assets[LV2SCN].path).toBe('scenes/level2.json');
+ // The second scene is a cook root: its assets ship even though the entry
+ // scene never references them.
+ expect(manifest.groups.main.assets[LV2TEX].path).toBe('assets/lv2.png');
+ // Boot registers every scene, booting into the entry.
+ const bundle = readFileSync(path.join(outMulti, 'game-bundle.js'), 'utf8');
+ expect(bundle).toContain('"main"');
+ expect(bundle).toContain('"level2"');
+ expect(bundle).toContain('firstScene: "main"');
+ // No .esscene rides in packOptions — nothing ships under that suffix.
+ const pcfg = JSON.parse(readFileSync(path.join(outMulti, 'project.config.json'), 'utf8'));
+ expect(pcfg.packOptions?.include ?? []).not.toContainEqual({ type: 'suffix', value: '.esscene' });
}, 60_000);
});
diff --git a/sdk/src/playRealmRuntime.ts b/sdk/src/playRealmRuntime.ts
index dbb1b55ea..837ac82bc 100644
--- a/sdk/src/playRealmRuntime.ts
+++ b/sdk/src/playRealmRuntime.ts
@@ -34,6 +34,12 @@ export interface PlayRealmRuntimeConfig {
canvas: HTMLCanvasElement;
/** The current scene as RAW (`@uuid:`) SceneData — handles are realm-local. */
sceneData: SceneData;
+ /** Additional switchable scenes beyond the entry (SceneManager targets).
+ * `path` entries load lazily through the runtime Assets on first switch. */
+ extraScenes?: Array<{ name: string; data?: SceneData; path?: string }>;
+ /** SceneManager name of the entry `sceneData` (default '__play'). Shipped
+ * builds pass the real scene name so game code can switch back to it. */
+ entrySceneName?: string;
/** Lowercased uuid → fetchable URL (e.g. `estella://project/<path>`). */
assetManifest: Record<string, string>;
/**
@@ -148,13 +154,17 @@ export async function initPlayRealmRuntime(config: PlayRealmRuntimeConfig): Prom
(ref) => resolvePlayAssetRef(ref, assetManifest, assetBaseUrl, config.assetPathMap),
);
}
+ const entryName = config.entrySceneName ?? '__play';
await initRuntime({
app,
module,
source,
catalog: config.catalogData ? Catalog.fromJson(config.catalogData) : undefined,
- scenes: [{ name: '__play', data: sceneData }],
- firstScene: '__play',
+ scenes: [
+ { name: entryName, data: sceneData },
+ ...(config.extraScenes ?? []).filter((s) => s.name !== entryName),
+ ],
+ firstScene: entryName,
aspectRatio: canvas.width / canvas.height,
physicsEnabled: config.physicsEnabled,
physicsConfig: config.physicsConfig,
diff --git a/sdk/src/runtimeLoader.ts b/sdk/src/runtimeLoader.ts
index 7baa6038f..d1d3aa352 100644
--- a/sdk/src/runtimeLoader.ts
+++ b/sdk/src/runtimeLoader.ts
@@ -289,13 +289,23 @@ export async function loadRuntimeScene(options: LoadRuntimeSceneOptions): Promis
export function createRuntimeSceneConfig(
name: string,
- sceneData: SceneData,
+ sceneData: SceneData | undefined,
options: Omit<LoadRuntimeSceneOptions, 'sceneData' | 'sceneName'>,
+ scenePath?: string,
): SceneConfig {
return {
name,
async setup() {
- await loadRuntimeScene({ ...options, sceneData, sceneName: name });
+ let data = sceneData;
+ if (!data) {
+ // Lazy scene: fetch by path through the per-App runtime Assets
+ // (installed by initRuntime before any scene loads), so the data
+ // arrives via the realm's backend/resolver — http on web, wx fs
+ // on WeChat — only when the game actually switches to it.
+ if (!scenePath) throw new Error(`scene "${name}" registered with neither data nor path`);
+ data = await options.app.getResource(AssetsResource).fetchJson<SceneData>(scenePath);
+ }
+ await loadRuntimeScene({ ...options, sceneData: data, sceneName: name });
},
};
}
@@ -318,7 +328,10 @@ export interface RuntimeInitConfig {
* without one. Applied when the per-App runtime Assets is first created.
*/
catalog?: Catalog;
- scenes: Array<{ name: string; data: SceneData }>;
+ /** Every scene the game can switch to. `data` loads eagerly at register
+ * time; `path` registers a lazy scene fetched through the runtime Assets
+ * on first {@link SceneManagerState.switchTo}/load. One of the two. */
+ scenes: Array<{ name: string; data?: SceneData; path?: string }>;
firstScene: string;
spineModule?: SpineWasmModule | null;
spineManager?: SpineManager | null;
@@ -356,7 +369,7 @@ export async function initRuntime(config: RuntimeInitConfig): Promise<void> {
const mgr = app.getResource(SceneManager);
for (const scene of config.scenes) {
- mgr.register(createRuntimeSceneConfig(scene.name, scene.data, sceneOpts));
+ mgr.register(createRuntimeSceneConfig(scene.name, scene.data, sceneOpts, scene.path));
}
if (firstScene) {
diff --git a/sdk/src/wechatRuntime.ts b/sdk/src/wechatRuntime.ts
index c0cf2ca23..6896e8745 100644
--- a/sdk/src/wechatRuntime.ts
+++ b/sdk/src/wechatRuntime.ts
@@ -159,10 +159,17 @@ export async function initWeChatRuntime(config: WeChatRuntimeConfig): Promise<vo
resolveRef: resolvePath,
};
- const scenes: Array<{ name: string; data: SceneData }> = [];
+ // The first scene loads eagerly (the game boots into it); every other
+ // registers lazily by path — SceneManager fetches scenes/<name>.json
+ // through the runtime Assets (wx fs backend) on the first switchTo.
+ const scenes: Array<{ name: string; data?: SceneData; path?: string }> = [];
for (const name of config.sceneNames) {
- const sceneText = await platformReadTextFile(`scenes/${name}.json`);
- scenes.push({ name, data: JSON.parse(sceneText) });
+ if (name === config.firstScene) {
+ const sceneText = await platformReadTextFile(`scenes/${name}.json`);
+ scenes.push({ name, data: JSON.parse(sceneText) as SceneData });
+ } else {
+ scenes.push({ name, path: `scenes/${name}.json` });
+ }
}
// The manifest rides into initRuntime, which sets it on the per-App runtime