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(wechat): runtime instantiates the staged wasm twins; exporter detects spine by real meta type

yhh0a988760a600
diff --git a/desktop/electron/exportWeChat.ts b/desktop/electron/exportWeChat.ts
index b279ea7ae..3fb07285e 100644
--- a/desktop/electron/exportWeChat.ts
+++ b/desktop/electron/exportWeChat.ts
@@ -55,7 +55,7 @@ interface CookManifest {
// so an unmapped type degrading to 'binary' is harmless.
const ADDRESSABLE_TYPE: Record<string, string> = {
texture: 'texture', material: 'material', audio: 'audio', 'bitmap-font': 'bitmap-font',
- prefab: 'prefab', 'spine-atlas': 'spine', 'spine-skeleton': 'spine',
+ prefab: 'prefab', spine: 'spine',
scene: 'json', 'anim-clip': 'json', tilemap: 'json', timeline: 'json', json: 'json', shader: 'text',
};
const addrType = (editorType: string): string => ADDRESSABLE_TYPE[editorType] ?? 'binary';
@@ -122,33 +122,40 @@ 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). */
+/** 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). */
async function scanWeChatSideModules(
sceneData: unknown,
cookEntries: CookManifest['entries'],
absOut: string,
wasmDir: string,
- warnings: 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');
+ // 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.
for (const e of cookEntries) {
+ if (e.type !== 'spine') continue;
+ const ext = path.extname(e.sourcePath ?? e.path).toLowerCase();
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));
+ let v: ReturnType<typeof detectSpineVersionJson> = null;
+ if (ext === '.skel') {
+ v = detectSpineVersion(new Uint8Array(await readFile(path.join(absOut, e.path))));
+ } else if (ext === '.json') {
+ v = detectSpineVersionJson(await readFile(path.join(absOut, e.path), 'utf8'));
}
- } catch { /* unreadable cook entry — skip */ }
+ if (v) ids.add(spineModuleId(v));
+ } catch { /* unreadable cook entry — cookAssets already warned; 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).`);
+ else errors.push(`scene needs "${id}" but ${file}.js is not in the wechat wasm dir — build it with \`node build-tools/cli.js build -t ${id === 'physics' ? 'physics-wechat' : 'spine-wechat'}\` and re-export.`);
}
return present;
}
@@ -251,9 +258,18 @@ export async function exportWeChat(opts: {
await mkdir(absOut, { recursive: true });
+ // KTX2 decode needs the Basis transcoder side module, which has no WeChat
+ // (WXWebAssembly) build yet — cooked .ktx2 textures could never load. Degrade
+ // to uncompressed textures visibly instead of shipping an undecodable pack.
+ let compressTextures = opts.compressTextures;
+ if (compressTextures) {
+ compressTextures = false;
+ warnings.push('compressTextures: the Basis KTX2 transcoder has no WeChat build yet — textures export uncompressed.');
+ }
+
// 1. Cook reachable assets (paths preserved) + the flat manifest.
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: [opts.entryScene], outDir: absOut, contentAddressed: opts.contentAddressed, compressTextures, atlasTextures: opts.atlasTextures });
warnings.push(...cook.warnings);
// 1b. Scan the scene for the optional modules it needs (physics/spine), so the
@@ -267,7 +283,7 @@ export async function exportWeChat(opts: {
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);
+ const sideModules = await scanWeChatSideModules(sceneRaw, cookEntries, absOut, opts.wasmDir, errors);
// 2. Flat manifest → AddressableManifest (asset-manifest.json); drop the web one.
progress({ phase: 'Building manifest' });
@@ -292,11 +308,15 @@ export async function exportWeChat(opts: {
// 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;
+ // The engine wasm path rides into the boot config: only the exporter knows
+ // 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 entrySrc =
`import { initWeChatRuntime } from 'esengine';\n` +
(scriptsAbs && existsSync(scriptsAbs) ? `import ${JSON.stringify(scriptsAbs)};\n` : '') +
`export function boot(engineFactory, sideModuleFactories) {\n` +
- ` return initWeChatRuntime({ engineFactory, 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([sceneName])}, firstScene: ${JSON.stringify(sceneName)}${opts.ySortLayers ? `, ySortLayers: ${opts.ySortLayers >>> 0}` : ''} });\n` +
`}\n`;
progress({ phase: 'Bundling game' });
try {
diff --git a/desktop/tests/export-wechat.test.ts b/desktop/tests/export-wechat.test.ts
index 8a7381eae..c6b8d116e 100644
--- a/desktop/tests/export-wechat.test.ts
+++ b/desktop/tests/export-wechat.test.ts
@@ -89,6 +89,9 @@ describe('exportGame (wechat)', () => {
const entry = readFileSync(path.join(out, 'game.js'), 'utf8');
expect(entry).toContain("require('./game-bundle.js')");
expect(entry).toContain("require('./wasm/esengine.js')");
+ // The boot config names the staged glue's .wasm twin — WXWebAssembly
+ // instantiates by package-relative path, so the runtime must not guess.
+ expect(bundle).toContain('wasm/esengine.wasm');
// Config + runtime copy.
const pcfg = JSON.parse(readFileSync(path.join(out, 'project.config.json'), 'utf8'));
@@ -130,6 +133,7 @@ describe('exportGame (wechat)', () => {
});
expect(res.ok).toBe(true);
expect(readFileSync(path.join(outWx, 'game.js'), 'utf8')).toContain("require('./wasm/esengine.wxgame.js')");
+ expect(readFileSync(path.join(outWx, 'game-bundle.js'), 'utf8')).toContain('wasm/esengine.wxgame.wasm');
expect(existsSync(path.join(outWx, 'wasm', 'esengine.wxgame.wasm'))).toBe(true);
expect(existsSync(path.join(outWx, 'wasm', 'physics.js'))).toBe(false);
expect(existsSync(path.join(outWx, 'wasm', 'physics.wasm'))).toBe(false);
@@ -153,6 +157,78 @@ describe('exportGame (wechat)', () => {
expect(existsSync(outMissing)).toBe(false);
}, 60_000);
+ it('detects a spine skeleton (authored meta type "spine") and ships exactly its module', async () => {
+ const SPINE = 'dddddddd-dddd-dddd-dddd-dddddddddddd';
+ 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'));
+ writeFileSync(
+ path.join(root, 'scenes', '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'));
+ const wxDir = path.join(root, '_wxwasm-spine');
+ mkdirSync(wxDir, { recursive: true });
+ writeFileSync(path.join(wxDir, 'esengine.js'), 'module.exports = () => Promise.resolve({});');
+ writeFileSync(path.join(wxDir, 'esengine.wasm'), 'wasmbytes');
+ writeFileSync(path.join(wxDir, 'spine42.js'), 'module.exports = () => {};');
+ writeFileSync(path.join(wxDir, 'spine42.wasm'), 'wasmbytes');
+
+ const outSpine = path.join(root, 'dist-wechat-spine');
+ const res = await exportGame({
+ root,
+ entryScene: 'scenes/spine.esscene',
+ gameHostEntry: 'unused-for-wechat',
+ scriptsEntry: 'src/main.ts',
+ sdkDistDir: path.join(root, '_sdk'),
+ wasmDir: wxDir,
+ outDir: outSpine,
+ platform: 'wechat',
+ });
+ expect(res.ok).toBe(true);
+ 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);
+ // 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');
+ }, 60_000);
+
+ it('a needed spine module missing from the runtime dir fails the export', async () => {
+ const outBroken = path.join(root, 'dist-wechat-spine-missing');
+ const res = await exportGame({
+ root,
+ entryScene: 'scenes/spine.esscene',
+ gameHostEntry: 'unused-for-wechat',
+ scriptsEntry: 'src/main.ts',
+ sdkDistDir: path.join(root, '_sdk'),
+ wasmDir: path.join(root, '_wxwasm'), // engine only — no spine42
+ outDir: outBroken,
+ platform: 'wechat',
+ });
+ expect(res.ok).toBe(false);
+ expect(res.errors.some((e) => e.includes('spine-wechat'))).toBe(true);
+ }, 60_000);
+
+ it('degrades compressTextures to PNG with a warning (no WeChat Basis build)', async () => {
+ const outCt = path.join(root, 'dist-wechat-ct');
+ const res = await exportGame({
+ root,
+ entryScene: 'scenes/main.esscene',
+ gameHostEntry: 'unused-for-wechat',
+ scriptsEntry: 'src/main.ts',
+ sdkDistDir: path.join(root, '_sdk'),
+ wasmDir: path.join(root, '_wxwasm'),
+ outDir: outCt,
+ platform: 'wechat',
+ compressTextures: true,
+ });
+ expect(res.ok).toBe(true);
+ expect(res.warnings.some((w) => w.includes('Basis'))).toBe(true);
+ const manifest = JSON.parse(readFileSync(path.join(outCt, 'asset-manifest.json'), 'utf8'));
+ expect(manifest.groups.main.assets[TEX].path).toMatch(/\.png$/); // not .ktx2
+ }, 60_000);
+
it('content-addressed export carries the logical path as the asset address', async () => {
const outCa = path.join(root, 'dist-wechat-ca');
const res = await exportGame({
diff --git a/sdk/src/sideModules/wechatHost.ts b/sdk/src/sideModules/wechatHost.ts
index f597427ed..ed60160e4 100644
--- a/sdk/src/sideModules/wechatHost.ts
+++ b/sdk/src/sideModules/wechatHost.ts
@@ -19,7 +19,9 @@ export function createWeChatSideModuleHost(factories: WeChatSideModuleFactories)
return createSideModuleHost(async (descriptor, id) => {
const factory = factories[id];
if (!factory) throw new Error(`side module "${id}" (${descriptor.file}) has no WeChat factory`);
- return instantiateViaPlatform(factory, `${descriptor.file}.wasm`);
+ // The exporter stages every runtime artifact under wasm/ — same registry,
+ // same layout, so the binary sits beside the glue game.js require()'d.
+ return instantiateViaPlatform(factory, `wasm/${descriptor.file}.wasm`);
});
}
diff --git a/sdk/src/wechatRuntime.ts b/sdk/src/wechatRuntime.ts
index 1b543eec6..c0cf2ca23 100644
--- a/sdk/src/wechatRuntime.ts
+++ b/sdk/src/wechatRuntime.ts
@@ -63,6 +63,10 @@ function instantiateModule<T>(
export interface WeChatRuntimeConfig {
engineFactory: (opts: unknown) => Promise<ESEngineModule>;
+ /** Package-relative path of the engine wasm binary. The exporter stages the
+ * runtime under wasm/ and knows which glue it shipped, so it passes the
+ * glue's `.wasm` twin here; defaults to the canonical -t wechat layout. */
+ engineWasmPath?: string;
sceneNames: string[];
firstScene: string;
runtimeConfig?: RuntimeBuildConfig;
@@ -116,7 +120,7 @@ export async function initWeChatRuntime(config: WeChatRuntimeConfig): Promise<vo
canvas.width = info.windowWidth * info.pixelRatio;
canvas.height = info.windowHeight * info.pixelRatio;
- const module = await instantiateModule(config.engineFactory, 'esengine.wasm', { canvas });
+ const module = await instantiateModule(config.engineFactory, config.engineWasmPath ?? 'wasm/esengine.wxgame.wasm', { canvas });
const gl = (canvas.getContext('webgl2') || canvas.getContext('webgl')) as WebGLRenderingContext | null;
if (!gl) {