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(export): playable/wechat embed side modules from a content scan
esenginea8702ad0f32e
diff --git a/build-tools/build.config.js b/build-tools/build.config.jsindex 2394b4c07..7248411de 100644--- a/build-tools/build.config.js+++ b/build-tools/build.config.js@@ -50,7 +50,10 @@ export default {physics: {buildDir: 'build-physics',cmakeFlags: ['-DES_BUILD_WEB=ON', '-DES_BUILD_TESTS=OFF', '-DES_ENABLE_BOX2D=ON'],- // ESM variant (EXPORT_ES6=1) for the web editor — imported like esengine.js.+ // ESM variant (EXPORT_ES6=1, `export default`) — the ONE physics build+ // for every realm. The SideModuleHost loader resolves the factory the+ // same way everywhere (fetch / inlined base64 / WeChat require), so+ // there is no separate side-module or playable physics build.targets: ['physics_module_esm'],outputs: {'sdk/physics.js': 'wasm/web/physics.js',@@ -66,41 +69,6 @@ export default {'sdk/basis.wasm': 'wasm/web/basis.wasm',},},- 'web-main': {- buildDir: 'build-web-main',- cmakeFlags: ['-DES_BUILD_WEB=ON', '-DES_BUILD_TESTS=OFF', '-DES_BUILD_MAIN_MODULE=ON'],- targets: ['esengine_sdk_main'],- outputs: {- 'sdk/esengine.js': 'wasm/web/esengine.js',- 'sdk/esengine.wasm': 'wasm/web/esengine.wasm',- },- },- 'wechat-main': {- buildDir: 'build-wxgame-main',- cmakeFlags: ['-DES_BUILD_WXGAME=ON', '-DES_BUILD_TESTS=OFF', '-DES_BUILD_MAIN_MODULE=ON'],- targets: ['esengine_wxgame_main'],- outputs: {- 'sdk/esengine.wxgame.js': 'wasm/wechat/esengine.wxgame.js',- 'sdk/esengine.wxgame.wasm': 'wasm/wechat/esengine.wxgame.wasm',- },- },- 'physics-side': {- buildDir: 'build-web-main',- cmakeFlags: ['-DES_BUILD_WEB=ON', '-DES_BUILD_TESTS=OFF', '-DES_ENABLE_BOX2D=ON', '-DES_BUILD_SIDE_MODULE=ON'],- targets: ['physics_side_module'],- outputs: {- 'sdk/physics.wasm': 'wasm/web/physics.wasm',- },- },- 'physics-playable': {- buildDir: 'build-physics-playable',- cmakeFlags: ['-DES_BUILD_WEB=ON', '-DES_BUILD_TESTS=OFF', '-DES_ENABLE_BOX2D=ON'],- targets: ['physics_module'],- outputs: {- 'sdk/physics.js': 'wasm/playable/physics.js',- 'sdk/physics.wasm': 'wasm/playable/physics.wasm',- },- },spine: {buildDir: 'build-web',cmakeFlags: ['-DES_BUILD_WEB=ON', '-DES_BUILD_TESTS=OFF'],diff --git a/build-tools/cli.js b/build-tools/cli.jsindex f20fb9d16..887f7b74b 100644--- a/build-tools/cli.js+++ b/build-tools/cli.js@@ -27,7 +27,7 @@ programprogram.command('build').description('Build ESEngine')- .option('-t, --target <target>', 'Build target (web, wechat, playable, spine, spine38, physics, basis, web-main, wechat-main, physics-side, sdk, all)', 'web')+ .option('-t, --target <target>', 'Build target (web, wechat, playable, spine, spine38, spine41, physics, basis, sdk, all)', 'web').option('-d, --debug', 'Debug build', false).option('-r, --release', 'Release build (default)', true).option('-c, --clean', 'Clean before build', false)@@ -51,7 +51,7 @@ programconst isDebug = options.debug && !options.release;const targets = options.target === 'all'- ? ['web', 'wechat', 'playable', 'spine', 'spine38', 'spine41', 'physics', 'physics-playable', 'basis']+ ? ['web', 'wechat', 'playable', 'spine', 'spine38', 'spine41', 'physics', 'basis']: [options.target];if (options.clean) {diff --git a/desktop/electron/exportPlayable.ts b/desktop/electron/exportPlayable.tsindex f3ee6131c..f59826afd 100644--- a/desktop/electron/exportPlayable.ts+++ b/desktop/electron/exportPlayable.ts@@ -21,6 +21,10 @@ import path from 'node:path';import { cookAssets } from './cookAssets';import type { OnExportProgress } from './exportProgress';import { esengineAlias } from './esengineResolve';+import {+ sceneUsesPhysics, detectSpineVersion, detectSpineVersionJson,+ spineModuleId, SIDE_MODULE_FILE,+} from './sideModuleScan';export interface ExportPlayableResult {ok: boolean;@@ -70,6 +74,51 @@ function indexHtml(title: string, globals: string, bundle: string): string {`;}+/**+ * The export-time mirror of the runtime's physics/spine self-gating: scan the+ * scene for needed modules and inline their glue+wasm as base64 (single-file, no+ * fetch). A needed module absent from `wasmDir` is pushed as a HARD error — the+ * playable would otherwise ship silently broken (the bug this whole path fixes).+ */+async function collectSideModules(+ sceneData: unknown,+ manifestEntries: CookManifest['entries'],+ cookDir: string,+ wasmDir: string,+ errors: string[],+): Promise<Record<string, { glueBase64: string; wasmBase64: string }>> {+ const ids = new Set<string>();+ if (sceneData && sceneUsesPhysics(sceneData as Parameters<typeof sceneUsesPhysics>[0])) ids.add('physics');+ for (const e of manifestEntries) {+ try {+ if (e.type === 'spine-skeleton') {+ const v = detectSpineVersion(new Uint8Array(await readFile(path.join(cookDir, e.path))));+ if (v) ids.add(spineModuleId(v));+ } else if (e.path.toLowerCase().endsWith('.json')) {+ const v = detectSpineVersionJson(await readFile(path.join(cookDir, e.path), 'utf8'));+ if (v) ids.add(spineModuleId(v));+ }+ } catch { /* unreadable cook entry — cookAssets already warned; skip */ }+ }++ const registry: Record<string, { glueBase64: string; wasmBase64: string }> = {};+ for (const id of ids) {+ const file = SIDE_MODULE_FILE[id];+ if (!file) { errors.push(`internal: no artifact mapping for side module "${id}"`); continue; }+ const gluePath = path.join(wasmDir, `${file}.js`);+ const wasmPath = path.join(wasmDir, `${file}.wasm`);+ if (!existsSync(gluePath) || !existsSync(wasmPath)) {+ errors.push(`scene needs "${id}" but ${file}.js/${file}.wasm are missing from the wasm dir — build the module and re-export.`);+ continue;+ }+ registry[id] = {+ glueBase64: (await readFile(gluePath)).toString('base64'),+ wasmBase64: (await readFile(wasmPath)).toString('base64'),+ };+ }+ return registry;+}+/*** Export the open project as a single-file playable ad. Reuses the shipped WEB* engine runtime (esengine.js glue + esengine.wasm) inlined — no separate@@ -106,8 +155,10 @@ export async function exportPlayable(opts: {// 2. Assets → base64 data URLs, keyed by the scene's @uuid: refs.progress({ phase: 'Encoding assets' });const assets: Record<string, string> = {};+ let manifestEntries: CookManifest['entries'] = [];try {const manifest = JSON.parse(await readFile(path.join(cookDir, 'assets.manifest.json'), 'utf8')) as CookManifest;+ manifestEntries = manifest.entries;for (const e of manifest.entries) {const buf = await readFile(path.join(cookDir, e.path));assets[`@uuid:${e.uuid}`] = `data:${mimeOf(e.path)};base64,${buf.toString('base64')}`;@@ -170,11 +221,19 @@ export async function exportPlayable(opts: {errors.push(`engine runtime not found in ${opts.wasmDir} (need esengine.js + esengine.wasm)`);}+ // 5b. Side modules (physics / spine): run the runtime's gating scan, then inline+ // exactly the modules the scene needs (playables are single-file + size-capped).+ // A needed module missing from wasmDir is a HARD error — better a failed+ // export than a playable that silently ships without physics.+ progress({ phase: 'Embedding modules' });+ const sideModules = await collectSideModules(scenes[0]?.data, manifestEntries, cookDir, opts.wasmDir, errors);+// 6. Assemble the single HTML, then drop the temp cook dir.progress({ phase: 'Assembling HTML' });const globals =`window.__ENGINE_GLUE__=${JSON.stringify(glue)};` +`window.__ENGINE_WASM__=${JSON.stringify(wasmB64)};` ++ `window.__SIDE_MODULES__=${JSON.stringify(sideModules)};` +`window.__GAME_ASSETS__=${JSON.stringify(assets)};` +`window.__GAME_SCENES__=${JSON.stringify(scenes)};` +`window.__GAME_FIRST__=${JSON.stringify(sceneName)};`;diff --git a/desktop/electron/exportWeChat.ts b/desktop/electron/exportWeChat.tsindex 39c1879ac..db88e2c07 100644--- a/desktop/electron/exportWeChat.ts+++ b/desktop/electron/exportWeChat.ts@@ -28,6 +28,10 @@ import path from 'node:path';import { cookAssets } from './cookAssets';import type { OnExportProgress } from './exportProgress';import { esengineAlias } from './esengineResolve';+import {+ sceneUsesPhysics, detectSpineVersion, detectSpineVersionJson,+ spineModuleId, SIDE_MODULE_FILE,+} from './sideModuleScan';export interface ExportWeChatResult {ok: boolean;@@ -81,16 +85,56 @@ function projectConfigJson(title: string, appid: string): string {}, null, 2) + '\n';}-/** The MiniGame entry WeChat runs: hand the wasm factory to the bundle's boot(). */-function gameEntryJs(): string {+/** The MiniGame entry WeChat runs: require the engine + the scene's optional+ * side modules (physics/spine), hand them to the bundle's boot(). WeChat has no+ * fetch/import — modules are pulled in by `require` here (outside the bundle). */+function gameEntryJs(sideModules: ReadonlyArray<{ id: string; file: string }>): string {+ const requires = sideModules+ .map((m) => ` ${JSON.stringify(m.id)}: asFactory(require('./wasm/${m.file}.js')),`)+ .join('\n');return `'use strict';// Generated by Estella exportGame (WeChat MiniGame entry).-const factory = require('./wasm/esengine.js');+const asFactory = (m) => (typeof m === 'function' ? m : (m && m.default) || m);+const engineFactory = asFactory(require('./wasm/esengine.js'));+const sideModuleFactories = {+${requires}+};const bundle = require('./game-bundle.js');-bundle.boot(typeof factory === 'function' ? factory : (factory && factory.default) || factory);+bundle.boot(engineFactory, sideModuleFactories);`;}+/** Mirror the runtime's physics/spine gating: which optional modules the scene+ * needs, and which are actually present in the wechat wasm dir (the rest warn). */+async function scanWeChatSideModules(+ sceneData: unknown,+ cookEntries: CookManifest['entries'],+ absOut: string,+ wasmDir: string,+ warnings: string[],+): Promise<Array<{ id: string; file: string }>> {+ const ids = new Set<string>();+ if (sceneData && sceneUsesPhysics(sceneData as Parameters<typeof sceneUsesPhysics>[0])) ids.add('physics');+ for (const e of cookEntries) {+ try {+ if (e.type === 'spine-skeleton') {+ const v = detectSpineVersion(new Uint8Array(await readFile(path.join(absOut, e.path))));+ if (v) ids.add(spineModuleId(v));+ } else if (e.path.toLowerCase().endsWith('.json')) {+ const v = detectSpineVersionJson(await readFile(path.join(absOut, e.path), 'utf8'));+ if (v) ids.add(spineModuleId(v));+ }+ } catch { /* unreadable cook entry — skip */ }+ }+ const present: Array<{ id: string; file: string }> = [];+ for (const id of ids) {+ const file = SIDE_MODULE_FILE[id];+ if (file && existsSync(path.join(wasmDir, `${file}.js`))) present.push({ id, file });+ else warnings.push(`scene needs "${id}" but ${file}.js is not in the wechat wasm dir — ${id} will be absent (provide a WeChat-targeted ${file} build).`);+ }+ return present;+}+/** Read the web cook's flat manifest → AddressableManifest the WeChat runtime reads. */async function buildAddressableManifest(absOut: string): Promise<string> {const cook = JSON.parse(await readFile(path.join(absOut, 'assets.manifest.json'), 'utf8')) as CookManifest;@@ -135,6 +179,19 @@ export async function exportWeChat(opts: {const cook = await cookAssets(opts.root, { entryScenes: [opts.entryScene], outDir: absOut });warnings.push(...cook.warnings);+ // 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, warnings);+// 2. Flat manifest → AddressableManifest (asset-manifest.json); drop the web one.progress({ phase: 'Building manifest' });try {@@ -148,7 +205,7 @@ export async function exportWeChat(opts: {progress({ phase: 'Transforming scene' });const sceneName = path.basename(opts.entryScene).replace(/\.[^.]+$/, '');try {- const raw = JSON.parse(await readFile(path.join(absOut, opts.entryScene), 'utf8'));+ 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) {@@ -161,8 +218,8 @@ export async function exportWeChat(opts: {const entrySrc =`import { initWeChatRuntime } from 'esengine';\n` +(scriptsAbs && existsSync(scriptsAbs) ? `import ${JSON.stringify(scriptsAbs)};\n` : '') +- `export function boot(engineFactory) {\n` +- ` return initWeChatRuntime({ engineFactory, sceneNames: ${JSON.stringify([sceneName])}, firstScene: ${JSON.stringify(sceneName)} });\n` ++ `export function boot(engineFactory, sideModuleFactories) {\n` ++ ` return initWeChatRuntime({ engineFactory, sideModuleFactories, sceneNames: ${JSON.stringify([sceneName])}, firstScene: ${JSON.stringify(sceneName)} });\n` +`}\n`;progress({ phase: 'Bundling game' });try {@@ -186,7 +243,7 @@ export async function exportWeChat(opts: {}// 5. Entry + config.- await writeFile(path.join(absOut, 'game.js'), gameEntryJs());+ await writeFile(path.join(absOut, 'game.js'), gameEntryJs(sideModules));await writeFile(path.join(absOut, 'game.json'), gameJson(opts.orientation ?? 'portrait'));await writeFile(path.join(absOut, 'project.config.json'), projectConfigJson(title, opts.appid ?? ''));diff --git a/desktop/electron/sideModuleScan.ts b/desktop/electron/sideModuleScan.tsnew file mode 100644index 000000000..b85c27fca--- /dev/null+++ b/desktop/electron/sideModuleScan.ts@@ -0,0 +1,103 @@+// SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file sideModuleScan.ts — the export-time half of side-module gating. The+ * runtime self-gates physics/spine off a scene scan (runtimeLoader ++ * SpineManager); for the INLINED targets (playable single-file) the+ * exporter must run the SAME scan so it embeds exactly the modules the+ * scene needs and no more (playables are size-capped). The constant lists+ * below mirror the SDK's so the two halves agree; keep them in sync.+ */++/** Component types whose presence means the scene needs physics.+ * Mirrors sdk/src/runtimeLoader.ts PHYSICS_COMPONENT_TYPES. */+const PHYSICS_COMPONENT_TYPES = new Set([+ 'RigidBody', 'BoxCollider', 'CircleCollider', 'CapsuleCollider',+ 'SegmentCollider', 'PolygonCollider', 'ChainCollider',+]);++interface SceneLike {+ entities?: Array<{ components?: Array<{ type?: string; data?: unknown }> }>;+}++/** True if any entity carries a physics component, or a TilemapLayer that bakes+ * collidable tiles (which spawn colliders at runtime). Mirrors runtimeLoader.sceneUsesPhysics. */+export function sceneUsesPhysics(scene: SceneLike): boolean {+ for (const entity of scene.entities ?? []) {+ for (const comp of entity.components ?? []) {+ if (comp.type && PHYSICS_COMPONENT_TYPES.has(comp.type)) return true;+ if (comp.type === 'TilemapLayer') {+ const ids = (comp.data as Record<string, unknown> | undefined)?.collidableTileIds;+ if (Array.isArray(ids) && ids.length > 0) return true;+ }+ }+ }+ return false;+}++export type SpineVersion = '3.8' | '4.1' | '4.2';++/** id → artifact base name. Mirrors sdk/src/sideModules/registry.ts SIDE_MODULES. */+export const SIDE_MODULE_FILE: Record<string, string> = {+ physics: 'physics',+ 'spine:3.8': 'spine38',+ 'spine:4.1': 'spine41',+ 'spine:4.2': 'spine42',+};++export function spineModuleId(version: SpineVersion): string {+ return `spine:${version}`;+}++// --- Spine skeleton version detection (mirrors SpineManager.detectVersion[Json]) ---++export function detectSpineVersionJson(json: string): SpineVersion | null {+ const m = json.match(/"spine"\s*:\s*"(\d+\.\d+)/);+ if (!m) return null;+ if (m[1].startsWith('4.2')) return '4.2';+ if (m[1].startsWith('4.1')) return '4.1';+ if (m[1].startsWith('3.')) return '3.8';+ return null;+}++export function detectSpineVersion(data: Uint8Array): SpineVersion | null {+ return tryRead4xVersion(data) ?? tryRead3xVersion(data);+}++function readVarint(data: Uint8Array, offset: number): { value: number; bytesRead: number } {+ let value = 0, shift = 0, bytesRead = 0;+ do {+ const b = data[offset + bytesRead++];+ value |= (b & 0x7f) << shift;+ shift += 7;+ if (!(b & 0x80)) break;+ } while (shift < 35);+ return { value, bytesRead };+}++function tryRead4xVersion(data: Uint8Array): SpineVersion | null {+ if (data.length < 10) return null;+ let pos = 8;+ const { value: len, bytesRead } = readVarint(data, pos);+ pos += bytesRead;+ if (len <= 1 || pos + len - 1 > data.length) return null;+ const ver = new TextDecoder().decode(data.subarray(pos, pos + len - 1));+ if (ver.startsWith('4.2')) return '4.2';+ if (ver.startsWith('4.1')) return '4.1';+ return null;+}++function tryRead3xVersion(data: Uint8Array): SpineVersion | null {+ if (data.length < 4) return null;+ let pos = 0;+ const { value: hashLen, bytesRead: hb } = readVarint(data, pos);+ pos += hb;+ if (hashLen > 0) pos += hashLen - 1;+ if (pos >= data.length) return null;+ const { value: verLen, bytesRead: vb } = readVarint(data, pos);+ pos += vb;+ if (verLen <= 1 || pos + verLen - 1 > data.length) return null;+ const ver = new TextDecoder().decode(data.subarray(pos, pos + verLen - 1));+ if (ver.startsWith('3.')) return '3.8';+ return null;+}diff --git a/desktop/src/playableHost.ts b/desktop/src/playableHost.tsindex 3b2509ff4..eb13e2282 100644--- a/desktop/src/playableHost.ts+++ b/desktop/src/playableHost.ts@@ -9,15 +9,18 @@* the SAME shipping runtime via initPlayableRuntime (play == ship). Nothing* is fetched — the whole game is one self-contained .html (ad-network ready).*/-import { createWebApp, setEditorMode, setPlayMode, initPlayableRuntime } from 'esengine';-import type { ESEngineModule as EngineModule, SceneData } from 'esengine';+import { createWebApp, setEditorMode, setPlayMode, initPlayableRuntime, createEmbeddedSideModuleHost } from 'esengine';+import type { ESEngineModule as EngineModule, SceneData, EmbeddedSideModuleRegistry } from 'esengine';type EngineFactory = (opts?: Record<string, unknown>) => Promise<EngineModule>;// Inlined by exportPlayable as <script> globals (kept out of the bundle so the// large base64 blobs aren't re-parsed as code). The glue is the WEB esengine.js-// (ESM) text; the wasm is base64-encoded esengine.wasm.+// (ESM) text; the wasm is base64-encoded esengine.wasm. __SIDE_MODULES__ holds+// the base64 glue+wasm for exactly the optional modules (physics/spine) the scene+// uses — the exporter ran the runtime's gating scan to pick them.declare const __ENGINE_GLUE__: string;declare const __ENGINE_WASM__: string;+declare const __SIDE_MODULES__: EmbeddedSideModuleRegistry;declare const __GAME_ASSETS__: Record<string, string>;declare const __GAME_SCENES__: Array<{ name: string; data: SceneData }>;declare const __GAME_FIRST__: string;@@ -69,6 +72,8 @@ async function boot(): Promise<void> {const app = createWebApp(module, {glContextHandle: glHandle,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__ : {}),});setEditorMode(false);setPlayMode(true);diff --git a/desktop/tests/export-playable.test.ts b/desktop/tests/export-playable.test.tsindex 433e30852..fcf7443b6 100644--- a/desktop/tests/export-playable.test.ts+++ b/desktop/tests/export-playable.test.ts@@ -42,7 +42,7 @@ beforeAll(() => {// Stub SDK dist exporting what the real host + scripts import (bundles for real).mkdirSync(path.join(root, '_sdk'), { recursive: true });writeFileSync(path.join(root, '_sdk', 'index.js'),- `export function createWebApp(){return{GL:{registerContext(){}}};}\nexport function setEditorMode(){}\nexport function setPlayMode(){}\nexport function initPlayableRuntime(){return Promise.resolve();}\nexport function defineComponent(){}\n`);+ `export function createWebApp(){return{GL:{registerContext(){}}};}\nexport function setEditorMode(){}\nexport function setPlayMode(){}\nexport function initPlayableRuntime(){return Promise.resolve();}\nexport function createEmbeddedSideModuleHost(){return{acquire(){return Promise.resolve(null);}};}\nexport function defineComponent(){}\n`);// Stub web wasm runtime (glue text + wasm) — playable inlines these, no separate build.mkdirSync(path.join(root, '_wasm'), { recursive: true });writeFileSync(path.join(root, '_wasm', 'esengine.js'), `export default function(){}/*WEB_GLUE*/\n`);@@ -90,3 +90,62 @@ describe('exportGame (playable)', () => {expect(html).toContain('<title>Playable Demo</title>');}, 60_000);});++/**+ * The fix this whole path delivers: the exporter runs the runtime's physics/spine+ * gating and inlines exactly those modules — so a physics scene ships with physics,+ * and a missing module fails the export loudly instead of shipping silently broken.+ */+describe('exportGame (playable) — side-module embedding', () => {+ const PSCN = 'dddddddd-dddd-dddd-dddd-dddddddddddd';++ function setupRoot(withPhysicsArtifact: boolean): { r: string; o: string } {+ const r = mkdtempSync(path.join(tmpdir(), 'estella-playable-phys-'));+ mkdirSync(path.join(r, 'scenes'), { recursive: true });+ // A RigidBody makes sceneUsesPhysics() true → the runtime needs physics.+ writeFileSync(path.join(r, 'scenes', 'main.esscene'),+ JSON.stringify({ version: '1.0', name: 'Main', entities: [{ id: 0, components: [{ type: 'RigidBody', data: { bodyType: 1 } }] }] }));+ writeFileSync(path.join(r, 'scenes', 'main.esscene.meta'), meta(PSCN, 'scene'));+ mkdirSync(path.join(r, '_sdk'), { recursive: true });+ writeFileSync(path.join(r, '_sdk', 'index.js'),+ `export function createWebApp(){return{GL:{registerContext(){}}};}\nexport function setEditorMode(){}\nexport function setPlayMode(){}\nexport function initPlayableRuntime(){return Promise.resolve();}\nexport function createEmbeddedSideModuleHost(){return{acquire(){return Promise.resolve(null);}};}\n`);+ mkdirSync(path.join(r, '_wasm'), { recursive: true });+ writeFileSync(path.join(r, '_wasm', 'esengine.js'), `export default function(){}\n`);+ writeFileSync(path.join(r, '_wasm', 'esengine.wasm'), 'WASMBYTES');+ if (withPhysicsArtifact) {+ writeFileSync(path.join(r, '_wasm', 'physics.js'), `export default function(){}/*PHYS_GLUE*/\n`);+ writeFileSync(path.join(r, '_wasm', 'physics.wasm'), 'PHYSWASM');+ }+ return { r, o: path.join(r, 'dist') };+ }++ const run = (r: string, o: string) => exportGame({+ root: r, entryScene: 'scenes/main.esscene', gameHostEntry: 'x', playableHostEntry: PLAYABLE_HOST,+ sdkDistDir: path.join(r, '_sdk'), wasmDir: path.join(r, '_wasm'), outDir: o, platform: 'playable',+ });++ it('inlines physics into __SIDE_MODULES__ when the scene uses physics', async () => {+ const { r, o } = setupRoot(true);+ try {+ const res = await run(r, o);+ expect(res.ok).toBe(true);+ const html = readFileSync(path.join(o, 'index.html'), 'utf8');+ expect(html).toContain('__SIDE_MODULES__');+ expect(html).toContain('"physics"');+ expect(html).toContain(Buffer.from('PHYSWASM').toString('base64')); // physics.wasm inlined+ } finally {+ rmSync(r, { recursive: true, force: true });+ }+ }, 60_000);++ it('fails the export when the scene needs physics but physics.wasm is absent', async () => {+ const { r, o } = setupRoot(false);+ try {+ const res = await run(r, o);+ expect(res.ok).toBe(false);+ expect(res.errors.join('\n')).toMatch(/physics/);+ } finally {+ rmSync(r, { recursive: true, force: true });+ }+ }, 60_000);+});