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(web): a browser without WebAssembly runs the game — the engine also ships as JavaScript
yhh2ab32d498973
diff --git a/build-tools/build.config.js b/build-tools/build.config.jsindex 3428ed203..f22e429a3 100644--- a/build-tools/build.config.js+++ b/build-tools/build.config.js@@ -16,6 +16,7 @@ export default {optimization: {web: { cmakeOpt: '-O2', wasmOpt: '-O2' },+ 'web-js': { cmakeOpt: '-O2', wasmOpt: '-O2' },wechat: { cmakeOpt: '-O2', wasmOpt: '-O2' },'wechat-glx': { cmakeOpt: '-O2', wasmOpt: '-O2' },'wechat-lite': { cmakeOpt: '-O2', wasmOpt: '-O2' },@@ -35,6 +36,21 @@ export default {'sdk/esengine.wasm': 'wasm/web/esengine.wasm',},},+ // The same engine as plain JavaScript (wasm2js), for a host with no+ // WebAssembly: an exported web page loads it only when `WebAssembly` is+ // absent (gameHost). No SIMD, no BigInt, no WebGPU — a host without wasm+ // has none of the three.+ 'web-js': {+ buildDir: 'build/cmake/web-js',+ cmakeFlags: ['-DES_BUILD_WEB=ON', '-DES_BUILD_TESTS=OFF', '-DES_WASM2JS=ON',+ '-DES_MAIN_DISABLE_SIMD=ON', '-DES_WASM_BIGINT=OFF'],+ targets: ['esengine_sdk'],+ // Beside the wasm engine, so the editor's copy and every web export+ // carry both and the page picks at boot.+ outputs: {+ 'sdk/esengine.js': 'wasm/web/esengine.asm.js',+ },+ },wechat: {buildDir: 'build/cmake/wxgame',cmakeFlags: ['-DES_BUILD_WXGAME=ON', '-DES_BUILD_TESTS=OFF'],diff --git a/cmake/Emscripten.cmake b/cmake/Emscripten.cmakeindex 5e5f6ded8..f5c773ac5 100644--- a/cmake/Emscripten.cmake+++ b/cmake/Emscripten.cmake@@ -29,6 +29,16 @@ option(ES_MAIN_DISABLE_SIMD "Disable wasm SIMD for the main module (compat fallb# Hosts on V8 older than 8.5 reject an i64 in a wasm↔JS signature ("wasm function# signature contains illegal type"); OFF legalizes i64 into i32 pairs instead.option(ES_WASM_BIGINT "Pass i64 across the wasm↔JS boundary as BigInt" ON)+# The engine as plain JavaScript (emscripten's wasm2js, -sWASM=0) for a host that+# has no WebAssembly at all: the same C++, the same embind surface, the same SDK —+# only the core's container changes. wasm2js has no SIMD and no BigInt i64, so a+# configure that asks for it gets neither (see the checks below).+option(ES_WASM2JS "Build the SDK engine as plain JavaScript (wasm2js) instead of wasm" OFF)+if(ES_WASM2JS)+ if(NOT ES_MAIN_DISABLE_SIMD OR ES_WASM_BIGINT)+ message(FATAL_ERROR "ES_WASM2JS needs -DES_MAIN_DISABLE_SIMD=ON -DES_WASM_BIGINT=OFF: wasm2js lowers neither SIMD nor BigInt i64.")+ endif()+endif()if(NOT ES_MAIN_DISABLE_SIMD)list(APPEND ES_EMSCRIPTEN_COMPILE_FLAGS -msimd128 -msse2)endif()@@ -256,7 +266,13 @@ function(es_apply_sdk_settings TARGET_NAME)if(ES_BUILD_WEB OR ES_BUILD_WXGAME)target_compile_options(${TARGET_NAME} PRIVATE ${ES_EMSCRIPTEN_COMPILE_FLAGS} -flto -fno-exceptions)- string(REPLACE ";" " " LINK_FLAGS_STR "${ES_EMSCRIPTEN_SDK_LINK_FLAGS}")+ set(_SDK_LINK ${ES_EMSCRIPTEN_SDK_LINK_FLAGS})+ if(ES_WASM2JS)+ # One output, the module itself in JS: no .wasm beside it to fetch.+ list(TRANSFORM _SDK_LINK REPLACE "^-sWASM=1$" "-sWASM=0")+ list(APPEND _SDK_LINK -sWASM_BIGINT=0)+ endif()+ string(REPLACE ";" " " LINK_FLAGS_STR "${_SDK_LINK}")set_target_properties(${TARGET_NAME} PROPERTIESSUFFIX ".js"LINK_FLAGS "${LINK_FLAGS_STR}"diff --git a/docs/astro/src/content/docs/publishing/overview.mdx b/docs/astro/src/content/docs/publishing/overview.mdxindex 431d774fc..26e44949a 100644--- a/docs/astro/src/content/docs/publishing/overview.mdx+++ b/docs/astro/src/content/docs/publishing/overview.mdx@@ -276,6 +276,43 @@ play == ship covers these modules too. See[App Setup & Lifecycle](/docs/core-concepts/app-lifecycle/#side-modules) for theruntime API.+## Browsers without WebAssembly++A Web export carries the engine twice: `wasm/esengine.wasm`, and the same engine+compiled to plain JavaScript as `wasm/esengine.asm.js`. The page picks at boot.+Where `WebAssembly` exists it loads the wasm engine, and the JavaScript one is+never downloaded. Where it does not exist (some locked-down WebViews and+embedded browsers), the page loads `esengine.asm.js`, and the game runs the same+scenes and scripts.++To try the JavaScript engine in an ordinary browser, add `?engine=js` to the+page URL.++What it costs, measured on `hello-world` in headless Chromium:++| | WebAssembly engine | JavaScript engine |+|---|---|---|+| Engine file | 2.1 MB (0.67 MB gzip) | 4.3 MB (0.98 MB gzip) |+| Main-thread time per frame | 9.3 ms | ~11.5 ms |++What it does not have:++- **WebGPU.** The JavaScript engine always renders through WebGL2.+- **Side modules** (physics, Spine, DragonBones, Basis, video). These are+ WebAssembly binaries. On a host without WebAssembly each one logs a single+ error naming the module and stays absent, and the features it provides do not run.+- **Compiled (`@compiled`) systems.** These are wasm modules too. They stay+ interpreted, which is the same result as an export without AOT.++To leave the file out (it is about 4 MB on the server, though nobody with+WebAssembly downloads it), set `engineJs` to `false`:++```json+"packaging": { "platforms": { "web": { "engineJs": false } } }+```++A browser with no WebAssembly then gets a clear error instead of a game.+## Build config & source maps- **Development** — an unminified build; pair it with source maps for debuggablediff --git a/docs/astro/src/content/docs/zh-cn/publishing/overview.mdx b/docs/astro/src/content/docs/zh-cn/publishing/overview.mdxindex 2f95cc3bd..190da85a0 100644--- a/docs/astro/src/content/docs/zh-cn/publishing/overview.mdx+++ b/docs/astro/src/content/docs/zh-cn/publishing/overview.mdx@@ -233,6 +233,40 @@ node build-tools/cli.js build -t wechat编辑器 origin 拉取侧模块——所以"玩到的即发布的"同样覆盖这些模块。运行时 API 见[应用设置与生命周期](/docs/zh-cn/core-concepts/app-lifecycle/#侧模块)。+## 不支持 WebAssembly 的浏览器++Web 导出会带两份引擎:`wasm/esengine.wasm`,以及同一引擎编译成纯 JavaScript 的+`wasm/esengine.asm.js`。页面启动时二选一。有 `WebAssembly` 的环境加载 wasm 引擎,+JavaScript 版本不会被下载。没有 `WebAssembly` 的环境(一些锁死的 WebView、+嵌入式浏览器)加载 `esengine.asm.js`,游戏照常运行同样的场景和脚本。++要在普通浏览器里试 JavaScript 引擎,在页面地址后加 `?engine=js`。++代价(`hello-world`,headless Chromium 实测):++| | WebAssembly 引擎 | JavaScript 引擎 |+|---|---|---|+| 引擎文件 | 2.1 MB(gzip 0.67 MB) | 4.3 MB(gzip 0.98 MB) |+| 每帧主线程耗时 | 9.3 ms | 约 11.5 ms |++它没有的:++- **WebGPU**:JavaScript 引擎始终走 WebGL2。+- **侧模块**(物理、Spine、DragonBones、Basis、视频):它们是 WebAssembly 二进制。+ 在没有 WebAssembly 的环境里,每个侧模块只报一条写明模块名的错误,然后保持缺席,+ 它提供的功能不会运行。+- **编译(`@compiled`)系统**:它们也是 wasm 模块,这里保持解释执行,+ 结果和不开 AOT 的导出一样。++不想带这个文件(服务器上约 4 MB,有 WebAssembly 的用户不会下载它),+把 `engineJs` 设为 `false`:++```json+"packaging": { "platforms": { "web": { "engineJs": false } } }+```++这样一来,没有 WebAssembly 的浏览器会看到一条明确的报错,而不是游戏。+## 构建配置与 source map- **Development** —— 不压缩的构建;配上 source map 得到可调试的输出。diff --git a/pipeline/src/export/exportGame.ts b/pipeline/src/export/exportGame.tsindex f30c05b08..88461e1fb 100644--- a/pipeline/src/export/exportGame.ts+++ b/pipeline/src/export/exportGame.ts@@ -472,6 +472,9 @@ function esengineGlobalPlugin(): Plugin {};}+/** The engine built as plain JavaScript (wasm2js), beside the wasm one in the runtime dir. */+export const ENGINE_JS_FILE = 'esengine.asm.js';+export interface ExportGameOptions {/** Editor LAN preview only; shipping exports leave the preview client out. */developmentPreview?: boolean;@@ -496,6 +499,8 @@ export interface ExportGameOptions {webChannel?: 'poki' | 'crazygames' | 'youtube';/** Origins the web page's policy lets the game connect to (project: packaging.platforms.web.connect). */webConnect?: string[];+ /** Web: carry the plain-JavaScript engine for browsers without WebAssembly. Absent ⇒ true. */+ webEngineJs?: boolean;leaderboardEncryptionKey?: string;sdkDistDir: string;/** The engine runtime to copy. */@@ -1208,6 +1213,11 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>await cp(opts.wasmDir, wasmOut, {recursive: true, filter: shipsSideModule(files.map((f) => f.file)),});+ // The plain-JavaScript engine is the web page's answer to a browser with no+ // WebAssembly; any other package has an engine of its own kind, or none.+ if (platform !== 'web' || opts.webEngineJs === false) {+ await rm(path.join(wasmOut, ENGINE_JS_FILE), { force: true });+ }} else errors.push(`wasm runtime dir not found: ${opts.wasmDir}`);}@@ -1247,6 +1257,7 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>...(debugChannel ? { debugChannel } : {}),...(existsSync(path.join(payloadDir, 'wasm', 'esengine.wasm'))? { engineBytes: statSync(path.join(payloadDir, 'wasm', 'esengine.wasm')).size } : {}),+ ...(existsSync(path.join(payloadDir, 'wasm', ENGINE_JS_FILE)) ? { engineJs: true } : {}),};await writeFile(path.join(payloadDir, 'game.config.json'), JSON.stringify(gameConfig, null, 2) + '\n');diff --git a/pipeline/src/export/projectExportOptions.ts b/pipeline/src/export/projectExportOptions.tsindex 9786572f2..7f2173224 100644--- a/pipeline/src/export/projectExportOptions.ts+++ b/pipeline/src/export/projectExportOptions.ts@@ -110,6 +110,7 @@ export async function projectExportOptions(: {}),...(platform === 'web' && (plat?.web?.channel === 'poki' || plat?.web?.channel === 'crazygames' || plat?.web?.channel === 'youtube') ? { webChannel: plat.web.channel } : {}),...(platform === 'web' && plat?.web?.connect?.length ? { webConnect: plat.web.connect } : {}),+ ...(platform === 'web' && plat?.web?.engineJs === false ? { webEngineJs: false } : {}),...(platform === 'web' && plat?.web?.channel === 'crazygames' && plat.web.leaderboardEncryptionKey? { leaderboardEncryptionKey: plat.web.leaderboardEncryptionKey } : {}),desktopProductName: plat?.desktop?.productName,diff --git a/pipeline/src/project/format.ts b/pipeline/src/project/format.tsindex 124615eb5..1ec0ea315 100644--- a/pipeline/src/project/format.ts+++ b/pipeline/src/project/format.ts@@ -453,6 +453,12 @@ export interface ProjectPackaging {/** Origins the page may open connections to (a game server): `wss://play.example.com`, or a bare `wss:`.* The page's Content-Security-Policy allows only its own origin otherwise. */connect?: string[];+ /**+ * Carry the engine built as plain JavaScript beside the wasm one (default true),+ * for a browser with no WebAssembly. It is fetched only there; elsewhere it is+ * ~4 MB the server holds and nobody downloads.+ */+ engineJs?: boolean;};wechat?: WeChatPackaging;douyin?: MiniGamePackaging;@@ -1015,6 +1021,7 @@ export function parseManifest(raw: unknown): ProjectManifest {const connect = cspConnectSources(web.connect as string[]);if (connect.length) config.connect = connect;}+ if (typeof web.engineJs === 'boolean') config.engineJs = web.engineJs;if (Object.keys(config).length) platforms.web = config;}const wx = pl.wechat as Record<string, unknown> | undefined;diff --git a/pipeline/src/runtime/gameHost.ts b/pipeline/src/runtime/gameHost.tsindex 3b7c9aa2e..a372460c0 100644--- a/pipeline/src/runtime/gameHost.ts+++ b/pipeline/src/runtime/gameHost.ts@@ -195,13 +195,25 @@ async function boot(): Promise<void> {splash?.reach('scene');const wasmBase = new URL('./wasm/', import.meta.url).href; // relative → mount-path agnostic- const { default: createModule } = (await import(/* @vite-ignore */ `${wasmBase}esengine.js`)) as {+ // A host with no WebAssembly (an old WebView, a locked-down runtime) gets the+ // same engine built as plain JavaScript, when the build carries it; `?engine=js`+ // asks for it anywhere, which is how it is tested in a browser that has wasm.+ const engineAsJs = (typeof WebAssembly === 'undefined'+ || new URLSearchParams(location.search).get('engine') === 'js') && cfg.engineJs === true;+ if (typeof WebAssembly === 'undefined' && !engineAsJs) {+ throw new Error('This browser has no WebAssembly, and this build carries no JavaScript engine '+ + '(packaging.platforms.web.engineJs is off).');+ }+ const { default: createModule } = (await import(+ /* @vite-ignore */ `${wasmBase}${engineAsJs ? 'esengine.asm.js' : 'esengine.js'}`)) as {default: (options?: Record<string, unknown>) => Promise<ESEngineModule>;};+ if (engineAsJs) console.info('[estella] engine: JavaScript build (no WebAssembly)');// The device has to exist before the module reads it, and the fallback IS the// contract. `?headless` pins WebGL2: a driver reads the frame back through the- // GL context, which is what the capture hook below has.- const wantsWebGPU = cfg.renderBackend === 'webgpu' && !headless;+ // GL context, which is what the capture hook below has. The JavaScript engine is+ // built without WebGPU: a host with no wasm has no WebGPU either.+ const wantsWebGPU = cfg.renderBackend === 'webgpu' && !headless && !engineAsJs;const gpu = await acquireWebGPUDevice(wantsWebGPU ? 'webgpu' : 'webgl2',(m) => console.error(m));if (wantsWebGPU && !gpu.device) console.warn(`[estella] WebGPU unavailable (${gpu.reason}) — using WebGL2.`);@@ -209,7 +221,8 @@ async function boot(): Promise<void> {const module = await createModule({canvas,locateFile: (p: string) => `${wasmBase}${p}`,- instantiateWasm: engineInstantiator(`${wasmBase}esengine.wasm`, splash, cfg.engineBytes),+ // The JavaScript engine is the whole module in its own file: nothing to instantiate.+ ...(engineAsJs ? {} : { instantiateWasm: engineInstantiator(`${wasmBase}esengine.wasm`, splash, cfg.engineBytes) }),print: (t: string) => console.log(t),printErr: (t: string) => console.error(t),...(gpu.device ? { preinitializedWebGPUDevice: gpu.device } : {}),diff --git a/sdk/src/app/app.ts b/sdk/src/app/app.tsindex b41f42f6b..e8f571612 100644--- a/sdk/src/app/app.ts+++ b/sdk/src/app/app.ts@@ -1193,6 +1193,14 @@ export class App {+ 'system reads the memory of one');}const memory = module.wasmMemory;+ // An engine built as plain JavaScript (wasm2js, for a host without+ // WebAssembly) has an ArrayBuffer where the Memory would be, and a+ // compiled system is a wasm module that cannot import it. Not an error:+ // every system keeps running interpreted, which is the no-cliff rule.+ if (memory && (typeof WebAssembly === 'undefined' || !(memory instanceof WebAssembly.Memory))) {+ log.info('runtime', 'AOT: this engine runs without WebAssembly, so its compiled systems stay interpreted');+ return 0;+ }if (!memory) {throw new Error('installCompiledSystems: this engine artifact does not export '+ "'wasmMemory', so there is no memory for the module to import — rebuild the engine");diff --git a/sdk/src/runtime/packagedRuntime.ts b/sdk/src/runtime/packagedRuntime.tsindex 52977955b..7eb6292dd 100644--- a/sdk/src/runtime/packagedRuntime.ts+++ b/sdk/src/runtime/packagedRuntime.ts@@ -93,6 +93,9 @@ export interface PackagedGameConfig {* counts, so the boot bar measures against this instead.*/engineBytes?: number;+ /** The package carries the engine built as plain JavaScript (wasm/esengine.asm.js),+ * which the page loads where there is no WebAssembly. */+ engineJs?: boolean;/*** Install physics even when the shipped scene shows no bodies — a project* that spawns them from script (Project Settings → Physics → Enabled).diff --git a/sdk/src/sideModules/host.ts b/sdk/src/sideModules/host.tsindex 975e0b3f0..29d4e4e97 100644--- a/sdk/src/sideModules/host.ts+++ b/sdk/src/sideModules/host.ts@@ -61,6 +61,16 @@ export function createSideModuleHost(instantiate: SideModuleInstantiator): SideMconst cached = cache.get(id);if (cached) return cached;const descriptor = sideModuleDescriptor(id);+ // A side module is a WebAssembly module; a host with none runs the+ // engine's JavaScript build, which carries the core and nothing beside+ // it. Said once, by name, instead of "WebAssembly is not defined".+ if (descriptor && typeof WebAssembly === 'undefined') {+ log.error('sidemodule', `"${id}" is a WebAssembly module and this host has no WebAssembly: `+ + 'the engine runs as JavaScript here, and the features it provides are unavailable');+ const none = Promise.resolve(null);+ cache.set(id, none);+ return none;+ }const pending: Promise<SideModule | null> = descriptor? instantiate(descriptor, id).catch((e: unknown) => {// Absent BY DESIGN is the answer null already means; only adiff --git a/sdk/tests/aot-js-engine.test.ts b/sdk/tests/aot-js-engine.test.tsnew file mode 100644index 000000000..768accf6e--- /dev/null+++ b/sdk/tests/aot-js-engine.test.ts@@ -0,0 +1,39 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file The engine built as plain JavaScript (wasm2js) has an ArrayBuffer where+ * the WebAssembly.Memory would be, and a compiled system is a wasm module+ * that cannot import it. Installing answers 0 and every system keeps+ * running interpreted: a browser without WebAssembly plays the same game.+ */+import { describe, it, expect } from 'vitest';+import { App } from '../src/app/app';+import { defineComponent } from '../src/ecs/component';+import { defineSystem } from '../src/ecs/system';+import { Query, Mut } from '../src/ecs/query';+import { createMockModule } from './mocks/wasm';+import { fadeManifest } from './helpers/aotFade';++describe('compiled systems on the JavaScript engine', () => {+ it('installs nothing and leaves the interpreted systems running', async () => {+ const app = App.new();+ const Fade = defineComponent('Fade', { alpha: 1, step: 0.1 });+ app.addSystem(defineSystem([Query(Mut(Fade))], (q) => {+ for (const [, row] of q) row.alpha -= row.step;+ }, { name: 'Fade' }));+ const module = createMockModule();+ // What wasm2js hands out: a Memory-shaped object over a plain ArrayBuffer.+ Object.assign(module, { wasmMemory: { buffer: new ArrayBuffer(1 << 16), grow: () => 0 } });+ app.connectCpp(module.getRegistry(), module);+ try {+ const notWasm = new Uint8Array([0, 0x61, 0x73, 0x6d, 1, 0, 0, 0]).buffer;+ expect(await app.installCompiledSystems(notWasm, fadeManifest())).toBe(0);+ const entity = app.world.spawn();+ app.world.insert(entity, Fade, { alpha: 1, step: 0.1 });+ await app.tick(1 / 60);+ expect(app.world.get(entity, Fade).alpha).toBeCloseTo(0.9);+ } finally {+ app.quit({ keepRenderer: true });+ }+ });+});diff --git a/sdk/tests/helpers/loadWasm.ts b/sdk/tests/helpers/loadWasm.tsindex ba9b6a096..742ffb19d 100644--- a/sdk/tests/helpers/loadWasm.ts+++ b/sdk/tests/helpers/loadWasm.ts@@ -62,8 +62,22 @@ export const HAS_WASM = !NO_WASM_MODE;let cachedModule: ESEngineModule | null = null;+/**+ * ESENGINE_ENGINE=asmjs runs the boundary suites on the engine built as plain+ * JavaScript (build/wasm/web/esengine.asm.js, wasm2js) instead of the wasm one —+ * the same C++ in the container a host without WebAssembly loads, held to the+ * same tests. Side modules stay wasm: only the core has a JS build.+ */+export const ENGINE_IS_ASMJS = process.env.ESENGINE_ENGINE === 'asmjs';+const ASMJS_FILE = resolve(__dirname, '../../../build/wasm/web/esengine.asm.js');+export async function loadWasmModule(): Promise<ESEngineModule> {if (cachedModule) return cachedModule;+ if (ENGINE_IS_ASMJS) {+ const factory = (await import(ASMJS_FILE)).default;+ cachedModule = await factory({}) as ESEngineModule;+ return cachedModule;+ }const wasmBinary = readFileSync(WASM_FILE);const factory = (await import(resolve(WASM_DIR, 'esengine.js'))).default;cachedModule = await factory({ wasmBinary }) as ESEngineModule;diff --git a/sdk/tests/sideModuleHost.test.ts b/sdk/tests/sideModuleHost.test.tsindex 2771a161c..014609576 100644--- a/sdk/tests/sideModuleHost.test.ts+++ b/sdk/tests/sideModuleHost.test.ts@@ -76,4 +76,24 @@ describe('createSideModuleHost', () => {spy.mockRestore();}});++ // The engine's JavaScript build runs where there is no WebAssembly, and a side+ // module is a wasm binary: say so by name, once, and never call the transport.+ it('answers null without instantiating on a host with no WebAssembly', async () => {+ const spy = vi.spyOn(console, 'error').mockImplementation(() => {});+ const saved = globalThis.WebAssembly;+ try {+ delete (globalThis as { WebAssembly?: unknown }).WebAssembly;+ const instantiate = vi.fn().mockResolvedValue({});+ const host = createSideModuleHost(instantiate);+ expect(await host.acquire('physics')).toBeNull();+ expect(await host.acquire('physics')).toBeNull();+ expect(instantiate).not.toHaveBeenCalled();+ expect(spy).toHaveBeenCalledTimes(1);+ expect(String(spy.mock.calls[0].join(' '))).toMatch(/no WebAssembly/);+ } finally {+ globalThis.WebAssembly = saved;+ spy.mockRestore();+ }+ });});