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): a mini-game compresses its side modules, not just its engine

esengine7f8c5d5831d7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e18edac00..88ddf88b0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,8 @@ published separately; it ships inside the editor.
### Added
+- **A mini-game's side modules compress too, not just its engine.** Brotli was applied to the engine binary alone, so a package that transcodes KTX2 textures still carried Basis at its full 1.1MB — 27% of WeChat's 4MB main-package cap on its own. They compress on the same switch now, and the loader is told which suffix the build staged instead of spelling `.wasm` itself. Measured on the platformer template: its WeChat package was 108% of the cap and is now 51.5%, with the side modules accounting for 902KB of that.
+
- **A mini-game says it is starting before it parses the game.** The host's loading indicator only appeared once `initMiniGameRuntime` ran, which is after the entry has required a megabyte of bundle — the longest silent stretch of a cold start. The generated entry now raises it on its first line.
- **The start screen is yours: a logo, a background and a minimum display time.** The exported page has shown real boot progress for a while, but always as the game's name on the engine's own dark ground. A project can now put its logo there — inlined into the page, because an image fetched over the network arrives in the same window the engine does, with nothing left to cover — pick the colour behind it, and hold the screen for a minimum time, so a boot that finishes in 120ms stops flashing a bar that appears and vanishes. The page also emits `esengine:bootprogress` and `esengine:firstframe`, which a portal's own loading screen can listen for before the game's bundle has run.
diff --git a/pipeline/src/export/exportMiniGame.ts b/pipeline/src/export/exportMiniGame.ts
index b88bb4109..8b3c0c23c 100644
--- a/pipeline/src/export/exportMiniGame.ts
+++ b/pipeline/src/export/exportMiniGame.ts
@@ -117,16 +117,21 @@ interface RuntimeLayout {
readonly files: ReadonlyArray<{ readonly src: string; readonly staged: string; readonly brotli?: true }>;
/** The 分包 the engine binary went into, for the host config to declare. */
readonly subpackage: { readonly name: string; readonly root: string } | null;
+ /** Suffix the side-module binaries landed under, for the boot config. */
+ readonly sideModuleSuffix: string;
}
/**
* Decided ONCE, read by the boot config and the copy loop: what lands is what
- * the loader is told. Only the ENGINE binary compresses — a side module's is
- * found at `wasm/<file>.wasm` by three hosts that spell that suffix themselves,
- * so renaming one here would leave all three naming a file that is not there.
+ * the loader is told. The side modules compress with the engine — the mini-game
+ * transport is TOLD the suffix (`sideModuleSuffix`) rather than spelling it.
*/
const ENGINE_SUBPACKAGE = 'engine';
+/** What a compressed binary is called. The vendor's loader takes this path
+ * verbatim, so the package carries one binary per module, not two. */
+const BROTLI_SUFFIX = '.wasm.br';
+
function planRuntimeLayout(
engineGlueFile: string,
sideModules: ReadonlyArray<{ file: string }>,
@@ -142,16 +147,21 @@ function planRuntimeLayout(
const binary = opts.brotli
? { src: engineBinary, staged: enginePath, brotli: true as const }
: { src: engineBinary, staged: enginePath };
+ const sideModuleSuffix = opts.brotli ? BROTLI_SUFFIX : '.wasm';
return {
enginePath,
runtimeDir: 'wasm',
subpackage: opts.subpackage ? { name: ENGINE_SUBPACKAGE, root } : null,
+ sideModuleSuffix,
files: [
{ src: engineGlueFile, staged: `wasm/${engineGlueFile}` },
binary,
...sideModules.flatMap((m) => [
{ src: `${m.file}.js`, staged: `wasm/${m.file}.js` },
- { src: `${m.file}.wasm`, staged: `wasm/${m.file}.wasm` },
+ // The glue stays raw: a vendor's brotli path takes wasm, not `.js`.
+ opts.brotli
+ ? { src: `${m.file}.wasm`, staged: `wasm/${m.file}${sideModuleSuffix}`, brotli: true as const }
+ : { src: `${m.file}.wasm`, staged: `wasm/${m.file}.wasm` },
]),
],
};
@@ -505,7 +515,7 @@ export async function exportMiniGame(profile: MiniGameExportProfile, opts: {
`export function boot(engineFactory, sideModuleFactories) {\n` +
(profile.platformInit ? ` ${profile.platformInit}();\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)}${runtimeArgs}${projectDeclarations.length > 0 ? `, sideModules: ${JSON.stringify(projectDeclarations)}` : ''}${aotArg} });\n` +
+ ` return ${profile.runtimeInit}({ engineFactory, engineWasmPath: ${JSON.stringify(engineWasmPath)}${runtimeLayout.sideModuleSuffix === '.wasm' ? '' : `, sideModuleSuffix: ${JSON.stringify(runtimeLayout.sideModuleSuffix)}`}, sideModuleFactories, sceneNames: ${JSON.stringify(scenes.map((s) => s.name))}, firstScene: ${JSON.stringify(sceneName)}${runtimeArgs}${projectDeclarations.length > 0 ? `, sideModules: ${JSON.stringify(projectDeclarations)}` : ''}${aotArg} });\n` +
`}\n`;
progress({ phase: 'Bundling game' });
/** What each subsystem costs in the bundle — empty if esbuild wrote no metafile. */
diff --git a/pipeline/tests/export-wechat.test.ts b/pipeline/tests/export-wechat.test.ts
index 646fa8a41..e8db914bf 100644
--- a/pipeline/tests/export-wechat.test.ts
+++ b/pipeline/tests/export-wechat.test.ts
@@ -562,6 +562,38 @@ describe('exportGame (wechat)', () => {
expect(existsSync(path.join(o, 'wasm', 'esengine.js'))).toBe(true);
}, 60_000);
+ // The side modules are the other half of the main package: basis alone is
+ // 1.1MB raw, 27% of the 4MB cap. They compress on the same switch, and the
+ // loader is TOLD the suffix rather than spelling `.wasm` itself.
+ it('compresses a side module too, and declares the suffix the loader must use', async () => {
+ const wxDir = path.join(root, '_wxwasm-spine');
+ const o = path.join(root, 'dist-wx-br-side');
+ const res = await exportGame({
+ root,
+ entryScene: 'scenes-spine/spine.esscene',
+ hostsDir: 'unused-for-wechat',
+ scriptsEntry: 'src/main.ts',
+ sdkDistDir: path.join(root, '_sdk'),
+ wasmDir: wxDir,
+ outDir: o,
+ platform: 'wechat',
+ compressWasm: true,
+ runtime: runtimeConfigOf({ designResolution: { width: 1280, height: 720 } }),
+ });
+ expect(res.ok, res.errors.join('\n')).toBe(true);
+
+ expect(existsSync(path.join(o, 'wasm', 'spine42.wasm.br'))).toBe(true);
+ expect(existsSync(path.join(o, 'wasm', 'spine42.wasm'))).toBe(false);
+ // The glue stays raw — a vendor's brotli path takes wasm, not `.js` — and
+ // the entry still requires it by that name.
+ expect(existsSync(path.join(o, 'wasm', 'spine42.js'))).toBe(true);
+ expect(readFileSync(path.join(o, 'game.js'), 'utf8')).toContain("require('./wasm/spine42.js')");
+
+ // The half a second derivation would get wrong in silence: nothing in the
+ // runtime knows the suffix unless the package says so.
+ expect(readFileSync(path.join(o, 'game-bundle.js'), 'utf8')).toContain('sideModuleSuffix');
+ }, 60_000);
+
// Policy without capability changes nothing, and neither does the reverse:
// the default export still ships the binary as it was built.
it('leaves the binary alone when the project did not ask', async () => {
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index ce8907ce0..a800d8aa0 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -10267,7 +10267,7 @@ Plugin
## createWeChatSideModuleHost — function @experimental
```
-(factories: MiniGameSideModuleFactories): SideModuleHost
+(factories: MiniGameSideModuleFactories, binarySuffix?: string): SideModuleHost
```
## createWebApp — function @experimental
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 58fe3cfd2..433b4f121 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -10500,7 +10500,7 @@ Plugin
## createWeChatSideModuleHost — function @experimental
```
-(factories: MiniGameSideModuleFactories): SideModuleHost
+(factories: MiniGameSideModuleFactories, binarySuffix?: string): SideModuleHost
```
## createWebApp — function @experimental
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index ba6028d70..c0d7c7c8f 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -10262,7 +10262,7 @@ Plugin
## createWeChatSideModuleHost — function @experimental
```
-(factories: MiniGameSideModuleFactories): SideModuleHost
+(factories: MiniGameSideModuleFactories, binarySuffix?: string): SideModuleHost
```
## createWebApp — function @experimental
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index ccbc89e48..41564a9f7 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -5160,6 +5160,7 @@ runtimeConfig: RuntimeBuildConfig | undefined
sceneNames: string[]
screenFit: { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number; } | undefined
sideModuleFactories: Partial<Record<SideModuleId, EmscriptenFactory>> | undefined
+sideModuleSuffix: string | undefined
sideModules: { id: string; file: string; globalName?: string; }[] | undefined
uiTheme: "dark" | "light" | undefined
uiThemeOverrides: ThemeOverrides | undefined
@@ -10460,7 +10461,7 @@ Plugin
## createMiniGameSideModuleHost — function @experimental
```
-(factories: MiniGameSideModuleFactories): SideModuleHost
+(factories: MiniGameSideModuleFactories, binarySuffix?: string): SideModuleHost
```
## createMockAdProvider — function @experimental
@@ -10525,7 +10526,7 @@ Plugin
## createWeChatSideModuleHost — function @experimental
```
-(factories: MiniGameSideModuleFactories): SideModuleHost
+(factories: MiniGameSideModuleFactories, binarySuffix?: string): SideModuleHost
```
## createWebApp — function @experimental
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 91f3f4e7c..46b692f0d 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -9282,6 +9282,7 @@ runtimeConfig: RuntimeBuildConfig | undefined
sceneNames: string[]
screenFit: { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number; } | undefined
sideModuleFactories: Partial<Record<SideModuleId, EmscriptenFactory>> | undefined
+sideModuleSuffix: string | undefined
sideModules: { id: string; file: string; globalName?: string; }[] | undefined
uiTheme: "dark" | "light" | undefined
uiThemeOverrides: ThemeOverrides | undefined
@@ -10290,7 +10291,7 @@ Plugin
## createWeChatSideModuleHost — function @experimental
```
-(factories: MiniGameSideModuleFactories): SideModuleHost
+(factories: MiniGameSideModuleFactories, binarySuffix?: string): SideModuleHost
```
## createWebApp — function @experimental
diff --git a/sdk/src/runtime/miniGameRuntime.ts b/sdk/src/runtime/miniGameRuntime.ts
index 78a0c01d7..d77464f37 100644
--- a/sdk/src/runtime/miniGameRuntime.ts
+++ b/sdk/src/runtime/miniGameRuntime.ts
@@ -109,6 +109,13 @@ export interface MiniGameRuntimeConfig {
* game.js supplies exactly the modules the scene needs. Physics + spine
* self-gate off these via {@link createMiniGameSideModuleHost}. */
sideModuleFactories?: MiniGameSideModuleFactories;
+ /**
+ * Suffix the export staged those binaries under — `.wasm.br` where the
+ * vendor's loader takes one and the project asked for it. Declared rather
+ * than guessed: the package carries ONE binary per module, and a loader that
+ * spelled the suffix itself would name a file the package does not have.
+ */
+ sideModuleSuffix?: string;
/**
* Project-supplied modules (`.esengine/modules/<id>/`) the export staged, so
* their ids resolve to an artifact name.
@@ -206,7 +213,7 @@ export async function initMiniGameRuntime(config: MiniGameRuntimeConfig): Promis
}),
// Physics + spine self-gate off these factories (require()'d in game.js).
sideModules: config.sideModuleFactories
- ? createMiniGameSideModuleHost(config.sideModuleFactories)
+ ? createMiniGameSideModuleHost(config.sideModuleFactories, config.sideModuleSuffix)
: undefined,
});
diff --git a/sdk/src/sideModules/miniGameHost.ts b/sdk/src/sideModules/miniGameHost.ts
index 5b8b171cb..7bf6ec560 100644
--- a/sdk/src/sideModules/miniGameHost.ts
+++ b/sdk/src/sideModules/miniGameHost.ts
@@ -17,13 +17,20 @@ import type { SideModuleId } from './registry';
/** id → the emscripten factory `require('./wasm/<file>.js')` returned. */
export type MiniGameSideModuleFactories = Partial<Record<SideModuleId, EmscriptenFactory>>;
-export function createMiniGameSideModuleHost(factories: MiniGameSideModuleFactories): SideModuleHost {
+/**
+ * `binarySuffix` is what the EXPORT staged, not what this guesses: a host whose
+ * loader takes `.wasm.br` gets a package with only the compressed binary in it,
+ * and a loader that appended `.wasm` itself would name a file that is not there.
+ */
+export function createMiniGameSideModuleHost(
+ factories: MiniGameSideModuleFactories, binarySuffix = '.wasm',
+): SideModuleHost {
return createSideModuleHost(async (descriptor, id) => {
const factory = factories[id];
if (!factory) throw new Error(`side module "${id}" (${descriptor.file}) has no mini-game factory`);
// 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`);
+ return instantiateViaPlatform(factory, `wasm/${descriptor.file}${binarySuffix}`);
});
}
diff --git a/tools/launchers/launch-minigame.mjs b/tools/launchers/launch-minigame.mjs
index 2036bd321..ec04033b1 100644
--- a/tools/launchers/launch-minigame.mjs
+++ b/tools/launchers/launch-minigame.mjs
@@ -71,8 +71,15 @@ function serve(root, page) {
}
const abs = path.join(root, rel);
if (!abs.startsWith(root)) { res.writeHead(403).end(); return; }
- res.writeHead(200, { 'content-type': MIME[path.extname(abs).toLowerCase()] ?? 'application/octet-stream' })
- .end(await readFile(abs));
+ // The vendor's loader takes a `.wasm.br` path and decompresses inside
+ // itself; nothing in a page can (Chromium's DecompressionStream has no
+ // brotli), so the transport does — the stand-in host sees raw wasm either way.
+ const brotli = abs.endsWith('.br');
+ const ext = path.extname(brotli ? abs.slice(0, -3) : abs).toLowerCase();
+ res.writeHead(200, {
+ 'content-type': MIME[ext] ?? 'application/octet-stream',
+ ...(brotli ? { 'content-encoding': 'br' } : {}),
+ }).end(await readFile(abs));
} catch {
res.writeHead(404).end();
}
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 03dd1915b..dd5961ce8 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -700,6 +700,8 @@ export const NOTED = {
{ internal: "the editor's preview page names the same subpaths it always did" },
'fix(settings): the module page reads the same asset table the build installs from':
{ note: 'The Engine Modules page no longer calls a module unused that the build then carries.' },
+ 'feat(export): a mini-game compresses its side modules, not just its engine':
+ { note: "A mini-game's side modules compress too, not just its engine." },
'feat(export): a mini-game entry raises the host indicator on its first line':
{ note: 'A mini-game says it is starting before it parses the game.' },
"feat(export): the start screen carries the project's logo, colour and hold":