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(aot): an Android package runs its @compiled systems as machine code
yhh3f85046311f1
diff --git a/build-tools/utils/aab.d.ts b/build-tools/utils/aab.d.tsindex 98a7c90f3..57f9f9cd9 100644--- a/build-tools/utils/aab.d.ts+++ b/build-tools/utils/aab.d.ts@@ -16,6 +16,8 @@ export function assembleAab(options: {key: SigningKey;/** Also carry the emulator's x86_64 libraries. Default: phone ABIs only. */emulatorAbi?: boolean;+ /** Libraries the export built, by ABI (the project's compiled systems): packaged beside the template's own in `lib/<abi>/`. An ABI the package does not carry is ignored. */+ extraLibs?: Record<string, string[]>;}): Buffer;export function aabFileName(appId: string): string;diff --git a/build-tools/utils/aab.js b/build-tools/utils/aab.jsindex f68640c09..ad55a1dd4 100644--- a/build-tools/utils/aab.js+++ b/build-tools/utils/aab.js@@ -19,7 +19,7 @@import path from 'path';import { existsSync, readFileSync } from 'fs';import { makeZip } from './zip.js';-import { packageEntries } from './apk.js';+import { packageEntries, extraLibEntries } from './apk.js';import { message, bytesField } from './protobuf.js';import { compileProtoManifest } from './androidProtoXml.js';import { appResources } from './androidResources.js';@@ -70,6 +70,7 @@ export function assembleAab(options) {...resources.files.map((f) => ({ ...f, name: `base/${f.name}` })),...(hasDex ? [{ name: 'base/dex/classes.dex', data: readFileSync(dex) }] : []),...abis.flatMap((abi) => packageEntries(path.join(templateDir, 'lib', abi), `base/lib/${abi}`)),+ ...abis.flatMap((abi) => extraLibEntries(options.extraLibs, abi, `base/lib/${abi}`)),...(existsSync(templateAssets) ? packageEntries(templateAssets, 'base/assets') : []),...packageEntries(contentDir, 'base/assets'),];diff --git a/build-tools/utils/android.d.ts b/build-tools/utils/android.d.tsnew file mode 100644index 000000000..32523d52e--- /dev/null+++ b/build-tools/utils/android.d.ts@@ -0,0 +1,19 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/** The Android SDK, or null when none is found. */+export function androidSdk(): string | null;+/** The newest entry under `dir`, or null. */+export function newest(dir: string): string | null;+/** The SDK, or a throw that says how to install one. */+export function requireSdk(): string;+/** The NDK (ANDROID_NDK_HOME / ANDROID_NDK_ROOT, else the newest under the SDK), or a throw. */+export function requireNdk(sdk: string): string;+/** aapt2 / zipalign / apksigner, from the newest installed build-tools. */+export function buildTool(sdk: string, name: string): string;+export function platformJar(sdk: string, platform?: string): string;+export function javaHome(explicit?: string): string | null;+export function jdkTool(name: string, explicit?: string): string;+/** A tool of the NDK's LLVM toolchain (clang, llvm-readelf, …), with the host's executable suffix. */+export function ndkTool(ndk: string, name: string): string;+export function ndkLibcxxShared(ndk: string, triple?: string): string;+export function sdkCmake(sdk: string): string | null;diff --git a/build-tools/utils/apk.d.ts b/build-tools/utils/apk.d.tsindex dba4818a1..8a5fffdba 100644--- a/build-tools/utils/apk.d.ts+++ b/build-tools/utils/apk.d.ts@@ -25,8 +25,11 @@ export function assembleApk(options: {icon?: Buffer;/** Also carry the emulator's x86_64 libraries. Default: phone ABIs only. */emulatorAbi?: boolean;+ /** Libraries the export built, by ABI (the project's compiled systems): packaged beside the template's own in `lib/<abi>/`. An ABI the package does not carry is ignored. */+ extraLibs?: Record<string, string[]>;}): Buffer;export function signApkV2(zip: Buffer, key: SigningKey): Buffer;export function packageEntries(dir: string, prefix: string): Array<{ name: string; data: Buffer }>;export function apkFileName(appId: string): string;+export function extraLibEntries(extraLibs: Record<string, string[]> | undefined, abi: string, prefix: string): Array<{ name: string; data: Buffer }>;diff --git a/build-tools/utils/apk.js b/build-tools/utils/apk.jsindex c83717f5e..623925f71 100644--- a/build-tools/utils/apk.js+++ b/build-tools/utils/apk.js@@ -141,6 +141,11 @@ export function packageEntries(dir, prefix) {* @param {Buffer} [options.icon] The launcher icon; the template's default when absent.* @returns {Buffer} the signed package.*/+/** One ABI's extra libraries as package entries. @internal */+export function extraLibEntries(extraLibs, abi, prefix) {+ return (extraLibs?.[abi] ?? []).map((file) => ({ name: `${prefix}/${path.basename(file)}`, data: readFileSync(file) }));+}+export function assembleApk(options) {const { templateDir, contentDir, app } = options;const dex = path.join(templateDir, 'classes.dex');@@ -166,6 +171,10 @@ export function assembleApk(options) {...(hasDex ? [{ name: 'classes.dex', data: readFileSync(dex) }] : []),...abis.flatMap((abi) => packageEntries(path.join(templateDir, 'lib', abi), `lib/${abi}`).map((e) => ({ ...e, store: true, align: PAGE_ALIGNMENT }))),+ // What the export built for each ABI (the project's compiled systems), loaded+ // by bare name from the same place, so stored and aligned the same way.+ ...abis.flatMap((abi) => extraLibEntries(options.extraLibs, abi, `lib/${abi}`)+ .map((e) => ({ ...e, store: true, align: PAGE_ALIGNMENT }))),// The template's assets (the SDK bytecode) first, so a project cannot// shadow them by accident and quietly change what the host boots....(existsSync(templateAssets) ? packageEntries(templateAssets, 'assets') : []),diff --git a/build-tools/utils/gradleProject.d.ts b/build-tools/utils/gradleProject.d.tsindex f13f178ae..882bda3ac 100644--- a/build-tools/utils/gradleProject.d.ts+++ b/build-tools/utils/gradleProject.d.ts@@ -13,6 +13,8 @@export interface AndroidProjectSources {/** The engine's shared libraries, one directory per ABI. */libs: string;+ /** Libraries the export built, by ABI (the project's compiled systems), copied into `jniLibs/<abi>/` beside the template's. */+ extraLibs?: Record<string, string[]>;/** The host's Java shim, as source — what the project compiles. */java: string;/** The manifest template the app's identity is substituted into. */diff --git a/build-tools/utils/gradleProject.js b/build-tools/utils/gradleProject.jsindex f48521903..f37f74e82 100644--- a/build-tools/utils/gradleProject.js+++ b/build-tools/utils/gradleProject.js@@ -257,6 +257,11 @@ export async function emitAndroidGradleProject(contentDir, app, sources, icon) {}await cp(sources.libs, path.join(mainDir, 'jniLibs'), { recursive: true });+ // What the export built per ABI (the project's compiled systems), beside the template's.+ for (const [abi, files] of Object.entries(sources.extraLibs ?? {})) {+ if (!abis.includes(abi)) continue;+ for (const file of files) await cp(file, path.join(mainDir, 'jniLibs', abi, path.basename(file)));+ }if (existsSync(sources.java)) {await cp(sources.java, path.join(mainDir, 'java'), { recursive: true });}diff --git a/desktop b/desktopindex c2be9b293..99fcc561c 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit c2be9b29379d39eac10866c454982926fbdd191d+Subproject commit 99fcc561c1a93d8e97733929b5900dab2aa880e4diff --git a/docs/astro/src/content/docs/publishing/android-ios.mdx b/docs/astro/src/content/docs/publishing/android-ios.mdxindex 917ad3275..a8f5a5350 100644--- a/docs/astro/src/content/docs/publishing/android-ios.mdx+++ b/docs/astro/src/content/docs/publishing/android-ios.mdx@@ -270,6 +270,17 @@ one thing that costs meaningfully more here than in a browser — prefer theengine's own systems and bulk APIs over hand-written per-entity iteration in thehot path.+**On Android, a system marked `@compiled` runs as machine code instead.** The+export cross-compiles every `/** @compiled */` system with the Android NDK, once per+64-bit ABI the package carries (arm64-v8a, and x86_64 for the emulator), and the+APK carries each build in `lib/<abi>/`. Where the interpreter spends microseconds+per entity, the compiled system spends tens of nanoseconds. The NDK must be+installed on the exporting machine (Android Studio's SDK Manager, or+`ANDROID_NDK_HOME`); the Package dialog says so when a project promises compiled+systems and it is missing. A system the host cannot bind falls back to the+interpreter for that frame, so a missing module costs speed, never correctness. iOS+still runs every system interpreted.+### The first launch after an installParsing the SDK bundle on a device takes ~14 s, and a compile cache does not existdiff --git a/docs/astro/src/content/docs/zh-cn/publishing/android-ios.mdx b/docs/astro/src/content/docs/zh-cn/publishing/android-ios.mdxindex b57e5fc04..b63d87de4 100644--- a/docs/astro/src/content/docs/zh-cn/publishing/android-ios.mdx+++ b/docs/astro/src/content/docs/zh-cn/publishing/android-ios.mdx@@ -228,6 +228,13 @@ Android 的下限是 29,因为引擎的字体路径调用 `AFontMatcher_create`,用 TypeScript 写的逐实体循环,是这里比浏览器里明显更贵的那一样东西——热路径上优先用引擎自己的系统和批量 API,而不是手写逐实体迭代。+**在 Android 上,标记了 `@compiled` 的系统改为以机器码运行。** 导出时会用 Android NDK+把每个 `/** @compiled */` 系统交叉编译,包里每个 64 位 ABI 各一份(arm64-v8a,模拟器还有+x86_64),APK 把它们放在 `lib/<abi>/`。解释器每个实体要花微秒级,编译后只要几十纳秒。导出机器+需要装好 NDK(Android Studio 的 SDK Manager,或设置 `ANDROID_NDK_HOME`);项目承诺了编译系统+而缺少 NDK 时,打包对话框会提示。宿主绑定不了的系统会在那一帧退回解释器,所以缺模块只影响速度,+不影响正确性。iOS 目前仍全部解释执行。+### 安装后的第一次启动在设备上解析 SDK bundle 要约 14 秒,而编译缓存要等一次启动付过账才存在——diff --git a/pipeline/src/bundle/buildCompiledSystems.ts b/pipeline/src/bundle/buildCompiledSystems.tsindex 95fef6272..e7ad0275c 100644--- a/pipeline/src/bundle/buildCompiledSystems.ts+++ b/pipeline/src/bundle/buildCompiledSystems.ts@@ -138,6 +138,8 @@ export interface BuildCompiledResult {/** Absolute path to the built module, or null when there was nothing to* build. Which KIND of module is the target the caller asked for. */modulePath: string | null;+ /** With `outputs`: each output's module, by its id (the first is `modulePath`). */+ modules?: Record<string, string>;manifest: CompiledSystemsManifest | null;errors: string[];/** Systems the subset refused that were NOT promised — information, not failure. */@@ -197,6 +199,15 @@ export async function buildCompiledSystems(cc: string | null;/** Runs a command; the toolchain's own runner, so env and logging match. */run: (cmd: string, args: string[], cwd: string) => Promise<{ code: number; stderr: string }>;+ /**+ * Native only: the machines to build the one C for, each with its own+ * compiler and flags — a cross-compiled package carries one module per ABI.+ * Replaces `cc` and the host's link flags; an empty list means no compiler+ * here, said with `missing`.+ */+ outputs?: ReadonlyArray<{ id: string; cc: string; flags: readonly string[]; module: string }>;+ /** What to say when `outputs` is empty. */+ missing?: string;},): Promise<BuildCompiledResult> {const plan = TARGETS[opts.target ?? 'wasm'];@@ -255,10 +266,10 @@ export async function buildCompiledSystems(};}- if (!opts.cc) {+ if (opts.outputs ? opts.outputs.length === 0 : !opts.cc) {return {ok: false, modulePath: null, manifest: null, notes,- errors: [`${chosen.length} system(s) are marked @compiled but ${plan.missing}`+ errors: [`${chosen.length} system(s) are marked @compiled but ${opts.outputs ? opts.missing ?? plan.missing : plan.missing}`+ ', or remove the marker'],};}@@ -279,15 +290,22 @@ export async function buildCompiledSystems(units.push(path.join(dir, 'systems_decl.c'));}- const modulePath = path.join(dir, plan.module);- const built = await opts.run(opts.cc, [- ...CFLAGS, '-Wall', '-Wextra',- ...plan.linkFlags(c.symbols),- '-o', modulePath, ...units,- ], dir);- if (built.code !== 0 || !existsSync(modulePath)) {- return { ok: false, modulePath: null, manifest: null, notes, errors: [built.stderr.trim()] };+ // One C, as many machines as were asked for: the host's own by default, or one+ // module per output (a cross-compiled package's ABIs), each in its own folder.+ const jobs = opts.outputs+ ? opts.outputs.map((o) => ({ id: o.id, cc: o.cc, flags: [...o.flags], out: path.join(dir, o.id, o.module) }))+ : [{ id: plan.module, cc: opts.cc!, flags: plan.linkFlags(c.symbols), out: path.join(dir, plan.module) }];+ const modules: Record<string, string> = {};+ for (const job of jobs) {+ mkdirSync(path.dirname(job.out), { recursive: true });+ const built = await opts.run(job.cc, [...CFLAGS, '-Wall', '-Wextra', ...job.flags, '-o', job.out, ...units], dir);+ if (built.code !== 0 || !existsSync(job.out)) {+ return { ok: false, modulePath: null, manifest: null, notes,+ errors: [`${opts.outputs ? `${job.id}: ` : ''}${built.stderr.trim()}`] };+ }+ modules[job.id] = job.out;}+ const modulePath = jobs[0].out;const manifest: CompiledSystemsManifest = {engineAbi: c.handshake.engineAbi,@@ -299,7 +317,7 @@ export async function buildCompiledSystems(systems: moduleDeclarations(lowered.module, inlined),};writeFileSync(path.join(dir, MANIFEST), `${JSON.stringify(manifest, null, 2)}\n`);- return { ok: true, modulePath, manifest, errors: [], notes };+ return { ok: true, modulePath, ...(opts.outputs ? { modules } : {}), manifest, errors: [], notes };}/** Read back what a previous build wrote, or null. */diff --git a/pipeline/src/export/androidAot.ts b/pipeline/src/export/androidAot.tsnew file mode 100644index 000000000..def68b2be--- /dev/null+++ b/pipeline/src/export/androidAot.ts@@ -0,0 +1,75 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file androidAot.ts+ * @brief Compiled systems for an Android package: the NDK's clang, once per ABI+ * the package carries.+ *+ * The same C the desktop builds, and the same 64-bit handshake: a phone's+ * interpreter is the QuickJS the desktop host embeds, and a compiled system takes+ * its frame from ~10 us/entity to tens of ns there. What differs is only WHERE the+ * machine code comes from (a cross-compiler, not the host's cc) and where it is+ * put: `lib/<abi>/` of the APK, as a `lib*.so`, which the system linker finds by+ * its bare name for whichever ABI the phone installed. So the package config+ * names the library bare, and each ABI directory holds its own build of it.+ *+ * A 32-bit ABI is left out: the handshake carries the address width, and a module+ * built with 8-byte addresses is refused by a 4-byte host — that ABI's systems+ * stay interpreted rather than read half a pointer.+ */+import { existsSync } from 'node:fs';+import { androidSdk, requireNdk, ndkTool } from '../../../build-tools/utils/android.js';++/** The library a packaged Android game's compiled systems are, in every `lib/<abi>/`. */+export const ANDROID_AOT_LIBRARY = 'libestella_systems.so';++/** The lowest Android the package installs on (the manifest's minSdk); the code is built for it. */+const ANDROID_API = 29;++/** ABIs a compiled module is built for, and the clang target of each. 64-bit only, see the file comment. */+const ANDROID_AOT_TRIPLES: Readonly<Record<string, string>> = {+ 'arm64-v8a': 'aarch64-linux-android',+ 'x86_64': 'x86_64-linux-android',+};++/** One compiler invocation: the NDK's clang, aimed at one ABI. */+export interface AndroidAotCompiler {+ abi: string;+ cc: string;+ flags: string[];+}++/**+ * The compilers for the @p abis a package carries, or a reason there are none.+ * ABIs with no 64-bit triple are reported in `skipped`, not refused.+ */+export function androidAotCompilers(abis: readonly string[]): {+ compilers: AndroidAotCompiler[]; skipped: string[]; missing: string | null;+} {+ const skipped = abis.filter((abi) => !ANDROID_AOT_TRIPLES[abi]);+ const wanted = abis.filter((abi) => ANDROID_AOT_TRIPLES[abi]);+ if (wanted.length === 0) return { compilers: [], skipped, missing: null };+ let ndk: string;+ try {+ const sdk = androidSdk();+ ndk = requireNdk(sdk ?? '');+ } catch (err) {+ return { compilers: [], skipped, missing: err instanceof Error ? err.message : String(err) };+ }+ const clang = ndkTool(ndk, 'clang');+ if (!existsSync(clang)) return { compilers: [], skipped, missing: `the NDK at ${ndk} has no clang (${clang})` };+ return {+ compilers: wanted.map((abi) => ({+ abi, cc: clang,+ // A position-independent shared object the system linker loads; the+ // exports are the module's own ES_EXPORT names.+ flags: [`--target=${ANDROID_AOT_TRIPLES[abi]}${ANDROID_API}`, '-shared', '-fPIC'],+ })),+ skipped, missing: null,+ };+}++/** Whether this machine can build an Android module at all (the editor's prerequisite probe). */+export function hasAndroidAotCompiler(): boolean {+ return androidAotCompilers(['arm64-v8a']).compilers.length > 0;+}diff --git a/pipeline/src/export/exportGame.ts b/pipeline/src/export/exportGame.tsindex 3cc6b1377..0b8e32f16 100644--- a/pipeline/src/export/exportGame.ts+++ b/pipeline/src/export/exportGame.ts@@ -70,8 +70,9 @@ import { orientationCss, orientationOverlayHtml, orientationLockScript, orientatimport { PAGE_BACKGROUND, splashCss, splashHtml, type SplashLook } from './splash';import { emitIosXcodeProject, type IosProjectSources } from '../../../build-tools/utils/iosProject.js';import { emitAndroidGradleProject } from '../../../build-tools/utils/gradleProject.js';-import { androidTemplateSources } from '../../../build-tools/utils/nativeTemplate.js';+import { androidTemplateSources, packageAbis } from '../../../build-tools/utils/nativeTemplate.js';import { assembleApk, apkFileName } from '../../../build-tools/utils/apk.js';+import { ANDROID_AOT_LIBRARY, androidAotCompilers } from './androidAot';import { assembleAab, aabFileName } from '../../../build-tools/utils/aab.js';import { assembleDesktopApp } from '../../../build-tools/utils/desktopApp.js';import { emitSteamBuild, defaultDepotId } from '../../../build-tools/utils/steamChannel.js';@@ -1115,8 +1116,19 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>// because the build dialog looks for the same compiler this does, before// an export starts.let aot: PackagedGameConfig['aot'];+ /** Android: each packaged ABI's build of the compiled systems, for lib/<abi>/ of the package. */+ let androidAotLibs: Record<string, string[]> | undefined;const aotTarget = compileTargetFor(platform);- const foreignOs = aotTarget === 'native' ? foreignDesktopOses(opts.desktopTemplates) : [];+ const foreignOs = aotTarget === 'native' && platform === 'desktop' ? foreignDesktopOses(opts.desktopTemplates) : [];+ // An Android package is cross-compiled, once per ABI it carries; with no template+ // there are no ABIs and nothing to package them into.+ const androidCompilers = platform === 'android' && opts.androidTemplate+ ? androidAotCompilers(packageAbis(opts.androidTemplate, { emulator: opts.androidEmulatorAbi === true }))+ : null;+ if (androidCompilers && androidCompilers.skipped.length > 0) {+ warnings.push(`Compiled systems run interpreted on ${androidCompilers.skipped.join(', ')}: a compiled module is `+ + 'built for 64-bit ABIs, whose address width the engine handshake checks.');+ }if (aotTarget !== null && foreignOs.length > 0) {// A compiled system is machine code for ONE machine, and this assembles an// app per installed template. Half a package with AOT is worse than a@@ -1131,14 +1143,25 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>const built = await buildCompiledSystems(opts.root, {mode: opts.aotMode ?? 'release',target: aotTarget,- cc: aotTarget === 'native' ? findHostCC() : resolveEmcc(opts.emcc),+ cc: aotTarget === 'native' ? (platform === 'android' ? null : findHostCC()) : resolveEmcc(opts.emcc),run: runEmcc,+ ...(platform === 'android' ? {+ outputs: (androidCompilers?.compilers ?? []).map((c) => ({ id: c.abi, cc: c.cc, flags: c.flags, module: ANDROID_AOT_LIBRARY })),+ missing: androidCompilers?.missing+ ?? 'there is no Android NDK — install one (Android Studio, SDK Manager) or set ANDROID_NDK_HOME',+ } : {}),});if (!built.ok) {errors.push(...built.errors);return { ok: false, platform, outDir: absOut, included: cook.included.length, warnings, errors };}- if (built.modulePath && built.manifest) {+ if (platform === 'android' && built.modules && built.manifest) {+ progress({ phase: 'Compiling systems', detail: `${built.manifest.systems.length} system(s) for ${Object.keys(built.modules).join(', ')}` });+ // Not content: each ABI's library goes in lib/<abi>/, where the system linker+ // finds it by its bare name for the ABI the phone installed.+ androidAotLibs = Object.fromEntries(Object.entries(built.modules).map(([abi, file]) => [abi, [file]]));+ aot = { module: ANDROID_AOT_LIBRARY, manifest: built.manifest };+ } else if (built.modulePath && built.manifest) {progress({ phase: 'Compiling systems', detail: `${built.manifest.systems.length} system(s)` });const name = path.basename(built.modulePath);await mkdir(path.join(payloadDir, 'aot'), { recursive: true });@@ -1339,7 +1362,7 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>} else if (wantsProject) {progress({ phase: 'Writing Android Studio project' });androidProject = await emitAndroidGradleProject(- absOut, appConfig, androidTemplateSources(template), icon);+ absOut, appConfig, { ...androidTemplateSources(template), ...(androidAotLibs ? { extraLibs: androidAotLibs } : {}) }, icon);} else {progress({ phase: 'Assembling the APK' });const release = opts.minify && opts.androidKey@@ -1352,6 +1375,7 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>const assembly = {templateDir: template, contentDir: absOut, app: appConfig, key, icon,emulatorAbi: opts.androidEmulatorAbi === true,+ ...(androidAotLibs ? { extraLibs: androidAotLibs } : {}),};apkFile = path.join(absOut, apkFileName(appConfig.id));await writeFile(apkFile, assembleApk(assembly));diff --git a/pipeline/src/export/platformCatalog.ts b/pipeline/src/export/platformCatalog.tsindex 456ba7d0a..8bbf85f86 100644--- a/pipeline/src/export/platformCatalog.ts+++ b/pipeline/src/export/platformCatalog.ts@@ -769,6 +769,8 @@ export interface AotToolchains {emcc: string | null;/** The host's own C compiler, for a library a native host loads. */cc: string | null;+ /** Whether the Android NDK is here, which cross-compiles an Android package's module. Absent: not probed. */+ ndk?: boolean;}/**@@ -789,9 +791,11 @@ function withAotPrereq(// One probe per road: a machine with emcc and no cc packages for the web// and not for the desktop, and being sent to install the other toolchain// is worse than being told nothing.- if (target === 'wasm' ? toolchains.emcc : toolchains.cc) continue;+ // Android cross-compiles: its compiler is the NDK, not this machine's own cc.+ const android = row.id === 'android';+ if (target === 'wasm' ? toolchains.emcc : android ? toolchains.ndk !== false : toolchains.cc) continue;row.ready = false;- row.prereq = { kind: 'toolchain-missing', tool: target === 'wasm' ? 'emsdk' : 'hostcc' };+ row.prereq = { kind: 'toolchain-missing', tool: target === 'wasm' ? 'emsdk' : android ? 'ndk' : 'hostcc' };}return rows;}diff --git a/pipeline/src/project/platforms.ts b/pipeline/src/project/platforms.tsindex ab7b51230..8d5739e5e 100644--- a/pipeline/src/project/platforms.ts+++ b/pipeline/src/project/platforms.ts@@ -175,7 +175,7 @@ export type PlatformPrereq =* target missing them still exports its content. `emsdk` gates the export* itself, because the compiled module ships inside the package.*/-export type ToolchainPiece = 'xcode' | 'macos' | 'emsdk' | 'hostcc';+export type ToolchainPiece = 'xcode' | 'macos' | 'emsdk' | 'hostcc' | 'ndk';/*** WHICH machine this target's compiled systems are built for, or null where it@@ -188,8 +188,10 @@ export type ToolchainPiece = 'xcode' | 'macos' | 'emsdk' | 'hostcc';*/export function compileTargetFor(platform: ExportPlatform): 'wasm' | 'native' | null {if (platform === 'web' || isMiniGamePlatform(platform)) return 'wasm';- if (platform === 'desktop') return 'native';- if (platform === 'playable' || platform === 'android' || platform === 'ios') return null;+ // Android is native too: the same 64-bit module, built by the NDK for each ABI+ // the package carries (export/androidAot.ts). iOS still waits on its link step.+ if (platform === 'desktop' || platform === 'android') return 'native';+ if (platform === 'playable' || platform === 'ios') return null;// A project platform is a mini-game platform: the playable ones are chosen// inside the built-in target, not offered as a row of their own.return 'wasm';diff --git a/pipeline/tests/apk-extra-libs.test.ts b/pipeline/tests/apk-extra-libs.test.tsnew file mode 100644index 000000000..8876539c4--- /dev/null+++ b/pipeline/tests/apk-extra-libs.test.ts@@ -0,0 +1,79 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * An Android package carries what the export built per ABI (its compiled systems)+ * beside the template's own libraries: in lib/<abi>/, stored and page-aligned, so+ * the system linker maps it straight out of the APK and finds it by bare name.+ */+import { describe, it, expect } from 'vitest';+import { mkdtempSync, mkdirSync, writeFileSync, copyFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { assembleApk } from '../../build-tools/utils/apk.js';+import { readZip } from '../../build-tools/utils/zip.js';+import { debugSigningKey } from '../../build-tools/utils/androidKeystore.js';+import { ANDROID_AOT_LIBRARY } from '../src/export/androidAot';++const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');++/** Compression method and data offset of each entry, from the central directory. */+function layoutOf(apk: Buffer): Map<string, { method: number; dataAt: number }> {+ let end = apk.length - 22;+ while (apk.readUInt32LE(end) !== 0x06054b50) end--;+ const count = apk.readUInt16LE(end + 10);+ let p = apk.readUInt32LE(end + 16);+ const out = new Map<string, { method: number; dataAt: number }>();+ for (let i = 0; i < count; i++) {+ const method = apk.readUInt16LE(p + 10);+ const nameLen = apk.readUInt16LE(p + 28), extraLen = apk.readUInt16LE(p + 30), commentLen = apk.readUInt16LE(p + 32);+ const local = apk.readUInt32LE(p + 42);+ const name = apk.toString('utf8', p + 46, p + 46 + nameLen);+ out.set(name, { method, dataAt: local + 30 + apk.readUInt16LE(local + 26) + apk.readUInt16LE(local + 28) });+ p += 46 + nameLen + extraLen + commentLen;+ }+ return out;+}++describe('an APK with compiled systems', () => {+ it('packages each ABI\'s module in lib/<abi>/, stored and page-aligned, and ignores an ABI it does not carry', () => {+ const dir = mkdtempSync(path.join(tmpdir(), 'estella-apk-aot-'));+ try {+ const template = path.join(dir, 'template');+ for (const abi of ['arm64-v8a', 'x86_64']) {+ mkdirSync(path.join(template, 'lib', abi), { recursive: true });+ writeFileSync(path.join(template, 'lib', abi, 'libestella_js_host.so'), Buffer.from(`host ${abi}`));+ }+ copyFileSync(path.join(ROOT, 'native/android/host/AndroidManifest.xml.in'), path.join(template, 'AndroidManifest.xml.in'));+ copyFileSync(path.join(ROOT, 'native/icon.png'), path.join(template, 'icon.png'));+ const content = path.join(dir, 'content');+ mkdirSync(content, { recursive: true });+ writeFileSync(path.join(content, 'game.config.json'), '{}');+ const built: Record<string, string[]> = {};+ for (const abi of ['arm64-v8a', 'x86_64', 'mips']) {+ const file = path.join(dir, 'aot', abi, ANDROID_AOT_LIBRARY);+ mkdirSync(path.dirname(file), { recursive: true });+ writeFileSync(file, Buffer.from(`systems ${abi}`));+ built[abi] = [file];+ }++ const apk = assembleApk({+ templateDir: template, contentDir: content,+ app: { id: 'com.example.aot', name: 'Aot', version: '1.0', versionCode: 1 } as never,+ key: debugSigningKey(), emulatorAbi: true, extraLibs: built,+ });++ const entries = new Map(readZip(apk).map((e) => [e.name, e.data]));+ const layout = layoutOf(apk);+ for (const abi of ['arm64-v8a', 'x86_64']) {+ const name = `lib/${abi}/${ANDROID_AOT_LIBRARY}`;+ expect(entries.get(name)?.toString(), name).toBe(`systems ${abi}`);+ expect(layout.get(name)?.method, `${name} stored`).toBe(0);+ expect((layout.get(name)?.dataAt ?? 1) % 4096, `${name} page-aligned`).toBe(0);+ }+ expect([...entries.keys()].some((n) => n.startsWith('lib/mips/'))).toBe(false);+ } finally {+ rmSync(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });+ }+ });+});diff --git a/pipeline/tests/build-compiled-systems.test.ts b/pipeline/tests/build-compiled-systems.test.tsindex ca97d453d..4fbd02d0c 100644--- a/pipeline/tests/build-compiled-systems.test.ts+++ b/pipeline/tests/build-compiled-systems.test.ts@@ -19,6 +19,9 @@ import { buildCompiledSystems, readCompiledManifest } from '../src/bundle/buildCimport { projectShapeDigest } from '../../sdk/src/ecs/aot/abiDigest';import { emccPath } from '../../build-tools/utils/emscripten.js';import { findHostCC, nativeModuleExt } from '../../compiler/src/hostCC';+import { ANDROID_AOT_LIBRARY, androidAotCompilers } from '../src/export/androidAot';+import { androidSdk, ndkTool, requireNdk } from '../../build-tools/utils/android.js';+import { spawnSync } from 'node:child_process';const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');@@ -431,6 +434,51 @@ describe('the AOT build step, for a host that loads a library', () => {});+/**+ * A phone: no JIT, the same QuickJS the desktop host embeds, so this is where a+ * compiled system pays most. The one C, cross-compiled by the NDK once per 64-bit+ * ABI, each a shared object the system linker loads by its bare name.+ */+describe('the AOT build step, for an Android package', () => {+ const android = androidAotCompilers(['arm64-v8a', 'x86_64', 'armeabi-v7a']);+ const HAS_NDK = android.compilers.length > 0;++ it('leaves 32-bit ABIs out and says so', () => {+ expect(android.skipped).toEqual(['armeabi-v7a']);+ });++ it.skipIf(!HAS_NDK)('builds one ELF shared object per ABI, for that machine, exporting the module table', async () => {+ const root = project({ 'src/components.ts': COMPONENTS, 'src/systems.ts': PROMISED });+ const out = await buildCompiledSystems(root, {+ mode: 'release', target: 'native', cc: null, run,+ outputs: android.compilers.map((c) => ({ id: c.abi, cc: c.cc, flags: c.flags, module: ANDROID_AOT_LIBRARY })),+ });+ expect(out.ok, out.errors.join('; ')).toBe(true);+ expect(Object.keys(out.modules!).sort()).toEqual(['arm64-v8a', 'x86_64']);+ expect(out.manifest?.systems.map((s) => s.name)).toEqual(['MoveSystem']);+ const readelf = ndkTool(requireNdk(androidSdk() ?? ''), 'llvm-readelf');+ const machine = { 'arm64-v8a': 'AArch64', x86_64: 'Advanced Micro Devices X86-64' } as Record<string, string>;+ for (const [abi, file] of Object.entries(out.modules!)) {+ expect(path.basename(file)).toBe(ANDROID_AOT_LIBRARY);+ const header = spawnSync(readelf, ['-h', file], { encoding: 'utf8' }).stdout;+ expect(header, abi).toContain('DYN (Shared object file)');+ expect(header, abi).toContain(machine[abi]);+ // What aot::Module reads out of the library: no manifest file rides along.+ const symbols = spawnSync(readelf, ['--dyn-syms', file], { encoding: 'utf8' }).stdout;+ for (const name of ['es_abi_hash', 'es_systems', 'es_system_count']) expect(symbols, `${abi} ${name}`).toContain(name);+ }+ }, 120_000);++ it('says what is missing when there is no NDK', async () => {+ const root = project({ 'src/components.ts': COMPONENTS, 'src/systems.ts': PROMISED });+ const out = await buildCompiledSystems(root, {+ mode: 'release', target: 'native', cc: null, run, outputs: [], missing: 'there is no Android NDK',+ });+ expect(out.ok).toBe(false);+ expect(out.errors[0]).toMatch(/no Android NDK/);+ });+});+/*** Two builds of one engine over one project's shapes. Probed before the pairing* existed: both produced the SAME engineAbi and the SAME projectShapes, and thediff --git a/pipeline/tests/export-aot.test.ts b/pipeline/tests/export-aot.test.tsindex efcb583bd..649d7e961 100644--- a/pipeline/tests/export-aot.test.ts+++ b/pipeline/tests/export-aot.test.ts@@ -11,7 +11,7 @@* brought its own memory or a data section to write over the engine's.*/import { describe, it, expect } from 'vitest';-import { mkdtempSync, mkdirSync, writeFileSync, readFileSync } from 'node:fs';+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, copyFileSync, readdirSync } from 'node:fs';import { tmpdir } from 'node:os';import path from 'node:path';import { fileURLToPath } from 'node:url';@@ -19,6 +19,8 @@ import { exportGame } from '../src/export/exportGame';import { OFFICIAL_PACKAGES } from './officialPackagesDir';import { emccPath } from '../../build-tools/utils/emscripten.js';import { writeFakeSdkDist } from './fixtures/fakeSdkDist';+import { ANDROID_AOT_LIBRARY, androidAotCompilers } from '../src/export/androidAot';+import { readZip } from '../../build-tools/utils/zip.js';const HERE = path.dirname(fileURLToPath(import.meta.url));const HOSTS = path.join(HERE, '..', 'src', 'runtime');@@ -135,3 +137,36 @@ describe('the promised systems in a web package', () => {expect(WebAssembly.Module.exports(mod).map((e) => e.name)).toContain('es_sys_MoveSystem');});});++describe('the promised systems in an Android package', () => {+ const NDK = androidAotCompilers(['arm64-v8a']).compilers.length > 0;+ it('reports whether this gate could run at all', () => {+ if (!NDK) console.warn('[export-aot] NO ANDROID NDK — the Android case did NOT run.');+ });++ it.skipIf(!NDK)('cross-compiles them per ABI into lib/<abi>/ of the APK, and names the library bare', async () => {+ const f = setup({ 'src/components.ts': COMPONENTS, 'src/systems.ts': PROMISED, 'src/main.ts': MAIN });+ const template = path.join(f.root, '_android');+ for (const abi of ['arm64-v8a', 'x86_64']) {+ mkdirSync(path.join(template, 'lib', abi), { recursive: true });+ writeFileSync(path.join(template, 'lib', abi, 'libestella_js_host.so'), `host ${abi}`);+ }+ const ROOT = path.resolve(HERE, '../..');+ copyFileSync(path.join(ROOT, 'native/android/host/AndroidManifest.xml.in'), path.join(template, 'AndroidManifest.xml.in'));+ copyFileSync(path.join(ROOT, 'native/icon.png'), path.join(template, 'icon.png'));+ const res = await exportGame({+ root: f.root, entryScene: 'scenes/main.esscene', hostsDir: HOSTS, packagesDir: OFFICIAL_PACKAGES,+ scriptsEntry: 'src/main.ts', sdkDistDir: path.join(f.root, '_sdk'), wasmDir: path.join(f.root, '_wasm'),+ outDir: f.out, platform: 'android', androidTemplate: template, androidEmulatorAbi: true,+ });+ expect(res.errors).toEqual([]);+ const cfg = JSON.parse(readFileSync(path.join(f.out, 'game.config.json'), 'utf8')) as { aot?: { module: string; manifest: { systems: { name: string }[] } } };+ expect(cfg.aot?.module).toBe(ANDROID_AOT_LIBRARY);+ expect(cfg.aot?.manifest.systems.map((s) => s.name)).toEqual(['MoveSystem']);+ const apk = readdirSync(f.out).find((n) => n.endsWith('.apk'))!;+ const names = readZip(readFileSync(path.join(f.out, apk))).map((e) => e.name);+ for (const abi of ['arm64-v8a', 'x86_64']) expect(names).toContain(`lib/${abi}/${ANDROID_AOT_LIBRARY}`);+ // Not content: the module is not staged into assets as a desktop's is.+ expect(names.some((n) => n.startsWith('assets/aot/'))).toBe(false);+ }, 180_000);+});