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.

fix(export): a shipped build is told about the 2.5D depth layers

yhh86662f8bf525
diff --git a/desktop/electron/exportGame.ts b/desktop/electron/exportGame.ts
index 13d8d6c06..61076b7b5 100644
--- a/desktop/electron/exportGame.ts
+++ b/desktop/electron/exportGame.ts
@@ -28,6 +28,9 @@ import { cookAssets, loadAssetGroups } from './cookAssets';
import { buildAddressableManifest } from './addressableManifest';
import { activeRemoteRoot } from '../../sdk/src/asset/assetGroups';
import type { PackagedGameConfig } from 'esengine';
+import {
+ DEFAULT_RUNTIME_CONFIG, packagedRuntimeFields, type RuntimeProjectConfig,
+} from '../src/project/runtimeConfig';
import { IMPORT_MAP_JSON, IMPORT_MAP_CSP_HASH } from './buildPlayRealm';
import { exportWeChat } from './exportWeChat';
import { exportMiniGame } from './exportMiniGame';
@@ -415,17 +418,14 @@ export interface ExportGameOptions {
/** Shipping config: minify the bundles, no sourcemap. Default off (dev). */
minify?: boolean;
sourcemap?: boolean;
- /** Bitmask of render layers (0..31) that y-sort (Project Settings → Rendering). */
- ySortLayers?: number;
- /** Project color space — 'linear' boots the shipped game on the linear-light pipeline. */
- colorSpace?: 'gamma' | 'linear';
- /** Project camera fit (Project Settings → Display) — the main camera letterboxes this
- * design resolution regardless of any UI Canvas. Absent ⇒ no fit (raw orthoSize). */
- screenFit?: { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number };
- /** Project widget theme (Project Settings → UI); absent = dark. */
- uiTheme?: 'light';
- /** Project theme color overrides (role → #rrggbbaa hex) — the host parses them. */
- uiThemeColors?: Record<string, string>;
+ /**
+ * The project's runtime settings, derived ONCE from the manifest
+ * (`runtimeConfigOf`) rather than re-listed per target. Every packaged build
+ * writes the same slice of it (`packagedRuntimeFields`), which is what stopped
+ * the 2.5D depth mask from reaching the play realm and no shipped build.
+ * Absent ⇒ a project that declared nothing.
+ */
+ runtime?: RuntimeProjectConfig;
/** Hot-update delivery baked into game.config.json: the CDN root `remote`-group
* assets resolve against + the storage key an applied update persists under.
* The addressable `asset-manifest.json` this export always emits enables it. */
@@ -532,6 +532,9 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>
// aspect) so a caller that omits it still ships consistently. The IPC handler resolves
// it from the manifest (explicit setting, else the design resolution's aspect).
const orientation: ScreenOrientation = opts.orientation ?? 'landscape';
+ // One derivation of the project's settings, forwarded whole. Every target used
+ // to take them as loose fields and each one had to remember the same list.
+ const runtime = opts.runtime ?? DEFAULT_RUNTIME_CONFIG;
const progress = opts.onProgress ?? (() => {});
const scenes = await discoverProjectScenes(opts.root, opts.entryScene, opts.scenesDir, opts.excludeScenes);
@@ -551,11 +554,7 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>
title,
appid: opts.wechatAppid,
orientation,
- ySortLayers: opts.ySortLayers,
- colorSpace: opts.colorSpace,
- screenFit: opts.screenFit,
- uiTheme: opts.uiTheme,
- uiThemeColors: opts.uiThemeColors,
+ runtime,
minify: opts.minify,
contentAddressed: opts.contentAddressed,
compressTextures: opts.compressTextures,
@@ -578,11 +577,7 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>
title,
appid: opts.wechatAppid,
orientation,
- ySortLayers: opts.ySortLayers,
- colorSpace: opts.colorSpace,
- screenFit: opts.screenFit,
- uiTheme: opts.uiTheme,
- uiThemeColors: opts.uiThemeColors,
+ runtime,
minify: opts.minify,
contentAddressed: opts.contentAddressed,
compressTextures: opts.compressTextures,
@@ -606,11 +601,7 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>
title,
orientation,
minify: opts.minify,
- ySortLayers: opts.ySortLayers,
- colorSpace: opts.colorSpace,
- screenFit: opts.screenFit,
- uiTheme: opts.uiTheme,
- uiThemeColors: opts.uiThemeColors,
+ runtime,
adProfile: opts.playableAdProfile,
onProgress: opts.onProgress,
});
@@ -740,11 +731,7 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>
// spelled differently here — the two sides share one declaration.
const gameConfig: PackagedGameConfig = {
entryScene: opts.entryScene, scenes,
- ...(opts.ySortLayers ? { ySortLayers: opts.ySortLayers } : {}),
- ...(opts.colorSpace === 'linear' ? { colorSpace: opts.colorSpace } : {}),
- ...(opts.screenFit && opts.screenFit.scaleMode >= 0 ? { screenFit: opts.screenFit } : {}),
- ...(opts.uiTheme === 'light' ? { uiTheme: opts.uiTheme } : {}),
- ...(opts.uiThemeColors && Object.keys(opts.uiThemeColors).length > 0 ? { uiThemeColors: opts.uiThemeColors } : {}),
+ ...packagedRuntimeFields(runtime),
...(hotUpdate ? { hotUpdate } : {}),
...(sideModuleDeclarations(projectModules, platform).length > 0
? { sideModules: sideModuleDeclarations(projectModules, platform) } : {}),
diff --git a/desktop/electron/exportMiniGame.ts b/desktop/electron/exportMiniGame.ts
index b4f03e965..cc8c5c32e 100644
--- a/desktop/electron/exportMiniGame.ts
+++ b/desktop/electron/exportMiniGame.ts
@@ -29,6 +29,9 @@
* own path. Pure Node (esbuild + fs) — IPC wiring is in main.ts.
*/
import { loadEsbuild } from './esbuildRuntime';
+import {
+ DEFAULT_RUNTIME_CONFIG, packagedRuntimeFields, type RuntimeProjectConfig,
+} from '../src/project/runtimeConfig';
import { writeFile, mkdir, cp, readFile, rename, rm } from 'node:fs/promises';
import { existsSync } from 'node:fs';
import path from 'node:path';
@@ -169,17 +172,9 @@ export async function exportMiniGame(profile: MiniGameExportProfile, opts: {
appid?: string;
/** Screen orientation (Project Settings) → game.json. */
orientation?: 'portrait' | 'landscape';
- /** Bitmask of render layers (0..31) that y-sort (Project Settings → Rendering). */
- ySortLayers?: number;
- /** Project color space — 'linear' boots the mini-game on the linear-light pipeline. */
- colorSpace?: 'gamma' | 'linear';
- /** Project camera fit (Project Settings → Display) — letterboxes the design resolution
- * without a UI Canvas; absent = no fit. */
- screenFit?: { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number };
- /** Project widget theme (Project Settings → UI); absent = dark. */
- uiTheme?: 'light';
- /** Project theme color overrides (role → #rrggbbaa hex) — parsed by the generated boot. */
- uiThemeColors?: Record<string, string>;
+ /** The project's runtime settings, derived once by `runtimeConfigOf`; the
+ * generated boot passes the packaged slice of them to the vendor runtime. */
+ runtime?: RuntimeProjectConfig;
minify?: boolean;
/** Emit content-addressed asset filenames (<hash><ext>) for dedup + immutable caching. */
contentAddressed?: boolean;
@@ -308,7 +303,18 @@ export async function exportMiniGame(profile: MiniGameExportProfile, opts: {
// which glue it staged (esengine.wxgame vs the web-aligned esengine), and the
// runtime must instantiate the staged glue's .wasm twin, not guess a name.
const engineWasmPath = `wasm/${engineGlueFile.replace(/\.js$/, '.wasm')}`;
- const themeColors = opts.uiThemeColors && Object.keys(opts.uiThemeColors).length > 0 ? opts.uiThemeColors : undefined;
+ // The packaged slice of the project's settings, GENERATED rather than listed:
+ // a setting added to packagedRuntimeFields reaches this boot without anyone
+ // having to remember that this template exists. Theme colours are the one that
+ // is not a plain value — the runtime takes parsed overrides, so a call is
+ // emitted for them instead.
+ const packaged = packagedRuntimeFields(opts.runtime ?? DEFAULT_RUNTIME_CONFIG);
+ const themeColors = packaged.uiThemeColors;
+ const runtimeArgs = Object.entries(packaged)
+ .map(([k, v]) => (k === 'uiThemeColors'
+ ? `, uiThemeOverrides: parseThemeOverrides(${JSON.stringify(v)})`
+ : `, ${k}: ${JSON.stringify(v)}`))
+ .join('');
// A vendor whose SDK entry does not install a platform on import (the
// family entry, esengine/minigame — it waits until the game names a host)
// gets its runtime profile installed here, at the top of boot(). Without
@@ -326,7 +332,7 @@ export async function exportMiniGame(profile: MiniGameExportProfile, opts: {
(scriptsAbs && existsSync(scriptsAbs) ? `import ${JSON.stringify(scriptsAbs)};\n` : '') +
`export function boot(engineFactory, sideModuleFactories) {\n` +
(installsPlatform ? ` installMiniGamePlatform(__platformProfile);\n` : '') +
- ` return ${profile.runtimeInit}({ engineFactory, engineWasmPath: ${JSON.stringify(engineWasmPath)}, sideModuleFactories, sceneNames: ${JSON.stringify(scenes.map((s) => s.name))}, firstScene: ${JSON.stringify(sceneName)}${opts.ySortLayers ? `, ySortLayers: ${opts.ySortLayers >>> 0}` : ''}${opts.colorSpace === 'linear' ? `, colorSpace: 'linear'` : ''}${opts.screenFit && opts.screenFit.scaleMode >= 0 ? `, screenFit: ${JSON.stringify(opts.screenFit)}` : ''}${opts.uiTheme === 'light' ? `, uiTheme: 'light'` : ''}${themeColors ? `, uiThemeOverrides: parseThemeOverrides(${JSON.stringify(themeColors)})` : ''}${projectDeclarations.length > 0 ? `, sideModules: ${JSON.stringify(projectDeclarations)}` : ''} });\n` +
+ ` return ${profile.runtimeInit}({ engineFactory, engineWasmPath: ${JSON.stringify(engineWasmPath)}, sideModuleFactories, sceneNames: ${JSON.stringify(scenes.map((s) => s.name))}, firstScene: ${JSON.stringify(sceneName)}${runtimeArgs}${projectDeclarations.length > 0 ? `, sideModules: ${JSON.stringify(projectDeclarations)}` : ''} });\n` +
`}\n`;
progress({ phase: 'Bundling game' });
try {
diff --git a/desktop/electron/exportPlayable.ts b/desktop/electron/exportPlayable.ts
index 7accb774b..31b2251dd 100644
--- a/desktop/electron/exportPlayable.ts
+++ b/desktop/electron/exportPlayable.ts
@@ -17,6 +17,9 @@
* + fs); IPC wiring in main.ts.
*/
import { loadEsbuild } from './esbuildRuntime';
+import {
+ DEFAULT_RUNTIME_CONFIG, packagedRuntimeFields, type RuntimeProjectConfig,
+} from '../src/project/runtimeConfig';
import { writeFile, mkdir, readFile, stat, rm } from 'node:fs/promises';
import { existsSync } from 'node:fs';
import path from 'node:path';
@@ -182,17 +185,9 @@ export async function exportPlayable(opts: {
* reaches the ad-network profile, which may declare it to the platform. */
orientation?: ScreenOrientation;
minify?: boolean;
- /** Bitmask of render layers (0..31) that y-sort (Project Settings → Rendering). */
- ySortLayers?: number;
- /** Project color space — 'linear' boots the playable on the linear-light pipeline. */
- colorSpace?: 'gamma' | 'linear';
- /** Project camera fit (design resolution + scale mode) — letterboxes the main camera
- * without a UI Canvas; absent = no fit. */
- screenFit?: { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number };
- /** Project widget theme (Project Settings → UI); absent = dark. */
- uiTheme?: 'light';
- /** Project theme color overrides (role → #rrggbbaa hex) — the host parses them. */
- uiThemeColors?: Record<string, string>;
+ /** The project's runtime settings, derived once by `runtimeConfigOf`; the page
+ * carries the packaged slice of them as one global the host reads. */
+ runtime?: RuntimeProjectConfig;
/** The ad network this package targets (Project Settings → Packaging → Playable):
* its size cap, its `<head>` markup and its click-through API. Absent ⇒ generic. */
adProfile?: PlayableAdProfile;
@@ -314,11 +309,10 @@ export async function exportPlayable(opts: {
`window.__GAME_PATHMAP__=${JSON.stringify(pathMap)};` +
`window.__GAME_SCENES__=${JSON.stringify(scenes)};` +
`window.__GAME_FIRST__=${JSON.stringify(sceneName)};` +
- `window.__GAME_YSORT__=${(opts.ySortLayers ?? 0) >>> 0};` +
- `window.__GAME_COLORSPACE__=${JSON.stringify(opts.colorSpace === 'linear' ? 'linear' : 'gamma')};` +
- (opts.screenFit && opts.screenFit.scaleMode >= 0 ? `window.__GAME_SCREENFIT__=${JSON.stringify(opts.screenFit)};` : '') +
- (opts.uiTheme === 'light' ? `window.__GAME_UITHEME__='light';` : '') +
- (opts.uiThemeColors && Object.keys(opts.uiThemeColors).length > 0 ? `window.__GAME_UITHEMECOLORS__=${JSON.stringify(opts.uiThemeColors)};` : '');
+ // ONE global for the project's settings, in the same shape game.config.json
+ // carries them. Five separate globals meant the host and the export had to
+ // agree on five names, and a sixth setting simply never got a global.
+ `window.__GAME_RUNTIME__=${JSON.stringify(packagedRuntimeFields(opts.runtime ?? DEFAULT_RUNTIME_CONFIG))};`;
const adProfile = opts.adProfile ?? genericPlayableProfile;
const network = playableAdInjection(adProfile, { title, orientation });
const outFile = path.join(absOut, 'index.html');
diff --git a/desktop/electron/main.ts b/desktop/electron/main.ts
index 77fd7b26b..330fb2f7c 100644
--- a/desktop/electron/main.ts
+++ b/desktop/electron/main.ts
@@ -74,7 +74,8 @@ import {
listPlayableNetworks, loadPlayableProfile,
type PlatformRuntimeDirs, type ProjectPlatformKind,
} from './platformCatalog';
-import { resolveLayout, resolveScripts, resolveOrientation, resolveScreenFit, resolveAppId, type ExportPlatform } from '../src/project/format';
+import { resolveLayout, resolveScripts, resolveOrientation, resolveAppId, type ExportPlatform } from '../src/project/format';
+import { runtimeConfigOf } from '../src/project/runtimeConfig';
import type { WorkspaceState } from '../src/project/format';
// Enable WebGPU in the renderer so the viewport's WebGPU backend (Settings →
@@ -1114,24 +1115,16 @@ ipcMain.handle(
phase: `ad network "${plat?.playable?.network}" not found — packaging generic`,
});
}
- const ySortLayers =
- (manifest.features?.rendering?.ySortLayers ?? []).reduce((m, i) => m | (1 << i), 0) >>> 0;
- const colorSpace = manifest.features?.rendering?.colorSpace === 'linear' ? 'linear' as const : undefined;
- // Project camera fit → runtime screenFit (only when the project opts in; scaleMode < 0 = off).
- const fit = resolveScreenFit(manifest);
- const screenFit = fit.scaleMode >= 0 ? fit : undefined;
- const uiTheme = manifest.features?.ui?.theme === 'light' ? 'light' as const : undefined;
- const uiThemeColors = manifest.features?.ui?.colors;
+ // Every project setting a runtime is told, derived in ONE place shared with
+ // the play realm (see runtimeConfig.ts). Listing them here is what left the
+ // 2.5D depth mask out of every shipped build while Play had it.
+ const runtime = runtimeConfigOf(manifest);
return exportGame({
root,
entryScene,
scenesDir: resolveLayout(manifest).scenes,
excludeScenes: manifest.packaging?.excludeScenes,
- ySortLayers,
- colorSpace,
- screenFit,
- uiTheme,
- uiThemeColors,
+ runtime,
gameHostEntry: path.join(HOSTS_DIR, 'gameHost.js'),
playableHostEntry: path.join(HOSTS_DIR, 'playableHost.js'),
scriptsEntry: resolveScripts(manifest).main,
diff --git a/desktop/src/playableHost.ts b/desktop/src/playableHost.ts
index cbd5ee9e9..746c9131a 100644
--- a/desktop/src/playableHost.ts
+++ b/desktop/src/playableHost.ts
@@ -12,6 +12,7 @@
*/
import { createWebApp, setEditorMode, setPlayMode, initPlayableRuntime, createEmbeddedSideModuleHost, parseThemeOverrides } from 'esengine';
import type { ESEngineModule as EngineModule, SceneData, EmbeddedSideModuleRegistry } from 'esengine';
+import type { PackagedRuntimeFields } from '@/project/runtimeConfig';
type EngineFactory = (opts?: Record<string, unknown>) => Promise<EngineModule>;
// Inlined by exportPlayable as <script> globals (kept out of the bundle so the
@@ -26,11 +27,10 @@ declare const __GAME_ASSETS__: Record<string, string>;
declare const __GAME_PATHMAP__: Record<string, string>;
declare const __GAME_SCENES__: Array<{ name: string; data: SceneData }>;
declare const __GAME_FIRST__: string;
-declare const __GAME_YSORT__: number;
-declare const __GAME_COLORSPACE__: 'gamma' | 'linear';
-declare const __GAME_SCREENFIT__: { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number };
-declare const __GAME_UITHEME__: 'light';
-declare const __GAME_UITHEMECOLORS__: Record<string, string>;
+/** The project's settings, in the same shape game.config.json carries them —
+ * one global, so a setting the export starts sending arrives without the host
+ * learning a new name for it. Absent fields are their defaults. */
+declare const __GAME_RUNTIME__: PackagedRuntimeFields;
function decodeBase64(b64: string): Uint8Array {
const raw = atob(b64);
@@ -40,6 +40,9 @@ function decodeBase64(b64: string): Uint8Array {
}
async function boot(): Promise<void> {
+ // An export built before this global simply has no settings to apply.
+ const runtimeConfig: PackagedRuntimeFields =
+ typeof __GAME_RUNTIME__ !== 'undefined' ? __GAME_RUNTIME__ : {};
const canvas = document.getElementById('canvas') as HTMLCanvasElement;
const resize = (): void => {
const dpr = window.devicePixelRatio || 1;
@@ -85,9 +88,9 @@ async function boot(): Promise<void> {
const app = createWebApp(module, {
renderSurface: { kind: 'gl-context', handle: glHandle },
// Older exports predate the color-space global; treat it as optional.
- colorSpace: typeof __GAME_COLORSPACE__ !== 'undefined' ? __GAME_COLORSPACE__ : undefined,
- // Present only when the project opts into a camera fit; optional otherwise.
- screenFit: typeof __GAME_SCREENFIT__ !== 'undefined' ? __GAME_SCREENFIT__ : undefined,
+ colorSpace: runtimeConfig.colorSpace,
+ // Present only when the project opts into a camera fit; absent otherwise.
+ screenFit: runtimeConfig.screenFit,
getViewportSize: () => ({ width: canvas.width, height: canvas.height }),
// Physics + spine resolve from the inlined base64 registry (no fetch).
sideModules: createEmbeddedSideModuleHost(typeof __SIDE_MODULES__ !== 'undefined' ? __SIDE_MODULES__ : {}),
@@ -118,11 +121,11 @@ async function boot(): Promise<void> {
assetPathMap: typeof __GAME_PATHMAP__ !== 'undefined' ? __GAME_PATHMAP__ : undefined,
scenes: __GAME_SCENES__,
firstScene: __GAME_FIRST__,
- // Older exports predate y-sort; treat the global as optional.
- ySortLayers: typeof __GAME_YSORT__ !== 'undefined' ? __GAME_YSORT__ : undefined,
- // Project widget theme + token overrides; optional like the rest.
- uiTheme: typeof __GAME_UITHEME__ !== 'undefined' ? __GAME_UITHEME__ : undefined,
- uiThemeOverrides: parseThemeOverrides(typeof __GAME_UITHEMECOLORS__ !== 'undefined' ? __GAME_UITHEMECOLORS__ : undefined),
+ ySortLayers: runtimeConfig.ySortLayers,
+ // The 2.5D opt-in, which a playable never used to be told at all.
+ depthLayers: runtimeConfig.depthLayers,
+ uiTheme: runtimeConfig.uiTheme,
+ uiThemeOverrides: parseThemeOverrides(runtimeConfig.uiThemeColors),
});
}
diff --git a/desktop/tests/export-game.test.ts b/desktop/tests/export-game.test.ts
index 2503410a6..4c60f9115 100644
--- a/desktop/tests/export-game.test.ts
+++ b/desktop/tests/export-game.test.ts
@@ -1,316 +1,320 @@
-// SPDX-License-Identifier: Apache-2.0
-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-/**
- * @file Game export orchestration (REARCH_EDITOR_REALM Phase S). Asserts
- * exportGame produces a self-contained web build: cooked assets + manifest,
- * the esbuild'd game host (esengine inlined, not external), the copied wasm
- * runtime, index.html, and the entry-scene config. (The host RENDERING is
- * proven separately by play:verify — gameHost reuses initPlayRealmRuntime.)
- */
-import { describe, it, expect, beforeAll, afterAll } from 'vitest';
-import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync, copyFileSync } from 'node:fs';
-import { createHash } from 'node:crypto';
-import { tmpdir } from 'node:os';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { exportGame } from '../electron/exportGame';
-
-const HERE = path.dirname(fileURLToPath(import.meta.url));
-const GAME_HOST = path.join(HERE, '..', 'src', 'gameHost.ts');
-
-let root: string;
-let out: string;
-const TEX = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa';
-const SCN = 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb';
-const meta = (uuid: string, type: string) => JSON.stringify({ uuid, version: '2.0', type, importer: {} });
-
-beforeAll(async () => {
- root = mkdtempSync(path.join(tmpdir(), 'estella-export-'));
- // A texture asset + sidecar.
- mkdirSync(path.join(root, 'assets'), { recursive: true });
- // A real PNG so the content-addressed + KTX2-compress export path has valid input.
- copyFileSync(path.resolve(HERE, '..', '..', 'examples', 'hello-world', 'assets', 'textures', 'logo.png'),
- path.join(root, 'assets', 'hero.png'));
- writeFileSync(path.join(root, 'assets', 'hero.png.meta'), meta(TEX, 'texture'));
- // A scene that references the texture by @uuid: + its sidecar.
- mkdirSync(path.join(root, 'scenes'), { recursive: true });
- writeFileSync(
- path.join(root, 'scenes', 'main.esscene'),
- JSON.stringify({ version: '1.0', name: 'Main', entities: [{ id: 0, components: [{ type: 'Sprite', data: { texture: `@uuid:${TEX}` } }] }] }),
- );
- writeFileSync(path.join(root, 'scenes', 'main.esscene.meta'), meta(SCN, 'scene'));
- // A project startup entry (esengine external) → bundled to scripts.mjs.
- mkdirSync(path.join(root, 'src'), { recursive: true });
- writeFileSync(path.join(root, 'src', 'main.ts'), `import { defineComponent } from 'esengine';\ndefineComponent('SpawnMarker', { rate: 1 });\n`);
- // Stand-in SDK dist + wasm runtime dirs to copy.
- mkdirSync(path.join(root, '_sdk'), { recursive: true });
- writeFileSync(path.join(root, '_sdk', 'index.js'), 'export const x = 1;');
- mkdirSync(path.join(root, '_wasm'), { recursive: true });
- writeFileSync(path.join(root, '_wasm', 'esengine.js'), 'export default () => {};');
- writeFileSync(path.join(root, '_wasm', 'esengine.wasm'), 'wasmbytes');
-
- out = path.join(root, 'dist-game');
-}, 60_000);
-
-afterAll(() => rmSync(root, { recursive: true, force: true }));
-
-
-/** Every asset in an addressable manifest, paired with its uuid key. */
-function manifestAssets(manifest: unknown): Array<[string, { type: string; path: string; address?: string; compressedFormats?: string[] }]> {
- const groups = (manifest as { groups: Record<string, { assets: Record<string, never> }> }).groups;
- return Object.values(groups).flatMap((g) => Object.entries(g.assets)) as never;
-}
-
-describe('exportGame', () => {
- it('produces an import-map web build (cook + host + sdk + scripts + wasm + html)', async () => {
- 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: out,
- title: 'My Game',
- });
-
- expect(res.ok).toBe(true);
- expect(res.errors).toEqual([]);
- // Reachability pulled the scene + its referenced texture into the build.
- expect(res.included).toBe(2);
-
- const has = (p: string) => existsSync(path.join(out, p));
- expect(has('index.html')).toBe(true);
- expect(has('game.js')).toBe(true);
- expect(has('scripts.mjs')).toBe(true);
- expect(has('sdk/index.js')).toBe(true);
- expect(has('game.config.json')).toBe(true);
- // The flat manifest is a build-time intermediate — only the addressable one ships.
- expect(has('assets.manifest.json')).toBe(false);
- expect(has('asset-manifest.json')).toBe(true);
- expect(has('scenes/main.esscene')).toBe(true);
- // Content-addressing is on by default now: the texture ships as assets/<hash>.png.
- const m = JSON.parse(readFileSync(path.join(out, 'asset-manifest.json'), 'utf8'));
- const tex = manifestAssets(m).find(([, a]) => a.type === 'texture')![1];
- expect(tex.path).toMatch(/^assets\/[0-9a-f]{16}\.png$/);
- expect(has(tex.path)).toBe(true);
- expect(has('wasm/esengine.js')).toBe(true);
-
- // The host + project bundle are esengine-EXTERNAL (small; resolved by the
- // import map) — NOT an inlined hundreds-of-KB SDK.
- const gameJs = readFileSync(path.join(out, 'game.js'), 'utf8');
- expect(gameJs.length).toBeLessThan(100_000);
- expect(readFileSync(path.join(out, 'scripts.mjs'), 'utf8')).toMatch(/from\s*["']esengine["']/);
-
- // index.html carries the import map + loads the host; config points at the scene.
- const html = readFileSync(path.join(out, 'index.html'), 'utf8');
- expect(html).toContain('importmap');
- expect(html).toContain('./sdk/index.js');
- expect(html).toContain('./game.js');
- // Web pins orientation (default landscape ⇒ rotate-to-fit overlay + best-effort lock).
- expect(html).toContain('id="rotate-hint"');
- expect(html).toContain('Rotate your device to landscape');
- expect(html).toMatch(/screen\.orientation[\s\S]*lock\("landscape"\)/);
- expect(JSON.parse(readFileSync(path.join(out, 'game.config.json'), 'utf8')).entryScene).toBe('scenes/main.esscene');
- }, 60_000);
-
- it('lists every inline script in the page CSP, for either orientation', async () => {
- for (const orientation of ['landscape', 'portrait'] as const) {
- const cspOut = path.join(root, `dist-game-csp-${orientation}`);
- 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: cspOut, orientation,
- });
- expect(res.ok).toBe(true);
-
- const html = readFileSync(path.join(cspOut, 'index.html'), 'utf8');
- const csp = /http-equiv="Content-Security-Policy"\s*\n?\s*content="([^"]+)"/.exec(html)?.[1];
- expect(csp).toBeTruthy();
- // A hash the policy omits means the browser blocks that script — which is how
- // the orientation lock came to be dead in a shipped build.
- const inline = [...html.matchAll(/<script(?![^>]*\bsrc=)[^>]*>([\s\S]*?)<\/script>/g)].map((m) => m[1]);
- expect(inline.length).toBe(2); // the import map + the orientation lock
- for (const body of inline) {
- expect(csp).toContain(`sha256-${createHash('sha256').update(body).digest('base64')}`);
- }
- }
- }, 60_000);
-
- it('writes the project camera fit into game.config.json (only when opted in)', async () => {
- const fitOut = path.join(root, 'dist-game-fit');
- 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: fitOut, title: 'Fit Game',
- screenFit: { designWidth: 1080, designHeight: 1920, scaleMode: 2, matchWidthOrHeight: 0.5 },
- });
- expect(res.ok).toBe(true);
- const cfg = JSON.parse(readFileSync(path.join(fitOut, 'game.config.json'), 'utf8'));
- expect(cfg.screenFit).toEqual({ designWidth: 1080, designHeight: 1920, scaleMode: 2, matchWidthOrHeight: 0.5 });
-
- // Off (scaleMode -1) ⇒ no screenFit key, so an unconfigured game's config is unchanged.
- const offOut = path.join(root, 'dist-game-fitoff');
- 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: offOut,
- screenFit: { designWidth: 1920, designHeight: 1080, scaleMode: -1, matchWidthOrHeight: 0.5 },
- });
- expect(JSON.parse(readFileSync(path.join(offOut, 'game.config.json'), 'utf8')).screenFit).toBeUndefined();
- }, 60_000);
-
- it('content-addresses + KTX2-compresses cooked assets when opted in', async () => {
- const out2 = path.join(root, 'dist-game-ca');
- 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: out2,
- title: 'CA Game',
- contentAddressed: true,
- compressTextures: true,
- });
- expect(res.ok).toBe(true);
- expect(res.errors).toEqual([]);
-
- const manifest = JSON.parse(readFileSync(path.join(out2, 'asset-manifest.json'), 'utf8'));
- const tex = manifestAssets(manifest).find(([uuid]) => uuid.toLowerCase() === TEX)![1];
- // The PNG was encoded to KTX2 and named by content hash; refs stay uuid-based.
- expect(tex.path).toMatch(/^assets\/[0-9a-f]{16}\.ktx2$/);
- expect(tex.compressedFormats).toEqual(['astc-4x4', 'etc2-rgba8', 's3tc-dxt5']);
- const bytes = readFileSync(path.join(out2, tex.path));
- const magic = [0xab, 0x4b, 0x54, 0x58, 0x20, 0x32, 0x30, 0xbb, 0x0d, 0x0a, 0x1a, 0x0a];
- expect(magic.every((b, i) => bytes[i] === b)).toBe(true);
-
- // The scene keeps its logical name and the whole build still assembled.
- expect(existsSync(path.join(out2, 'scenes/main.esscene'))).toBe(true);
- 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('excludeScenes drops a scene from the build; the entry is immune', async () => {
- const outEx = path.join(root, 'dist-game-excluded');
- 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: outEx,
- title: 'My Game',
- // level2 excluded; excluding the entry must be ignored — it boots the game.
- excludeScenes: ['scenes/level2.esscene', 'scenes/main.esscene'],
- });
- expect(res.ok).toBe(true);
- const cfg = JSON.parse(readFileSync(path.join(outEx, 'game.config.json'), 'utf8'));
- expect(cfg.scenes).toEqual([{ name: 'main', path: 'scenes/main.esscene' }]);
- expect(existsSync(path.join(outEx, 'scenes/level2.esscene'))).toBe(false);
- }, 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({
- root,
- entryScene: 'scenes/main.esscene',
- gameHostEntry: GAME_HOST,
- scriptsEntry: 'src/main.ts',
- sdkDistDir: path.join(root, '_sdk'),
- wasmDir: path.join(root, '_no-such-wasm'),
- outDir: out3,
- title: 'My Game',
- });
- expect(res.ok).toBe(false);
- expect(res.errors.some((e) => e.includes('wasm runtime dir not found'))).toBe(true);
- }, 60_000);
-
- // A third-party runtime (a vector-animation player, another solver) as an
- // ordinary side module: staged beside the engine's own and declared in the
- // config, which is the whole difference between `acquire('rive')` working and
- // a game having to fetch and instantiate a wasm by hand.
- it("ships a project's own native module and declares it for the runtime", async () => {
- const modDir = path.join(root, '.esengine', 'modules', 'rive');
- mkdirSync(path.join(modDir, 'web'), { recursive: true });
- writeFileSync(path.join(modDir, 'module.json'), JSON.stringify({ file: 'rive', globalName: 'RiveModule' }));
- writeFileSync(path.join(modDir, 'web', 'rive.js'), 'var RiveModule = () => Promise.resolve({});');
- writeFileSync(path.join(modDir, 'web', 'rive.wasm'), '\0asm');
-
- const outMod = path.join(root, 'dist-game-module');
- 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: outMod,
- title: 'My Game',
- });
- expect(res.ok).toBe(true);
-
- // Beside the engine's own artifacts — one place, so every transport finds it.
- expect(existsSync(path.join(outMod, 'wasm', 'rive.js'))).toBe(true);
- expect(existsSync(path.join(outMod, 'wasm', 'rive.wasm'))).toBe(true);
- expect(existsSync(path.join(outMod, 'wasm', 'esengine.js'))).toBe(true);
-
- const cfg = JSON.parse(readFileSync(path.join(outMod, 'game.config.json'), 'utf8'));
- expect(cfg.sideModules).toEqual([{ id: 'rive', file: 'rive', globalName: 'RiveModule' }]);
-
- rmSync(path.join(root, '.esengine'), { recursive: true, force: true });
- }, 60_000);
-
- it('says so when a project module has no build for the target, rather than shipping a broken package', async () => {
- const modDir = path.join(root, '.esengine', 'modules', 'rive');
- mkdirSync(path.join(modDir, 'web'), { recursive: true });
- writeFileSync(path.join(modDir, 'web', 'rive.js'), 'export default () => Promise.resolve({});');
-
- const outMod = path.join(root, 'dist-game-module-android');
- 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: outMod,
- platform: 'android',
- title: 'My Game',
- });
- expect(res.ok).toBe(true);
- expect(res.warnings.join('\n')).toContain('app binary');
- // Not declared, because it was not staged: a declaration whose binary is
- // absent reports a missing file instead of an unsupported target.
- const cfg = JSON.parse(readFileSync(path.join(outMod, 'game.config.json'), 'utf8'));
- expect(cfg.sideModules).toBeUndefined();
-
- rmSync(path.join(root, '.esengine'), { recursive: true, force: true });
- }, 60_000);
-});
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Game export orchestration (REARCH_EDITOR_REALM Phase S). Asserts
+ * exportGame produces a self-contained web build: cooked assets + manifest,
+ * the esbuild'd game host (esengine inlined, not external), the copied wasm
+ * runtime, index.html, and the entry-scene config. (The host RENDERING is
+ * proven separately by play:verify — gameHost reuses initPlayRealmRuntime.)
+ */
+import { describe, it, expect, beforeAll, afterAll } from 'vitest';
+import { runtimeConfigOf } from '@/project/runtimeConfig';
+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync, copyFileSync } from 'node:fs';
+import { createHash } from 'node:crypto';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { exportGame } from '../electron/exportGame';
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const GAME_HOST = path.join(HERE, '..', 'src', 'gameHost.ts');
+
+let root: string;
+let out: string;
+const TEX = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa';
+const SCN = 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb';
+const meta = (uuid: string, type: string) => JSON.stringify({ uuid, version: '2.0', type, importer: {} });
+
+beforeAll(async () => {
+ root = mkdtempSync(path.join(tmpdir(), 'estella-export-'));
+ // A texture asset + sidecar.
+ mkdirSync(path.join(root, 'assets'), { recursive: true });
+ // A real PNG so the content-addressed + KTX2-compress export path has valid input.
+ copyFileSync(path.resolve(HERE, '..', '..', 'examples', 'hello-world', 'assets', 'textures', 'logo.png'),
+ path.join(root, 'assets', 'hero.png'));
+ writeFileSync(path.join(root, 'assets', 'hero.png.meta'), meta(TEX, 'texture'));
+ // A scene that references the texture by @uuid: + its sidecar.
+ mkdirSync(path.join(root, 'scenes'), { recursive: true });
+ writeFileSync(
+ path.join(root, 'scenes', 'main.esscene'),
+ JSON.stringify({ version: '1.0', name: 'Main', entities: [{ id: 0, components: [{ type: 'Sprite', data: { texture: `@uuid:${TEX}` } }] }] }),
+ );
+ writeFileSync(path.join(root, 'scenes', 'main.esscene.meta'), meta(SCN, 'scene'));
+ // A project startup entry (esengine external) → bundled to scripts.mjs.
+ mkdirSync(path.join(root, 'src'), { recursive: true });
+ writeFileSync(path.join(root, 'src', 'main.ts'), `import { defineComponent } from 'esengine';\ndefineComponent('SpawnMarker', { rate: 1 });\n`);
+ // Stand-in SDK dist + wasm runtime dirs to copy.
+ mkdirSync(path.join(root, '_sdk'), { recursive: true });
+ writeFileSync(path.join(root, '_sdk', 'index.js'), 'export const x = 1;');
+ mkdirSync(path.join(root, '_wasm'), { recursive: true });
+ writeFileSync(path.join(root, '_wasm', 'esengine.js'), 'export default () => {};');
+ writeFileSync(path.join(root, '_wasm', 'esengine.wasm'), 'wasmbytes');
+
+ out = path.join(root, 'dist-game');
+}, 60_000);
+
+afterAll(() => rmSync(root, { recursive: true, force: true }));
+
+
+/** Every asset in an addressable manifest, paired with its uuid key. */
+function manifestAssets(manifest: unknown): Array<[string, { type: string; path: string; address?: string; compressedFormats?: string[] }]> {
+ const groups = (manifest as { groups: Record<string, { assets: Record<string, never> }> }).groups;
+ return Object.values(groups).flatMap((g) => Object.entries(g.assets)) as never;
+}
+
+describe('exportGame', () => {
+ it('produces an import-map web build (cook + host + sdk + scripts + wasm + html)', async () => {
+ 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: out,
+ title: 'My Game',
+ });
+
+ expect(res.ok).toBe(true);
+ expect(res.errors).toEqual([]);
+ // Reachability pulled the scene + its referenced texture into the build.
+ expect(res.included).toBe(2);
+
+ const has = (p: string) => existsSync(path.join(out, p));
+ expect(has('index.html')).toBe(true);
+ expect(has('game.js')).toBe(true);
+ expect(has('scripts.mjs')).toBe(true);
+ expect(has('sdk/index.js')).toBe(true);
+ expect(has('game.config.json')).toBe(true);
+ // The flat manifest is a build-time intermediate — only the addressable one ships.
+ expect(has('assets.manifest.json')).toBe(false);
+ expect(has('asset-manifest.json')).toBe(true);
+ expect(has('scenes/main.esscene')).toBe(true);
+ // Content-addressing is on by default now: the texture ships as assets/<hash>.png.
+ const m = JSON.parse(readFileSync(path.join(out, 'asset-manifest.json'), 'utf8'));
+ const tex = manifestAssets(m).find(([, a]) => a.type === 'texture')![1];
+ expect(tex.path).toMatch(/^assets\/[0-9a-f]{16}\.png$/);
+ expect(has(tex.path)).toBe(true);
+ expect(has('wasm/esengine.js')).toBe(true);
+
+ // The host + project bundle are esengine-EXTERNAL (small; resolved by the
+ // import map) — NOT an inlined hundreds-of-KB SDK.
+ const gameJs = readFileSync(path.join(out, 'game.js'), 'utf8');
+ expect(gameJs.length).toBeLessThan(100_000);
+ expect(readFileSync(path.join(out, 'scripts.mjs'), 'utf8')).toMatch(/from\s*["']esengine["']/);
+
+ // index.html carries the import map + loads the host; config points at the scene.
+ const html = readFileSync(path.join(out, 'index.html'), 'utf8');
+ expect(html).toContain('importmap');
+ expect(html).toContain('./sdk/index.js');
+ expect(html).toContain('./game.js');
+ // Web pins orientation (default landscape ⇒ rotate-to-fit overlay + best-effort lock).
+ expect(html).toContain('id="rotate-hint"');
+ expect(html).toContain('Rotate your device to landscape');
+ expect(html).toMatch(/screen\.orientation[\s\S]*lock\("landscape"\)/);
+ expect(JSON.parse(readFileSync(path.join(out, 'game.config.json'), 'utf8')).entryScene).toBe('scenes/main.esscene');
+ }, 60_000);
+
+ it('lists every inline script in the page CSP, for either orientation', async () => {
+ for (const orientation of ['landscape', 'portrait'] as const) {
+ const cspOut = path.join(root, `dist-game-csp-${orientation}`);
+ 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: cspOut, orientation,
+ });
+ expect(res.ok).toBe(true);
+
+ const html = readFileSync(path.join(cspOut, 'index.html'), 'utf8');
+ const csp = /http-equiv="Content-Security-Policy"\s*\n?\s*content="([^"]+)"/.exec(html)?.[1];
+ expect(csp).toBeTruthy();
+ // A hash the policy omits means the browser blocks that script — which is how
+ // the orientation lock came to be dead in a shipped build.
+ const inline = [...html.matchAll(/<script(?![^>]*\bsrc=)[^>]*>([\s\S]*?)<\/script>/g)].map((m) => m[1]);
+ expect(inline.length).toBe(2); // the import map + the orientation lock
+ for (const body of inline) {
+ expect(csp).toContain(`sha256-${createHash('sha256').update(body).digest('base64')}`);
+ }
+ }
+ }, 60_000);
+
+ it('writes the project camera fit into game.config.json (only when opted in)', async () => {
+ const fitOut = path.join(root, 'dist-game-fit');
+ 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: fitOut, title: 'Fit Game',
+ runtime: runtimeConfigOf({
+ designResolution: { width: 1080, height: 1920 },
+ features: { rendering: { cameraScaleMode: 'expand' } },
+ }),
+ });
+ expect(res.ok).toBe(true);
+ const cfg = JSON.parse(readFileSync(path.join(fitOut, 'game.config.json'), 'utf8'));
+ expect(cfg.screenFit).toEqual({ designWidth: 1080, designHeight: 1920, scaleMode: 2, matchWidthOrHeight: 0.5 });
+
+ // Off (scaleMode -1) ⇒ no screenFit key, so an unconfigured game's config is unchanged.
+ const offOut = path.join(root, 'dist-game-fitoff');
+ 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: offOut,
+ runtime: runtimeConfigOf({ designResolution: { width: 1920, height: 1080 } }),
+ });
+ expect(JSON.parse(readFileSync(path.join(offOut, 'game.config.json'), 'utf8')).screenFit).toBeUndefined();
+ }, 60_000);
+
+ it('content-addresses + KTX2-compresses cooked assets when opted in', async () => {
+ const out2 = path.join(root, 'dist-game-ca');
+ 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: out2,
+ title: 'CA Game',
+ contentAddressed: true,
+ compressTextures: true,
+ });
+ expect(res.ok).toBe(true);
+ expect(res.errors).toEqual([]);
+
+ const manifest = JSON.parse(readFileSync(path.join(out2, 'asset-manifest.json'), 'utf8'));
+ const tex = manifestAssets(manifest).find(([uuid]) => uuid.toLowerCase() === TEX)![1];
+ // The PNG was encoded to KTX2 and named by content hash; refs stay uuid-based.
+ expect(tex.path).toMatch(/^assets\/[0-9a-f]{16}\.ktx2$/);
+ expect(tex.compressedFormats).toEqual(['astc-4x4', 'etc2-rgba8', 's3tc-dxt5']);
+ const bytes = readFileSync(path.join(out2, tex.path));
+ const magic = [0xab, 0x4b, 0x54, 0x58, 0x20, 0x32, 0x30, 0xbb, 0x0d, 0x0a, 0x1a, 0x0a];
+ expect(magic.every((b, i) => bytes[i] === b)).toBe(true);
+
+ // The scene keeps its logical name and the whole build still assembled.
+ expect(existsSync(path.join(out2, 'scenes/main.esscene'))).toBe(true);
+ 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('excludeScenes drops a scene from the build; the entry is immune', async () => {
+ const outEx = path.join(root, 'dist-game-excluded');
+ 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: outEx,
+ title: 'My Game',
+ // level2 excluded; excluding the entry must be ignored — it boots the game.
+ excludeScenes: ['scenes/level2.esscene', 'scenes/main.esscene'],
+ });
+ expect(res.ok).toBe(true);
+ const cfg = JSON.parse(readFileSync(path.join(outEx, 'game.config.json'), 'utf8'));
+ expect(cfg.scenes).toEqual([{ name: 'main', path: 'scenes/main.esscene' }]);
+ expect(existsSync(path.join(outEx, 'scenes/level2.esscene'))).toBe(false);
+ }, 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({
+ root,
+ entryScene: 'scenes/main.esscene',
+ gameHostEntry: GAME_HOST,
+ scriptsEntry: 'src/main.ts',
+ sdkDistDir: path.join(root, '_sdk'),
+ wasmDir: path.join(root, '_no-such-wasm'),
+ outDir: out3,
+ title: 'My Game',
+ });
+ expect(res.ok).toBe(false);
+ expect(res.errors.some((e) => e.includes('wasm runtime dir not found'))).toBe(true);
+ }, 60_000);
+
+ // A third-party runtime (a vector-animation player, another solver) as an
+ // ordinary side module: staged beside the engine's own and declared in the
+ // config, which is the whole difference between `acquire('rive')` working and
+ // a game having to fetch and instantiate a wasm by hand.
+ it("ships a project's own native module and declares it for the runtime", async () => {
+ const modDir = path.join(root, '.esengine', 'modules', 'rive');
+ mkdirSync(path.join(modDir, 'web'), { recursive: true });
+ writeFileSync(path.join(modDir, 'module.json'), JSON.stringify({ file: 'rive', globalName: 'RiveModule' }));
+ writeFileSync(path.join(modDir, 'web', 'rive.js'), 'var RiveModule = () => Promise.resolve({});');
+ writeFileSync(path.join(modDir, 'web', 'rive.wasm'), '\0asm');
+
+ const outMod = path.join(root, 'dist-game-module');
+ 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: outMod,
+ title: 'My Game',
+ });
+ expect(res.ok).toBe(true);
+
+ // Beside the engine's own artifacts — one place, so every transport finds it.
+ expect(existsSync(path.join(outMod, 'wasm', 'rive.js'))).toBe(true);
+ expect(existsSync(path.join(outMod, 'wasm', 'rive.wasm'))).toBe(true);
+ expect(existsSync(path.join(outMod, 'wasm', 'esengine.js'))).toBe(true);
+
+ const cfg = JSON.parse(readFileSync(path.join(outMod, 'game.config.json'), 'utf8'));
+ expect(cfg.sideModules).toEqual([{ id: 'rive', file: 'rive', globalName: 'RiveModule' }]);
+
+ rmSync(path.join(root, '.esengine'), { recursive: true, force: true });
+ }, 60_000);
+
+ it('says so when a project module has no build for the target, rather than shipping a broken package', async () => {
+ const modDir = path.join(root, '.esengine', 'modules', 'rive');
+ mkdirSync(path.join(modDir, 'web'), { recursive: true });
+ writeFileSync(path.join(modDir, 'web', 'rive.js'), 'export default () => Promise.resolve({});');
+
+ const outMod = path.join(root, 'dist-game-module-android');
+ 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: outMod,
+ platform: 'android',
+ title: 'My Game',
+ });
+ expect(res.ok).toBe(true);
+ expect(res.warnings.join('\n')).toContain('app binary');
+ // Not declared, because it was not staged: a declaration whose binary is
+ // absent reports a missing file instead of an unsupported target.
+ const cfg = JSON.parse(readFileSync(path.join(outMod, 'game.config.json'), 'utf8'));
+ expect(cfg.sideModules).toBeUndefined();
+
+ rmSync(path.join(root, '.esengine'), { recursive: true, force: true });
+ }, 60_000);
+});
diff --git a/desktop/tests/export-playable.test.ts b/desktop/tests/export-playable.test.ts
index e69eac487..81c722415 100644
--- a/desktop/tests/export-playable.test.ts
+++ b/desktop/tests/export-playable.test.ts
@@ -8,6 +8,7 @@
* by the user in a browser / ad preview (no playable simulator here).
*/
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
+import { runtimeConfigOf } from '@/project/runtimeConfig';
import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
@@ -200,13 +201,19 @@ describe('exportGame (playable)', () => {
root, entryScene: 'scenes/main.esscene', gameHostEntry: 'unused-for-playable',
playableHostEntry: PLAYABLE_HOST, scriptsEntry: 'src/main.ts',
sdkDistDir: path.join(root, '_sdk'), wasmDir: path.join(root, '_wasm'),
- outDir: o, platform: 'playable', screenFit: { designWidth: 750, designHeight: 1334, scaleMode: 1, matchWidthOrHeight: 0.5 },
+ outDir: o, platform: 'playable',
+ runtime: runtimeConfigOf({
+ designResolution: { width: 750, height: 1334 },
+ features: { rendering: { cameraScaleMode: 'fixed-height', depthLayers: [2] } },
+ }),
});
expect(res.ok).toBe(true);
const html = readFileSync(path.join(o, 'index.html'), 'utf8');
- expect(html).toContain('__GAME_SCREENFIT__');
+ expect(html).toContain('__GAME_RUNTIME__');
expect(html).toMatch(/"scaleMode":1/);
expect(html).toMatch(/"designWidth":750/);
+ // The 2.5D opt-in ships too: it used to reach the play realm and no build.
+ expect(html).toMatch(/"depthLayers":4/);
}, 60_000);
// A portrait project must ALSO stay playable in a landscape container: the page
diff --git a/desktop/tests/export-wechat.test.ts b/desktop/tests/export-wechat.test.ts
index 7fa7e2998..3f1585986 100644
--- a/desktop/tests/export-wechat.test.ts
+++ b/desktop/tests/export-wechat.test.ts
@@ -10,6 +10,7 @@
* simulator here.)
*/
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
+import { runtimeConfigOf } from '@/project/runtimeConfig';
import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
@@ -66,7 +67,10 @@ describe('exportGame (wechat)', () => {
platform: 'wechat',
wechatAppid: 'wxTEST0123456789',
orientation: 'landscape',
- screenFit: { designWidth: 1280, designHeight: 720, scaleMode: 2, matchWidthOrHeight: 0.5 },
+ runtime: runtimeConfigOf({
+ designResolution: { width: 1280, height: 720 },
+ features: { rendering: { cameraScaleMode: 'expand', depthLayers: [1] } },
+ }),
});
expect(res.ok).toBe(true);
@@ -96,6 +100,9 @@ describe('exportGame (wechat)', () => {
// The project camera fit rides the boot config into initWeChatRuntime.
expect(bundle).toContain('screenFit');
expect(bundle).toMatch(/"scaleMode":\s*2/);
+ // Same generated boot carries the 2.5D opt-in — one packaged slice, so a
+ // setting cannot reach one target and not another.
+ expect(bundle).toMatch(/depthLayers:\s*2/);
// Config + runtime copy.
const pcfg = JSON.parse(readFileSync(path.join(out, 'project.config.json'), 'utf8'));