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
feat(export): a WeChat project can render through EmscriptenGLX
esenginee1a04682beb9
diff --git a/.github/actions/editor-host/action.yml b/.github/actions/editor-host/action.ymlindex 0b5145694..f97ec58ad 100644--- a/.github/actions/editor-host/action.yml+++ b/.github/actions/editor-host/action.yml@@ -21,6 +21,12 @@ runs:name: wasm-wechatpath: build/wasm/wechat/+ - name: Download wechat GLX wasm artifact+ uses: actions/download-artifact@v8+ with:+ name: wasm-wechat-glx+ path: build/wasm/wechat-glx/+- name: Build SDKshell: bashrun: pnpm --filter ./sdk build@@ -28,9 +34,10 @@ runs:- name: Stage wasm for the editor hostshell: bashrun: |- mkdir -p desktop/public/wasm desktop/public/wasm-wechat+ mkdir -p desktop/public/wasm desktop/public/wasm-wechat desktop/public/wasm-wechat-glxcp build/wasm/web/* desktop/public/wasm/cp build/wasm/wechat/* desktop/public/wasm-wechat/+ cp build/wasm/wechat-glx/* desktop/public/wasm-wechat-glx/- name: Build editor renderer bundleshell: bashdiff --git a/.github/workflows/build.yml b/.github/workflows/build.ymlindex 6ad9cd2a0..77b66ab9a 100644--- a/.github/workflows/build.yml+++ b/.github/workflows/build.yml@@ -68,6 +68,16 @@ jobs:key: ${{ runner.os }}-emscriptenmax-size: 2G+ # `-t all` builds the WeChat GLX engine with WeChat's library and emsdk 4.0.10+ # (build-tools/toolchain/glx.js); both are pinned, so they are fetched once.+ - name: Cache the GLX toolchain+ uses: actions/cache@v4+ with:+ path: |+ tools/emsdk-glx+ build/glx+ key: glx-emsdk-4.0.10-lib-0.1.11-${{ runner.os }}-${{ runner.arch }}+- name: Build Web targetrun: node build-tools/cli.js build -t web --no-sync@@ -104,6 +114,13 @@ jobs:path: build/wasm/wechat/retention-days: 3+ - name: Upload wechat GLX wasm artifact+ uses: actions/upload-artifact@v7+ with:+ name: wasm-wechat-glx+ path: build/wasm/wechat-glx/+ retention-days: 3+# The C++ harnesses as the release build compiles them, on a runner of their own# so the jobs waiting on the engine binaries are not also waiting on these.cpp-tests:@@ -757,6 +774,12 @@ jobs:if: ${{ !cancelled() && matrix.shard == 1 && steps.toolchain.outcome == 'success' }}run: pnpm run verify:cooked+ # Most hosts a GLX package reaches offer no GLX context; there it must draw+ # through WebGL2 like any other. The stand-in host is one of them.+ - name: Check a WeChat package built with EmscriptenGLX draws without it+ if: ${{ !cancelled() && matrix.shard == 2 }}+ run: pnpm run verify:glx+# A development build dials the editor, and the frame debugger captures and# replays its frame over that socket — the web road and a mini-game's.- name: Check a development build can be frame-debugged from the editordiff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.ymlindex 126951194..fdafb9947 100644--- a/.github/workflows/nightly.yml+++ b/.github/workflows/nightly.yml@@ -55,6 +55,16 @@ jobs:key: ${{ runner.os }}-emscriptenmax-size: 2G+ # `-t all` builds the WeChat GLX engine with WeChat's library and emsdk 4.0.10+ # (build-tools/toolchain/glx.js); both are pinned, so they are fetched once.+ - name: Cache the GLX toolchain+ uses: actions/cache@v4+ with:+ path: |+ tools/emsdk-glx+ build/glx+ key: glx-emsdk-4.0.10-lib-0.1.11-${{ runner.os }}-${{ runner.arch }}+- name: Build every targetrun: node build-tools/cli.js build -t all --no-sync@@ -75,6 +85,13 @@ jobs:path: build/wasm/wechat/retention-days: 3+ - name: Upload wechat GLX wasm artifact+ uses: actions/upload-artifact@v7+ with:+ name: wasm-wechat-glx+ path: build/wasm/wechat-glx/+ retention-days: 3+# The three criteria that ask what a COMPILED system does on a host with no JIT# can only be answered against a template — and against THIS branch's, not a# release's: the host is half of what they measure, so answering with adiff --git a/.github/workflows/release-desktop.yml b/.github/workflows/release-desktop.ymlindex a2db4c563..08af23db7 100644--- a/.github/workflows/release-desktop.yml+++ b/.github/workflows/release-desktop.yml@@ -105,6 +105,16 @@ jobs:key: ${{ runner.os }}-emscriptenmax-size: 2G+ # `-t all` builds the WeChat GLX engine with WeChat's library and emsdk 4.0.10+ # (build-tools/toolchain/glx.js); both are pinned, so they are fetched once.+ - name: Cache the GLX toolchain+ uses: actions/cache@v4+ with:+ path: |+ tools/emsdk-glx+ build/glx+ key: glx-emsdk-4.0.10-lib-0.1.11-${{ runner.os }}-${{ runner.arch }}+- name: Build engine and sync to desktoprun: node build-tools/cli.js build -t all@@ -115,6 +125,7 @@ jobs:path: |desktop/public/wasmdesktop/public/wasm-wechat+ desktop/public/wasm-wechat-glxdesktop/public/wasm-quickgameretention-days: 3diff --git a/.gitignore b/.gitignoreindex 8228d41d2..18e87eaff 100644--- a/.gitignore+++ b/.gitignore@@ -180,3 +180,6 @@ native/ios/app.generated.ymlpipeline/src/.build-*/.aot-verify/.walkthrough/++# emsdk 4.0.10 for the WeChat EmscriptenGLX engine only (build-tools/toolchain/glx.js)+tools/emsdk-glx/diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0b71ac03e..9128a9210 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -17,6 +17,7 @@ published separately; it ships inside the editor.### Added- **Android release signing.** A Shipping APK (and App Bundle) is signed with the release key the project names under Project Settings → Android → Signing — two PEM paths, the passphrase kept in this machine's keychain (the command line reads `ESTELLA_ANDROID_KEY_PASSPHRASE`); Development builds keep the development key. A Shipping build without one says it will be refused by Google Play.+- **EmscriptenGLX on WeChat.** A WeChat project can ship the engine linked with WeChat's EmscriptenGLX (Project Settings → WeChat → Render through EmscriptenGLX, off by default), which issues the engine's GL calls natively instead of through JavaScript: a draw-heavy scene spent about 12% less time rendering on an Android phone. It adds about 310KB of wasm and needs base library 3.8.12 on Android, or iOS in 高性能+ mode; any other host renders through WebGL2 as before, and the log says which. The engine is built once with `node build-tools/cli.js build -t wechat-glx`, which fetches WeChat's library at a pinned version and hash, and emsdk 4.0.10 beside the main one; an export that asks for it without it says so.- **Export profiles.** A project can name several exports of one target in `packaging.profiles` — a test and a production WeChat build, each with its own AppID, CDN root and development or shipping configuration, writing only what differs from the project's settings. The Build dialog creates, edits and deletes them per target, marking each setting a profile overrides with a reset that hands it back to the project; `estella export --profile <name>` and the agent's `export_game` build the same one, and the size history records which profile a build used.### Changeddiff --git a/CMakeLists.txt b/CMakeLists.txtindex fa42d152e..40efca0e3 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -42,6 +42,7 @@ option(ES_ENABLE_BITMAP_TEXT "Enable Bitmap text rendering" ON)option(ES_ENABLE_WEBGPU "Enable the WebGPU render backend (emdawnwebgpu port)" OFF)option(ES_ENABLE_BASIS "Build the Basis Universal KTX2 transcoder module" OFF)option(ES_BUILD_MAIN_MODULE "Build as MAIN_MODULE for dynamic linking" OFF)+set(ES_WXGAME_GLX_LIB "" CACHE FILEPATH "WeChat EmscriptenGLX static library to link into the mini-game engine (empty: none)")option(ES_BUILD_SIDE_MODULE "Build side modules for dynamic linking" OFF)# The physics standalone module ships in two JS-glue flavours from the same wasm:# the default require()-style module (WeChat host) and an ES6 variant imported likediff --git a/build-tools/build.config.js b/build-tools/build.config.jsindex e2c9dc760..2a4d1003e 100644--- a/build-tools/build.config.js+++ b/build-tools/build.config.js@@ -17,6 +17,7 @@ export default {optimization: {web: { cmakeOpt: '-O2', wasmOpt: '-O2' },wechat: { cmakeOpt: '-O2', wasmOpt: '-O2' },+ 'wechat-glx': { cmakeOpt: '-O2', wasmOpt: '-O2' },quickgame: { cmakeOpt: '-O2', wasmOpt: '-O2' },},@@ -42,6 +43,20 @@ export default {'sdk/esengine.wxgame.wasm': 'wasm/wechat/esengine.wxgame.wasm',},},+ // The WeChat engine with EmscriptenGLX linked in, for a project that turns it+ // on: WeChat publishes the library for emsdk 4.0.10, so this one target+ // builds with that emsdk (build-tools/toolchain/glx.js).+ 'wechat-glx': {+ buildDir: 'build/cmake/wxgame-glx',+ cmakeFlags: ['-DES_BUILD_WXGAME=ON', '-DES_BUILD_TESTS=OFF'],+ targets: ['esengine_wxgame'],+ emsdk: '4.0.10',+ glx: true,+ outputs: {+ 'sdk/esengine.wxgame.js': 'wasm/wechat-glx/esengine.wxgame.js',+ 'sdk/esengine.wxgame.wasm': 'wasm/wechat-glx/esengine.wxgame.wasm',+ },+ },// The mini-game engine for vivo's quick-game V8 (8.3), which refuses both a// SIMD opcode ("Invalid opcode (enable with --experimental-wasm-simd)") and// an i64 in a wasm↔JS signature ("wasm function signature contains illegal type").@@ -246,6 +261,7 @@ export default {// wasm-wechat first) — web-aligned filenames (physics.js, spine42.js, …)// would otherwise overwrite the web modules in desktop/public/wasm.'build/wasm/wechat': 'desktop/public/wasm-wechat',+ 'build/wasm/wechat-glx': 'desktop/public/wasm-wechat-glx','build/wasm/quickgame': 'desktop/public/wasm-quickgame',},sdk: {diff --git a/build-tools/tasks/wasm.js b/build-tools/tasks/wasm.jsindex c84600045..aa50a328a 100644--- a/build-tools/tasks/wasm.js+++ b/build-tools/tasks/wasm.js@@ -8,6 +8,7 @@ import * as logger from '../utils/logger.js';import { runCommand, getCpuCount } from '../utils/emscripten.js';import { hashFiles, hashDirectory, HashCache } from '../utils/hash.js';import { generateShaderEmbeds } from './shader-embeds.js';+import { GLX_EMSDK, glxEmsdkEnv, glxLibrary } from '../toolchain/glx.js';/*** The one flag a probe build adds, and it adds ONLY this one.@@ -156,9 +157,14 @@ async function executeWasmBuild(target, targetConfig, { debug, clean, buildDir,const buildType = debug ? 'Debug' : 'Release';const optConfig = config.optimization[target];+ // A target pinned to another emsdk builds in that emsdk's environment, and+ // only its own children see it.+ const env = targetConfig.emsdk === GLX_EMSDK ? glxEmsdkEnv((m) => logger.info(m)) : undefined;+ const glxFlags = targetConfig.glx ? [`-DES_WXGAME_GLX_LIB=${await glxLibrary()}`] : [];const cmakeArgs = ['cmake',...targetConfig.cmakeFlags,+ ...glxFlags,...testProbeFlags(),...extraCmakeFlags(),`-DCMAKE_BUILD_TYPE=${buildType}`,@@ -182,7 +188,7 @@ async function executeWasmBuild(target, targetConfig, { debug, clean, buildDir,cmakeArgs.push(rootDir);logger.debug(`CMake configure: emcmake ${cmakeArgs.join(' ')}`);- await runCommand('emcmake', cmakeArgs, { cwd: buildDir });+ await runCommand('emcmake', cmakeArgs, { cwd: buildDir, env });const cpuCount = getCpuCount();const buildArgs = ['--build', '.', '-j', String(cpuCount)];@@ -192,14 +198,14 @@ async function executeWasmBuild(target, targetConfig, { debug, clean, buildDir,}logger.debug(`CMake build: cmake ${buildArgs.join(' ')}`);- await runCommand('cmake', buildArgs, { cwd: buildDir });+ await runCommand('cmake', buildArgs, { cwd: buildDir, env });const wasmOptLevel = config.optimization[target]?.wasmOpt || '-O2';- await optimizeWasmFiles(buildDir, targetConfig.outputs, wasmOptLevel);+ await optimizeWasmFiles(buildDir, targetConfig.outputs, wasmOptLevel, env);await copyOutputs(buildDir, outputDir, targetConfig.outputs);}-async function optimizeWasmFiles(buildDir, outputs, optLevel = '-O2') {+async function optimizeWasmFiles(buildDir, outputs, optLevel = '-O2', env = undefined) {const wasmFiles = Object.keys(outputs).filter(src => src.endsWith('.wasm'));if (wasmFiles.length === 0) return;@@ -210,7 +216,7 @@ async function optimizeWasmFiles(buildDir, outputs, optLevel = '-O2') {try {const before = (await stat(wasmPath)).size;- await runCommand('wasm-opt', [optLevel, '--enable-bulk-memory', '--enable-nontrapping-float-to-int', '--enable-simd', '-o', wasmPath, wasmPath], { silent: true });+ await runCommand('wasm-opt', [optLevel, '--enable-bulk-memory', '--enable-nontrapping-float-to-int', '--enable-simd', '-o', wasmPath, wasmPath], { silent: true, env });const after = (await stat(wasmPath)).size;const reduction = ((1 - after / before) * 100).toFixed(1);logger.debug(`wasm-opt ${optLevel}: ${src} ${(before / 1024).toFixed(0)}KB → ${(after / 1024).toFixed(0)}KB (-${reduction}%)`);diff --git a/build-tools/toolchain/glx.js b/build-tools/toolchain/glx.jsnew file mode 100644index 000000000..b71b074c8--- /dev/null+++ b/build-tools/toolchain/glx.js@@ -0,0 +1,121 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file glx.js — what the WeChat EmscriptenGLX engine is built with: WeChat's+ * prebuilt library, and the one emsdk it was built for.+ *+ * The library is WeChat's binary, so it is fetched at a pinned version and+ * checked against a pinned hash rather than kept in this repository. WeChat+ * publishes it for emsdk 3.1.17, 3.1.74 and 4.0.10 only, so this target alone+ * builds with 4.0.10 (in tools/emsdk-glx, or ESTELLA_GLX_EMSDK); every other+ * target keeps the main emsdk.+ */+import path from 'path';+import https from 'https';+import { createHash } from 'crypto';+import { spawnSync } from 'child_process';+import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync, rmSync } from 'fs';+import { fileURLToPath } from 'url';++const REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');++export const GLX_VERSION = '0.1.11';+export const GLX_EMSDK = '4.0.10';+/** sha256 of WeChat's libs_emscriptenglx.zip at {@link GLX_VERSION}. */+const GLX_ZIP_SHA256 = '7e6dd0b69e097575985265835fdf567895224f8e09c2fe29ba41f987d66bdb5c';+const GLX_URL = `https://game.weixin.qq.com/cgi-bin/gamewxagwasmsplitwap/getunityplugininfo?download=1&biz_id=1&version=${GLX_VERSION}`;++function download(url, redirects = 5) {+ return new Promise((resolve, reject) => {+ https.get(url, (res) => {+ if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location && redirects > 0) {+ res.resume();+ resolve(download(new URL(res.headers.location, url).toString(), redirects - 1));+ return;+ }+ if (res.statusCode !== 200) {+ res.resume();+ reject(new Error(`GET ${url} answered ${res.statusCode}`));+ return;+ }+ const parts = [];+ res.on('data', (c) => parts.push(c));+ res.on('end', () => resolve(Buffer.concat(parts)));+ res.on('error', reject);+ }).on('error', reject);+ });+}++/** Unzip with whichever tool this machine has: `unzip` on macOS and Linux,+ * bsdtar (`tar`) on Windows, which reads zip where GNU tar does not. */+function unzip(zip, into) {+ for (const [cmd, args] of [['unzip', ['-o', '-q', zip, '-d', into]], ['tar', ['-xf', zip, '-C', into]]]) {+ const r = spawnSync(cmd, args, { stdio: 'ignore' });+ if (r.status === 0) return;+ }+ throw new Error(`could not extract ${zip}: neither unzip nor tar read it`);+}++/** The GLX static library for {@link GLX_EMSDK}, fetched once into build/glx. */+export async function glxLibrary() {+ const dir = path.join(REPO_ROOT, 'build', 'glx', GLX_VERSION);+ const lib = path.join(dir, `libemscriptenglx_${GLX_EMSDK}.a`);+ if (existsSync(lib)) return lib;+ mkdirSync(dir, { recursive: true });+ const zip = await download(GLX_URL);+ const sha = createHash('sha256').update(zip).digest('hex');+ if (sha !== GLX_ZIP_SHA256) {+ throw new Error(`EmscriptenGLX ${GLX_VERSION} from WeChat does not match its pinned hash `+ + `(got ${sha}); refusing to link it. If WeChat republished it, check the new one and update GLX_ZIP_SHA256.`);+ }+ const zipPath = path.join(dir, 'libs_emscriptenglx.zip');+ writeFileSync(zipPath, zip);+ unzip(zipPath, dir);+ rmSync(zipPath, { force: true });+ if (!existsSync(lib)) throw new Error(`EmscriptenGLX ${GLX_VERSION} carries no library for emsdk ${GLX_EMSDK}`);+ return lib;+}++function emsdkRoot() {+ return process.env.ESTELLA_GLX_EMSDK || path.join(REPO_ROOT, 'tools', 'emsdk-glx');+}++function activeVersion(root) {+ const config = path.join(root, '.emscripten');+ if (!existsSync(config)) return null;+ const version = path.join(root, 'upstream', 'emscripten', 'emscripten-version.txt');+ return existsSync(version) ? readFileSync(version, 'utf8').replace(/["\s]/g, '') : null;+}++/**+ * The environment a child needs to build with emsdk {@link GLX_EMSDK}, installing+ * it into tools/emsdk-glx the first time (a git clone plus a download of about+ * 1.5 GB). Returned rather than applied: only the GLX target's children use it.+ */+export function glxEmsdkEnv(log = console.log) {+ const root = emsdkRoot();+ if (activeVersion(root) !== GLX_EMSDK) {+ const emsdk = path.join(root, process.platform === 'win32' ? 'emsdk.bat' : 'emsdk');+ if (!existsSync(emsdk)) {+ log(`Fetching emsdk into ${root} for the WeChat GLX engine (once)`);+ const clone = spawnSync('git', ['clone', '--depth', '1', 'https://github.com/emscripten-core/emsdk.git', root], { stdio: 'inherit' });+ if (clone.status !== 0) throw new Error('could not clone emsdk for the GLX engine');+ }+ for (const args of [['install', GLX_EMSDK], ['activate', '--embedded', GLX_EMSDK]]) {+ log(`emsdk ${args.join(' ')}`);+ const r = spawnSync(emsdk, args, { cwd: root, stdio: 'inherit', shell: process.platform === 'win32' });+ if (r.status !== 0) throw new Error(`emsdk ${args.join(' ')} failed`);+ }+ }+ const bin = [root, path.join(root, 'upstream', 'emscripten'), path.join(root, 'upstream', 'bin')];+ const nodeDir = existsSync(path.join(root, 'node')) ? readdirSync(path.join(root, 'node'))[0] : null;+ return {+ EMSDK: root,+ EM_CONFIG: path.join(root, '.emscripten'),+ // Its own sysroot cache: one inherited from the main emsdk holds 5.x's libraries.+ EM_CACHE: path.join(root, 'upstream', 'emscripten', 'cache'),+ ...(nodeDir ? { EMSDK_NODE: path.join(root, 'node', nodeDir, 'bin', process.platform === 'win32' ? 'node.exe' : 'node') } : {}),+ PATH: bin.join(path.delimiter) + path.delimiter + (process.env.PATH || ''),+ };+}+diff --git a/cmake/Emscripten.cmake b/cmake/Emscripten.cmakeindex 96ca357c9..a088db7ec 100644--- a/cmake/Emscripten.cmake+++ b/cmake/Emscripten.cmake@@ -273,6 +273,16 @@ function(es_apply_wxgame_sdk_settings TARGET_NAME)if(NOT ES_WASM_BIGINT)list(APPEND _WXGAME_LINK -sWASM_BIGINT=0)endif()+ # WeChat's EmscriptenGLX: its gl* run inside the wasm and hand commands to+ # the host, falling back to emscripten_gl* where the host has no GLX. The+ # runtime starts it (miniGameRuntime) when the entry points are exported.+ if(ES_WXGAME_GLX_LIB)+ list(FILTER _WXGAME_LINK EXCLUDE REGEX "^-sEXPORTED_(FUNCTIONS|RUNTIME_METHODS)=")+ list(APPEND _WXGAME_LINK+ "${ES_WXGAME_GLX_LIB}"+ "-sEXPORTED_FUNCTIONS=['_malloc','_free','_glxInit','_glxInitBufferDataAndGlState','_glxUpdateContextId']"+ "-sEXPORTED_RUNTIME_METHODS=['ccall','cwrap','HEAPF32','HEAPU8','HEAPU32','GL','FS','wasmMemory','stringToUTF8','lengthBytesUTF8']")+ endif()string(REPLACE ";" " " LINK_FLAGS_STR "${_WXGAME_LINK}")set_target_properties(${TARGET_NAME} PROPERTIESSUFFIX ".js"diff --git a/desktop b/desktopindex 7988d526a..2ffa46e9f 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit 7988d526acd0b7cbdd83dfdb5383b957621aef7a+Subproject commit 2ffa46e9f332d346a2075e501e4c4c30944d76f1diff --git a/docs/astro/src/content/docs/publishing/wechat.mdx b/docs/astro/src/content/docs/publishing/wechat.mdxindex f493e948a..9ee44e857 100644--- a/docs/astro/src/content/docs/publishing/wechat.mdx+++ b/docs/astro/src/content/docs/publishing/wechat.mdx@@ -92,6 +92,28 @@ on the WeChat page of **Package Project** keep it out of the 4 MB main package:startup. It no longer counts against the main package; startup waits forthat download, with the loading bar showing its progress.+## EmscriptenGLX++WeChat's EmscriptenGLX runs the engine's GL calls inside the wasm and hands them+to the host in batches, instead of crossing into JavaScript for each one. In a+scene of about a thousand draw calls it cut render time by about 12% on an+Android phone.++Turn on **Render through EmscriptenGLX** on the WeChat page of **Package+Project**, and build the engine it needs once:++```bash+node build-tools/cli.js build -t wechat-glx+```++The build downloads WeChat's library at a pinned version and checks its hash,+and uses emsdk 4.0.10 (installed into `tools/emsdk-glx` the first time) — the+version that library is published for. It adds about 310 KB of wasm.++It takes effect on Android with base library 3.8.12 or later, and on iOS in+高性能+ mode. Any other host, including DevTools, renders through WebGL2 as+before; the log's `rendering through …` line says which one a device used.+## Subpackages (分包)Lazy asset groups become WeChat **subPackages** in `game.json`. At runtime,diff --git a/docs/astro/src/content/docs/zh-cn/publishing/wechat.mdx b/docs/astro/src/content/docs/zh-cn/publishing/wechat.mdxindex 4729b23c7..8e2031c56 100644--- a/docs/astro/src/content/docs/zh-cn/publishing/wechat.mdx+++ b/docs/astro/src/content/docs/zh-cn/publishing/wechat.mdx@@ -66,6 +66,23 @@ node build-tools/cli.js build -t videodec-wechat # 视频(MPEG-1 wasm 解码暂存的自定义扩展名(`.skel`、`.atlas`、`.bin` 等)生成 `packOptions.include`规则,让开发者工具打包并读取它们。+## EmscriptenGLX++微信的 EmscriptenGLX 让引擎的 GL 调用在 wasm 内执行、批量交给宿主,而不必每一次都跨到+JavaScript。在约一千次 draw call 的场景里,它在 Android 手机上让渲染耗时少了约 12%。++在 **打包项目** 的微信页打开 **通过 EmscriptenGLX 渲染**,并构建一次它需要的引擎:++```bash+node build-tools/cli.js build -t wechat-glx+```++构建会下载固定版本的微信库并校验哈希,并使用 emsdk 4.0.10(首次安装到 `tools/emsdk-glx`)——+那个库只为这个版本发布。wasm 多约 310 KB。++它在基础库 3.8.12 及以上的 Android、以及开启高性能+模式的 iOS 上生效。其他宿主(包括开发者工具)+照旧走 WebGL2;日志里的 `rendering through …` 一行会说明设备用的是哪一条。+## 分包(subpackages)惰性资源分组会成为 `game.json` 里的微信 **subPackages**。运行时,diff --git a/package.json b/package.jsonindex 50c653189..29f49452f 100644--- a/package.json+++ b/package.json@@ -38,6 +38,7 @@"test": "vitest run --config vitest.engine.config.ts","verify:aot": "rm -rf .aot-verify && node pipeline/bin/estella.mjs export examples/ecs-basics --out .aot-verify && node tools/run-electron.mjs tools/launchers/headless-aot-verify.mjs .aot-verify","verify:cooked": "node tools/with-env.mjs ESTELLA_COOK_FIXTURE=1 -- pnpm --filter @estella/pipeline exec vitest run tests/cooked-verify-fixture.test.ts && node tools/run-electron.mjs tools/launchers/headless-cooked-verify.mjs",+ "verify:glx": "node tools/verify-glx-fallback.mjs","verify:remote-capture": "node tools/verify-remote-capture.mjs --platform web && node tools/verify-remote-capture.mjs --platform wechat","verify:hotupdate": "node tools/with-env.mjs ESTELLA_HOTUPDATE_FIXTURE=1 -- pnpm --filter @estella/pipeline exec vitest run tests/hotupdate-verify-fixture.test.ts && node tools/run-electron.mjs tools/launchers/headless-hotupdate-verify.mjs"},diff --git a/pipeline/src/export/exportGame.ts b/pipeline/src/export/exportGame.tsindex 8f281d121..d1939dfae 100644--- a/pipeline/src/export/exportGame.ts+++ b/pipeline/src/export/exportGame.ts@@ -557,6 +557,8 @@ export interface ExportGameOptions {hotUpdate?: { remoteRoot?: string; persistUpdateKey?: string };/** The export profile this build was made with, recorded in its size history. */profile?: string;+ /** WeChat: ship the EmscriptenGLX engine (`packaging.platforms.wechat.emscriptenGLX`). */+ miniGameGlx?: boolean;/** Signing key files the project names, checked against its repository. */secretFiles?: readonly string[];/** iOS: where the prebuilt engine + app shell live, so the export can wrap@@ -743,6 +745,7 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>scriptsEntry: opts.scriptsEntry,sdkDir: opts.sdkDistDir,wasmDir: opts.wasmDir,+ engineGlx: opts.miniGameGlx,outDir: opts.outDir,hostsDir: opts.hostsDir,packagesDir: opts.packagesDir,@@ -784,6 +787,7 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>scriptsEntry: opts.scriptsEntry,sdkDir: opts.sdkDistDir,wasmDir: opts.wasmDir,+ engineGlx: opts.miniGameGlx,outDir: opts.outDir,hostsDir: opts.hostsDir,packagesDir: opts.packagesDir,diff --git a/pipeline/src/export/exportMiniGame.ts b/pipeline/src/export/exportMiniGame.tsindex 1f820c475..fce356b53 100644--- a/pipeline/src/export/exportMiniGame.ts+++ b/pipeline/src/export/exportMiniGame.ts@@ -267,6 +267,9 @@ export async function exportMiniGame(profile: MiniGameExportProfile, opts: {scriptsEntry?: string;sdkDir: string;wasmDir: string;+ /** WeChat: ship the engine built with EmscriptenGLX, from the `-glx` runtime+ * beside `wasmDir`; the side modules still come from `wasmDir`. */+ engineGlx?: boolean;outDir: string;/** Where the runtime hosts live — sources in dev, a prebuilt tree in a packaged* editor. A built-in vendor's platform profile is resolved against it. */@@ -332,8 +335,20 @@ export async function exportMiniGame(profile: MiniGameExportProfile, opts: {// 0. The generated entry unconditionally requires the engine glue, so a// missing vendor runtime cannot produce a runnable package — fail before// cooking. By its ACTUAL name in the wasm dir; see MINIGAME_ENGINE_GLUE.+ const glxDir = `${opts.wasmDir.replace(/[\\/]+$/, '')}-glx`;+ const glx = opts.engineGlx === true && profile.id === 'wechat';+ if (glx && !profile.engineGlueCandidates.some((f) => existsSync(path.join(glxDir, f)))) {+ errors.push(`this project renders through EmscriptenGLX, and there is no GLX engine in ${glxDir} — `+ + 'build it with `node build-tools/cli.js build -t wechat-glx`, or turn EmscriptenGLX off in Project Settings → WeChat');+ return { ok: false, platform: profile.id, outDir: absOut, included: 0, warnings, errors };+ }+ /** The engine's own files come from the GLX runtime when the project asked for it. */+ const runtimeFile = (name: string): string => {+ const fromGlx = path.join(glxDir, name);+ return glx && existsSync(fromGlx) ? fromGlx : path.join(opts.wasmDir, name);+ };const engineGlueFile = profile.engineGlueCandidates- .find((f) => existsSync(path.join(opts.wasmDir, f)));+ .find((f) => existsSync(runtimeFile(f)));if (!engineGlueFile) {// The optional-module targets come off the profile, so the guidance names// THIS vendor's builds rather than a hardcoded WeChat pair.@@ -351,9 +366,9 @@ export async function exportMiniGame(profile: MiniGameExportProfile, opts: {// ...and it has to be a build this host can load. The browser artifact throws// `Unexpected token 'export'` at the entry's first line: a package that exports// clean, installs, and never reaches a frame.- if (isEsModule(await readFile(path.join(opts.wasmDir, engineGlueFile), 'utf8'))) {+ if (isEsModule(await readFile(runtimeFile(engineGlueFile), 'utf8'))) {errors.push(- `${path.join(opts.wasmDir, engineGlueFile)} is an ES module, and a ${profile.id} package requires its engine — `+ `${runtimeFile(engineGlueFile)} is an ES module, and a ${profile.id} package requires its engine — `+ `build the mini-game engine with \`node build-tools/cli.js build -t ${profile.wasmBuildHint}\``,);return { ok: false, platform: profile.id, outDir: absOut, included: 0, warnings, errors };@@ -698,7 +713,7 @@ export async function exportMiniGame(profile: MiniGameExportProfile, opts: {// not from the engine runtime dir, and are staged below.const { transform } = await loadEsbuild();for (const f of runtimeLayout.files) {- const src = path.join(opts.wasmDir, f.src);+ const src = runtimeFile(f.src);if (!existsSync(src)) {errors.push(`${profile.id} runtime file missing: ${f.src} (in ${opts.wasmDir}) — rebuild with \`node build-tools/cli.js build -t ${profile.wasmBuildHint}\``);continue;diff --git a/pipeline/src/export/projectExportOptions.ts b/pipeline/src/export/projectExportOptions.tsindex bdf0f6850..2b0aa8cab 100644--- a/pipeline/src/export/projectExportOptions.ts+++ b/pipeline/src/export/projectExportOptions.ts@@ -99,6 +99,7 @@ export async function projectExportOptions(miniGameVersionCode: quickGame.versionCode,miniGameReleaseKey: (await readReleaseKey(root, quickGame.releaseKey)) ?? undefined,} : {}),+ ...(platform === 'wechat' && plat?.wechat?.emscriptenGLX ? { miniGameGlx: true } : {}),androidVersionCode: plat?.android?.versionCode,androidAppBundle: plat?.android?.appBundle,androidOutput: plat?.android?.output,diff --git a/pipeline/src/project/format.ts b/pipeline/src/project/format.tsindex 94bd0b17a..8925b2df6 100644--- a/pipeline/src/project/format.ts+++ b/pipeline/src/project/format.ts@@ -207,7 +207,15 @@ export type RenderResolutionMode = 'surface' | 'design' | 'integer';* vendor asks the same question and a package built for one is rejected by the* other. */export interface MiniGamePackaging { appid?: string; }-export type WeChatPackaging = MiniGamePackaging;+export interface WeChatPackaging extends MiniGamePackaging {+ /**+ * Render through WeChat's EmscriptenGLX: the engine's GL calls run inside the+ * wasm and reach the host in batches. The package ships the GLX engine (about+ * 310 KB more); a host without GLX (base library < 3.8.12, or iOS outside+ * 高性能+) renders through WebGL2 as before.+ */+ emscriptenGLX?: boolean;+}/** A quick game ships a signed `.rpk`: `appid` is its package name (ending in* `.minigame`), and the release key is what a vendor binds that name to. */export interface QuickGamePackaging extends MiniGamePackaging {@@ -397,7 +405,7 @@ export interface ProjectPackaging {/** Per-platform packaging config: each target's slice of the app identity, plus* whatever only it has (a WeChat appid, an Android versionCode). */platforms?: {- wechat?: MiniGamePackaging;+ wechat?: WeChatPackaging;douyin?: MiniGamePackaging;bilibili?: MiniGamePackaging;quickgame?: QuickGamePackaging;@@ -856,6 +864,7 @@ export function parseManifest(raw: unknown): ProjectManifest {if (wx && typeof wx === 'object') {const w: WeChatPackaging = {};if (typeof wx.appid === 'string') w.appid = wx.appid;+ if (typeof wx.emscriptenGLX === 'boolean') w.emscriptenGLX = wx.emscriptenGLX;// Legacy per-platform orientation → the project-wide field (WeChat first).if (!orientation && (wx.orientation === 'portrait' || wx.orientation === 'landscape')) orientation = wx.orientation;if (Object.keys(w).length > 0) platforms.wechat = w;diff --git a/pipeline/tests/export-wechat.test.ts b/pipeline/tests/export-wechat.test.tsindex 28656f7c7..0152c1f0b 100644--- a/pipeline/tests/export-wechat.test.ts+++ b/pipeline/tests/export-wechat.test.ts@@ -655,6 +655,38 @@ describe('exportGame (wechat)', () => {expect(existsSync(path.join(o, 'wasm', 'esengine.wasm.br'))).toBe(false);expect(readFileSync(path.join(o, 'game-bundle.js'), 'utf8')).toContain('wasm/esengine.wasm');}, 60_000);+ // The GLX engine is a separate build beside the plain one; a project that asks+ // for it must ship THAT binary, and one that has not built it must hear how.+ it('ships the EmscriptenGLX engine from the -glx runtime when the project asks for it', async () => {+ const base = path.join(root, '_wxwasm-g');+ for (const [dir, bytes] of [[base, 'plainbytes'], [`${base}-glx`, 'glxbytes']] as const) {+ mkdirSync(dir, { recursive: true });+ writeFileSync(path.join(dir, 'esengine.js'), 'module.exports = () => Promise.resolve({});');+ writeFileSync(path.join(dir, 'esengine.wasm'), bytes);+ }+ const o = path.join(root, 'dist-wx-glx');+ const exportWith = (wasmDir: string) => exportGame({+ root,+ entryScene: 'scenes/main.esscene',+ hostsDir: 'unused-for-wechat', packagesDir: OFFICIAL_PACKAGES,+ scriptsEntry: 'src/main.ts',+ sdkDistDir: path.join(root, '_sdk'),+ wasmDir,+ outDir: o,+ platform: 'wechat',+ miniGameAppid: 'wxTEST0123456789',+ miniGameGlx: true,+ runtime: runtimeConfigOf({ designResolution: { width: 1280, height: 720 } }),+ });+ const res = await exportWith(base);+ expect(res.ok).toBe(true);+ expect(readFileSync(path.join(o, 'wasm', 'esengine.wasm'), 'utf8')).toBe('glxbytes');++ const missing = await exportWith(path.join(root, '_wxwasm'));+ expect(missing.ok).toBe(false);+ expect(missing.errors.join('\n')).toContain('build -t wechat-glx');+ }, 60_000);+// Moving the binary out of the 4MB main package means four things must agree:// where it lands, what the loader is told, what game.json declares, and that// the entry asks the host for the 分包 before the engine is instantiated.diff --git a/pipeline/tests/project-export-options.test.ts b/pipeline/tests/project-export-options.test.tsindex 02bd86d6a..9d623349f 100644--- a/pipeline/tests/project-export-options.test.ts+++ b/pipeline/tests/project-export-options.test.ts@@ -52,6 +52,13 @@ describe('the export a project describes', () => {});});+ it('ships the EmscriptenGLX engine to WeChat only, and only when the project asked', async () => {+ const glx = parseManifest({ formatVersion: '1', name: 'p', packaging: { platforms: { wechat: { emscriptenGLX: true } } } });+ expect((await projectExportOptions(root, glx, 'wechat')).miniGameGlx).toBe(true);+ expect((await projectExportOptions(root, glx, 'douyin')).miniGameGlx).toBeUndefined();+ expect((await projectExportOptions(root, manifest, 'wechat')).miniGameGlx).toBeUndefined();+ });+it('cooks assets the way the project asked when the caller says nothing', async () => {const skip = parseManifest({ formatVersion: '1', name: 'p', packaging: { assetCompression: 'skip' } });expect(await projectExportOptions(root, skip, 'web'))diff --git a/sdk/src/runtime/miniGameRuntime.ts b/sdk/src/runtime/miniGameRuntime.tsindex e39a762b6..c7b5c0236 100644--- a/sdk/src/runtime/miniGameRuntime.ts+++ b/sdk/src/runtime/miniGameRuntime.ts@@ -215,6 +215,19 @@ export function hostProgress(global: {};}+/** What a GLX context carries (WeChat's "EmscriptenGLX 原生引擎接入"). */+export interface GlxContext { isWebGL2: boolean; platform: number; ctxid: number }+export type GlxModule = { ccall(name: string, ret: string | null, args: string[], values: unknown[]): unknown; wxContextGlobal?: GlxContext };++/** Starts the linked GLX in the order WeChat's guide gives: told whether the host+ * gave a GLX context at all, then, when it did, its buffers and GL state. */+export function startGlx(module: GlxModule, glx: GlxContext | undefined): void {+ module.ccall('glxInit', null, ['bool'], [!!glx]);+ if (!glx || module.wxContextGlobal !== undefined) return;+ module.wxContextGlobal = { ...glx };+ module.ccall('glxInitBufferDataAndGlState', null, ['number', 'number'], [glx.isWebGL2 ? 2 : 1, glx.platform]);+}+export async function initMiniGameRuntime(config: MiniGameRuntimeConfig): Promise<void> {// Before the engine boots, so a boot that fails is still heard by the editor.if (config.debugChannel) startDebugChannel(config.debugChannel);@@ -245,7 +258,13 @@ export async function initMiniGameRuntime(config: MiniGameRuntimeConfig): Promisconst module = await instantiateModule(config.engineFactory, config.engineWasmPath, tag, { canvas });progress.reach('engine');- const gl = canvas.getContext('webgl2') as WebGLRenderingContext | null;+ // EmscriptenGLX runs the engine's GL calls inside the wasm and hands them to+ // the host in batches. Asked for only when the engine was linked with it and+ // the host offers it; anything else is the ordinary WebGL2 context.+ const glxLinked = typeof (module as { _glxInit?: unknown })._glxInit === 'function';+ const hostEnv = (adapter.host as { env?: { isSupportEmscriptenGLX?: boolean } }).env;+ const wantGlx = glxLinked && hostEnv?.isSupportEmscriptenGLX === true;+ const gl = canvas.getContext(wantGlx ? 'wxwebgl2' : 'webgl2') as WebGLRenderingContext | null;if (!gl) {// The renderer is GLSL ES 3.0 throughout, so a WebGL1 context would boot// to shader failures and a black screen; this says why instead.@@ -256,12 +275,17 @@ export async function initMiniGameRuntime(config: MiniGameRuntimeConfig): Promisreturn;}+ const glx = (gl as { emscriptenGLX?: GlxContext }).emscriptenGLX;+ if (glxLinked) startGlx(module as unknown as GlxModule, glx);+ log.info(tag, glx ? 'rendering through EmscriptenGLX' : `rendering through WebGL2${glxLinked ? ' (this host offers no EmscriptenGLX)' : ''}`);+hideCoreExtensions(gl);const glHandle = module.GL.registerContext(gl, {majorVersion: 2,minorVersion: 0,enableExtensionsByDefault: true,});+ if (glx) (module as unknown as GlxModule).ccall('glxUpdateContextId', 'number', ['number'], [glx.ctxid]);const app = createWebApp(module, {renderSurface: { kind: 'gl-context', handle: glHandle },diff --git a/sdk/tests/minigame-glx.test.ts b/sdk/tests/minigame-glx.test.tsnew file mode 100644index 000000000..30926dd96--- /dev/null+++ b/sdk/tests/minigame-glx.test.ts@@ -0,0 +1,32 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file An engine linked with EmscriptenGLX is started in the order WeChat's+ * guide requires, and on a host without it is told so and nothing more.+ */+import { describe, it, expect } from 'vitest';+import { startGlx, type GlxModule } from '../src/runtime/miniGameRuntime';++function recordingModule(): GlxModule & { calls: Array<[string, unknown[]]> } {+ const calls: Array<[string, unknown[]]> = [];+ return { calls, ccall: (name, _ret, _types, values) => { calls.push([name, values]); } };+}++describe('startGlx', () => {+ it('inits, publishes the context, then sets up buffers and GL state', () => {+ const m = recordingModule();+ startGlx(m, { isWebGL2: true, platform: 2, ctxid: 5 });+ expect(m.calls).toEqual([+ ['glxInit', [true]],+ ['glxInitBufferDataAndGlState', [2, 2]],+ ]);+ expect(m.wxContextGlobal).toEqual({ isWebGL2: true, platform: 2, ctxid: 5 });+ });++ it('tells a linked engine the host gave no GLX context, and stops there', () => {+ const m = recordingModule();+ startGlx(m, undefined);+ expect(m.calls).toEqual([['glxInit', [false]]]);+ expect(m.wxContextGlobal).toBeUndefined();+ });+});diff --git a/tools/launchers/launch-minigame.mjs b/tools/launchers/launch-minigame.mjsindex 85e5d93df..7044ffb04 100644--- a/tools/launchers/launch-minigame.mjs+++ b/tools/launchers/launch-minigame.mjs@@ -142,7 +142,8 @@ async function main() {if (/\[minigame\] boot failed|\[estella\]|uncaught|is not a function|no such file/i.test(msg)) {errors.push(msg.slice(0, 400));}- if (/^\[(minigame|engine|estella)\]/.test(msg)) console.log(` ${msg}`);+ // The engine names the GL path it took; a check about EmscriptenGLX reads it.+ if (/^\[(minigame|engine|estella)\]|rendering through /.test(msg)) console.log(` ${msg}`);});win.webContents.on('render-process-gone', (_e, d) => errors.push(`render process gone: ${d.reason}`));diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 1f60b781d..aac5dc8cf 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -1180,4 +1180,8 @@ export const NOTED = {{ note: 'Project Settings says the start screen\'s logo is for web exports; a mini-game shows its host\'s own start screen and loading text.' },'feat(export): the start screen shows the game\'s code downloading':{ internal: 'Reverted before release: golden web packages stalled after 29 frames on the CI runners; see the revert.' },+ 'feat(export): a WeChat project can render through EmscriptenGLX':+ { note: '**EmscriptenGLX on WeChat.** A WeChat project can ship the engine linked with WeChat\'s EmscriptenGLX (Project Settings → WeChat → Render through EmscriptenGLX, off by default), which issues the engine\'s GL calls natively instead of through JavaScript: a draw-heavy scene spent about 12% less time rendering on an Android phone. It adds about 310KB of wasm and needs base library 3.8.12 on Android, or iOS in 高性能+ mode; any other host renders through WebGL2 as before, and the log says which. The engine is built once with `node build-tools/cli.js build -t wechat-glx`, which fetches WeChat\'s library at a pinned version and hash, and emsdk 4.0.10 beside the main one; an export that asks for it without it says so.' },+ 'feat(settings): WeChat\'s EmscriptenGLX is a project setting':+ { note: '**EmscriptenGLX on WeChat.** A WeChat project can ship the engine linked with WeChat\'s EmscriptenGLX (Project Settings → WeChat → Render through EmscriptenGLX, off by default), which issues the engine\'s GL calls natively instead of through JavaScript: a draw-heavy scene spent about 12% less time rendering on an Android phone. It adds about 310KB of wasm and needs base library 3.8.12 on Android, or iOS in 高性能+ mode; any other host renders through WebGL2 as before, and the log says which. The engine is built once with `node build-tools/cli.js build -t wechat-glx`, which fetches WeChat\'s library at a pinned version and hash, and emsdk 4.0.10 beside the main one; an export that asks for it without it says so.' },};diff --git a/tools/verify-glx-fallback.mjs b/tools/verify-glx-fallback.mjsnew file mode 100644index 000000000..998eebf59--- /dev/null+++ b/tools/verify-glx-fallback.mjs@@ -0,0 +1,71 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file verify-glx-fallback — a WeChat package built with EmscriptenGLX still+ * draws on a host that offers none.+ *+ * Most hosts a GLX package lands on (DevTools, iOS without 高性能+, an old base+ * library) have no GLX context, and the engine linked with it must then render+ * through WebGL2 like any other. The stand-in host is such a host, so this+ * exports a project with the setting on, checks the package carries the GLX+ * engine rather than the plain one, and boots it: the engine has to say it saw+ * no GLX, and the frame has to be drawn.+ *+ * node tools/verify-glx-fallback.mjs (needs build/wasm/wechat and build/wasm/wechat-glx)+ */+import { spawnSync } from 'node:child_process';+import { cpSync, readFileSync, writeFileSync, rmSync, mkdtempSync } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { runElectron } from './lib/electronRun.mjs';++const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');+const ENGINE = 'esengine.wxgame.wasm';+const work = mkdtempSync(path.join(tmpdir(), 'glx-fallback-'));+const project = path.join(work, 'project');+const out = path.join(work, 'out');++const problems = [];+const check = (ok, what) => {+ console.log(`${ok ? '✓' : '✗'} ${what}`);+ if (!ok) problems.push(what);+};++try {+ cpSync(path.join(ROOT, 'examples', 'hello-world'), project, { recursive: true });+ const manifestPath = path.join(project, 'project.esproject');+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));+ manifest.packaging ??= {};+ manifest.packaging.platforms ??= {};+ manifest.packaging.platforms.wechat = { ...manifest.packaging.platforms.wechat, emscriptenGLX: true };+ writeFileSync(manifestPath, JSON.stringify(manifest, null, 2));++ const exported = spawnSync(process.execPath, [+ path.join(ROOT, 'pipeline', 'bin', 'estella.mjs'), 'export', project,+ '--platform', 'wechat', '--wasm', path.join(ROOT, 'build', 'wasm', 'wechat'), '--out', out,+ ], { encoding: 'utf8', cwd: ROOT });+ if (exported.status !== 0) {+ console.error(`${exported.stdout}${exported.stderr}`.trim().split('\n').slice(-8).join('\n'));+ throw new Error('the GLX export failed');+ }++ const shipped = readFileSync(path.join(out, 'wasm', ENGINE));+ check(shipped.equals(readFileSync(path.join(ROOT, 'build', 'wasm', 'wechat-glx', ENGINE))),+ 'the package carries the GLX engine');++ const run = runElectron([path.join(ROOT, 'tools', 'launchers', 'launch-minigame.mjs'), '--dir', out,+ '--timeout', '60000'], { cwd: ROOT, encoding: 'utf8' });+ const log = `${run.stdout ?? ''}${run.stderr ?? ''}`;+ check(log.includes('rendering through WebGL2 (this host offers no EmscriptenGLX)'),+ 'the engine saw the host offers no GLX and took WebGL2');+ check(run.status === 0 && /painted=true live=true/.test(log), 'the frame is drawn');+ if (problems.length > 0) console.log(log.trim().split('\n').slice(-15).join('\n'));+} finally {+ rmSync(work, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });+}++if (problems.length > 0) {+ console.error(`verify-glx-fallback: ${problems.length} problem(s)`);+ process.exit(1);+}