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
refactor(native): the host writes only the bindings the engine cannot declare
yhh75cc15137701
diff --git a/.vscode/c_cpp_properties.json b/.vscode/c_cpp_properties.jsonindex 0a4c62b88..90c267214 100644--- a/.vscode/c_cpp_properties.json+++ b/.vscode/c_cpp_properties.json@@ -14,7 +14,7 @@"${workspaceFolder}/third_party/nlohmann","${workspaceFolder}/third_party/box2d/include","${workspaceFolder}/build/quickjs_headers",- "${workspaceFolder}/native/host_js",+ "${workspaceFolder}/native/host","${workspaceFolder}/third_party","${env:ESTELLA_DAWN_DIR}/include","${env:ESTELLA_DAWN_BUILD}/gen/include",@@ -87,7 +87,7 @@"name": "Native Host (Android)","includePath": ["${workspaceFolder}/src",- "${workspaceFolder}/native/host_js",+ "${workspaceFolder}/native/host","${workspaceFolder}/third_party","${workspaceFolder}/third_party/glm","${workspaceFolder}/third_party/stb",@@ -112,7 +112,7 @@"name": "Native Host (iOS)","includePath": ["${workspaceFolder}/src",- "${workspaceFolder}/native/host_js",+ "${workspaceFolder}/native/host","${workspaceFolder}/third_party","${workspaceFolder}/third_party/glm","${workspaceFolder}/third_party/stb",diff --git a/build-tools/cli.js b/build-tools/cli.jsindex f7af1928d..4760648da 100644--- a/build-tools/cli.js+++ b/build-tools/cli.js@@ -163,15 +163,15 @@ program.option('--target <target>', 'android or ios', 'android').option('--dawn <dir>', 'Dawn source dir (or ESTELLA_DAWN_DIR); see native/README.md').option('--dawn-build <dir>', 'Dawn arm64 build dir for this target (or ESTELLA_DAWN_BUILD)')- .option('--quickjs <dir>', 'QuickJS-ng source dir (or ESTELLA_QUICKJS_DIR); also builds the JS host')+ .option('--quickjs <dir>', 'QuickJS-ng source dir (or ESTELLA_QUICKJS_DIR)').option('--abi <abi>', 'Android ABI', 'arm64-v8a').option('--platform <platform>', 'Android platform', 'android-33').option('--ios-min <version>', 'iOS deployment target', '17.0').option('--simulator', 'iOS: build the simulator slice (needs a simulator Dawn)', false).option('--package', 'Android: also package a signed APK (aapt2 + zipalign + apksigner)', false)- .option('--host <host>', 'Android --package: js (QuickJS host) or cpp (smoke test)').option('--keystore <path>', 'Android --package: signing keystore (default: the debug one)')- .option('--content <dir>', 'Ship an exported project (cli exportGame --platform native) as the app content')+ .option('--jdk <dir>', 'JDK home for the APK step (else JAVA_HOME, or the JDK Android Studio bundles)')+ .option('--content <dir>', 'Ship an exported project (Package Project -> Android / iOS) as the app content').option('-v, --verbose', 'Verbose output', false).action(async (options) => {logger.setVerbose(options.verbose);@@ -186,8 +186,8 @@ programiosMin: options.iosMin,simulator: options.simulator,package: options.package,- host: options.host,keystore: options.keystore,+ jdk: options.jdk,content: options.content,});} catch (err) {diff --git a/build-tools/tasks/native.js b/build-tools/tasks/native.jsindex 27f0a9bf7..bb8cf61b9 100644--- a/build-tools/tasks/native.js+++ b/build-tools/tasks/native.js@@ -39,7 +39,10 @@ async function generateNativeBindings(rootDir, genDir, python) {// the binding TUs themselves, which this build compiles (see ESEngineSources).async function generateNativeFunctionBindings(rootDir, genDir, python) {const out = path.join(genDir, 'NativeFunctionBindings.generated.cpp');- const headers = ['RendererBindings.hpp', 'UIBindings.hpp'].map(+ // Every binding TU the native build compiles (see cmake/ESEngineSources.cmake).+ // ResourceManagerBindings is the texture surface the asset pipeline uploads+ // through: the host used to hand-write a second copy of it.+ const headers = ['RendererBindings.hpp', 'UIBindings.hpp', 'ResourceManagerBindings.hpp'].map((h) => path.join(rootDir, 'src', 'esengine', 'bindings', h));await runCommand(python, [path.join(rootDir, 'tools', 'eht.py'),@@ -74,8 +77,36 @@ async function generateSdkBundle(rootDir, genDir) {return headerPath;}-// Both generated artifacts go in the build tree; nothing committed can drift from-// the reflection / SDK source.+// Embed the host bootstrap (native/host/bootstrap.js) the same way. It is real+// JavaScript — the bridge install and the default init/update — so it lives as a+// .js file that can be linted and diffed, not as a C++ string literal.+async function generateBootstrap(rootDir, genDir) {+ const source = path.join(rootDir, 'native', 'host', 'bootstrap.js');+ if (!existsSync(source)) throw new Error(`Host bootstrap not found at ${source}.`);+ const header =+ '// native/host/bootstrap.js, embedded by `cli native` — DO NOT EDIT.\n'+ + '#pragma once\n'+ + 'static const char* kHostBootstrapJS = R"ESJS(\n'+ + readFileSync(source, 'utf8')+ + ')ESJS";\n';+ const headerPath = path.join(genDir, 'host_bootstrap.h');+ writeFileSync(headerPath, header, 'utf8');+ return headerPath;+}++// Stage the QuickJS public header where the editor's C++ config looks for it+// (`build/quickjs_headers`, in .vscode/c_cpp_properties.json). IntelliSense would+// otherwise need ESTELLA_QUICKJS_DIR exported into the session that launched the+// editor — a machine-specific env var, set outside the repo, that goes stale. One+// build now makes every host TU resolve.+async function stageEditorHeaders(rootDir, quickjs) {+ const dest = path.join(rootDir, 'build', 'quickjs_headers');+ await mkdir(dest, { recursive: true });+ await cp(path.join(quickjs, 'quickjs.h'), path.join(dest, 'quickjs.h'));+}++// Every generated artifact goes in the build tree; nothing committed can drift+// from the reflection / SDK / bootstrap source.async function prepareGenerated(rootDir, buildDir, quickjs) {if (!existsSync(quickjs)) {throw new Error(`QuickJS source dir not found: ${quickjs}. Clone `@@ -90,6 +121,9 @@ async function prepareGenerated(rootDir, buildDir, quickjs) {await generateNativeFunctionBindings(rootDir, genDir, python);logger.step('Embedding the real SDK bundle (dist/index.native.bundled.js)...');await generateSdkBundle(rootDir, genDir);+ logger.step('Embedding the host bootstrap (native/host/bootstrap.js)...');+ await generateBootstrap(rootDir, genDir);+ await stageEditorHeaders(rootDir, quickjs);return genDir;}@@ -139,7 +173,7 @@ async function buildAndroidHost(options) {'-DCMAKE_BUILD_TYPE=Release',// Emit build-native/compile_commands.json so editor IntelliSense (the// "Native Host" c_cpp_properties config) resolves the NDK / Dawn / QuickJS- // includes for native/host_js without hardcoding any machine paths.+ // includes for native/host without hardcoding any machine paths.'-DCMAKE_EXPORT_COMPILE_COMMANDS=ON',`-DESTELLA_DAWN_DIR=${dawnDir}`,`-DESTELLA_DAWN_BUILD=${dawnBuild}`,@@ -153,15 +187,12 @@ async function buildAndroidHost(options) {logger.step('Building native host...');await runCommand(cmake, ['--build', buildDir, '-j', String(getCpuCount())], { cwd: rootDir });- logger.success(`Native host: ${path.join('build-native', 'libestella_host.so')}`);- if (quickjs) {- logger.success(`JS host: ${path.join('build-native', 'libestella_js_host.so')}`);- }+ logger.success(`Host: ${path.join('build-native', 'libestella_js_host.so')}`);if (options.package) {await packageNativeApk({- host: options.host || (quickjs ? 'js' : 'cpp'),- dawnBuild, abi, platform, keystore: options.keystore, content: options.content,+ dawnBuild, abi, platform, keystore: options.keystore, jdk: options.jdk,+ content: options.content,});}}diff --git a/build-tools/tasks/nativePackage.js b/build-tools/tasks/nativePackage.jsindex 3b9bc6b13..a401e46b6 100644--- a/build-tools/tasks/nativePackage.js+++ b/build-tools/tasks/nativePackage.js@@ -12,34 +12,21 @@ import { mkdir, copyFile, cp, rm } from 'fs/promises';import config from '../build.config.js';import * as logger from '../utils/logger.js';import { runCommand } from '../utils/emscripten.js';-import { requireSdk, requireNdk, buildTool, platformJar, ndkTool, ndkLibcxxShared } from '../utils/android.js';+import { requireSdk, requireNdk, buildTool, platformJar, ndkTool, ndkLibcxxShared, javaHome, jdkTool } from '../utils/android.js';-const HOSTS = {- // The product-shaped runtime: the QuickJS host + the SDK + a game asset.- js: {- manifest: 'host_js',- library: 'libestella_js_host.so',- assets: ['game.js', 'logo.png'],- apk: 'estella-js-host.apk',- },- // The pure-C++ smoke test: one ECS scene, no JS, no assets.- cpp: {- manifest: 'host_cpp',- library: 'libestella_host.so',- assets: [],- apk: 'estella-host.apk',- },-};+const HOST_LIBRARY = 'libestella_js_host.so';+const HOST_APK = 'estella-js-host.apk';+const HOST_MANIFEST = 'host';// A debug keystore is enough to sideload; Android Studio uses the same one. Create// it on first use so packaging never stops to ask for credentials.-async function debugKeystore() {+async function debugKeystore(jdk) {const home = process.env.HOME || process.env.USERPROFILE || '';const keystore = path.join(home, '.android', 'debug.keystore');if (existsSync(keystore)) return keystore;logger.step('Creating the Android debug keystore...');await mkdir(path.dirname(keystore), { recursive: true });- await runCommand('keytool', [+ await runCommand(jdkTool('keytool', jdk), ['-genkeypair', '-keystore', keystore, '-storepass', 'android', '-keypass', 'android','-alias', 'androiddebugkey', '-keyalg', 'RSA', '-keysize', '2048', '-validity', '10000','-dname', 'CN=Android Debug,O=Android,C=US',@@ -49,21 +36,23 @@ async function debugKeystore() {// APKs are zips; `jar` ships with the JDK that apksigner already requires, so it// is the one archiver we can count on wherever packaging runs.-async function addToApk(apk, stagingDir) {- await runCommand('jar', ['ufM', apk, '-C', stagingDir, 'lib']);+//+// It carries the ASSETS too, rather than letting `aapt2 link -A` do it: on Windows+// aapt2 writes nested asset paths with backslashes ("assets/assets\scenes\x"), and+// a zip entry name must use forward slashes — so AAssetManager could not open+// anything in a subdirectory. Invisible while the packaged content was a handful+// of flat files; every real project export has directories.+async function addToApk(apk, stagingDir, entries, jdk) {+ await runCommand(jdkTool('jar', jdk), ['ufM', apk, ...entries.flatMap((e) => ['-C', stagingDir, e])]);}export async function packageNativeApk(options = {}) {- const hostKey = (options.host || 'js').toLowerCase();- const host = HOSTS[hostKey];- if (!host) throw new Error(`Unknown --host ${hostKey} (expected js or cpp).`);-const rootDir = config.paths.root;const buildDir = path.join(rootDir, 'build-native');- const library = path.join(buildDir, host.library);+ const library = path.join(buildDir, HOST_LIBRARY);if (!existsSync(library)) {- throw new Error(`${host.library} not found in build-native/. Build it first: `- + `node build-tools/cli.js native${hostKey === 'js' ? ' --quickjs <dir>' : ''} --dawn <src> --dawn-build <build>.`);+ throw new Error(`${HOST_LIBRARY} not found in build-native/. Build it first: `+ + 'node build-tools/cli.js native --quickjs <dir> --dawn <src> --dawn-build <build>.');}const dawnBuild = options.dawnBuild || process.env.ESTELLA_DAWN_BUILD;@@ -76,61 +65,66 @@ export async function packageNativeApk(options = {}) {const abi = options.abi || 'arm64-v8a';const platform = options.platform || 'android-33';- const staging = path.join(buildDir, `apk-${hostKey}`);+ const staging = path.join(buildDir, 'apk');const libDir = path.join(staging, 'lib', abi);await rm(staging, { recursive: true, force: true });await mkdir(libDir, { recursive: true });logger.step('Staging the native libraries...');- await copyFile(library, path.join(libDir, host.library));+ await copyFile(library, path.join(libDir, HOST_LIBRARY));await copyFile(ndkLibcxxShared(ndk), path.join(libDir, 'libc++_shared.so'));// Dawn carries debug info an APK does not need — it dominates the payload.await runCommand(ndkTool(ndk, 'llvm-strip'), ['--strip-all', '-o', path.join(libDir, 'libwebgpu_dawn.so'), dawnLib,]);- // assets/ is what the host's readAsset() sees. `--content <dir>` ships an- // exported project (cooked assets + manifests + scenes + game.config.json);- // without it the built-in demo assets ride along instead.+ // assets/ is what the host's readAsset() sees, and what goes in is an editor+ // export — cooked assets + manifests + scenes + game.config.json. A whole-+ // directory copy, so nothing here carries a file list that could drift from+ // what the export actually wrote.let assetsDir = null;if (options.content) {const content = path.isAbsolute(options.content) ? options.content : path.join(rootDir, options.content);if (!existsSync(content)) throw new Error(`--content dir not found: ${content}`);assetsDir = path.join(staging, 'assets');- await cp(content, assetsDir, { recursive: true });logger.step(`Staging exported content from ${path.relative(rootDir, content)}...`);- } else if (host.assets.length) {- assetsDir = path.join(staging, 'assets');- await mkdir(assetsDir, { recursive: true });- for (const asset of host.assets) {- await copyFile(path.join(rootDir, 'native', 'host_js', asset), path.join(assetsDir, asset));- }+ await cp(content, assetsDir, { recursive: true });+ } else {+ // Nothing to run: the host boots game.config.json and there is no built-in+ // fallback, by design — the packaged game takes the same path every real+ // game takes.+ throw new Error('The host needs a project to run: pass --content <dir> from '+ + "Package Project -> Android (or `exportGame({ platform: 'android' })`).");}const unsigned = path.join(staging, 'unsigned.apk');- const aligned = path.join(buildDir, host.apk);+ const aligned = path.join(buildDir, HOST_APK);logger.step('Linking resources (aapt2)...');+ // aapt2 produces the base APK from the manifest alone; the payload (libraries+ // and assets) is added below, where the entry names are ours to control.await runCommand(buildTool(sdk, 'aapt2'), ['link',- '--manifest', path.join(rootDir, 'native', 'android', host.manifest, 'AndroidManifest.xml'),+ '--manifest', path.join(rootDir, 'native', 'android', HOST_MANIFEST, 'AndroidManifest.xml'),'-I', platformJar(sdk, platform),- ...(assetsDir ? ['-A', assetsDir] : []),'-o', unsigned,]);- logger.step('Adding the native libraries...');- await addToApk(unsigned, staging);+ logger.step('Adding the native libraries and the game...');+ await addToApk(unsigned, staging, ['lib', 'assets'], options.jdk);logger.step('Aligning + signing...');await rm(aligned, { force: true });await runCommand(buildTool(sdk, 'zipalign'), ['-f', '4', unsigned, aligned]);- const keystore = options.keystore || await debugKeystore();+ const keystore = options.keystore || await debugKeystore(options.jdk);+ // apksigner is a launcher script that finds java through JAVA_HOME; hand it the+ // JDK we located so it works on a machine that never exported one.+ const home = javaHome(options.jdk);await runCommand(buildTool(sdk, 'apksigner'), ['sign', '--ks', keystore,...(options.keystore ? [] : ['--ks-pass', 'pass:android', '--key-pass', 'pass:android','--ks-key-alias', 'androiddebugkey']),aligned,- ]);+ ], home ? { env: { ...process.env, JAVA_HOME: home } } : undefined);logger.success(`APK: ${path.relative(rootDir, aligned)}`);logger.info('Install it with: adb install -r ' + path.relative(rootDir, aligned));diff --git a/build-tools/utils/android.js b/build-tools/utils/android.jsindex 8e1ecd35d..32cd27e6a 100644--- a/build-tools/utils/android.js+++ b/build-tools/utils/android.js@@ -61,6 +61,45 @@ export function platformJar(sdk, platform) {return jar;}+/**+ * The JDK the APK step runs on. Packaging needs one for `jar` and `keytool`, and+ * apksigner needs one to launch at all — but a machine that got its JDK through+ * Android Studio has it bundled beside the IDE with nothing exported, so none of+ * them are on PATH. Looks where a JDK actually lives; null when there is none.+ *+ * @param explicit An explicitly configured JDK home (`--jdk`), which always wins.+ */+export function javaHome(explicit) {+ const roots = [+ explicit,+ process.env.ESTELLA_JDK,+ process.env.JAVA_HOME,+ // Android Studio's bundled runtime (JetBrains Runtime), at its default+ // install location per platform.+ ...(process.platform === 'darwin'+ ? ['/Applications/Android Studio.app/Contents/jbr/Contents/Home']+ : process.platform === 'win32'+ ? [+ path.join(process.env['ProgramFiles'] || 'C:\\Program Files', 'Android', 'Android Studio', 'jbr'),+ path.join(process.env['LOCALAPPDATA'] || '', 'Programs', 'Android Studio', 'jbr'),+ ]+ : ['/opt/android-studio/jbr', path.join(process.env.HOME || '', 'android-studio', 'jbr')]),+ ].filter(Boolean);+ return roots.find((root) => existsSync(path.join(root, 'bin', 'java' + exe))) ?? null;+}++/** A JDK tool (`jar`, `keytool`) from {@link javaHome}, or from PATH when a JDK is+ * already exported there. */+export function jdkTool(name, explicit) {+ const home = javaHome(explicit);+ if (home) return path.join(home, 'bin', name + exe);+ if (process.env.PATH?.split(path.delimiter).some((dir) => existsSync(path.join(dir, name + exe)))) {+ return name;+ }+ throw new Error(`No JDK found for \`${name}\` (the APK step needs one, as does apksigner). `+ + 'Set JAVA_HOME, or pass --jdk <dir> — Android Studio bundles one at <install>/jbr.');+}+/** The NDK's LLVM toolchain dir — its host tag is the only entry under prebuilt/. */function llvmPrebuilt(ndk) {const prebuilt = path.join(ndk, 'toolchains', 'llvm', 'prebuilt');diff --git a/build-tools/utils/emscripten.js b/build-tools/utils/emscripten.jsindex fb70df864..ed889d2b5 100644--- a/build-tools/utils/emscripten.js+++ b/build-tools/utils/emscripten.js@@ -204,11 +204,18 @@ export function runCommand(command, args, options = {}) {logger.debug(`Running: ${command} ${args.join(' ')}`);- const proc = spawn(command, args, {+ // Windows runs these through cmd, which re-splits the whole line on spaces:+ // an unquoted `C:\Program Files\...` (where the Android SDK and a bundled+ // JDK normally live) would arrive as two arguments. Quote what needs it —+ // only under the shell, since a direct spawn passes argv through intact.+ const shell = process.platform === 'win32';+ const quoted = (s) => (shell && /\s/.test(s) && !/^".*"$/.test(s) ? `"${s}"` : s);++ const proc = spawn(quoted(command), args.map(quoted), {cwd,env: { ...process.env, ...env },stdio: silent ? 'pipe' : 'inherit',- shell: process.platform === 'win32',+ shell,});let stdout = '';diff --git a/cmake/ESEngineSources.cmake b/cmake/ESEngineSources.cmakeindex ce536d0aa..60cba7f9c 100644--- a/cmake/ESEngineSources.cmake+++ b/cmake/ESEngineSources.cmake@@ -59,6 +59,10 @@ if(NOT ES_BUILD_WEB AND NOT ES_BUILD_WXGAME)list(APPEND ESENGINE_SOURCES${ESENGINE_ROOT}/src/esengine/bindings/RendererBindings.cpp${ESENGINE_ROOT}/src/esengine/bindings/UIBindings.cpp+ # The texture surface the asset pipeline uploads through. Native took a+ # hand-written copy of these for a while, drifting from the web's; it now+ # compiles the same TU and registers the same rm_* entry points.+ ${ESENGINE_ROOT}/src/esengine/bindings/ResourceManagerBindings.cpp# activeCtx()'s unset fallback. A host that installs its own context (the# native one does, at boot) never reaches it, but the inline accessor# references it, so the definition has to link.diff --git a/native/CMakeLists.txt b/native/CMakeLists.txtindex 9a5ea156e..39a40f5a4 100644--- a/native/CMakeLists.txt+++ b/native/CMakeLists.txt@@ -75,7 +75,7 @@ set(ESENGINE_ROOT "${REPO}")list(APPEND CMAKE_MODULE_PATH "${REPO}/cmake")set(ES_ENABLE_WEBGPU ON)# Text is on: the SDK's `Text` draws through the shared glyph atlas (the host-# rasterizes — see host_js/glyph_raster.cpp — and needs the engine's own+# rasterizes — see host/media/glyph_raster.cpp — and needs the engine's own# SdfGenerator so both platforms encode the field identically), and the C++# BitmapText path comes along with it. Neither needs freetype/msdfgen.set(ES_ENABLE_BITMAP_TEXT ON)@@ -90,19 +90,11 @@ target_include_directories(esengine PUBLICtarget_compile_definitions(esengine PUBLIC ES_ENABLE_WEBGPU ES_ENABLE_BITMAP_TEXT) # NOT ES_PLATFORM_WEBtarget_link_libraries(esengine PUBLIC glm yogacore webgpu_dawn)-# Reference host: boots EstellaContext with an injected WebGPUDevice over the-# NativeActivity's ANativeWindow and renders one ECS scene. See host_cpp/main.cpp.-if(ANDROID)- add_library(estella_host SHARED host_cpp/main.cpp)- target_link_libraries(estella_host esengine native_app_glue android log)- set_target_properties(estella_host PROPERTIES LINK_FLAGS "-u ANativeActivity_onCreate")-endif()--# JS host (opt-in): a QuickJS game script drives the engine through the-# EHT-generated bindings + the real SDK ptrAccessors. Built only when QuickJS is-# provided; the `node build-tools/cli.js native --quickjs <dir>` orchestration-# fetches QuickJS, generates NativeBindings.generated.cpp (single reflection-# source) and ptraccessors_js.h into ESTELLA_NATIVE_GEN_DIR, then configures this.+# The host (opt-in): a QuickJS runtime drives the engine through the EHT-generated+# bindings + the real SDK. Built only when QuickJS is provided; the+# `node build-tools/cli.js native --quickjs <dir>` orchestration fetches QuickJS,+# generates NativeBindings.generated.cpp (single reflection source), ptraccessors_js.h,+# the SDK bundle and bootstrap.js into ESTELLA_NATIVE_GEN_DIR, then configures this.if(ESTELLA_QUICKJS_DIR)if(NOT ESTELLA_NATIVE_GEN_DIR)set(ESTELLA_NATIVE_GEN_DIR "${CMAKE_BINARY_DIR}/gen")@@ -131,25 +123,38 @@ if(ESTELLA_QUICKJS_DIR)target_compile_options(qjs PRIVATE -Wno-unused -Wno-sign-compare)# basis_universal transcoder (KTX2 -> ETC2/ASTC/BC), one big vendored TU behind- # host_js/ktx2_decode.cpp, plus basis's bundled single-file zstd decoder (KTX2+ # host/media/ktx2_decode.cpp, plus basis's bundled single-file zstd decoder (KTX2# zstd supercompression). Third-party, so silence their warnings.set(BASIS_TRANSCODER "${TP}/basis_universal/transcoder/basisu_transcoder.cpp")set(BASIS_ZSTD "${TP}/basis_universal/zstd/zstddeclib.c")set_source_files_properties("${BASIS_TRANSCODER}" "${BASIS_ZSTD}" PROPERTIES COMPILE_OPTIONS "-w")- # host_js/host_core.cpp is the platform-independent host; each platform adds its own- # glue TU (the event loop, the window, the packaged assets).+ # The host, by concern: the runtime + the es_* bindings + the frame are shared,+ # and each platform adds its own glue TU (the event loop, the window, the+ # packaged assets). See native/host/Host.hpp for the layering.+ set(HOST_SOURCES+ host/Host.cpp+ host/Runtime.cpp+ host/EsnShim.cpp+ host/bindings/EcsBindings.cpp+ host/bindings/RenderBindings.cpp+ host/bindings/AssetBindings.cpp+ host/bindings/AudioBindings.cpp+ host/bindings/NetBindings.cpp+ host/media/native_audio.cpp+ host/media/ktx2_decode.cpp+ host/media/glyph_raster.cpp+ "${BASIS_TRANSCODER}" "${BASIS_ZSTD}" "${NATIVE_BINDINGS}" "${NATIVE_FN_BINDINGS}")+if(ESTELLA_IOS)# Static: the thin Xcode app (native/ios) links this plus the libraries- # below. -ObjC on the app keeps the Obj-C classes in main_ios.mm alive.- add_library(estella_js_host STATIC host_js/host_core.cpp host_js/main_ios.mm- host_js/native_audio.cpp host_js/ktx2_decode.cpp host_js/glyph_raster.cpp- "${BASIS_TRANSCODER}" "${BASIS_ZSTD}" "${NATIVE_BINDINGS}" "${NATIVE_FN_BINDINGS}")+ # below. -ObjC on the app keeps the Obj-C classes in platform/ios.mm alive.+ add_library(estella_js_host STATIC ${HOST_SOURCES} host/platform/ios.mm)# miniaudio's CoreAudio backend uses AVAudioSession (Obj-C), so its TU must# be Objective-C++ on Apple; it also forces MA_NO_RUNTIME_LINKING there, so# the audio frameworks are linked at build time (the app links the merged# archive, so these also live in native/ios/project.yml).- set_source_files_properties(host_js/native_audio.cpp PROPERTIES+ set_source_files_properties(host/media/native_audio.cpp PROPERTIESCOMPILE_OPTIONS "-x;objective-c++")target_link_libraries(estella_js_host esengine qjs"-framework UIKit" "-framework QuartzCore" "-framework Foundation"@@ -165,16 +170,16 @@ if(ESTELLA_QUICKJS_DIR)else()# Android: plain C++; miniaudio dlopens AAudio/OpenSL at runtime (no extra# link libs). native_audio.cpp's Obj-C paths are __APPLE__-guarded out.- add_library(estella_js_host SHARED host_js/host_core.cpp host_js/main_android.cpp- host_js/native_audio.cpp host_js/ktx2_decode.cpp host_js/glyph_raster.cpp- "${BASIS_TRANSCODER}" "${BASIS_ZSTD}" "${NATIVE_BINDINGS}" "${NATIVE_FN_BINDINGS}")+ add_library(estella_js_host SHARED ${HOST_SOURCES} host/platform/android.cpp)target_link_libraries(estella_js_host esengine qjs native_app_glue android log)set_target_properties(estella_js_host PROPERTIES LINK_FLAGS "-u ANativeActivity_onCreate")endif()- # host_js/ holds esn_shim.hpp + host_core.hpp (the generated TU includes the shim);- # the gen dir holds ptraccessors_js.h and the embedded SDK bundle; third_party/miniaudio- # is the audio engine header.+ # host/ is the include root: every host TU spells its siblings from there+ # ("Bindings.hpp", "media/glyph_raster.hpp"), and the generated TUs include+ # esn_shim.hpp by name. The gen dir holds ptraccessors_js.h, the embedded SDK+ # bundle and the embedded bootstrap; third_party/miniaudio is the audio engine+ # header.target_include_directories(estella_js_host PRIVATE- "${CMAKE_CURRENT_SOURCE_DIR}/host_js" "${ESTELLA_NATIVE_GEN_DIR}" "${TP}/miniaudio"+ "${CMAKE_CURRENT_SOURCE_DIR}/host" "${ESTELLA_NATIVE_GEN_DIR}" "${TP}/miniaudio""${TP}/basis_universal/transcoder")endif()diff --git a/native/README.md b/native/README.mdindex 0af39a5fe..2be8f3819 100644--- a/native/README.md+++ b/native/README.md@@ -7,25 +7,36 @@ Vulkan on Android) — a real native app, **not a WebView**. Game scripts run onembedded JS engine ([QuickJS-ng](https://github.com/quickjs-ng/quickjs)); theengine runs native (full speed), so only the game script is interpreted.-This directory holds two reference hosts + the build recipe:--- **`host_cpp/`** — a pure-C++ host that renders one ECS scene (no JS). A smoke test- for the engine core on native Dawn. Android only; always built there.-- **`host_js/`** — the JS host: a QuickJS game script drives the engine through the- **real esengine SDK**. The SDK is bundled to one file- (`dist/index.native.bundled.js`, installing `ESEngine`) and the game authors with- `ESEngine.createNativeWorld()` — the same `World` the web build uses. Built when- you pass `--quickjs` (this is the product-shaped runtime). It is one host with a- platform seam, not one per OS:- - `host_js/host_core.{hpp,cpp}` — Dawn bring-up, the `es_*` bindings, the SDK bundle- and the frame. Platform-independent; everything that differs sits behind- `eshost::Platform`.- - `host_js/main_android.cpp` — NativeActivity, APK assets, Vulkan, the ALooper loop.- - `host_js/main_ios.mm` — a CAMetalLayer view, bundle assets, Metal, CADisplayLink.-- **`android/`** — the APK manifests (`host_cpp/`, `host_js/`), packaged by `--package`.+This directory holds the host and the build recipe:++- **`host/`** — the app. A QuickJS runtime drives the engine through the **real+ esengine SDK**, bundled to one file (`dist/index.native.bundled.js`, installing+ `ESEngine`); an editor export boots on it through the same `App` and `World` the+ web build uses. One host with a platform seam, not one per OS:+ - `Host.{hpp,cpp}` — the contract a platform implements (`eshost::Platform`) and+ the entry points its event loop drives: boot, the frame, lifecycle.+ - `Runtime.{hpp,cpp}` — the QuickJS runtime and the state the host shares: the+ environment the language does not ship (console, timers, a clock), the eval ++ bytecode cache, and the layered boot (SDK bundle → bootstrap → project).+ - `bootstrap.js` — the host's own JavaScript (the bridge install and the default+ init/update), embedded at build time. A real .js file, not a C++ literal.+ - `bindings/` — the `es_*` surface, one TU per pillar (Ecs, Render, Assets,+ Audio, Net). Only what cannot be generated; see below.+ - `EsnShim.cpp` + `esn_shim.hpp` — what the GENERATED bindings call: the engine+ singletons, entity round-tripping, the JS value readers.+ - `media/` — glyph rasterization, KTX2 transcode, the miniaudio engine.+ - `platform/android.cpp` — NativeActivity, APK assets, Vulkan, the ALooper loop.+ - `platform/ios.mm` — a CAMetalLayer view, bundle assets, Metal, CADisplayLink.+- **`android/`** — the APK manifest, packaged by `--package`.- **`ios/`** — the Xcode app shell (xcodegen) that signs and packages the iOSbuild. It is only an entry point; the app lives in the static library.+There is no built-in demo game and no second, JS-free host. What runs is an editor+export, always: a parallel content path drifts from the one every real game takes,+and boot already separates the layers — the engine core, Dawn and the surface are+all up (and logged) before the first line of JS runs, so a failure names its own+layer.+Dawn and QuickJS are **not vendored** (multi-GB / separate project); the recipefetches them, the way Dawn fetches its own deps. Nothing here is compiled by theweb/emscripten build or CI — it is inert until you run the native build below.@@ -40,10 +51,29 @@ the tree:| Render surface | `WebGPUDevice::configureSurface(NativeSurface)` | `CAMetalLayer*` / `ANativeWindow*` → `WGPUSurface` (commit `bfc495da`) || Instance / present | `WebGPUDevice(device, instance)` + `present()` | host shares its instance; flips the swapchain (native-only) || GL gate | `EstellaContext` under `ES_PLATFORM_WEB` | native drops the WebGL entry |-| Glyph source | `Platform::loadFont` + `host_js/glyph_raster.cpp` | the device has no 2D canvas: the OS names a font file, stb_truetype rasterizes, the engine's own `sdfFromAlpha` encodes |+| Glyph source | `Platform::loadFont` + `host/media/glyph_raster.cpp` | the device has no 2D canvas: the OS names a font file, stb_truetype rasterizes, the engine's own `sdfFromAlpha` encodes || Bindings | `python -m eht --native-output` | `es_set_<C>` / `es_<C>_buffer` from the same reflection as the web embind bindings |+| Entry points | `python -m eht --native-functions` | `es_renderer_*`, `es_uiLayout_*`, `es_rm_*` — QuickJS wrappers over the SAME `bindings/*.hpp` declarations embind registers || Data marshalling | `sdk/src/ecs/ptrAccessors.generated.ts` | POD components are wasm32/arm64 layout-identical → the generated accessors write native component memory unchanged (via a zero-copy `ArrayBuffer`) |-| Host platform | `eshost::Platform` (`host_js/host_core.hpp`) | packaged assets, cache dir, backend, window surface + size, log — the only things the two OS glue files answer differently |+| Host platform | `eshost::Platform` (`host/Host.hpp`) | packaged assets, cache dir, backend, window surface + size, log — the only things the two OS glue files answer differently |++### What is hand-written, and why++The `es_*` globals the SDK reads off `globalThis` are mostly GENERATED, from the+declarations embind registers on the web — so one implementation serves both+platforms, and both get its `BoundarySpan` validation. `native/host/bindings/`+holds only what has no generated form:++| Kept by hand | Why |+|---|---|+| entity + hierarchy | the web reaches the registry as an embind **class**; no binding header declares this surface |+| KTX2 transcode, glyph rasterization | native-only — the web decodes with WebGL2 + a wasm transcoder, and rasterizes on a 2D canvas |+| surface size, camera list, texture dimensions | their web siblings return an `emscripten::val`, which the boundary cannot marshal |+| assets, fetch, audio, cache, UTF-8, console/timers | the host's answer to what a browser hands the web build for free. There is nothing in the engine to generate them from |++Everything else — the frame, the UI layout, the whole texture surface, the text+batch — comes from EHT. Adding an entry point to a `bindings/*.hpp` is all it+takes for the device to have it.## Build (Android arm64)@@ -67,43 +97,46 @@ cmake -S "$DAWN" -B "$DAWN/out-android" -G Ninja \cmake --build "$DAWN/out-android" --target webgpu_dawn```-**Build the hosts** through the orchestrated task:+**Build the host** through the orchestrated task. Build the SDK bundle first (it+produces the QuickJS-loadable `dist/index.native.bundled.js`), clone QuickJS-ng+(core is dtoa/libregexp/libunicode/quickjs.c), and pass `--quickjs`:```sh-# C++ host only.-node build-tools/cli.js native --dawn "$DAWN" --dawn-build "$DAWN/out-android"--# + JS host: build the SDK bundle first (produces the QuickJS-loadable-# dist/index.native.bundled.js), clone QuickJS-ng (core is-# dtoa/libregexp/libunicode/quickjs.c), and pass --quickjs. The task generates,-# into build-native/gen/ (never committed, so nothing can drift from its source):-# * NativeBindings.generated.cpp — from the SAME reflection as the web bindings-# (python -m eht --native-output ... --native-only)-# * esengine_bundle.h — the real SDK bundle embedded as a C string(cd sdk && pnpm run build)git clone --depth 1 https://github.com/quickjs-ng/quickjs "$QJS"node build-tools/cli.js native --dawn "$DAWN" --dawn-build "$DAWN/out-android" --quickjs "$QJS"```+The task generates, into `build-native/gen/` (never committed, so nothing can+drift from its source):++* `NativeBindings.generated.cpp` — per-component accessors, from the SAME+ reflection as the web bindings (`eht --native-output ... --native-only`)+* `NativeFunctionBindings.generated.cpp` — the engine's binding entry points, from+ the same `bindings/*.hpp` declarations embind registers (`eht --native-functions`)+* `esengine_bundle.h` / `host_bootstrap.h` — the real SDK bundle and the host+ bootstrap, embedded as C strings+Paths may also come from `ESTELLA_DAWN_DIR` / `ESTELLA_DAWN_BUILD` /-`ESTELLA_QUICKJS_DIR`. Outputs: `build-native/libestella_host.so`, and with-`--quickjs`, `build-native/libestella_js_host.so`.+`ESTELLA_QUICKJS_DIR`. Output: `build-native/libestella_js_host.so`.**Package a signed APK** by adding `--package` — the Android counterpart of whatXcode does for `native/ios`, and still no gradle (a NativeActivity has no Java):```shnode build-tools/cli.js native --dawn "$DAWN" --dawn-build "$DAWN/out-android" \- --quickjs "$QJS" --package # --host cpp for the smoke-test APK+ --quickjs "$QJS" --package --content dist-androidadb install -r build-native/estella-js-host.apk```-It runs `aapt2 link` over `native/android/host_{js,cpp}/AndroidManifest.xml`, stages+It runs `aapt2 link` over `native/android/host/AndroidManifest.xml` to produce the+base APK from the manifest, then adds the payload with `jar`:`lib/arm64-v8a/{libestella*_host.so,libwebgpu_dawn.so,libc++_shared.so}` (Dawn-stripped with the NDK's `llvm-strip`), packs the game and its content into-`assets/` where the host's `readAsset()` looks, then `zipalign -f 4` and-`apksigner sign`. Signing uses the Android debug keystore — created on first use —-unless you pass `--keystore`.+stripped with the NDK's `llvm-strip`) and the exported project under `assets/`,+where the host's `readAsset()` looks. Then `zipalign -f 4` and `apksigner sign`.+Signing uses the Android debug keystore — created on first use — unless you pass+`--keystore`. The JDK those steps need is located the way the SDK and NDK are+(`JAVA_HOME`, or the one Android Studio bundles); `--jdk <dir>` overrides.## Build (iOS arm64)@@ -128,7 +161,7 @@ cmake --build "$DAWN/out-ios" --target webgpu_dawn```**Build the host, then run it from Xcode.** There is no pure-C++ reference host on-iOS — the app *is* the JS host, so `--quickjs` is required:+iOS — the app *is* the host, so `--quickjs` is required:```sh(cd sdk && pnpm run build)@@ -154,32 +187,35 @@ simulator would need a third Dawn.Then pick your Team under *Signing & Capabilities*, select your device and Run.The CMake build merges host + engine + QuickJS + Dawn into one archive(`build-native-ios/libestella_ios.a`), so the Xcode project is a signing and-packaging shell: `App/main.m` calls `EstellaRunApp()`, and the game (`host_js/game.js`,-`host_js/logo.png`) ships as bundle resources — the same project-relative paths the APK-serves from `assets/`.+packaging shell: `App/main.m` calls `EstellaRunApp()`, and the exported project+ships as bundle resources — the same project-relative paths the APK serves from+`assets/`.-## Shipping a project (Stage C)+## Shipping a project-The demo above is a hand-written `game.js`. A real game comes out of the editor:-**Package Project → Mobile** (or `exportGame({ platform: 'native' })`) writes the-cooked assets, both manifests, the scenes and `game.config.json` — content only,-since the engine, the SDK and the game runtime all ship inside the app binary.-Pass that directory to the build and it becomes the app's content:+A game comes out of the editor. **Package Project → Android** (or **→ iOS**, or+`exportGame({ platform: 'android' })`) writes the cooked assets, both manifests,+the scenes and `game.config.json` — content only, since the engine, the SDK and+the game runtime all ship inside the app binary. Both platforms write the SAME+payload; what differs is the toolchain that wraps it, which is why they are two+rows in the dialog rather than one "mobile". Pass that directory to the build and+it becomes the app's content:```sh# Android: it becomes the APK's assets/node build-tools/cli.js native --dawn "$DAWN" --dawn-build "$DAWN/out-android" \- --quickjs "$QJS" --package --content dist-native+ --quickjs "$QJS" --package --content dist-android# iOS: it stages into native/ios/Content (a folder reference), then rebuild in Xcodenode build-tools/cli.js native --target ios --dawn "$DAWN" \- --dawn-build "$DAWN/out-ios" --quickjs "$QJS" --content dist-native+ --dawn-build "$DAWN/out-ios" --quickjs "$QJS" --content dist-ios```-The host decides which it is from what it finds: `game.config.json` boots the-exported project through `ESEngine.initNativeGame`, otherwise `game.js` runs. A-project's own scripts (`defineComponent` / `defineSystem`) bundle to `scripts.js`-and evaluate before the scene loads, bound to the host's SDK instance.+`game.config.json` is what the host boots, through `ESEngine.initNativeGame`;+without one it says so and stops, rather than falling back to something a real+game never runs. A project's own scripts (`defineComponent` / `defineSystem`)+bundle to `scripts.js` and evaluate before the scene loads, bound to the host's+SDK instance.## Gotchas (all resolved; each cost a build)@@ -190,7 +226,15 @@ and evaluate before the scene loads, bound to the host's SDK instance.4. `ALooper_pollAll` is gone in NDK 28 — use `ALooper_pollOnce`.5. `configureSwapchain` must use `CompositeAlphaMode::Auto`, not `Opaque` — anative Vulkan surface (Adreno) rejects Opaque outright.-6. MIUI blocks `adb install` on a locked screen — unlock + allow USB install.+6. MIUI blocks `adb install` on a locked screen — unlock + allow USB install. It+ also blocks `adb shell input keyevent`, so a dozing screen cannot be woken from+ the host: a screenshot then reads back all black and the frame loop is+ legitimately stopped (the surface is gone). Unlock before you conclude anything+ about rendering.+7. `aapt2 link -A <dir>` on Windows writes nested asset paths with backslashes+ (`assets/assets\scenes\x`), and a zip entry name must use forward slashes — so+ `AAssetManager` cannot open anything in a subdirectory. The packaging step adds+ `assets/` with `jar` instead, which writes them correctly.7. Xcode ships the iPhoneOS **SDK** without the device **platform** components, sothe CMake build works while `xcodebuild` rejects every iOS destination("iOS X.Y is not installed"). Install it under *Xcode → Settings → Components*.@@ -199,32 +243,34 @@ and evaluate before the scene loads, bound to the host's SDK instance.## Status-**Android** is proven on device (Snapdragon 8 Elite / Adreno 830, 120 fps).-**iOS** runs: the demo renders in the simulator at a steady 60 fps — the clear-colour, a ShapeRenderer and `logo.png` loaded through the real `Assets.loadTexture`-pipeline — booting in ~20 ms off the bytecode cache. An **exported project** runs-too: the camera-follow example's scene loads from its cooked content and renders.+**Android** is proven on device (Snapdragon 8 Elite / Adreno 830) running an+**editor export**: the camera-follow example, packaged with **Package Project →+Android** and shipped by `--package --content`, renders its world at a+vsync-locked 120 fps and boots in ~57 ms (Dawn + EstellaContext 35 ms, then the+SDK bundle off its bytecode cache).++**iOS** runs in the simulator at a steady 60 fps, booting in ~20 ms off the+bytecode cache; an exported project loads from its cooked content and renders.Not yet run on a physical device, which needs your signing.-The engine core + render path are proven on device. The JS host runs the **real-SDK**: `ESEngine.createNativeApp()`-returns the same `App` + `World` the web build uses, connected to the native core-through the generated registry + memory backend; the host binds the entity /-hierarchy / component functions the SDK reads off `globalThis`, plus the input and-texture bindings.+The engine core + render path are proven on device. The host runs the **real+SDK**: `ESEngine.createNativeApp()` returns the same `App` + `World` the web build+uses, connected to the native core through the generated registry + memory+backend; the host binds only what cannot be generated (see above), and the rest —+the frame, the UI layout, the texture surface, the text batch — reaches the engine+through wrappers over the same declarations embind registers.System bindings landing incrementally through the real SDK surfaces:- **Input** (Stage B) — host touch → the SDK's `inputPlugin` → the `Input` resource (device-verified).- **Assets** (Stage B) — `ESEngine.Assets.loadTexture(path)` runs the SAME asset pipeline theweb build uses: the platform decodes the image (`bridge.loadImagePixels`) and the- **native ResourceManager** (`createNativeResourceManager`, over the host's- `es_createTexture` / `es_releaseTexture` / `es_getTextureDimensions`) uploads the- bytes directly — no wasm heap. `game.js` now loads its logo through this channel- instead of a hand-rolled `es_createTexture`. Cooked-asset import settings (filter /+ **native ResourceManager** (`createNativeResourceManager`) uploads the bytes+ directly — no wasm heap — through the engine's OWN `rm_createTextureEx`, the same+ entry point embind exposes to the web. Cooked-asset import settings (filter /wrap, from a scene's `textureImporterSettings`) flow through the shared runtime- loader and `es_createTexture` honors them exactly as the web embind path does, so- pixel-art stays crisp on device.+ loader into that one implementation, so pixel-art stays crisp on device by the+ same code that keeps it crisp in a browser.- **Audio** (Stage C) — `ESEngine.Audio.playSFX` / `playTrack` runs the SAME Audio API theweb build uses. The engine is [miniaudio](https://miniaud.io) (CoreAudio on iOS,AAudio/OpenSL on Android): it decodes and mixes natively, so nothing per-sample runsdiff --git a/native/android/host_js/AndroidManifest.xml b/native/android/host/AndroidManifest.xmlsimilarity index 100%rename from native/android/host_js/AndroidManifest.xmlrename to native/android/host/AndroidManifest.xmldiff --git a/native/android/host_cpp/AndroidManifest.xml b/native/android/host_cpp/AndroidManifest.xmldeleted file mode 100644index b5baef196..000000000--- a/native/android/host_cpp/AndroidManifest.xml+++ /dev/null@@ -1,11 +0,0 @@-<?xml version="1.0" encoding="utf-8"?>-<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.estella.host" android:versionCode="1" android:versionName="1.0">- <uses-sdk android:minSdkVersion="26" android:targetSdkVersion="33" />- <uses-feature android:name="android.hardware.vulkan.version" android:version="0x400003" android:required="true" />- <application android:label="EstellaHost" android:hasCode="false" android:extractNativeLibs="true">- <activity android:name="android.app.NativeActivity" android:label="EstellaHost" android:configChanges="orientation|keyboardHidden|screenSize|screenLayout|density" android:exported="true">- <meta-data android:name="android.app.lib_name" android:value="estella_host" />- <intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter>- </activity>- </application>-</manifest>diff --git a/native/host/Bindings.hpp b/native/host/Bindings.hppnew file mode 100644index 000000000..c1ba121c0--- /dev/null+++ b/native/host/Bindings.hpp@@ -0,0 +1,53 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Bindings.hpp+ * @brief The es_* surface the SDK reaches the engine through, declared one+ * pillar at a time.+ * @details The SDK's native path reads its primitives off `globalThis`:+ * `createNativeRegistry` and `NativeMemoryProvider` want the entity and+ * component calls, `createNativeResourceManager` wants the texture ones,+ * `createHostBridge` wants assets / networking / audio. Each group is+ * one TU under bindings/, so adding a call means editing the file that+ * owns that pillar — not a 1400-line middle.+ *+ * Two of those groups are NOT here, because they are generated from the+ * same reflection the web's embind bindings come from:+ * * `esn_register` — es_set_<C> / es_<C>_buffer / _has / _remove+ * * `esn_register_functions` — es_renderer_* / es_uiLayout_* / …+ * Only what has no web counterpart is written by hand below.+ *+ * @author ESEngine Team+ * @date 2026+ *+ * @copyright Copyright (c) 2026 ESEngine Team+ * Licensed under the Apache License, Version 2.0.+ */+#pragma once++#include "Runtime.hpp"++namespace eshost {++/** Entity + hierarchy: the base Registry surface the SDK's World drives. */+void registerEcsBindings(HostState& h, JSValue global);++/** Textures, the clear colour, the surface size, the camera list and the text+ * batch — what the SDK's renderer and glyph atlas need from the device. */+void registerRenderBindings(HostState& h, JSValue global);++/** Packaged assets, image decode, the on-disk cache and UTF-8 decoding. */+void registerAssetBindings(HostState& h, JSValue global);++/** es_audio* over the native engine — bound ONLY when a sound device came up, so+ * the SDK's hasAudioBindings() gates the native backend on real availability. */+void registerAudioBindings(HostState& h, JSValue global);++/** es_fetch over the platform's native networking. */+void registerNetBindings(HostState& h, JSValue global);++/** Run the JS callbacks for HTTP replies that arrived since the last frame. JS+ * thread only; {@link deliverFetch} queued them from the completion thread. */+void drainFetches(HostState& h);++} // namespace eshostdiff --git a/native/host/EsnShim.cpp b/native/host/EsnShim.cppnew file mode 100644index 000000000..1b17d9fa7--- /dev/null+++ b/native/host/EsnShim.cpp@@ -0,0 +1,81 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file EsnShim.cpp+ * @brief The host side of esn_shim.hpp — what the GENERATED bindings call.+ * @details Both generated TUs (per-component accessors and the engine's binding+ * entry points) are written against this handful of free functions: the+ * engine singletons the host runs one of, entity round-tripping, and the+ * JS value readers. Keeping them in one TU is what lets the generator+ * stay ignorant of how this host stores its state.+ *+ * @author ESEngine Team+ * @date 2026+ *+ * @copyright Copyright (c) 2026 ESEngine Team+ * Licensed under the Apache License, Version 2.0.+ */+#include "esn_shim.hpp"++#include "Runtime.hpp"++using namespace esengine;++// — Engine singletons: the host runs exactly one of each, so a binding+// declaration that takes one by reference consumes no JS argument. —++esengine::ecs::Registry& esn_reg() { return *eshost::host().registry; }++esengine::resource::ResourceManager& esn_rm() {+ return eshost::host().ctx->require<esengine::resource::ResourceManager>();+}++// — Entity ids cross the boundary as the native Entity's raw u32. —++esengine::Entity esn_entity(JSContext* ctx, JSValueConst v) {+ uint32_t raw = Entity::INVALID_RAW;+ JS_ToUint32(ctx, &raw, v);+ return Entity::fromRaw(raw);+}++// — Field readers the per-component marshalling is emitted against. —++bool esn_getnum(JSContext* ctx, JSValueConst obj, const char* key, double* out) {+ JSValue p = JS_GetPropertyStr(ctx, obj, key);+ bool ok = !JS_IsUndefined(p) && !JS_IsNull(p) && JS_ToFloat64(ctx, out, p) == 0;+ JS_FreeValue(ctx, p);+ return ok;+}++bool esn_getbool(JSContext* ctx, JSValueConst obj, const char* key, int* out) {+ JSValue p = JS_GetPropertyStr(ctx, obj, key);+ if (JS_IsUndefined(p) || JS_IsNull(p)) { JS_FreeValue(ctx, p); return false; }+ *out = JS_ToBool(ctx, p);+ JS_FreeValue(ctx, p);+ return true;+}++void esn_getvec(JSContext* ctx, JSValueConst obj, const char* key, float* dst, int n) {+ JSValue arr = JS_GetPropertyStr(ctx, obj, key);+ if (JS_IsArray(arr)) {+ for (int i = 0; i < n; ++i) {+ JSValue el = JS_GetPropertyUint32(ctx, arr, (uint32_t)i);+ double d = 0;+ JS_ToFloat64(ctx, &d, el);+ dst[i] = (float)d;+ JS_FreeValue(ctx, el);+ }+ }+ JS_FreeValue(ctx, arr);+}++// The generated wrappers for entry points that take a `uintptr_t` buffer read+// their bytes through this: on the web that argument is a wasm heap offset, here+// it is memory the wrapper owns for the duration of the call.+void esn_bytes(JSContext* ctx, JSValueConst v, std::vector<esengine::u8>& out) {+ eshost::readByteSource(ctx, v, out);+}++JSValue esn_arraybuffer(JSContext* ctx, void* ptr, size_t size) {+ return JS_NewArrayBuffer(ctx, reinterpret_cast<uint8_t*>(ptr), size, nullptr, nullptr, false);+}diff --git a/native/host/Host.cpp b/native/host/Host.cppnew file mode 100644index 000000000..72f2cad30--- /dev/null+++ b/native/host/Host.cpp@@ -0,0 +1,230 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Host.cpp+ * @brief Boot, the frame, and the lifecycle signals — the entry points a+ * platform's event loop drives (see Host.hpp).+ * @details What is left in C++ once the engine is native and the game is the real+ * SDK: bring Dawn up, hand the engine its device, start the JS runtime,+ * and then, each frame, let the SDK's App tick and flip the swapchain. The+ * frame itself belongs to the SDK — its render system resolves the+ * scene's cameras and drives RenderFrame through the generated+ * es_renderer_* bindings, the same code path the web build takes.+ *+ * @author ESEngine Team+ * @date 2026+ *+ * @copyright Copyright (c) 2026 ESEngine Team+ * Licensed under the Apache License, Version 2.0.+ */+#include "Bindings.hpp"++#include "esengine/bindings/ActiveContext.hpp" // g_activeContext — the context the generated bindings act on+#include "esengine/core/World.hpp"+#include "esengine/ecs/TransformSystem.hpp"+#include "esengine/renderer/RenderContext.hpp"+#include "esengine/renderer/RenderFrame.hpp"++#include <glm/gtc/matrix_transform.hpp>++using namespace esengine;++namespace eshost {+namespace {++/** Has the SDK's render pipeline taken over the frame? It declares itself through+ * `es_jsOwnsFrame` (see HOST_FLAGS in the SDK's nativeBindings) once installed. */+bool jsOwnsFrame(HostState& h) {+ JSValue global = JS_GetGlobalObject(h.js);+ JSValue v = JS_GetPropertyStr(h.js, global, "es_jsOwnsFrame");+ const bool owns = JS_ToBool(h.js, v) != 0;+ JS_FreeValue(h.js, v);+ JS_FreeValue(h.js, global);+ return owns;+}++/** The clear colour of the host's fallback pass. A game's own clear colour comes+ * from its Canvas, through the SDK's pipeline; this only paints the frames where+ * that pipeline is not installed. */+constexpr glm::vec4 kFallbackClear{0.07f, 0.08f, 0.12f, 1.0f};++/** One full-viewport pass, for a host build whose renderer bindings are absent.+ * A shipped app never takes this path (they are generated); it exists so such a+ * build shows the scene rather than a blank surface. */+void fallbackFrame(HostState& h) {+ auto& ctx = *h.ctx;+ ctx.require<RenderContext>().setFrameTime((f32)h.frame / 60.0f, (u32)h.w, (u32)h.h);+ World world{*h.registry, ctx.services(), 1.0f / 60.0f};+ ctx.require<ecs::TransformSystem>().update(world);+ const glm::mat4 vp = glm::ortho(0.0f, h.w, 0.0f, h.h);+ auto& rf = ctx.require<RenderFrame>();+ rf.begin(vp, 0, RenderFrame::PassClear{true, true, kFallbackClear});+ rf.collectAll(*h.registry);+ rf.flush();+ rf.end();+}++/** Ask Dawn for an adapter and a device on the platform's backend, enabling the+ * block-compression families this adapter supports (a device rejects a format it+ * did not opt into, even when the adapter advertises it). */+bool createDevice(HostState& h) {+ WGPUInstanceFeatureName feats[] = {WGPUInstanceFeatureName_TimedWaitAny};+ WGPUInstanceDescriptor idesc = {};+ idesc.requiredFeatureCount = 1;+ idesc.requiredFeatures = feats;+ h.instance = wgpuCreateInstance(&idesc);++ WGPURequestAdapterOptions opts = {};+ opts.backendType = h.platform->backend();+ auto onAdapter = [](WGPURequestAdapterStatus s, WGPUAdapter ad, WGPUStringView, void* u, void*) {+ if (s == WGPURequestAdapterStatus_Success) *static_cast<WGPUAdapter*>(u) = ad; };+ WGPURequestAdapterCallbackInfo aci = {};+ aci.mode = WGPUCallbackMode_WaitAnyOnly; aci.callback = onAdapter; aci.userdata1 = &h.adapter;+ WGPUFutureWaitInfo af = {wgpuInstanceRequestAdapter(h.instance, &opts, aci), 0};+ wgpuInstanceWaitAny(h.instance, 1, &af, UINT64_MAX);+ if (!h.adapter) { ESHOST_LOGE("no adapter"); return false; }++ WGPUFeatureName compFeats[3];+ size_t compCount = 0;+ for (WGPUFeatureName f : {WGPUFeatureName_TextureCompressionETC2,+ WGPUFeatureName_TextureCompressionASTC,+ WGPUFeatureName_TextureCompressionBC}) {+ if (wgpuAdapterHasFeature(h.adapter, f)) compFeats[compCount++] = f;+ }+ auto onDevice = [](WGPURequestDeviceStatus s, WGPUDevice d, WGPUStringView, void* u, void*) {+ if (s == WGPURequestDeviceStatus_Success) *static_cast<WGPUDevice*>(u) = d; };+ WGPUDeviceDescriptor dd = {};+ dd.requiredFeatureCount = compCount;+ dd.requiredFeatures = compCount ? compFeats : nullptr;+ WGPURequestDeviceCallbackInfo dci = {};+ dci.mode = WGPUCallbackMode_WaitAnyOnly; dci.callback = onDevice; dci.userdata1 = &h.device;+ WGPUFutureWaitInfo df = {wgpuAdapterRequestDevice(h.adapter, &dd, dci), 0};+ wgpuInstanceWaitAny(h.instance, 1, &df, UINT64_MAX);+ if (!h.device) { ESHOST_LOGE("no device"); return false; }+ return true;+}++} // namespace++bool bindSurface() {+ HostState& h = host();+ u32 w = 0, hh = 0;+ h.platform->surfaceSize(w, hh);+ h.w = (f32)w;+ h.h = (f32)hh;+ if (!h.gfx->configureSurface(h.platform->surface(), w, hh)) {+ ESHOST_LOGE("configureSurface failed");+ return false;+ }+ h.surfaceReady = true;+ return true;+}++void surfaceLost() {+ if (hostAlive()) host().surfaceReady = false;+}++bool booted() { return hostAlive() && host().ready; }++bool surfaceBound() { return hostAlive() && host().surfaceReady; }++bool boot(Platform& platform) {+ createHost(platform);+ HostState& h = host();++ const double t0 = nowMs();+ if (!createDevice(h)) return false;++ auto device = makeUnique<WebGPUDevice>(h.device, h.instance, h.adapter);+ h.gfx = device.get();+ if (!bindSurface()) return false;++ static EstellaContext context;+ h.ctx = &context;+ // The binding entry points (the generated es_* wrappers call the same ones+ // embind does) reach the engine through activeCtx(); install ours, exactly as+ // the web entry does at initRenderer. Without this they would act on the+ // fallback context and render into a different engine than the host presents.+ g_activeContext = &context;+ context.state().viewport_width = (i32)h.w;+ context.state().viewport_height = (i32)h.h;+ if (!context.init(std::move(device))) { ESHOST_LOGE("context.init failed"); return false; }++ static ecs::Registry registry;+ h.registry = ®istry;+ ESHOST_LOGI("boot ms — Dawn instance/adapter/device + EstellaContext: %.0f", nowMs() - t0);+ ESHOST_LOGI("audio: %s", h.audio.init() ? "native engine up (miniaudio)" : "no device — silent");++ initRuntime(h);+ if (!runPackagedGame(h)) return false;+ h.ready = true;+ ESHOST_LOGI("real SDK up (%dx%d) — esengine World over native Dawn", (int)h.w, (int)h.h);+ return true;+}++void frame() {+ if (!booted() || !host().surfaceReady) return;+ HostState& h = host();+ JSValue dt = JS_NewFloat64(h.js, 1.0 / 60.0);+ callJs(h, "update", 1, &dt);+ JS_FreeValue(h.js, dt);+ pumpJs(h); // run the App tick's async systems and any timers they set++ // Notify JS of voices that ended on their own (the audio thread never touches+ // QuickJS; we poll on this thread and push, like touch). onEnd handlers may+ // start new sounds synchronously — safe, pumpEnded iterates a snapshot.+ h.audio.pumpEnded([&h](int voiceId) {+ JSValue arg = JS_NewInt32(h.js, voiceId);+ callJs(h, "es_onNativeAudioEnded", 1, &arg);+ JS_FreeValue(h.js, arg);+ });++ // Run the callbacks for any HTTP replies that landed since last frame, then+ // let their .then() continuations run.+ drainFetches(h);+ pumpJs(h);++ // app.tick above ran the SDK's render system, which resolved the scene's+ // cameras and drove RenderFrame through the es_renderer_* bindings. What is+ // left here is what only a host can do: flip the swapchain.+ if (!jsOwnsFrame(h)) fallbackFrame(h);+ h.gfx->present();+ if (++h.frame % 120 == 0) ESHOST_LOGI("real-SDK frame %llu", (unsigned long long)h.frame);+}++// Push one host touch to the game's es_onNativeTouch(type,id,x,y), which fans it+// out to the NativeBridge's registered listener.+void touch(int type, int id, float x, float y) {+ if (!booted()) return;+ HostState& h = host();+ JSValue args[4] = {+ JS_NewInt32(h.js, type), JS_NewInt32(h.js, id),+ JS_NewFloat64(h.js, x), JS_NewFloat64(h.js, y),+ };+ callJs(h, "es_onNativeTouch", 4, args);+ for (JSValue& v : args) JS_FreeValue(h.js, v);+}++// The app went to background (visible=false) or returned. Suspend/resume the+// audio device at the native layer — correct even while the JS tick is paused —+// then push the signal to JS, where the Lifecycle plugin auto-pauses the game.+void setVisible(bool visible) {+ if (!booted()) return;+ HostState& h = host();+ if (visible) h.audio.resumeAll(); else h.audio.suspendAll();+ JSValue arg = JS_NewBool(h.js, visible);+ callJs(h, "es_onNativeVisibility", 1, &arg);+ JS_FreeValue(h.js, arg);+ pumpJs(h);+}++// OS memory pressure — let the SDK's residency caches drop evictable entries+// (the audio buffer cache trims). Held buffers keep playing; only re-fetch cost+// returns for evicted ones.+void memoryWarning() {+ if (!booted()) return;+ callJs(host(), "es_onNativeMemoryWarning", 0, nullptr);+ pumpJs(host());+}++} // namespace eshostdiff --git a/native/host_js/host_core.hpp b/native/host/Host.hppsimilarity index 86%rename from native/host_js/host_core.hpprename to native/host/Host.hppindex a23676c06..0494c6267 100644--- a/native/host_js/host_core.hpp+++ b/native/host/Host.hpp@@ -1,20 +1,24 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team/**- * @file host_core.hpp- * @brief The platform-independent JS host: Dawn bring-up, the es_* native- * bindings, the SDK bundle + game boot, and the frame.+ * @file Host.hpp+ * @brief The host's public contract: the platform seam every OS answers, and+ * the handful of entry points its event loop drives.* @details Three layers run a native Estella game, and only the first is C++:* 1. This host — boots Dawn, installs the es_* bindings as globals,* feeds host touch to JS, reads packaged assets, and renders.* 2. The SDK bundle (dist/index.native.bundled.js, embedded): the real* esengine TS SDK — createNativeApp / World / Input — as `ESEngine`.- * 3. The game (game.js, a packaged asset loaded at runtime): developer- * content. It calls ESEngine.createNativeApp(__esNativeBridge).+ * 3. The game: an editor export (game.config.json + cooked assets ++ * scenes) packaged with the app, booted by bootstrap.js through+ * ESEngine.initNativeGame.*+ * The host itself is split by concern: Runtime.hpp owns the QuickJS+ * runtime and the shared state, bindings/ owns the es_* surface (one TU+ * per pillar), and Host.cpp owns boot, the frame and lifecycle.* Everything that differs between Android and iOS lives behind- * {@link eshost::Platform}; the glue (js/main_android.cpp,- * js/main_ios.mm) implements it and owns the event loop.+ * {@link eshost::Platform}; the glue (platform/android.cpp,+ * platform/ios.mm) implements it and owns the event loop.** @author ESEngine Team* @date 2026@@ -98,7 +102,7 @@ struct Platform {** This is the ONLY per-OS part of text: which file to open. Android asks its* font matcher (which handles CJK fallback), iOS asks Core Text; the- * rasterization and the SDF conversion are shared (see glyph_raster.hpp). */+ * rasterization and the SDF conversion are shared (see media/glyph_raster.hpp). */virtual FontFile loadFont(const std::string& family, esengine::u32 codepoint, int style) = 0;/** Perform an HTTP request off the main thread (NSURLSession / a JNI@@ -113,8 +117,9 @@ struct Platform {* queued and the JS callback runs on the next frame, on the JS thread. */void deliverFetch(FetchResult result);-/** @brief Boots Dawn, EstellaContext, QuickJS, the SDK bundle and game.js. Call- * once, when a window first exists; @p platform must outlive the host.+/** @brief Boots Dawn, EstellaContext, QuickJS, the SDK bundle and the packaged+ * project. Call once, when a window first exists; @p platform must+ * outlive the host.* @return false if any stage failed (the reason is already logged). */bool boot(Platform& platform);diff --git a/native/host/Runtime.cpp b/native/host/Runtime.cppnew file mode 100644index 000000000..b1c48b051--- /dev/null+++ b/native/host/Runtime.cpp@@ -0,0 +1,396 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Runtime.cpp+ * @brief The QuickJS runtime the host owns: the environment the language does+ * not ship, the binding installation, and the boot of the SDK + game.+ * @details QuickJS is a language, not a runtime — no console, no timers, no+ * clock. Those are the host's job and they live here, beside the eval+ * helpers and the bytecode cache that makes a ~700 KB SDK bundle load in+ * milliseconds instead of seconds.+ *+ * Three layers are stacked here, in order: the SDK bundle (embedded,+ * installs `ESEngine`), bootstrap.js (embedded, installs the bridge and+ * the default init/update), and the packaged project (read off the+ * device).+ *+ * @author ESEngine Team+ * @date 2026+ *+ * @copyright Copyright (c) 2026 ESEngine Team+ * Licensed under the Apache License, Version 2.0.+ */+#include "Bindings.hpp"++#include "esn_shim.hpp" // esn_register / esn_register_functions+#include "esengine_bundle.h" // the real SDK, bundled: installs globalThis.ESEngine+#include "host_bootstrap.h" // bootstrap.js, embedded++#include <cstdarg>+#include <cstdio>+#include <cstring>+#include <ctime>++using namespace esengine;++namespace eshost {++// =============================================================================+// The state singleton+// =============================================================================++namespace {+HostState* g_host = nullptr;+}++HostState& host() { return *g_host; }+bool hostAlive() { return g_host != nullptr; }++void createHost(Platform& platform) {+ static HostState state;+ g_host = &state;+ state.platform = &platform;+ state.cacheDir = platform.cacheDir();+}++void hostLog(bool error, const char* fmt, ...) {+ char buf[1024];+ va_list args;+ va_start(args, fmt);+ vsnprintf(buf, sizeof(buf), fmt, args);+ va_end(args);+ if (g_host && g_host->platform) g_host->platform->log(error, buf);+}++double nowMs() {+ struct timespec ts;+ clock_gettime(CLOCK_MONOTONIC, &ts);+ return ts.tv_sec * 1000.0 + ts.tv_nsec / 1e6;+}++// =============================================================================+// Value readers+// =============================================================================++void readByteSource(JSContext* ctx, JSValueConst v, std::vector<u8>& out) {+ // Raw ArrayBuffer first — a typed-array view is not one, so it falls through.+ size_t rawSize = 0;+ if (uint8_t* raw = JS_GetArrayBuffer(ctx, &rawSize, v)) {+ out.assign(raw, raw + rawSize);+ return;+ }+ JS_FreeValue(ctx, JS_GetException(ctx)); // not a raw ArrayBuffer — try a view++ size_t byteOffset = 0, byteLen = 0, bytesPerEl = 0;+ JSValue ab = JS_GetTypedArrayBuffer(ctx, v, &byteOffset, &byteLen, &bytesPerEl);+ if (!JS_IsException(ab)) {+ size_t abSize = 0;+ uint8_t* base = JS_GetArrayBuffer(ctx, &abSize, ab);+ if (base && byteOffset + byteLen <= abSize) {+ out.assign(base + byteOffset, base + byteOffset + byteLen);+ }+ JS_FreeValue(ctx, ab);+ return;+ }+ JS_FreeValue(ctx, ab);+ JS_FreeValue(ctx, JS_GetException(ctx)); // not a typed array — clear + index it+ uint32_t len = 0;+ JSValue lv = JS_GetPropertyStr(ctx, v, "length");+ JS_ToUint32(ctx, &len, lv);+ JS_FreeValue(ctx, lv);+ out.resize(len);+ for (uint32_t i = 0; i < len; ++i) {+ JSValue el = JS_GetPropertyUint32(ctx, v, i);+ int32_t iv = 0;+ JS_ToInt32(ctx, &iv, el);+ out[i] = (u8)iv;+ JS_FreeValue(ctx, el);+ }+}++// =============================================================================+// The environment QuickJS does not ship: console, timers, a clock+// =============================================================================++namespace {++JSValue jsConsoleWrite(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv, bool error) {+ std::string line;+ for (int i = 0; i < argc; ++i) {+ const char* s = JS_ToCString(ctx, argv[i]);+ if (!s) continue;+ if (!line.empty()) line += ' ';+ line += s;+ JS_FreeCString(ctx, s);+ }+ hostLog(error, "%s", line.c_str());+ return JS_UNDEFINED;+}+JSValue js_consoleLog(JSContext* ctx, JSValueConst t, int argc, JSValueConst* argv) {+ return jsConsoleWrite(ctx, t, argc, argv, false);+}+JSValue js_consoleError(JSContext* ctx, JSValueConst t, int argc, JSValueConst* argv) {+ return jsConsoleWrite(ctx, t, argc, argv, true);+}++JSValue jsAddTimer(JSContext* ctx, int argc, JSValueConst* argv, bool repeat) {+ if (argc < 1 || !JS_IsFunction(ctx, argv[0])) return JS_NewInt64(ctx, 0);+ double delay = 0;+ if (argc > 1) JS_ToFloat64(ctx, &delay, argv[1]);+ if (!(delay >= 0)) delay = 0; // also catches NaN+ HostState& h = host();+ const int64_t id = h.nextTimerId++;+ // A zero-delay interval would fire forever within one pump; clamp as browsers do.+ h.timers.push_back(Timer{id, nowMs() + delay, repeat ? (delay > 1 ? delay : 1) : 0,+ JS_DupValue(ctx, argv[0])});+ return JS_NewInt64(ctx, id);+}+JSValue js_setTimeout(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {+ return jsAddTimer(ctx, argc, argv, false);+}+JSValue js_setInterval(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {+ return jsAddTimer(ctx, argc, argv, true);+}+JSValue js_clearTimer(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {+ int64_t id = 0;+ if (argc > 0) JS_ToInt64(ctx, &id, argv[0]);+ HostState& h = host();+ for (auto it = h.timers.begin(); it != h.timers.end(); ++it) {+ if (it->id != id) continue;+ JS_FreeValue(h.js, it->fn);+ h.timers.erase(it);+ break;+ }+ return JS_UNDEFINED;+}++JSValue js_performanceNow(JSContext* ctx, JSValueConst, int, JSValueConst*) {+ return JS_NewFloat64(ctx, nowMs());+}++/** Drain QuickJS's microtask queue. app.tick() is async: its synchronous prefix+ * (finishPlugins, resource inserts) runs on call, but the systems run in jobs. */+void pumpJobs(HostState& h) {+ JSContext* c;+ while (JS_ExecutePendingJob(h.rt, &c) > 0) { /* ran a job */ }+}++/** Fire the timers that came due. Callbacks may add or clear timers, so they run+ * off a snapshot rather than while iterating. */+void pumpTimers(HostState& h) {+ const double now = nowMs();+ std::vector<Timer> due;+ for (auto it = h.timers.begin(); it != h.timers.end();) {+ if (it->due > now) { ++it; continue; }+ due.push_back(*it);+ if (it->interval > 0) { it->due = now + it->interval; ++it; }+ else it = h.timers.erase(it);+ }+ for (Timer& t : due) {+ JSValue r = JS_Call(h.js, t.fn, JS_UNDEFINED, 0, nullptr);+ if (JS_IsException(r)) logJsError(h.js, "timer callback");+ JS_FreeValue(h.js, r);+ if (t.interval <= 0) JS_FreeValue(h.js, t.fn); // the erased entry's reference+ }+}++// FNV-1a of the bundle — a changed SDK invalidates its bytecode cache.+uint64_t hashBytes(const char* p, size_t n) {+ uint64_t h = 1469598103934665603ull;+ for (size_t i = 0; i < n; i++) { h ^= (uint8_t)p[i]; h *= 1099511628211ull; }+ return h;+}++/**+ * Evaluate a global script, reusing a cached bytecode compile. QuickJS is an+ * interpreter: parsing the ~700 KB SDK bundle costs ~8 s every launch. So compile+ * once (JS_WriteObject the bytecode, tagged with the bundle hash), and on later+ * launches JS_ReadObject it — skipping the parse. The same QuickJS build writes and+ * reads it, so the format always matches; the hash guards against a stale bundle,+ * and a bad read just recompiles. Cache file: [8-byte hash][bytecode].+ */+JSValue evalCachedScript(HostState& h, const char* src, size_t srcLen, const char* filename,+ const std::string& cachePath) {+ const uint64_t want = hashBytes(src, srcLen);++ if (!cachePath.empty()) {+ FILE* f = fopen(cachePath.c_str(), "rb");+ if (f) {+ uint64_t got = 0;+ std::vector<u8> bc;+ if (fread(&got, sizeof(got), 1, f) == 1 && got == want) {+ fseek(f, 0, SEEK_END);+ long sz = ftell(f);+ fseek(f, (long)sizeof(got), SEEK_SET);+ if (sz > (long)sizeof(got)) {+ bc.resize((size_t)sz - sizeof(got));+ if (fread(bc.data(), 1, bc.size(), f) != bc.size()) bc.clear();+ }+ }+ fclose(f);+ if (!bc.empty()) {+ JSValue obj = JS_ReadObject(h.js, bc.data(), bc.size(), JS_READ_OBJ_BYTECODE);+ if (!JS_IsException(obj)) {+ ESHOST_LOGI("SDK bundle: loaded from bytecode cache");+ return JS_EvalFunction(h.js, obj);+ }+ JSValue e = JS_GetException(h.js); JS_FreeValue(h.js, e); // stale/corrupt -> recompile+ }+ }+ }++ // Parse once (slow), cache the bytecode, run.+ JSValue fn = JS_Eval(h.js, src, srcLen, filename, JS_EVAL_TYPE_GLOBAL | JS_EVAL_FLAG_COMPILE_ONLY);+ if (JS_IsException(fn)) return fn;+ if (!cachePath.empty()) {+ size_t bcLen = 0;+ uint8_t* bc = JS_WriteObject(h.js, &bcLen, fn, JS_WRITE_OBJ_BYTECODE);+ if (bc) {+ FILE* f = fopen(cachePath.c_str(), "wb");+ if (f) { fwrite(&want, sizeof(want), 1, f); fwrite(bc, 1, bcLen, f); fclose(f); }+ js_free(h.js, bc);+ ESHOST_LOGI("SDK bundle: compiled + cached bytecode (%zu bytes)", bcLen);+ }+ }+ return JS_EvalFunction(h.js, fn); // consumes fn+}++} // namespace++// =============================================================================+// Eval helpers+// =============================================================================++void logJsError(JSContext* ctx, const char* where) {+ JSValue e = JS_GetException(ctx);+ const char* s = JS_ToCString(ctx, e);+ ESHOST_LOGE("JS error in %s: %s", where, s ? s : "?");+ if (s) JS_FreeCString(ctx, s);+ // The stack too: a bare message ("Maximum call stack size exceeded") says+ // nothing about which SDK path produced it, and a device is where you find out.+ JSValue stack = JS_GetPropertyStr(ctx, e, "stack");+ if (!JS_IsUndefined(stack) && !JS_IsException(stack)) {+ const char* st = JS_ToCString(ctx, stack);+ if (st) { ESHOST_LOGE(" stack: %s", st); JS_FreeCString(ctx, st); }+ }+ JS_FreeValue(ctx, stack);+ JS_FreeValue(ctx, e);+}++void evalJs(HostState& h, const char* src, const char* name) {+ JSValue r = JS_Eval(h.js, src, strlen(src), name, JS_EVAL_TYPE_GLOBAL);+ if (JS_IsException(r)) logJsError(h.js, name);+ JS_FreeValue(h.js, r);+}++void callJs(HostState& h, const char* fn, int argc, JSValue* argv) {+ JSValue global = JS_GetGlobalObject(h.js);+ JSValue f = JS_GetPropertyStr(h.js, global, fn);+ if (JS_IsFunction(h.js, f)) {+ JSValue r = JS_Call(h.js, f, global, argc, argv);+ if (JS_IsException(r)) logJsError(h.js, fn);+ JS_FreeValue(h.js, r);+ }+ JS_FreeValue(h.js, f);+ JS_FreeValue(h.js, global);+}++void pumpJs(HostState& h) {+ pumpJobs(h);+ pumpTimers(h);+ pumpJobs(h);+}++void bindGlobal(HostState& h, JSValue global, const char* name, JSCFunction* fn, int argc) {+ JS_SetPropertyStr(h.js, global, name, JS_NewCFunction(h.js, fn, name, argc));+}++// =============================================================================+// Bring-up+// =============================================================================++void initRuntime(HostState& h) {+ const double t0 = nowMs();+ h.rt = JS_NewRuntime();+ h.js = JS_NewContext(h.rt);+ JSValue global = JS_GetGlobalObject(h.js);++ JS_SetPropertyStr(h.js, global, "W", JS_NewFloat64(h.js, h.w));+ JS_SetPropertyStr(h.js, global, "H", JS_NewFloat64(h.js, h.h));+ JS_SetPropertyStr(h.js, global, "S", JS_NewFloat64(h.js, h.w < h.h ? h.w : h.h));++ // The host environment the SDK expects but QuickJS (a language, not a runtime)+ // does not provide: console, timers and a monotonic clock. Without them a+ // rejected promise is silent and the asset cache's setTimeout throws.+ JSValue console = JS_NewObject(h.js);+ for (const char* name : {"log", "info", "debug", "trace"}) {+ JS_SetPropertyStr(h.js, console, name, JS_NewCFunction(h.js, js_consoleLog, name, 1));+ }+ for (const char* name : {"warn", "error"}) {+ JS_SetPropertyStr(h.js, console, name, JS_NewCFunction(h.js, js_consoleError, name, 1));+ }+ JS_SetPropertyStr(h.js, global, "console", console);++ bindGlobal(h, global, "setTimeout", js_setTimeout, 2);+ bindGlobal(h, global, "setInterval", js_setInterval, 2);+ bindGlobal(h, global, "clearTimeout", js_clearTimer, 1);+ bindGlobal(h, global, "clearInterval", js_clearTimer, 1);+ JSValue perf = JS_NewObject(h.js);+ JS_SetPropertyStr(h.js, perf, "now", JS_NewCFunction(h.js, js_performanceNow, "now", 0));+ JS_SetPropertyStr(h.js, global, "performance", perf);++ // The es_* surface, one pillar at a time (see Bindings.hpp).+ registerEcsBindings(h, global);+ registerRenderBindings(h, global);+ registerAssetBindings(h, global);+ registerAudioBindings(h, global);+ registerNetBindings(h, global);++ // The generated halves: per-component accessors, then the engine's binding+ // entry points — both from the same reflection the web's embind bindings come+ // from, so the SDK reaches the engine by the same names on either platform.+ esn_register(h.js, global);+ esn_register_functions(h.js, global);+ JS_FreeValue(h.js, global);++ // Layer 1: the real SDK bundle, embedded — installs `ESEngine`.+ const double tCtx = nowMs();+ std::string bcPath = h.cacheDir.empty() ? std::string() : (h.cacheDir + "/esengine.native.bc");+ JSValue br = evalCachedScript(h, kSdkBundleJS, strlen(kSdkBundleJS), "esengine.native.js", bcPath);+ if (JS_IsException(br)) logJsError(h.js, "SDK bundle");+ JS_FreeValue(h.js, br);+ const double tBundle = nowMs();++ // Layer 2: the host bootstrap — the bridge over the es_* bindings, and the+ // default init/update that boots a packaged project.+ evalJs(h, kHostBootstrapJS, "bootstrap.js");+ ESHOST_LOGI("boot ms — qjs ctx: %.0f | SDK bundle eval: %.0f", tCtx - t0, tBundle - tCtx);+}++bool runPackagedGame(HostState& h) {+ // Layer 3: the game. The package IS an editor export — game.config.json,+ // the manifests, the cooked assets and the scenes — which boots through the+ // bootstrap's default init/update. There is no second way in: a hand-written+ // script would be a parallel content path that drifts from the one every real+ // game takes. The project's own scripts must register their components BEFORE+ // the scene loads, so they run first.+ const double t0 = nowMs();+ if (readAsset(h, "game.config.json").empty()) {+ ESHOST_LOGE("nothing to run: no game.config.json. Package a project "+ "(Package Project -> Android / iOS) and ship it with "+ "`cli native --content <dir>`.");+ return false;+ }+ std::vector<u8> scripts = readAsset(h, "scripts.js");+ if (!scripts.empty()) {+ evalJs(h, std::string(reinterpret_cast<const char*>(scripts.data()), scripts.size()).c_str(),+ "scripts.js");+ }+ const double tScripts = nowMs();+ callJs(h, "init", 0, nullptr);+ pumpJs(h);+ ESHOST_LOGI("boot ms — project scripts: %.0f | init(): %.0f", tScripts - t0, nowMs() - tScripts);+ return true;+}++} // namespace eshostdiff --git a/native/host/Runtime.hpp b/native/host/Runtime.hppnew file mode 100644index 000000000..e2a1c336c--- /dev/null+++ b/native/host/Runtime.hpp@@ -0,0 +1,149 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Runtime.hpp+ * @brief The host's INTERNAL surface: the state every part of it shares, and+ * the QuickJS plumbing the binding TUs are written against.+ * @details Not part of the host's contract with a platform — that is Host.hpp.+ * This is what Host.cpp and the binding TUs share: one state struct, the+ * JS runtime that owns the language-level environment QuickJS does not+ * ship (console, timers, a clock), and the value readers every binding+ * needs. A binding TU includes this and nothing else of the host.+ *+ * @author ESEngine Team+ * @date 2026+ *+ * @copyright Copyright (c) 2026 ESEngine Team+ * Licensed under the Apache License, Version 2.0.+ */+#pragma once++#include "Host.hpp"+#include "media/native_audio.hpp"++extern "C" {+#include "quickjs.h"+}++#include "esengine/core/EstellaContext.hpp"+#include "esengine/ecs/Registry.hpp"+#include "esengine/renderer/webgpu/WebGPUDevice.hpp"++#include <cstdint>+#include <string>+#include <unordered_map>+#include <vector>++namespace eshost {++/** A pending setTimeout / setInterval callback. QuickJS is only the language: the+ * timers, like console, are the host's job. */+struct Timer {+ int64_t id;+ double due; ///< nowMs() deadline.+ double interval; ///< Repeat period; 0 for a one-shot.+ JSValue fn;+};++/**+ * Everything one running host owns. Single-instance by construction (a native app+ * has one window and one JS runtime), reached through {@link host}.+ */+struct HostState {+ Platform* platform = nullptr;++ // — Graphics: Dawn, and the engine context drawing through it —+ WGPUInstance instance = nullptr;+ WGPUAdapter adapter = nullptr;+ WGPUDevice device = nullptr;+ esengine::WebGPUDevice* gfx = nullptr;+ esengine::EstellaContext* ctx = nullptr;+ esengine::ecs::Registry* registry = nullptr;++ // — Script: the QuickJS runtime the SDK and the game run in —+ JSRuntime* rt = nullptr;+ JSContext* js = nullptr;+ std::vector<Timer> timers;+ int64_t nextTimerId = 1;+ std::unordered_map<int, JSValue> fetchCallbacks; ///< in-flight es_fetch id -> JS callback+ int nextFetchId = 1;++ AudioEngine audio; ///< native sound (miniaudio); silent if no device+ std::string cacheDir; ///< app private dir — SDK bytecode cache + asset cache++ esengine::f32 w = 0, h = 0;+ bool ready = false; ///< engine + JS booted once+ bool surfaceReady = false; ///< a live window surface is bound (false while screen off)+ uint64_t frame = 0;+};++/** The running host. Valid from the first line of {@link boot}; a binding can only+ * run after that, so bindings dereference it without checking. */+HostState& host();++/** Whether {@link host} is usable at all — for the entry points an event loop may+ * call before boot (or after a failed one). */+bool hostAlive();++/** Installs the state singleton. Called once, by boot(). */+void createHost(Platform& platform);++// =============================================================================+// Logging — the platform's log sink, printf-shaped+// =============================================================================++void hostLog(bool error, const char* fmt, ...);++#define ESHOST_LOGI(...) ::eshost::hostLog(false, __VA_ARGS__)+#define ESHOST_LOGE(...) ::eshost::hostLog(true, __VA_ARGS__)++// =============================================================================+// The JS runtime+// =============================================================================++/** Monotonic milliseconds — the host clock behind performance.now() and timers. */+double nowMs();++/**+ * Bring up QuickJS with the environment the SDK expects but the language does not+ * provide (console, timers, performance), install every es_* binding, then+ * evaluate the SDK bundle and bootstrap.js. Leaves the packaged project's own+ * scripts and init() to {@link runPackagedGame}.+ */+void initRuntime(HostState& h);++/** Evaluate the packaged project (scripts.js, then init()). Returns false when the+ * package carries no export to run — already logged. */+bool runPackagedGame(HostState& h);++/** Bind one global function. */+void bindGlobal(HostState& h, JSValue global, const char* name, JSCFunction* fn, int argc);++/** Report a pending JS exception through the platform log, with its stack. */+void logJsError(JSContext* ctx, const char* where);++/** Evaluate a global script; exceptions are logged, not propagated. */+void evalJs(HostState& h, const char* src, const char* name);++/** Call a global function by name; missing is a no-op, exceptions are logged. */+void callJs(HostState& h, const char* fn, int argc, JSValue* argv);++/** One turn of the host's event loop: microtasks, then timers, then whatever+ * microtasks those timers queued. */+void pumpJs(HostState& h);++// =============================================================================+// Value readers shared by the binding TUs+// =============================================================================++/**+ * Read a byte source into @p out, whatever shape the SDK handed over: a raw+ * ArrayBuffer (audio clip bytes, cache writes), a typed-array view (texture+ * pixels), or a plain JS number array.+ */+void readByteSource(JSContext* ctx, JSValueConst v, std::vector<esengine::u8>& out);++/** A packaged, project-relative file. Empty when missing or before boot. */+std::vector<esengine::u8> readAsset(HostState& h, const char* path);++} // namespace eshostdiff --git a/native/host/bindings/AssetBindings.cpp b/native/host/bindings/AssetBindings.cppnew file mode 100644index 000000000..ecc157d50--- /dev/null+++ b/native/host/bindings/AssetBindings.cpp@@ -0,0 +1,155 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file AssetBindings.cpp+ * @brief Packaged files, image decode, the writable cache, and UTF-8 decoding.+ * @details What the SDK's platform layer reads a game off the device with. The+ * decode path is "Path 2" — the host decodes an image to RGBA and the+ * native ResourceManager uploads the bytes — because there is no+ * offscreen DOM canvas here. The cache is the hot-update offline store:+ * content-addressed keys written after verification, so a returning+ * player boots updated content with no network.+ *+ * @author ESEngine Team+ * @date 2026+ *+ * @copyright Copyright (c) 2026 ESEngine Team+ * Licensed under the Apache License, Version 2.0.+ */+#include "Bindings.hpp"++// stb_image for the native image-decode path (NativeBridge.loadImagePixels). The+// engine core doesn't use stb_image, so this TU owns the implementation.+#define STB_IMAGE_IMPLEMENTATION+#include "stb_image.h"++#include <cstdio>++using namespace esengine;++namespace eshost {+namespace {++// es_readAsset(path) -> ArrayBuffer | null. Backs the bridge's readFile.+JSValue js_readAsset(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {+ const char* path = JS_ToCString(ctx, argv[0]);+ if (!path) return JS_NULL;+ std::vector<u8> bytes = readAsset(host(), path);+ JS_FreeCString(ctx, path);+ if (bytes.empty()) return JS_NULL;+ return JS_NewArrayBufferCopy(ctx, bytes.data(), bytes.size());+}++// es_loadImagePixels(path) -> { width, height, pixels: ArrayBuffer(RGBA) } | null.+// Decodes a packaged image asset to top-first RGBA via stb_image.+JSValue js_loadImagePixels(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {+ const char* path = JS_ToCString(ctx, argv[0]);+ if (!path) return JS_NULL;+ std::vector<u8> file = readAsset(host(), path);+ JS_FreeCString(ctx, path);+ if (file.empty()) return JS_NULL;+ int w = 0, h = 0, ch = 0;+ stbi_uc* px = stbi_load_from_memory(file.data(), (int)file.size(), &w, &h, &ch, 4);+ if (!px) { ESHOST_LOGE("stb_image decode failed"); return JS_NULL; }+ JSValue buf = JS_NewArrayBufferCopy(ctx, px, (size_t)w * (size_t)h * 4);+ stbi_image_free(px);+ JSValue obj = JS_NewObject(ctx);+ JS_SetPropertyStr(ctx, obj, "width", JS_NewInt32(ctx, w));+ JS_SetPropertyStr(ctx, obj, "height", JS_NewInt32(ctx, h));+ JS_SetPropertyStr(ctx, obj, "pixels", buf); // ArrayBuffer; the bootstrap wraps it Uint8Array+ return obj;+}++// The host's writable store, under Platform::cacheDir(). Backs both the+// hot-update offline cache and (through it) key-value storage. Keys are+// content hashes or plain names; anything else is refused rather than escaping+// the directory.+std::string cachePathFor(const char* key) {+ if (!key || !*key || host().cacheDir.empty()) return {};+ for (const char* c = key; *c; ++c) {+ const bool ok = (*c >= 'a' && *c <= 'z') || (*c >= 'A' && *c <= 'Z')+ || (*c >= '0' && *c <= '9') || *c == '.' || *c == '_' || *c == '-';+ if (!ok) return {};+ }+ return host().cacheDir + "/" + key;+}++// es_readCacheFile(key) -> ArrayBuffer | null.+JSValue js_readCacheFile(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {+ const char* key = JS_ToCString(ctx, argv[0]);+ const std::string path = cachePathFor(key);+ if (key) JS_FreeCString(ctx, key);+ if (path.empty()) return JS_NULL;+ FILE* f = fopen(path.c_str(), "rb");+ if (!f) return JS_NULL;+ fseek(f, 0, SEEK_END);+ const long size = ftell(f);+ fseek(f, 0, SEEK_SET);+ std::vector<u8> bytes(size > 0 ? (size_t)size : 0);+ if (!bytes.empty() && fread(bytes.data(), 1, bytes.size(), f) != bytes.size()) bytes.clear();+ fclose(f);+ if (bytes.empty()) return JS_NULL;+ return JS_NewArrayBufferCopy(ctx, bytes.data(), bytes.size());+}++// es_writeCacheFile(key, ArrayBuffer | TypedArray | string) -> bool. A string is+// written as UTF-8, so script-side JSON needs no TextEncoder.+JSValue js_writeCacheFile(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {+ if (argc < 2) return JS_FALSE;+ const char* key = JS_ToCString(ctx, argv[0]);+ const std::string path = cachePathFor(key);+ if (key) JS_FreeCString(ctx, key);+ if (path.empty()) return JS_FALSE;+ std::vector<u8> bytes;+ if (JS_IsString(argv[1])) {+ size_t len = 0;+ if (const char* text = JS_ToCStringLen(ctx, &len, argv[1])) {+ bytes.assign(text, text + len);+ JS_FreeCString(ctx, text);+ }+ } else {+ readByteSource(ctx, argv[1], bytes);+ }+ FILE* f = fopen(path.c_str(), "wb");+ if (!f) return JS_FALSE;+ const bool ok = bytes.empty() || fwrite(bytes.data(), 1, bytes.size(), f) == bytes.size();+ fclose(f);+ return ok ? JS_TRUE : JS_FALSE;+}++// es_utf8Decode(ArrayBuffer | TypedArray) -> string. Backs the TextDecoder the+// platform layer uses to read packaged JSON (manifests, scenes); QuickJS parses+// UTF-8 natively, so this beats decoding byte-by-byte in script.+JSValue js_utf8Decode(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {+ if (argc < 1) return JS_NewString(ctx, "");+ size_t size = 0;+ if (uint8_t* raw = JS_GetArrayBuffer(ctx, &size, argv[0])) {+ return JS_NewStringLen(ctx, reinterpret_cast<const char*>(raw), size);+ }+ JS_FreeValue(ctx, JS_GetException(ctx)); // not an ArrayBuffer — try a view+ size_t offset = 0, length = 0, bytesPerEl = 0;+ JSValue ab = JS_GetTypedArrayBuffer(ctx, argv[0], &offset, &length, &bytesPerEl);+ if (JS_IsException(ab)) { JS_FreeValue(ctx, JS_GetException(ctx)); return JS_NewString(ctx, ""); }+ uint8_t* base = JS_GetArrayBuffer(ctx, &size, ab);+ JSValue out = (base && offset + length <= size)+ ? JS_NewStringLen(ctx, reinterpret_cast<const char*>(base + offset), length)+ : JS_NewString(ctx, "");+ JS_FreeValue(ctx, ab);+ return out;+}++} // namespace++std::vector<u8> readAsset(HostState& h, const char* path) {+ return h.platform ? h.platform->readAsset(path) : std::vector<u8>{};+}++void registerAssetBindings(HostState& h, JSValue global) {+ bindGlobal(h, global, "es_readAsset", js_readAsset, 1);+ bindGlobal(h, global, "es_loadImagePixels", js_loadImagePixels, 1);+ bindGlobal(h, global, "es_readCacheFile", js_readCacheFile, 1);+ bindGlobal(h, global, "es_writeCacheFile", js_writeCacheFile, 2);+ bindGlobal(h, global, "es_utf8Decode", js_utf8Decode, 1);+}++} // namespace eshostdiff --git a/native/host/bindings/AudioBindings.cpp b/native/host/bindings/AudioBindings.cppnew file mode 100644index 000000000..a78e282b2--- /dev/null+++ b/native/host/bindings/AudioBindings.cpp@@ -0,0 +1,126 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file AudioBindings.cpp+ * @brief es_audio* over the host's native engine (miniaudio).+ * @details Host-owned by nature: the engine core has no audio subsystem to+ * generate a binding from — on the web this surface is WebAudio, and on+ * a mini-game it is the vendor's InnerAudioContext. The SDK's+ * NativeAudioBackend is a thin shell over exactly these calls, mirroring+ * the WeChat backend over its host's.+ *+ * Bound ONLY when a sound device came up, so the SDK's hasAudioBindings()+ * gates the native backend on real availability: a host with no device+ * binds none of them and audio falls back to the Null backend.+ *+ * @author ESEngine Team+ * @date 2026+ *+ * @copyright Copyright (c) 2026 ESEngine Team+ * Licensed under the Apache License, Version 2.0.+ */+#include "Bindings.hpp"++using namespace esengine;++namespace eshost {+namespace {++// es_audioLoad(ArrayBuffer | TypedArray) -> { id, duration, bytes } | null. The+// SDK hands the compressed clip bytes; the engine decodes + registers them.+JSValue js_audioLoad(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {+ if (argc < 1) return JS_NULL;+ std::vector<u8> bytes;+ readByteSource(ctx, argv[0], bytes);+ if (bytes.empty()) return JS_NULL;+ auto r = host().audio.load(bytes.data(), bytes.size());+ if (r.id < 0) return JS_NULL;+ JSValue o = JS_NewObject(ctx);+ JS_SetPropertyStr(ctx, o, "id", JS_NewInt32(ctx, r.id));+ JS_SetPropertyStr(ctx, o, "duration", JS_NewFloat64(ctx, r.duration));+ JS_SetPropertyStr(ctx, o, "bytes", JS_NewInt64(ctx, r.bytes));+ return o;+}++JSValue js_audioUnload(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {+ int32_t id = 0; JS_ToInt32(ctx, &id, argv[0]);+ host().audio.unload(id);+ return JS_UNDEFINED;+}++// es_audioPlay(bufferId, volume, pan, loop, rate) -> voiceId (-1 if unknown).+JSValue js_audioPlay(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {+ int32_t buf = 0; JS_ToInt32(ctx, &buf, argv[0]);+ double vol = 1, pan = 0, rate = 1;+ if (argc > 1) JS_ToFloat64(ctx, &vol, argv[1]);+ if (argc > 2) JS_ToFloat64(ctx, &pan, argv[2]);+ const bool loop = argc > 3 && JS_ToBool(ctx, argv[3]);+ if (argc > 4) JS_ToFloat64(ctx, &rate, argv[4]);+ return JS_NewInt32(ctx, host().audio.play(buf, (f32)vol, (f32)pan, loop, (f32)rate));+}++// The voice-scoped commands all take the voice id as argv[0].+int32_t voiceArg(JSContext* ctx, JSValueConst* argv) {+ int32_t v = 0; JS_ToInt32(ctx, &v, argv[0]); return v;+}+JSValue js_audioStop(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {+ host().audio.stop(voiceArg(ctx, argv)); return JS_UNDEFINED;+}+JSValue js_audioPause(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {+ host().audio.pause(voiceArg(ctx, argv)); return JS_UNDEFINED;+}+JSValue js_audioResume(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {+ host().audio.resume(voiceArg(ctx, argv)); return JS_UNDEFINED;+}+JSValue js_audioSetVolume(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {+ double v = 1; JS_ToFloat64(ctx, &v, argv[1]);+ host().audio.setVolume(voiceArg(ctx, argv), (f32)v); return JS_UNDEFINED;+}+JSValue js_audioSetPan(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {+ double p = 0; JS_ToFloat64(ctx, &p, argv[1]);+ host().audio.setPan(voiceArg(ctx, argv), (f32)p); return JS_UNDEFINED;+}+JSValue js_audioSetLoop(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {+ host().audio.setLoop(voiceArg(ctx, argv), JS_ToBool(ctx, argv[1]) != 0); return JS_UNDEFINED;+}+JSValue js_audioSetRate(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {+ double r = 1; JS_ToFloat64(ctx, &r, argv[1]);+ host().audio.setRate(voiceArg(ctx, argv), (f32)r); return JS_UNDEFINED;+}++// es_audioVoiceState(voiceId) -> { playing, currentTime } | null (null once ended).+JSValue js_audioVoiceState(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {+ auto st = host().audio.voiceState(voiceArg(ctx, argv));+ if (!st.valid) return JS_NULL;+ JSValue o = JS_NewObject(ctx);+ JS_SetPropertyStr(ctx, o, "playing", JS_NewBool(ctx, st.playing));+ JS_SetPropertyStr(ctx, o, "currentTime", JS_NewFloat64(ctx, st.currentTime));+ return o;+}+JSValue js_audioSuspendAll(JSContext* ctx, JSValueConst, int, JSValueConst*) {+ host().audio.suspendAll(); return JS_UNDEFINED;+}+JSValue js_audioResumeAll(JSContext* ctx, JSValueConst, int, JSValueConst*) {+ host().audio.resumeAll(); return JS_UNDEFINED;+}++} // namespace++void registerAudioBindings(HostState& h, JSValue global) {+ if (!h.audio.ready()) return;+ bindGlobal(h, global, "es_audioLoad", js_audioLoad, 1);+ bindGlobal(h, global, "es_audioUnload", js_audioUnload, 1);+ bindGlobal(h, global, "es_audioPlay", js_audioPlay, 5);+ bindGlobal(h, global, "es_audioStop", js_audioStop, 1);+ bindGlobal(h, global, "es_audioPause", js_audioPause, 1);+ bindGlobal(h, global, "es_audioResume", js_audioResume, 1);+ bindGlobal(h, global, "es_audioSetVolume", js_audioSetVolume, 2);+ bindGlobal(h, global, "es_audioSetPan", js_audioSetPan, 2);+ bindGlobal(h, global, "es_audioSetLoop", js_audioSetLoop, 2);+ bindGlobal(h, global, "es_audioSetRate", js_audioSetRate, 2);+ bindGlobal(h, global, "es_audioVoiceState", js_audioVoiceState, 1);+ bindGlobal(h, global, "es_audioSuspendAll", js_audioSuspendAll, 0);+ bindGlobal(h, global, "es_audioResumeAll", js_audioResumeAll, 0);+}++} // namespace eshostdiff --git a/native/host/bindings/EcsBindings.cpp b/native/host/bindings/EcsBindings.cppnew file mode 100644index 000000000..737ac16fb--- /dev/null+++ b/native/host/bindings/EcsBindings.cpp@@ -0,0 +1,78 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file EcsBindings.cpp+ * @brief Entity + hierarchy — the base Registry surface the SDK's World drives.+ * @details Entity ids cross as the native Entity's raw u32 (round-tripped via+ * Entity::fromRaw), so a hierarchy query returns ids the SDK recognises.+ *+ * Hand-written because there is nothing to generate from: the web build+ * reaches the registry as an embind CLASS, not as free binding entry+ * points, so no binding header declares this surface. Everything+ * per-component — es_set_<C>, es_<C>_buffer, _has, _remove — IS generated,+ * from the same reflection the web's embind bindings come from.+ *+ * @author ESEngine Team+ * @date 2026+ *+ * @copyright Copyright (c) 2026 ESEngine Team+ * Licensed under the Apache License, Version 2.0.+ */+#include "Bindings.hpp"++#include "esn_shim.hpp" // esn_entity++#include "esengine/ecs/TransformSystem.hpp" // ecs::setParent+#include "esengine/ecs/components/Hierarchy.hpp" // Parent / Children++using namespace esengine;++namespace eshost {+namespace {++JSValue js_createEntity(JSContext* ctx, JSValueConst, int, JSValueConst*) {+ return JS_NewUint32(ctx, host().registry->create().id());+}+JSValue js_destroyEntity(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {+ host().registry->destroy(esn_entity(ctx, argv[0]));+ return JS_UNDEFINED;+}+JSValue js_setParent(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {+ ecs::setParent(*host().registry, esn_entity(ctx, argv[0]), esn_entity(ctx, argv[1]));+ return JS_UNDEFINED;+}+JSValue js_hasParent(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {+ return JS_NewBool(ctx, host().registry->has<ecs::Parent>(esn_entity(ctx, argv[0])));+}+JSValue js_removeParent(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {+ ecs::setParent(*host().registry, esn_entity(ctx, argv[0]), INVALID_ENTITY);+ return JS_UNDEFINED;+}+JSValue js_hasChildren(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {+ auto* c = host().registry->tryGet<ecs::Children>(esn_entity(ctx, argv[0]));+ return JS_NewBool(ctx, c && !c->entities.empty());+}+JSValue js_getChildren(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {+ JSValue arr = JS_NewArray(ctx);+ if (auto* c = host().registry->tryGet<ecs::Children>(esn_entity(ctx, argv[0]))) {+ uint32_t i = 0;+ for (Entity child : c->entities) {+ JS_SetPropertyUint32(ctx, arr, i++, JS_NewUint32(ctx, child.id()));+ }+ }+ return arr;+}++} // namespace++void registerEcsBindings(HostState& h, JSValue global) {+ bindGlobal(h, global, "es_createEntity", js_createEntity, 0);+ bindGlobal(h, global, "es_destroyEntity", js_destroyEntity, 1);+ bindGlobal(h, global, "es_setParent", js_setParent, 2);+ bindGlobal(h, global, "es_hasParent", js_hasParent, 1);+ bindGlobal(h, global, "es_removeParent", js_removeParent, 1);+ bindGlobal(h, global, "es_hasChildren", js_hasChildren, 1);+ bindGlobal(h, global, "es_getChildren", js_getChildren, 1);+}++} // namespace eshostdiff --git a/native/host/bindings/NetBindings.cpp b/native/host/bindings/NetBindings.cppnew file mode 100644index 000000000..8c64186de--- /dev/null+++ b/native/host/bindings/NetBindings.cpp@@ -0,0 +1,161 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file NetBindings.cpp+ * @brief es_fetch over the platform's native networking, and the thread-safe+ * hand-back that makes it usable from JS.+ * @details Host-owned: the OS owns the TLS stack, so the request itself is one of+ * the few things that genuinely differs per platform (NSURLSession /+ * a JNI HttpURLConnection). Everything around it is here — the request is+ * read off a JS object, handed to {@link Platform::startFetch}, and the+ * reply comes back on whatever thread the completion runs on. That reply+ * is queued as POD and drained on the JS thread in the frame loop, so no+ * JS value is ever touched off-thread.+ *+ * @author ESEngine Team+ * @date 2026+ *+ * @copyright Copyright (c) 2026 ESEngine Team+ * Licensed under the Apache License, Version 2.0.+ */+#include "Bindings.hpp"++#include <mutex>+#include <queue>+#include <utility>++using namespace esengine;++namespace eshost {+namespace {++// HTTP replies cross back from whatever thread the platform's completion runs on.+// The platform enqueues here (POD only, no JS); the frame loop drains it on the JS+// thread and runs the callbacks. A namespace-scope queue, so deliverFetch (a free+// function the glue calls) is safe before boot and after teardown alike.+std::mutex g_fetchMutex;+std::queue<FetchResult> g_fetchQueue;++std::string fetchStrProp(JSContext* ctx, JSValueConst obj, const char* key, const char* dflt) {+ JSValue v = JS_GetPropertyStr(ctx, obj, key);+ std::string out = dflt ? dflt : "";+ if (JS_IsString(v)) {+ if (const char* s = JS_ToCString(ctx, v)) { out = s; JS_FreeCString(ctx, s); }+ }+ JS_FreeValue(ctx, v);+ return out;+}++void readFetchHeaders(JSContext* ctx, JSValueConst obj, FetchRequest& req) {+ JSValue h = JS_GetPropertyStr(ctx, obj, "headers");+ if (JS_IsObject(h)) {+ JSPropertyEnum* tab = nullptr;+ uint32_t len = 0;+ if (JS_GetOwnPropertyNames(ctx, &tab, &len, h, JS_GPN_STRING_MASK | JS_GPN_ENUM_ONLY) == 0) {+ for (uint32_t i = 0; i < len; ++i) {+ const char* key = JS_AtomToCString(ctx, tab[i].atom);+ JSValue val = JS_GetProperty(ctx, h, tab[i].atom);+ const char* vs = JS_ToCString(ctx, val);+ if (key && vs) req.headers.emplace_back(key, vs);+ if (vs) JS_FreeCString(ctx, vs);+ if (key) JS_FreeCString(ctx, key);+ JS_FreeValue(ctx, val);+ }+ JS_FreePropertyEnum(ctx, tab, len);+ }+ }+ JS_FreeValue(ctx, h);+}++// es_fetch(request, callback): request = { url, method?, headers?, body?,+// responseType? }. Runs the request off the main thread and calls back with+// { ok, status, statusText, headers, arrayBuffer | text, error? }. The bridge+// wraps this in a Promise. responseType 'text' returns a string; everything else+// returns an ArrayBuffer (the bridge decodes text/json from it on demand).+JSValue js_fetch(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {+ if (argc < 2 || !JS_IsObject(argv[0]) || !JS_IsFunction(ctx, argv[1])) return JS_UNDEFINED;+ HostState& h = host();+ FetchRequest req;+ req.id = h.nextFetchId++;+ req.url = fetchStrProp(ctx, argv[0], "url", "");+ req.method = fetchStrProp(ctx, argv[0], "method", "GET");+ req.wantText = fetchStrProp(ctx, argv[0], "responseType", "arraybuffer") == "text";+ readFetchHeaders(ctx, argv[0], req);+ JSValue body = JS_GetPropertyStr(ctx, argv[0], "body");+ if (JS_IsString(body)) {+ size_t len = 0;+ if (const char* s = JS_ToCStringLen(ctx, &len, body)) {+ req.body.assign(s, s + len);+ JS_FreeCString(ctx, s);+ }+ } else if (!JS_IsUndefined(body) && !JS_IsNull(body)) {+ readByteSource(ctx, body, req.body);+ }+ JS_FreeValue(ctx, body);++ h.fetchCallbacks[req.id] = JS_DupValue(ctx, argv[1]);+ if (req.url.empty()) {+ FetchResult err;+ err.id = req.id;+ err.error = "es_fetch: missing url";+ deliverFetch(std::move(err));+ } else {+ h.platform->startFetch(req);+ }+ return JS_UNDEFINED;+}++JSValue makeFetchResult(HostState& h, const FetchResult& r) {+ JSValue o = JS_NewObject(h.js);+ JS_SetPropertyStr(h.js, o, "ok", JS_NewBool(h.js, r.ok));+ JS_SetPropertyStr(h.js, o, "status", JS_NewInt32(h.js, r.status));+ JS_SetPropertyStr(h.js, o, "statusText", JS_NewString(h.js, r.statusText.c_str()));+ if (!r.error.empty()) JS_SetPropertyStr(h.js, o, "error", JS_NewString(h.js, r.error.c_str()));+ JSValue headers = JS_NewObject(h.js);+ for (const auto& kv : r.headers) {+ JS_SetPropertyStr(h.js, headers, kv.first.c_str(), JS_NewString(h.js, kv.second.c_str()));+ }+ JS_SetPropertyStr(h.js, o, "headers", headers);+ if (r.isText) {+ JS_SetPropertyStr(h.js, o, "text",+ JS_NewStringLen(h.js, reinterpret_cast<const char*>(r.body.data()), r.body.size()));+ } else {+ JS_SetPropertyStr(h.js, o, "arrayBuffer",+ JS_NewArrayBufferCopy(h.js, r.body.data(), r.body.size()));+ }+ return o;+}++} // namespace++void drainFetches(HostState& h) {+ std::queue<FetchResult> done;+ { std::lock_guard<std::mutex> lk(g_fetchMutex); done.swap(g_fetchQueue); }+ while (!done.empty()) {+ const FetchResult r = std::move(done.front());+ done.pop();+ auto it = h.fetchCallbacks.find(r.id);+ if (it == h.fetchCallbacks.end()) continue; // never happens, but stay safe+ JSValue cb = it->second;+ h.fetchCallbacks.erase(it);+ JSValue arg = makeFetchResult(h, r);+ JSValue ret = JS_Call(h.js, cb, JS_UNDEFINED, 1, &arg);+ if (JS_IsException(ret)) logJsError(h.js, "es_fetch callback");+ JS_FreeValue(h.js, ret);+ JS_FreeValue(h.js, arg);+ JS_FreeValue(h.js, cb);+ }+}++void registerNetBindings(HostState& h, JSValue global) {+ bindGlobal(h, global, "es_fetch", js_fetch, 2);+}++// Thread-safe: the platform's HTTP completion (any thread) queues its reply here;+// the frame loop drains it on the JS thread (drainFetches). No JS is touched here.+void deliverFetch(FetchResult result) {+ std::lock_guard<std::mutex> lk(g_fetchMutex);+ g_fetchQueue.push(std::move(result));+}++} // namespace eshostdiff --git a/native/host/bindings/RenderBindings.cpp b/native/host/bindings/RenderBindings.cppnew file mode 100644index 000000000..d722c3031--- /dev/null+++ b/native/host/bindings/RenderBindings.cpp@@ -0,0 +1,162 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file RenderBindings.cpp+ * @brief The rendering calls that have no generated form — and only those.+ * @details Most of what the SDK's renderer, asset pipeline and glyph atlas need is+ * GENERATED from the `bindings` headers: `es_renderer_*` drives the frame,+ * `es_rm_*` creates, releases and updates textures, `es_renderer_submitTextBatch`+ * takes the laid-out glyph quads. Those come from the same declarations+ * embind registers on the web, so one implementation serves both platforms+ * and both get its BoundarySpan validation.+ *+ * Three things cannot come from there, and are here:+ * * KTX2 transcode — native-only; the web path is WebGL2 + a wasm+ * transcoder, so there is no shared entry point to generate from.+ * * Glyph rasterization — the device has no 2D canvas, so the host owns+ * the font stack. Also native-only.+ * * Two queries whose web siblings return an `emscripten::val`+ * (the surface size and the camera list), a shape the boundary+ * cannot marshal.+ *+ * @author ESEngine Team+ * @date 2026+ *+ * @copyright Copyright (c) 2026 ESEngine Team+ * Licensed under the Apache License, Version 2.0.+ */+#include "Bindings.hpp"++#include "media/glyph_raster.hpp"+#include "media/ktx2_decode.hpp"++#include "esengine/ecs/components/Camera.hpp"+#include "esengine/ecs/components/Transform.hpp"+#include "esengine/resource/ResourceManager.hpp"++using namespace esengine;++namespace eshost {+namespace {++// es_createTextureKTX2(ArrayBuffer|TypedArray, srgb?) -> { id, width, height } | null.+// Transcodes a KTX2/Basis container to the best device-supported compressed format+// (or RGBA32) and uploads it. Native-only: the web transcodes in a wasm module and+// uploads through WebGL2, so there is no engine entry point shared with it.+JSValue js_createTextureKTX2(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {+ if (argc < 1) return JS_NULL;+ std::vector<u8> bytes;+ readByteSource(ctx, argv[0], bytes);+ if (bytes.empty()) return JS_NULL;+ const bool srgb = argc > 1 && JS_ToBool(ctx, argv[1]) != 0;+ auto r = transcodeKTX2(bytes.data(), bytes.size(), srgb,+ host().ctx->require<resource::ResourceManager>(), *host().gfx);+ if (r.handle < 0) return JS_NULL;+ JSValue o = JS_NewObject(ctx);+ JS_SetPropertyStr(ctx, o, "id", JS_NewInt32(ctx, r.handle));+ JS_SetPropertyStr(ctx, o, "width", JS_NewInt32(ctx, r.width));+ JS_SetPropertyStr(ctx, o, "height", JS_NewInt32(ctx, r.height));+ return o;+}++// es_getTextureDimensions(handle) -> { width, height } | null. The engine's+// rm_getTextureDimensions returns an emscripten::val, so this one query stays+// hand-written; it reads the same ResourceManager that entry point would.+JSValue js_getTextureDimensions(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {+ int64_t id = 0;+ JS_ToInt64(ctx, &id, argv[0]);+ auto* tex = host().ctx->require<resource::ResourceManager>().getTexture(+ resource::TextureHandle((u32)id));+ if (!tex) return JS_NULL;+ JSValue obj = JS_NewObject(ctx);+ JS_SetPropertyStr(ctx, obj, "width", JS_NewInt32(ctx, (int32_t)tex->getWidth()));+ JS_SetPropertyStr(ctx, obj, "height", JS_NewInt32(ctx, (int32_t)tex->getHeight()));+ return obj;+}++// es_rasterizeGlyph({ codepoint, fontFamily, style, pixelSize, sdf, padding })+// -> { pixels: ArrayBuffer, width, height, advance, bearingX, bearingY } | null.+// The device's answer to the browser's 2D canvas; see media/glyph_raster.hpp.+JSValue js_rasterizeGlyph(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {+ if (argc < 1 || !hostAlive() || !host().platform) return JS_NULL;+ JSValue req = argv[0];++ const auto numberField = [&](const char* name, double fallback) {+ JSValue v = JS_GetPropertyStr(ctx, req, name);+ double out = fallback;+ if (!JS_IsUndefined(v)) JS_ToFloat64(ctx, &out, v);+ JS_FreeValue(ctx, v);+ return out;+ };+ const auto boolField = [&](const char* name) {+ JSValue v = JS_GetPropertyStr(ctx, req, name);+ const bool out = JS_ToBool(ctx, v) != 0;+ JS_FreeValue(ctx, v);+ return out;+ };++ std::string family;+ JSValue familyVal = JS_GetPropertyStr(ctx, req, "fontFamily");+ if (const char* s = JS_ToCString(ctx, familyVal)) {+ family = s;+ JS_FreeCString(ctx, s);+ }+ JS_FreeValue(ctx, familyVal);++ const auto glyph = rasterizeGlyph(+ *host().platform,+ (uint32_t)numberField("codepoint", 0),+ family,+ (int)numberField("style", 0),+ (float)numberField("pixelSize", 48),+ boolField("sdf"),+ (float)numberField("padding", 6));+ if (!glyph.ok) return JS_NULL;++ JSValue o = JS_NewObject(ctx);+ JS_SetPropertyStr(ctx, o, "pixels",+ glyph.rgba.empty() ? JS_NewArrayBufferCopy(ctx, nullptr, 0)+ : JS_NewArrayBufferCopy(ctx, glyph.rgba.data(), glyph.rgba.size()));+ JS_SetPropertyStr(ctx, o, "width", JS_NewInt32(ctx, glyph.width));+ JS_SetPropertyStr(ctx, o, "height", JS_NewInt32(ctx, glyph.height));+ JS_SetPropertyStr(ctx, o, "advance", JS_NewFloat64(ctx, glyph.advance));+ JS_SetPropertyStr(ctx, o, "bearingX", JS_NewFloat64(ctx, glyph.bearingX));+ JS_SetPropertyStr(ctx, o, "bearingY", JS_NewFloat64(ctx, glyph.bearingY));+ return o;+}++// es_renderer_surfaceSize() -> { width, height }: the camera plugin reads it per+// frame, so a rotation reaches the projection without an event.+JSValue js_renderer_surfaceSize(JSContext* ctx, JSValueConst, int, JSValueConst*) {+ JSValue o = JS_NewObject(ctx);+ JS_SetPropertyStr(ctx, o, "width", JS_NewInt32(ctx, hostAlive() ? (int32_t)host().w : 0));+ JS_SetPropertyStr(ctx, o, "height", JS_NewInt32(ctx, hostAlive() ? (int32_t)host().h : 0));+ return o;+}++// es_registry_getCameraEntities() -> [entity]. Active cameras with a Transform,+// as the web binding reports them (its sibling returns an emscripten::val array).+JSValue js_registry_getCameraEntities(JSContext* ctx, JSValueConst, int, JSValueConst*) {+ JSValue arr = JS_NewArray(ctx);+ if (!hostAlive() || !host().registry) return arr;+ auto& registry = *host().registry;+ uint32_t n = 0;+ for (auto entity : registry.view<ecs::Camera, ecs::Transform>()) {+ if (registry.get<ecs::Camera>(entity).isActive) {+ JS_SetPropertyUint32(ctx, arr, n++, JS_NewInt32(ctx, (int32_t)entity.id()));+ }+ }+ return arr;+}++} // namespace++void registerRenderBindings(HostState& h, JSValue global) {+ bindGlobal(h, global, "es_createTextureKTX2", js_createTextureKTX2, 2);+ bindGlobal(h, global, "es_getTextureDimensions", js_getTextureDimensions, 1);+ bindGlobal(h, global, "es_rasterizeGlyph", js_rasterizeGlyph, 1);+ bindGlobal(h, global, "es_renderer_surfaceSize", js_renderer_surfaceSize, 0);+ bindGlobal(h, global, "es_registry_getCameraEntities", js_registry_getCameraEntities, 0);+}++} // namespace eshostdiff --git a/native/host/bootstrap.js b/native/host/bootstrap.jsnew file mode 100644index 000000000..38c60b04f--- /dev/null+++ b/native/host/bootstrap.js@@ -0,0 +1,41 @@+// The host bootstrap — HOST code, not game code. Embedded into the binary at+// build time (build-tools/tasks/native.js writes host_bootstrap.h), the way the+// SDK bundle is, and evaluated right after it.+//+// A real .js file rather than a C++ string literal: it is JavaScript, so it should+// be lintable, highlightable and diffable as JavaScript.+//+// Deliberately small. The bridge itself is assembled by the SDK+// (createHostBridge) from the es_* primitives the host binds — typed there+// against the interface it must satisfy — so what is left here is only what a JS+// string in the host can do: the TextDecoder shim, and the default entry points.++// The platform layer decodes packaged JSON through TextDecoder; QuickJS has none,+// so route it to the host's UTF-8 decoder. Only utf-8 is meaningful here.+globalThis.TextDecoder = function TextDecoder() {};+globalThis.TextDecoder.prototype.decode = function (buf) {+ return buf == null ? '' : es_utf8Decode(buf);+};++// The whole host contract in one check — the JS globals a bare engine lacks and+// the es_* bindings this shell binds — so a gap is named here, not downstream.+ESEngine.assertNativeHost(globalThis);++// The bridge over the host's es_* bindings; it also installs es_onNativeTouch,+// the entry point the host calls per touch.+globalThis.__esNativeBridge = ESEngine.createHostBridge(globalThis);++// Boot an EXPORTED project: game.config.json, the manifests, the cooked assets+// and the scenes, all read off the device. This is the only way in — a packaged+// game always comes from the editor.+globalThis.__esGame = null;+globalThis.init = function () {+ ESEngine.initNativeGame({ bridge: globalThis.__esNativeBridge, scope: globalThis, width: W, height: H })+ .then(function (game) { globalThis.__esGame = game; })+ .catch(function (e) {+ console.error('exported game failed to boot:', e && e.message ? e.message : e);+ });+};+globalThis.update = function (dt) {+ if (globalThis.__esGame) globalThis.__esGame.app.tick(dt);+};diff --git a/native/host_js/esn_shim.hpp b/native/host/esn_shim.hppsimilarity index 75%rename from native/host_js/esn_shim.hpprename to native/host/esn_shim.hppindex 51925c035..04af3aca4 100644--- a/native/host_js/esn_shim.hpp+++ b/native/host/esn_shim.hpp@@ -1,6 +1,6 @@// Runtime shim the EHT-generated native bindings call. The generator emits the// per-field marshalling (reflection-driven); this header declares the plumbing-// (registry access, entity lookup, JS-value readers) that the host defines.+// (engine singletons, entity lookup, JS-value readers) that the host defines.//// NativeBindings.generated.cpp includes this header first, then self-includes// each bound component's header — so the shim itself needs no component headers.@@ -10,13 +10,18 @@ extern "C" {#include "quickjs.h"}-#include "esengine/ecs/Registry.hpp" // esengine::ecs::Registry + esengine::Entity-#include "esengine/core/Types.hpp" // esengine::u8+#include "esengine/ecs/Registry.hpp" // esengine::ecs::Registry + esengine::Entity+#include "esengine/resource/ResourceManager.hpp" // esengine::resource::ResourceManager+#include "esengine/core/Types.hpp" // esengine::u8#include <vector>-// --- provided by the host (js/main.cpp) --------------------------------------+// --- provided by the host (host/Runtime.cpp) ---------------------------------+// The engine singletons a binding declaration takes by reference: the host runs+// exactly one of each, so the generated wrapper passes these instead of reading+// a JS argument.esengine::ecs::Registry& esn_reg();+esengine::resource::ResourceManager& esn_rm();esengine::Entity esn_entity(JSContext* ctx, JSValueConst v);// Read obj[key] as a number into *out; returns true if present & numeric.bool esn_getnum(JSContext* ctx, JSValueConst obj, const char* key, double* out);diff --git a/native/host_js/glyph_raster.cpp b/native/host/media/glyph_raster.cppsimilarity index 99%rename from native/host_js/glyph_raster.cpprename to native/host/media/glyph_raster.cppindex 8d79fd758..8d6fe228a 100644--- a/native/host_js/glyph_raster.cpp+++ b/native/host/media/glyph_raster.cpp@@ -6,7 +6,7 @@*/#include "glyph_raster.hpp"-#include "host_core.hpp"+#include "Host.hpp"#include "esengine/text/SdfGenerator.hpp"diff --git a/native/host_js/glyph_raster.hpp b/native/host/media/glyph_raster.hppsimilarity index 100%rename from native/host_js/glyph_raster.hpprename to native/host/media/glyph_raster.hppdiff --git a/native/host_js/ktx2_decode.cpp b/native/host/media/ktx2_decode.cppsimilarity index 100%rename from native/host_js/ktx2_decode.cpprename to native/host/media/ktx2_decode.cppdiff --git a/native/host_js/ktx2_decode.hpp b/native/host/media/ktx2_decode.hppsimilarity index 100%rename from native/host_js/ktx2_decode.hpprename to native/host/media/ktx2_decode.hppdiff --git a/native/host_js/native_audio.cpp b/native/host/media/native_audio.cppsimilarity index 100%rename from native/host_js/native_audio.cpprename to native/host/media/native_audio.cppdiff --git a/native/host_js/native_audio.hpp b/native/host/media/native_audio.hppsimilarity index 100%rename from native/host_js/native_audio.hpprename to native/host/media/native_audio.hppdiff --git a/native/host_js/main_android.cpp b/native/host/platform/android.cppsimilarity index 99%rename from native/host_js/main_android.cpprename to native/host/platform/android.cppindex 9ee40406a..f872f65ab 100644--- a/native/host_js/main_android.cpp+++ b/native/host/platform/android.cpp@@ -24,8 +24,8 @@#include <thread>-#include "host_core.hpp"-#include "glyph_raster.hpp" // GLYPH_BOLD / GLYPH_ITALIC, for the font match+#include "Host.hpp"+#include "media/glyph_raster.hpp" // GLYPH_BOLD / GLYPH_ITALIC, for the font match#define LOG_TAG "EstellaSDK"@@ -297,7 +297,7 @@ void onAppCmd(android_app* app, int32_t cmd) {} // namespacevoid android_main(android_app* app) {- g_platform.assets = app->activity->assetManager; // APK assets/ (game.js + content)+ g_platform.assets = app->activity->assetManager; // APK assets/ (the exported project)g_platform.vm = app->activity->vm; // for JNI HttpURLConnection (es_fetch)if (app->activity->internalDataPath) g_platform.cache = app->activity->internalDataPath;app->onAppCmd = onAppCmd;diff --git a/native/host_js/main_ios.mm b/native/host/platform/ios.mmsimilarity index 99%rename from native/host_js/main_ios.mmrename to native/host/platform/ios.mmindex a9a273d81..aedf8843f 100644--- a/native/host_js/main_ios.mm+++ b/native/host/platform/ios.mm@@ -24,8 +24,8 @@#import <QuartzCore/CAMetalLayer.h>#import <CoreText/CoreText.h>-#include "host_core.hpp"-#include "glyph_raster.hpp" // GLYPH_BOLD / GLYPH_ITALIC, for the font match+#include "Host.hpp"+#include "media/glyph_raster.hpp" // GLYPH_BOLD / GLYPH_ITALIC, for the font matchusing esengine::u32;using esengine::u8;diff --git a/native/host_cpp/main.cpp b/native/host_cpp/main.cppdeleted file mode 100644index a739ae705..000000000--- a/native/host_cpp/main.cpp+++ /dev/null@@ -1,229 +0,0 @@-// Reference native host: boots EstellaContext with every WebGPU-relevant subsystem-// and renders one ECS scene through the production path — TransformSystem ->-// RenderFrame.begin/collectAll/flush/end -> present. The web harness-// (tests/renderer/webgpu_engine_bringup.cpp) gets its device from-// emscripten_webgpu_get_device() + configureSurface("#canvas"); this host builds-// the instance/adapter/device itself and calls-// configureSurface(NativeSurface{AndroidWindow}). Native Dawn -> Vulkan, no wasm.--#include <android_native_app_glue.h>-#include <android/log.h>-#include <android/native_window.h>--#include "esengine/core/EstellaContext.hpp"-#include "esengine/core/World.hpp"-#include "esengine/ecs/Registry.hpp"-#include "esengine/ecs/TransformSystem.hpp"-#include "esengine/ecs/components/Transform.hpp"-#include "esengine/ecs/components/Sprite.hpp"-#include "esengine/ecs/components/ShapeRenderer.hpp"-#include "esengine/ecs/components/Light2D.hpp"-#include "esengine/renderer/RenderContext.hpp"-#include "esengine/renderer/RenderFrame.hpp"-#include "esengine/renderer/webgpu/WebGPUDevice.hpp"-#include "esengine/resource/ResourceManager.hpp"--#include <glm/gtc/matrix_transform.hpp>--#define LOG_TAG "EstellaFrame"-#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)-#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)--using namespace esengine;--namespace {--struct App {- WGPUInstance instance = nullptr;- WGPUAdapter adapter = nullptr;- WGPUDevice device = nullptr;- WebGPUDevice* gfx = nullptr; // owned by context after init; raw for present()- EstellaContext* ctx = nullptr;- ecs::Registry* registry = nullptr;- f32 w = 0, h = 0;- f32 elapsed = 0.0f;- bool ready = false;- uint64_t frame = 0;-};--void onDeviceError(WGPUDevice const*, WGPUErrorType t, WGPUStringView m, void*, void*) {- LOGE("uncaptured error (0x%x): %.*s", (unsigned)t, (int)m.length, m.data ? m.data : "");-}-void onAdapter(WGPURequestAdapterStatus s, WGPUAdapter a, WGPUStringView m, void* ud1, void*) {- if (s == WGPURequestAdapterStatus_Success) *static_cast<WGPUAdapter*>(ud1) = a;- else LOGE("adapter fail: %.*s", (int)m.length, m.data ? m.data : "");-}-void onDevice(WGPURequestDeviceStatus s, WGPUDevice d, WGPUStringView m, void* ud1, void*) {- if (s == WGPURequestDeviceStatus_Success) *static_cast<WGPUDevice*>(ud1) = d;- else LOGE("device fail: %.*s", (int)m.length, m.data ? m.data : "");-}--void buildScene(EstellaContext& ctx, ecs::Registry& reg, f32 W, f32 H) {- auto& rm = ctx.require<resource::ResourceManager>();- const f32 s = (W < H ? W : H); // short side, for pixel sizes-- // 2x2 four-colour checker (red/green/blue/yellow).- const u8 checker[16] = {- 255, 0, 0, 255, 0, 255, 0, 255,- 0, 0, 255, 255, 255, 255, 0, 255,- };- auto checkerTex = rm.createTexture(2, 2, ConstSpan<u8>(checker, sizeof(checker)), TextureFormat::RGBA8);- const u8 white[4] = {255, 255, 255, 255};- auto whiteTex = rm.createTexture(1, 1, ConstSpan<u8>(white, sizeof(white)), TextureFormat::RGBA8);-- // Checker sprite, upper area.- {- auto e = reg.create();- auto& t = reg.emplace<ecs::Transform>(e);- t.position = {W * 0.5f, H * 0.62f, 0.0f};- auto& sp = reg.emplace<ecs::Sprite>(e);- sp.texture = checkerTex;- sp.size = {s * 0.5f, s * 0.5f};- }- // Magenta SDF circle, middle.- {- auto e = reg.create();- auto& t = reg.emplace<ecs::Transform>(e);- t.position = {W * 0.32f, H * 0.42f, 0.0f};- auto& sh = reg.emplace<ecs::ShapeRenderer>(e);- sh.shapeType = 0; // circle- sh.color = {1.0f, 0.0f, 1.0f, 1.0f};- sh.size = {s * 0.28f, s * 0.28f};- }- // Lit white sprite + a red point light + ambient, so lighting shows.- {- auto e = reg.create();- auto& t = reg.emplace<ecs::Transform>(e);- t.position = {W * 0.68f, H * 0.42f, 0.0f};- auto& sp = reg.emplace<ecs::Sprite>(e);- sp.texture = whiteTex;- sp.size = {s * 0.28f, s * 0.28f};- sp.lit = true;- }- {- auto e = reg.create();- auto& t = reg.emplace<ecs::Transform>(e);- t.position = {W * 0.68f, H * 0.42f, 0.0f};- auto& l = reg.emplace<ecs::Light2D>(e);- l.type = static_cast<i32>(ecs::Light2DType::Point);- l.color = {1.0f, 0.3f, 0.1f, 1.0f};- l.intensity = 1.5f;- l.radius = s * 0.5f;- }- {- auto e = reg.create();- reg.emplace<ecs::Transform>(e);- auto& l = reg.emplace<ecs::Light2D>(e);- l.type = static_cast<i32>(ecs::Light2DType::Ambient);- l.color = {1.0f, 1.0f, 1.0f, 1.0f};- l.intensity = 0.25f;- }-}--void renderScene(App& a) {- if (!a.ready) return;- auto& ctx = *a.ctx;- auto& reg = *a.registry;-- a.elapsed += 1.0f / 60.0f;- ctx.require<RenderContext>().setFrameTime(a.elapsed, (u32)a.w, (u32)a.h);-- World world{reg, ctx.services(), 1.0f / 60.0f};- ctx.require<ecs::TransformSystem>().update(world);-- // World units are pixels, y up.- const glm::mat4 vp = glm::ortho(0.0f, a.w, 0.0f, a.h);-- auto& rf = ctx.require<RenderFrame>();- rf.begin(vp, 0, RenderFrame::PassClear{true, true, glm::vec4(0.08f, 0.09f, 0.13f, 1.0f)});- rf.collectAll(reg);- rf.flush();- rf.end();-- a.gfx->present();-- if (++a.frame % 120 == 0) LOGI("engine scene frame %llu", (unsigned long long)a.frame);-}--void initEngine(App& a, ANativeWindow* window) {- WGPUInstanceFeatureName feats[] = {WGPUInstanceFeatureName_TimedWaitAny};- WGPUInstanceDescriptor idesc = {};- idesc.requiredFeatureCount = 1;- idesc.requiredFeatures = feats;- a.instance = wgpuCreateInstance(&idesc);-- WGPURequestAdapterOptions opts = {};- opts.powerPreference = WGPUPowerPreference_HighPerformance;- opts.backendType = WGPUBackendType_Vulkan;- WGPURequestAdapterCallbackInfo aci = {};- aci.mode = WGPUCallbackMode_WaitAnyOnly;- aci.callback = onAdapter;- aci.userdata1 = &a.adapter;- WGPUFutureWaitInfo af = {wgpuInstanceRequestAdapter(a.instance, &opts, aci), 0};- wgpuInstanceWaitAny(a.instance, 1, &af, UINT64_MAX);- if (!a.adapter) { LOGE("no adapter"); return; }-- WGPUDeviceDescriptor dd = {};- dd.uncapturedErrorCallbackInfo.callback = onDeviceError;- WGPURequestDeviceCallbackInfo dci = {};- dci.mode = WGPUCallbackMode_WaitAnyOnly;- dci.callback = onDevice;- dci.userdata1 = &a.device;- WGPUFutureWaitInfo df = {wgpuAdapterRequestDevice(a.adapter, &dd, dci), 0};- wgpuInstanceWaitAny(a.instance, 1, &df, UINT64_MAX);- if (!a.device) { LOGE("no device"); return; }-- a.w = (f32)ANativeWindow_getWidth(window);- a.h = (f32)ANativeWindow_getHeight(window);-- auto device = makeUnique<WebGPUDevice>(a.device, a.instance);- a.gfx = device.get(); // stays valid: context owns it, we only borrow for present()- if (!a.gfx->configureSurface(WebGPUDevice::NativeSurface{WebGPUDevice::NativeWindowKind::AndroidWindow, window},- (u32)a.w, (u32)a.h)) {- LOGE("configureSurface failed");- return;- }-- static EstellaContext context;- a.ctx = &context;- context.state().viewport_width = (i32)a.w;- context.state().viewport_height = (i32)a.h;- if (!context.init(std::move(device))) { LOGE("context.init failed"); return; }-- static ecs::Registry registry;- a.registry = ®istry;- buildScene(context, registry, a.w, a.h);-- a.ready = true;- LOGI("full engine up (%dx%d) — production render path on native Dawn", (int)a.w, (int)a.h);-}--void onAppCmd(android_app* app, int32_t cmd) {- App* a = static_cast<App*>(app->userData);- switch (cmd) {- case APP_CMD_INIT_WINDOW:- if (app->window && !a->ready) { LOGI("APP_CMD_INIT_WINDOW"); initEngine(*a, app->window); }- break;- default:- break;- }-}--} // namespace--void android_main(android_app* app) {- App a;- app->userData = &a;- app->onAppCmd = onAppCmd;- while (true) {- int events;- android_poll_source* source;- int timeoutMs = a.ready ? 0 : -1;- while (ALooper_pollOnce(timeoutMs, nullptr, &events, (void**)&source) >= 0) {- if (source) source->process(app, source);- if (app->destroyRequested) return;- timeoutMs = 0;- }- renderScene(a);- }-}diff --git a/native/host_js/beep.wav b/native/host_js/beep.wavdeleted file mode 100644index 27b4238a8..000000000Binary files a/native/host_js/beep.wav and /dev/null differdiff --git a/native/host_js/game.js b/native/host_js/game.jsdeleted file mode 100644index 049443314..000000000--- a/native/host_js/game.js+++ /dev/null@@ -1,126 +0,0 @@-// Demo game — pure game logic, loaded at runtime as a packaged asset (the APK's-// assets/ on Android, the app bundle on iOS; NOT compiled into the C++ host).-// It authors through the real SDK exactly like a web-// game: ESEngine.createNativeApp + world.spawn/insert + the Input and Assets-// resources. The host provides `ESEngine` (SDK bundle), the `es_*` globals, the-// frame constants W/H/S, and the platform bridge `__esNativeBridge`.-//-// A sprite follows the touch; a shape orbits — proof the real App runs on device.--var app, world, input, follower, orbit, t = 0.0;--function init() {- app = ESEngine.createNativeApp(globalThis.__esNativeBridge, globalThis);- app.tick(0); // sync through finishPlugins: binds input + inserts Input- world = app.world;- input = app.getResource(ESEngine.Input);- var assets = app.getResource(ESEngine.Assets);-- // The frame belongs to the SDK here, exactly as on the web: a Canvas gives the- // design resolution and the clear colour, a Camera gives the projection. The- // host no longer decides either — it presents what this camera renders.- var stage = world.spawn();- world.insert(stage, ESEngine.Transform, { position: { x: W * 0.5, y: H * 0.5, z: 0 } });- world.insert(stage, ESEngine.UINode, {});- world.insert(stage, ESEngine.Canvas, {- designResolution: { x: W, y: H }, scaleMode: 2 /* Expand */,- backgroundColor: { r: 0.07, g: 0.08, b: 0.12, a: 1 } });-- var camera = world.spawn();- world.insert(camera, ESEngine.Transform, { position: { x: W * 0.5, y: H * 0.5, z: 0 } });- world.insert(camera, ESEngine.Camera, {- projectionType: 1 /* orthographic */, orthoSize: H * 0.5, isActive: true, clearFlags: 3 });-- // Fallback 2x2 checker (a tiny inline texture) while the real image loads.- // Nearest filter + clamp (format 1, no flip, filter 0, wrap 1) so the scaled-up- // pixels stay crisp — the same import-settings path a cooked pixel-art texture- // takes, exercised on every boot.- var tex = es_createTexture(2, 2, [- 255, 0, 0, 255, 0, 255, 0, 255,- 0, 0, 255, 255, 255, 255, 0, 255 ], 1, false, 0, 1);-- follower = world.spawn();- world.insert(follower, ESEngine.Transform, { position: { x: W * 0.5, y: H * 0.5, z: 0 } });- world.insert(follower, ESEngine.Sprite, {- texture: tex, color: { r: 1, g: 1, b: 1, a: 1 }, size: { x: S * 0.28, y: S * 0.28 } });-- // Load logo.png through the REAL SDK asset pipeline — the SAME Assets API a web- // game uses. Assets.loadTexture decodes the image via the platform- // (bridge.loadImagePixels) and uploads it through the native ResourceManager,- // returning a tracked handle. No hand-rolled es_createTexture: the demo now- // exercises the unified asset channel, not a bespoke native texture path.- assets.loadTexture('logo.png').then(function (result) {- world.insert(follower, ESEngine.Sprite, {- texture: result.handle, color: { r: 1, g: 1, b: 1, a: 1 },- size: { x: S * 0.28, y: S * 0.28 } });- }, function (err) {- console.error('logo.png failed to load:', err && err.message ? err.message : err);- });-- orbit = world.spawn();- world.insert(orbit, ESEngine.Transform, { position: { x: W * 0.5, y: H * 0.75, z: 0 } });- world.insert(orbit, ESEngine.ShapeRenderer, {- shapeType: 0, color: { r: 1, g: 0.2, b: 0.9, a: 1 }, size: { x: S * 0.12, y: S * 0.12 } });-- // Stage: a KTX2 compressed texture through the SAME Assets API. The host- // transcodes it (basis) to a device-supported format (ASTC/ETC2) and uploads- // the compressed blocks — no WebGL2, no wasm transcoder.- var ktx2Sprite = world.spawn();- world.insert(ktx2Sprite, ESEngine.Transform, { position: { x: W * 0.5, y: H * 0.28, z: 0 } });- assets.loadTexture('green.ktx2').then(function (res) {- world.insert(ktx2Sprite, ESEngine.Sprite, {- texture: res.handle, color: { r: 1, g: 1, b: 1, a: 1 },- size: { x: S * 0.24, y: S * 0.24 } });- console.log('[demo] ktx2: loaded ' + res.width + 'x' + res.height + ' handle=' + res.handle);- }, function (e) {- console.error('[demo] ktx2 failed:', e && e.message ? e.message : e);- });-- // Stage C: a startup chime through the REAL SDK Audio API. The native audio- // backend decodes beep.wav and plays it in the host's miniaudio engine — the- // audio pillar on device, the same Audio API a web game calls.- var audio = ESEngine.Audio && app.getResource(ESEngine.Audio);- if (audio) {- audio.playTrack('beep.wav', { volume: 0.4 }).then(function (h) {- console.log('[demo] audio: ' + (h- ? 'playing (isPlaying=' + h.isPlaying + ', duration=' + h.duration.toFixed(2) + 's)'- : 'null handle — no native audio backend'));- }, function (e) {- console.error('[demo] audio failed:', e && e.message ? e.message : e);- });- } else {- console.log('[demo] audio: no Audio resource');- }-- // Stage: text through the SAME `Text` component a web game authors. The host- // rasterizes each glyph from the OS font stack (there is no 2D canvas here)- // and the SDK's glyph atlas, layout and batching do the rest — including the- // per-codepoint font fallback that makes the CJK line resolve.- var label = world.spawn();- world.insert(label, ESEngine.Transform, { position: { x: W * 0.5, y: H * 0.62, z: 0 } });- world.insert(label, ESEngine.Text, {- content: 'Estella 原生文本', fontSize: S * 0.075, align: 1,- color: { r: 1, g: 0.92, b: 0.4, a: 1 } });-- // Stage: prove native networking — es_fetch over NSURLSession/OkHttp, TLS by- // the OS. The async reply lands back on the JS thread via the frame loop.- globalThis.__esNativeBridge.fetch('https://example.com').then(function (r) {- var bytes = r.arrayBuffer ? r.arrayBuffer.byteLength : (r.text ? r.text.length : 0);- console.log('[demo] fetch: ok=' + r.ok + ' status=' + r.status + ' bytes=' + bytes);- }, function (e) {- console.error('[demo] fetch failed:', e && e.message ? e.message : e);- });-}--function update(dt) {- t += dt;- app.tick(dt); // run the App loop (host pumps its async jobs)- // Follow the touch once there's been one (host touch is top-left origin; the- // world is y-up). Before any touch, the logo sits centered.- var p = input.getMousePosition();- if (p.x !== 0 || p.y !== 0) {- world.insert(follower, ESEngine.Transform, { position: { x: p.x, y: H - p.y, z: 0 } });- }- world.insert(orbit, ESEngine.Transform, {- position: { x: W * 0.5 + Math.cos(t * 1.2) * S * 0.3, y: H * 0.75, z: 0 } });-}diff --git a/native/host_js/green.ktx2 b/native/host_js/green.ktx2deleted file mode 100644index a4727d8ea..000000000Binary files a/native/host_js/green.ktx2 and /dev/null differdiff --git a/native/host_js/host_core.cpp b/native/host_js/host_core.cppdeleted file mode 100644index 1981f5bfd..000000000--- a/native/host_js/host_core.cpp+++ /dev/null@@ -1,1385 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file host_core.cpp- * @brief Implements the platform-independent JS host (see host_core.hpp).- * @details The host installs the native side of the registry contract as globals:- * * entity + hierarchy (hand-written here): es_createEntity /- * es_destroyEntity / es_setParent / es_hasParent / es_removeParent /- * es_hasChildren / es_getChildren- * * per-component (EHT-generated, esn_register): es_set_<C> /- * es_<C>_buffer / es_<C>_has / es_<C>_remove- * * resources + assets (hand-written): es_createTexture, es_setClear,- * es_readAsset- * createNativeRegistry + NativeMemoryProvider inside the SDK bundle read- * these off globalThis. Entity ids cross as the native Entity's raw u32- * (round-tripped via Entity::fromRaw), so hierarchy queries return ids- * the SDK recognises.- *- * @author ESEngine Team- * @date 2026- *- * @copyright Copyright (c) 2026 ESEngine Team- * Licensed under the Apache License, Version 2.0.- */-#include "host_core.hpp"--#include "esn_shim.hpp" // quickjs + the esn_* plumbing decls (+ esn_register)-#include "esengine_bundle.h" // the real SDK, bundled: installs globalThis.ESEngine-#include "native_audio.hpp" // the miniaudio-backed engine behind es_audio*-#include "ktx2_decode.hpp" // basis_universal transcode behind es_createTextureKTX2-#include "glyph_raster.hpp" // stb_truetype + the engine's SDF, behind es_rasterizeGlyph--#include "esengine/core/EstellaContext.hpp"-#include "esengine/bindings/ActiveContext.hpp" // g_activeContext — the context the generated bindings act on-#include "esengine/core/World.hpp"-#include "esengine/ecs/TransformSystem.hpp" // TransformSystem + ecs::setParent-#include "esengine/ecs/components/Hierarchy.hpp" // Parent / Children-#include "esengine/ecs/components/Camera.hpp" // the scene queries the camera plugin makes-#include "esengine/ecs/components/Canvas.hpp"-#include "esengine/ecs/components/Transform.hpp"-#include "esengine/renderer/RenderContext.hpp"-#include "esengine/renderer/RenderFrame.hpp"-#include "esengine/renderer/Texture.hpp" // TextureSpecification + filter/wrap for import settings-#include "esengine/resource/ResourceManager.hpp"-#include "esengine/resource/ShaderParser.hpp" // linearColorSpace() — texture format at the JS boundary--#include <glm/gtc/matrix_transform.hpp>--// stb_image for the native image-decode path (NativeBridge.loadImagePixels). The-// engine core doesn't use stb_image, so this TU owns the implementation.-#define STB_IMAGE_IMPLEMENTATION-#include "stb_image.h"--#include <cstdarg>-#include <cstdint>-#include <cstdio>-#include <cstring>-#include <ctime>-#include <mutex>-#include <queue>-#include <string>-#include <unordered_map>-#include <utility>-#include <vector>--using namespace esengine;--// Host platform bootstrap — HOST code, not game. The bridge itself is assembled-// by the SDK (createHostBridge) from the es_* primitives below: it is typed there-// against the interface it must satisfy, so this stays the few things only a JS-// string here can do — the TextDecoder shim and the default boot entry points.-static const char* kBootstrapJS = R"JS(-// The platform layer decodes packaged JSON through TextDecoder; QuickJS has none,-// so route it to the host's UTF-8 decoder. Only utf-8 is meaningful here.-globalThis.TextDecoder = function TextDecoder() {};-globalThis.TextDecoder.prototype.decode = function (buf) {- return buf == null ? '' : es_utf8Decode(buf);-};--// The whole host contract in one check — the JS globals a bare engine lacks and-// the es_* bindings this shell binds — so a gap is named here, not downstream.-ESEngine.assertNativeHost(globalThis);--// The bridge over the host's es_* bindings; it also installs es_onNativeTouch,-// the entry point the host calls per touch.-globalThis.__esNativeBridge = ESEngine.createHostBridge(globalThis);--// Default boot: run an EXPORTED project — game.config.json, the manifests, the-// cooked assets and the scenes, all read off the device. A packaged game.js (the-// hand-written-script path) replaces these two functions instead.-globalThis.__esGame = null;-globalThis.init = function () {- ESEngine.initNativeGame({ bridge: globalThis.__esNativeBridge, scope: globalThis, width: W, height: H })- .then(function (game) { globalThis.__esGame = game; })- .catch(function (e) {- console.error('exported game failed to boot:', e && e.message ? e.message : e);- });-};-globalThis.update = function (dt) {- if (globalThis.__esGame) globalThis.__esGame.app.tick(dt);-};-)JS";--namespace {--// A pending setTimeout / setInterval callback. QuickJS is only the language: the-// timers, like console, are the host's job.-struct Timer {- int64_t id;- double due; ///< nowMs() deadline.- double interval; ///< Repeat period; 0 for a one-shot.- JSValue fn;-};--struct App {- eshost::Platform* platform = nullptr;- WGPUInstance instance = nullptr;- WGPUAdapter adapter = nullptr;- WGPUDevice device = nullptr;- WebGPUDevice* gfx = nullptr;- EstellaContext* ctx = nullptr;- ecs::Registry* registry = nullptr;- JSRuntime* rt = nullptr;- JSContext* js = nullptr;- eshost::AudioEngine audio; // native sound (miniaudio); silent if no device- std::string cacheDir; // app private dir — SDK bytecode cache- std::vector<Timer> timers;- int64_t next_timer_id = 1;- std::unordered_map<int, JSValue> fetchCallbacks; // in-flight es_fetch id -> JS callback- int nextFetchId = 1;- glm::vec4 clear{0.07f, 0.08f, 0.12f, 1.0f};- f32 w = 0, h = 0;- bool ready = false; // engine + JS booted once- bool surfaceReady = false; // a live window surface is bound (false while screen off)- uint64_t frame = 0;-};--App* g_app = nullptr;--// HTTP replies cross back from whatever thread the platform's completion runs on.-// The platform enqueues here (POD only, no JS); the frame loop drains it on the JS-// thread and runs the callbacks. Kept outside App so deliverFetch (a free function-// the glue calls) needs no App pointer and is safe before/after boot.-std::mutex g_fetchMutex;-std::queue<eshost::FetchResult> g_fetchQueue;--double nowMs();--void hostLog(bool error, const char* fmt, ...) {- char buf[1024];- va_list args;- va_start(args, fmt);- vsnprintf(buf, sizeof(buf), fmt, args);- va_end(args);- if (g_app && g_app->platform) g_app->platform->log(error, buf);-}--} // namespace--#define LOGI(...) hostLog(false, __VA_ARGS__)-#define LOGE(...) hostLog(true, __VA_ARGS__)--// ---- the esn_shim plumbing the generated component bindings call --------------ecs::Registry& esn_reg() { return *g_app->registry; }--// Entity ids cross the boundary as the native Entity's raw u32.-Entity esn_entity(JSContext* ctx, JSValueConst v) {- uint32_t raw = Entity::INVALID_RAW;- JS_ToUint32(ctx, &raw, v);- return Entity::fromRaw(raw);-}--bool esn_getnum(JSContext* ctx, JSValueConst obj, const char* key, double* out) {- JSValue p = JS_GetPropertyStr(ctx, obj, key);- bool ok = !JS_IsUndefined(p) && !JS_IsNull(p) && JS_ToFloat64(ctx, out, p) == 0;- JS_FreeValue(ctx, p);- return ok;-}-bool esn_getbool(JSContext* ctx, JSValueConst obj, const char* key, int* out) {- JSValue p = JS_GetPropertyStr(ctx, obj, key);- if (JS_IsUndefined(p) || JS_IsNull(p)) { JS_FreeValue(ctx, p); return false; }- *out = JS_ToBool(ctx, p);- JS_FreeValue(ctx, p);- return true;-}-void esn_getvec(JSContext* ctx, JSValueConst obj, const char* key, float* dst, int n) {- JSValue arr = JS_GetPropertyStr(ctx, obj, key);- if (JS_IsArray(arr)) {- for (int i = 0; i < n; ++i) {- JSValue el = JS_GetPropertyUint32(ctx, arr, (uint32_t)i);- double d = 0;- JS_ToFloat64(ctx, &d, el);- dst[i] = (float)d;- JS_FreeValue(ctx, el);- }- }- JS_FreeValue(ctx, arr);-}-namespace { void readByteSource(JSContext* ctx, JSValueConst v, std::vector<u8>& out); }--// The generated wrappers for entry points that take a `uintptr_t` buffer read-// their bytes through this: on the web that argument is a wasm heap offset, here-// it is memory the wrapper owns for the duration of the call.-void esn_bytes(JSContext* ctx, JSValueConst v, std::vector<u8>& out) {- readByteSource(ctx, v, out);-}--JSValue esn_arraybuffer(JSContext* ctx, void* ptr, size_t size) {- return JS_NewArrayBuffer(ctx, reinterpret_cast<uint8_t*>(ptr), size, nullptr, nullptr, false);-}--namespace {--// ---- entity + hierarchy: the base Registry surface the SDK World drives --------JSValue js_createEntity(JSContext* ctx, JSValueConst, int, JSValueConst*) {- return JS_NewUint32(ctx, g_app->registry->create().id());-}-JSValue js_destroyEntity(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {- g_app->registry->destroy(esn_entity(ctx, argv[0]));- return JS_UNDEFINED;-}-JSValue js_setParent(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {- ecs::setParent(*g_app->registry, esn_entity(ctx, argv[0]), esn_entity(ctx, argv[1]));- return JS_UNDEFINED;-}-JSValue js_hasParent(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {- return JS_NewBool(ctx, g_app->registry->has<ecs::Parent>(esn_entity(ctx, argv[0])));-}-JSValue js_removeParent(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {- ecs::setParent(*g_app->registry, esn_entity(ctx, argv[0]), INVALID_ENTITY);- return JS_UNDEFINED;-}-JSValue js_hasChildren(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {- auto* c = g_app->registry->tryGet<ecs::Children>(esn_entity(ctx, argv[0]));- return JS_NewBool(ctx, c && !c->entities.empty());-}-JSValue js_getChildren(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {- JSValue arr = JS_NewArray(ctx);- if (auto* c = g_app->registry->tryGet<ecs::Children>(esn_entity(ctx, argv[0]))) {- uint32_t i = 0;- for (Entity child : c->entities) {- JS_SetPropertyUint32(ctx, arr, i++, JS_NewUint32(ctx, child.id()));- }- }- return arr;-}--// ---- resources + clear (not reflected; the native ResourceManagerBindings analog) ---JSValue js_setClear(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {- double r = 0, g = 0, b = 0;- JS_ToFloat64(ctx, &r, argv[0]); JS_ToFloat64(ctx, &g, argv[1]); JS_ToFloat64(ctx, &b, argv[2]);- g_app->clear = {(f32)r, (f32)g, (f32)b, 1.0f};- return JS_UNDEFINED;-}-// Read a byte source into `out`, whatever shape the SDK handed us: a raw-// ArrayBuffer (audio clip bytes, cache writes), a Uint8Array (texture pixels), or-// a plain JS number array (the tiny inline checker some scripts build).-void readByteSource(JSContext* ctx, JSValueConst v, std::vector<u8>& out) {- // Raw ArrayBuffer first — a typed-array view is not one, so it falls through.- size_t rawSize = 0;- if (uint8_t* raw = JS_GetArrayBuffer(ctx, &rawSize, v)) {- out.assign(raw, raw + rawSize);- return;- }- JS_FreeValue(ctx, JS_GetException(ctx)); // not a raw ArrayBuffer — try a view-- size_t byteOffset = 0, byteLen = 0, bytesPerEl = 0;- JSValue ab = JS_GetTypedArrayBuffer(ctx, v, &byteOffset, &byteLen, &bytesPerEl);- if (!JS_IsException(ab)) {- size_t abSize = 0;- uint8_t* base = JS_GetArrayBuffer(ctx, &abSize, ab);- if (base && byteOffset + byteLen <= abSize) {- out.assign(base + byteOffset, base + byteOffset + byteLen);- }- JS_FreeValue(ctx, ab);- return;- }- JS_FreeValue(ctx, ab);- JS_FreeValue(ctx, JS_GetException(ctx)); // not a typed array — clear + index it- uint32_t len = 0;- JSValue lv = JS_GetPropertyStr(ctx, v, "length");- JS_ToUint32(ctx, &len, lv);- JS_FreeValue(ctx, lv);- out.resize(len);- for (uint32_t i = 0; i < len; ++i) {- JSValue el = JS_GetPropertyUint32(ctx, v, i);- int32_t iv = 0;- JS_ToInt32(ctx, &iv, el);- out[i] = (u8)iv;- JS_FreeValue(ctx, el);- }-}--// The texture format at the JS boundary — mirrors bindings/ResourceManagerBindings-// boundaryTextureFormat so native and web upload colour identically (format 0 = RGB8;-// else sRGB variant under the linear pipeline, plain RGBA8 in gamma).-TextureFormat boundaryTextureFormat(int32_t format) {- if (format == 0) return TextureFormat::RGB8;- if (resource::ShaderParser::linearColorSpace()) return TextureFormat::SRGB8A8;- return TextureFormat::RGBA8;-}--// es_createTexture(w, h, pixels, format?, flip?, filter?, wrap?) -> handle id.-// Backs the native ResourceManager's createTextureFromBytes: the SDK decodes an-// image to RGBA (loadImagePixels) and hands the bytes here — no wasm heap.-//-// filter/wrap carry the cooked-asset import settings (a scene's-// textureImporterSettings, threaded through the shared runtime loader). Each is a-// number or undefined; honor them exactly as the web embind rm_createTextureEx-// does (filter 0=Nearest/else Linear; wrap 0=Repeat/1=ClampToEdge/2=MirroredRepeat)-// so native sampling matches web — pixel art stays crisp. With neither, the plain-// createTexture path is unchanged.-JSValue js_createTexture(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {- int32_t w = 0, h = 0;- JS_ToInt32(ctx, &w, argv[0]);- JS_ToInt32(ctx, &h, argv[1]);- std::vector<u8> pixels;- readByteSource(ctx, argv[2], pixels);-- int32_t format = 1; // default: colour (RGBA8 / sRGB)- if (argc > 3 && !JS_IsUndefined(argv[3])) JS_ToInt32(ctx, &format, argv[3]);- const bool flip = (argc > 4 && !JS_IsUndefined(argv[4])) ? JS_ToBool(ctx, argv[4]) != 0 : false;- const TextureFormat fmt = boundaryTextureFormat(format);- auto& rm = g_app->ctx->require<resource::ResourceManager>();-- const bool hasFilter = argc > 5 && !JS_IsUndefined(argv[5]);- const bool hasWrap = argc > 6 && !JS_IsUndefined(argv[6]);- if (!hasFilter && !hasWrap) {- auto handle = rm.createTexture(- (u32)w, (u32)h, ConstSpan<u8>(pixels.data(), pixels.size()), fmt, flip);- return JS_NewInt64(ctx, (int64_t)handle.id());- }-- TextureSpecification spec;- spec.width = (u32)w;- spec.height = (u32)h;- spec.format = fmt;- spec.generateMips = false; // decoded 2D sprites, like the web Ex path- if (hasFilter) {- int32_t f = 1;- JS_ToInt32(ctx, &f, argv[5]);- spec.minFilter = (f == 0) ? TextureFilter::Nearest : TextureFilter::Linear;- spec.magFilter = spec.minFilter;- }- if (hasWrap) {- int32_t wm = 1;- JS_ToInt32(ctx, &wm, argv[6]);- const TextureWrap tw = (wm == 0) ? TextureWrap::Repeat- : (wm == 2) ? TextureWrap::MirroredRepeat- : TextureWrap::ClampToEdge;- spec.wrapS = tw;- spec.wrapT = tw;- }- auto handle = rm.createTexture(spec);- if (auto* tex = rm.getTexture(handle); tex && !pixels.empty()) {- const u64 required = (u64)w * (u64)h * (fmt == TextureFormat::RGB8 ? 3 : 4);- if (pixels.size() >= required) tex->setDataRaw(pixels.data(), (u32)required, flip);- }- return JS_NewInt64(ctx, (int64_t)handle.id());-}--// es_createTextureKTX2(ArrayBuffer|TypedArray, srgb?) -> { id, width, height } | null.-// Transcodes a KTX2/Basis container to the best device-supported compressed format-// (or RGBA32) and uploads it — the native counterpart of the web WebGL2 path.-JSValue js_createTextureKTX2(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {- if (argc < 1) return JS_NULL;- std::vector<u8> bytes;- readByteSource(ctx, argv[0], bytes);- if (bytes.empty()) return JS_NULL;- const bool srgb = argc > 1 && JS_ToBool(ctx, argv[1]) != 0;- auto r = eshost::transcodeKTX2(bytes.data(), bytes.size(), srgb,- g_app->ctx->require<resource::ResourceManager>(), *g_app->gfx);- if (r.handle < 0) return JS_NULL;- JSValue o = JS_NewObject(ctx);- JS_SetPropertyStr(ctx, o, "id", JS_NewInt32(ctx, r.handle));- JS_SetPropertyStr(ctx, o, "width", JS_NewInt32(ctx, r.width));- JS_SetPropertyStr(ctx, o, "height", JS_NewInt32(ctx, r.height));- return o;-}--// es_releaseTexture(handle) — drop one native ResourceManager reference.-JSValue js_releaseTexture(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {- int64_t id = 0;- JS_ToInt64(ctx, &id, argv[0]);- g_app->ctx->require<resource::ResourceManager>().releaseTexture(- resource::TextureHandle((u32)id));- return JS_UNDEFINED;-}--// es_getTextureDimensions(handle) -> { width, height } | null.-JSValue js_getTextureDimensions(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {- int64_t id = 0;- JS_ToInt64(ctx, &id, argv[0]);- auto* tex = g_app->ctx->require<resource::ResourceManager>().getTexture(- resource::TextureHandle((u32)id));- if (!tex) return JS_NULL;- JSValue obj = JS_NewObject(ctx);- JS_SetPropertyStr(ctx, obj, "width", JS_NewInt32(ctx, (int32_t)tex->getWidth()));- JS_SetPropertyStr(ctx, obj, "height", JS_NewInt32(ctx, (int32_t)tex->getHeight()));- return obj;-}--// es_getTextureRenderId(handle) -> the id a draw command binds this texture by-// (Texture::getId(), backend-neutral). The SDK's glyph atlas passes it straight-// to the text batch, exactly as the web path does through getTextureGLId.-JSValue js_getTextureRenderId(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {- int64_t id = 0;- JS_ToInt64(ctx, &id, argv[0]);- auto* tex = g_app->ctx->require<resource::ResourceManager>().getTexture(- resource::TextureHandle((u32)id));- return JS_NewInt64(ctx, tex ? (int64_t)tex->getId() : 0);-}--// es_updateTextureSubregion(handle, x, y, w, h, pixels) — upload one rect of an-// existing texture. The dynamic glyph atlas packs glyphs into a page this way-// instead of re-uploading the whole page per glyph.-JSValue js_updateTextureSubregion(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {- if (argc < 6) return JS_UNDEFINED;- int64_t id = 0; JS_ToInt64(ctx, &id, argv[0]);- int32_t x = 0, y = 0, w = 0, h = 0;- JS_ToInt32(ctx, &x, argv[1]); JS_ToInt32(ctx, &y, argv[2]);- JS_ToInt32(ctx, &w, argv[3]); JS_ToInt32(ctx, &h, argv[4]);- if (w <= 0 || h <= 0) return JS_UNDEFINED;- std::vector<u8> pixels;- readByteSource(ctx, argv[5], pixels);- if (pixels.empty()) return JS_UNDEFINED;- auto* tex = g_app->ctx->require<resource::ResourceManager>().getTexture(- resource::TextureHandle((u32)id));- if (!tex) return JS_UNDEFINED;- // updateSubRegion bounds-checks the rect and the buffer size itself.- tex->updateSubRegion((u32)x, (u32)y, (u32)w, (u32)h, pixels.data(), (u32)pixels.size(), /*flipY=*/false);- return JS_UNDEFINED;-}--// es_rasterizeGlyph({ codepoint, fontFamily, style, pixelSize, sdf, padding })-// -> { pixels: ArrayBuffer, width, height, advance, bearingX, bearingY } | null.-// The device's answer to the browser's 2D canvas; see glyph_raster.hpp.-JSValue js_rasterizeGlyph(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {- if (argc < 1 || !g_app || !g_app->platform) return JS_NULL;- JSValue req = argv[0];-- const auto numberField = [&](const char* name, double fallback) {- JSValue v = JS_GetPropertyStr(ctx, req, name);- double out = fallback;- if (!JS_IsUndefined(v)) JS_ToFloat64(ctx, &out, v);- JS_FreeValue(ctx, v);- return out;- };- const auto boolField = [&](const char* name) {- JSValue v = JS_GetPropertyStr(ctx, req, name);- const bool out = JS_ToBool(ctx, v) != 0;- JS_FreeValue(ctx, v);- return out;- };-- std::string family;- JSValue familyVal = JS_GetPropertyStr(ctx, req, "fontFamily");- if (const char* s = JS_ToCString(ctx, familyVal)) {- family = s;- JS_FreeCString(ctx, s);- }- JS_FreeValue(ctx, familyVal);-- const auto glyph = eshost::rasterizeGlyph(- *g_app->platform,- (uint32_t)numberField("codepoint", 0),- family,- (int)numberField("style", 0),- (float)numberField("pixelSize", 48),- boolField("sdf"),- (float)numberField("padding", 6));- if (!glyph.ok) return JS_NULL;-- JSValue o = JS_NewObject(ctx);- JS_SetPropertyStr(ctx, o, "pixels",- glyph.rgba.empty() ? JS_NewArrayBufferCopy(ctx, nullptr, 0)- : JS_NewArrayBufferCopy(ctx, glyph.rgba.data(), glyph.rgba.size()));- JS_SetPropertyStr(ctx, o, "width", JS_NewInt32(ctx, glyph.width));- JS_SetPropertyStr(ctx, o, "height", JS_NewInt32(ctx, glyph.height));- JS_SetPropertyStr(ctx, o, "advance", JS_NewFloat64(ctx, glyph.advance));- JS_SetPropertyStr(ctx, o, "bearingX", JS_NewFloat64(ctx, glyph.bearingX));- JS_SetPropertyStr(ctx, o, "bearingY", JS_NewFloat64(ctx, glyph.bearingY));- return o;-}--// Read a typed array's elements without copying more than the view. Returns the-// element pointer + count, or {nullptr, 0} when the value is not a typed array.-template <typename T>-std::pair<const T*, size_t> typedArrayView(JSContext* ctx, JSValueConst v, std::vector<u8>& storage) {- storage.clear();- readByteSource(ctx, v, storage);- if (storage.size() < sizeof(T)) return {nullptr, 0};- return {reinterpret_cast<const T*>(storage.data()), storage.size() / sizeof(T)};-}--// es_submitTextBatch(vertices, vertexCount, indices, textureId, transform,-// entity, layer, depth, sdf)-// The SDK lays glyph quads out against the atlas and hands them here — the native-// counterpart of the web's renderer_submitTextBatch, minus the wasm heap.-JSValue js_submitTextBatch(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {- if (argc < 9 || !g_app || !g_app->ctx) return JS_UNDEFINED;- std::vector<u8> vBytes, iBytes, tBytes;- auto [vertices, vertexFloats] = typedArrayView<f32>(ctx, argv[0], vBytes);- int32_t vertexCount = 0; JS_ToInt32(ctx, &vertexCount, argv[1]);- auto [indices, indexCount] = typedArrayView<u16>(ctx, argv[2], iBytes);- int64_t textureId = 0; JS_ToInt64(ctx, &textureId, argv[3]);- auto [transform, transformFloats] = typedArrayView<f32>(ctx, argv[4], tBytes);- int64_t entity = 0; JS_ToInt64(ctx, &entity, argv[5]);- int32_t layer = 0; JS_ToInt32(ctx, &layer, argv[6]);- double depth = 0; JS_ToFloat64(ctx, &depth, argv[7]);- const bool sdf = JS_ToBool(ctx, argv[8]) != 0;-- // The vertex format is x,y,u,v,r,g,b,a — 8 floats each; validate before the- // renderer trusts the spans, as the web binding's boundarySpan does.- if (!vertices || !indices || !transform) return JS_UNDEFINED;- if (vertexCount <= 0 || indexCount == 0 || transformFloats < 16) return JS_UNDEFINED;- if (vertexFloats < (size_t)vertexCount * 8) return JS_UNDEFINED;-- g_app->ctx->require<RenderFrame>().submitTextBatch(- vertices, vertexCount, indices, (i32)indexCount, (u32)textureId, transform,- Entity::fromRaw((u32)entity), layer, (f32)depth, sdf);- return JS_UNDEFINED;-}--// ---- the frame --------------------------------------------------------------//-// The es_renderer_* entry points are GENERATED (NativeFunctionBindings.generated.cpp)-// from the same declarations embind registers on the web, and call the same-// binding TU — so the SDK's camera plugin and render pipeline drive a device-// frame through one implementation. What stays here is what has no web-// counterpart: the surface size, and the camera list (its web sibling returns an-// emscripten::val, which does not exist natively).--// es_renderer_surfaceSize() -> { width, height }: the camera plugin reads it per-// frame, so a rotation reaches the projection without an event.-JSValue js_renderer_surfaceSize(JSContext* ctx, JSValueConst, int, JSValueConst*) {- JSValue o = JS_NewObject(ctx);- JS_SetPropertyStr(ctx, o, "width", JS_NewInt32(ctx, g_app ? (int32_t)g_app->w : 0));- JS_SetPropertyStr(ctx, o, "height", JS_NewInt32(ctx, g_app ? (int32_t)g_app->h : 0));- return o;-}--JSValue js_registry_getCameraEntities(JSContext* ctx, JSValueConst, int, JSValueConst*) {- JSValue arr = JS_NewArray(ctx);- if (!g_app || !g_app->registry) return arr;- uint32_t n = 0;- // Active cameras with a Transform, as the web binding reports them.- for (auto entity : g_app->registry->view<ecs::Camera, ecs::Transform>()) {- if (g_app->registry->get<ecs::Camera>(entity).isActive) {- JS_SetPropertyUint32(ctx, arr, n++, JS_NewInt32(ctx, (int32_t)entity.id()));- }- }- return arr;-}--std::vector<u8> readAsset(App& a, const char* path) {- return a.platform ? a.platform->readAsset(path) : std::vector<u8>{};-}--// es_readAsset(path) -> ArrayBuffer | null. Backs the bridge's readFile.-JSValue js_readAsset(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {- const char* path = JS_ToCString(ctx, argv[0]);- if (!path) return JS_NULL;- std::vector<u8> bytes = readAsset(*g_app, path);- JS_FreeCString(ctx, path);- if (bytes.empty()) return JS_NULL;- return JS_NewArrayBufferCopy(ctx, bytes.data(), bytes.size());-}--// es_loadImagePixels(path) -> { width, height, pixels: ArrayBuffer(RGBA) } | null.-// Decodes a packaged image asset to top-first RGBA via stb_image — the native-// NativeBridge.loadImagePixels ("Path 2": decode -> createTextureFromPixels).-JSValue js_loadImagePixels(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {- const char* path = JS_ToCString(ctx, argv[0]);- if (!path) return JS_NULL;- std::vector<u8> file = readAsset(*g_app, path);- JS_FreeCString(ctx, path);- if (file.empty()) return JS_NULL;- int w = 0, h = 0, ch = 0;- stbi_uc* px = stbi_load_from_memory(file.data(), (int)file.size(), &w, &h, &ch, 4);- if (!px) { LOGE("stb_image decode failed"); return JS_NULL; }- JSValue buf = JS_NewArrayBufferCopy(ctx, px, (size_t)w * (size_t)h * 4);- stbi_image_free(px);- JSValue obj = JS_NewObject(ctx);- JS_SetPropertyStr(ctx, obj, "width", JS_NewInt32(ctx, w));- JS_SetPropertyStr(ctx, obj, "height", JS_NewInt32(ctx, h));- JS_SetPropertyStr(ctx, obj, "pixels", buf); // ArrayBuffer; the bootstrap wraps it Uint8Array- return obj;-}--// ---- audio: es_audio* over the native AudioEngine (miniaudio) -----------------// Bound only when the engine has a device (see initJS); a host without one binds-// none, so the SDK's hasAudioBindings() is false and audio stays the Null backend.--// es_audioLoad(ArrayBuffer | TypedArray) -> { id, duration, bytes } | null. The-// SDK hands the compressed clip bytes; the engine decodes + registers them.-JSValue js_audioLoad(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {- if (argc < 1) return JS_NULL;- std::vector<u8> bytes;- readByteSource(ctx, argv[0], bytes);- if (bytes.empty()) return JS_NULL;- auto r = g_app->audio.load(bytes.data(), bytes.size());- if (r.id < 0) return JS_NULL;- JSValue o = JS_NewObject(ctx);- JS_SetPropertyStr(ctx, o, "id", JS_NewInt32(ctx, r.id));- JS_SetPropertyStr(ctx, o, "duration", JS_NewFloat64(ctx, r.duration));- JS_SetPropertyStr(ctx, o, "bytes", JS_NewInt64(ctx, r.bytes));- return o;-}-JSValue js_audioUnload(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {- int32_t id = 0; JS_ToInt32(ctx, &id, argv[0]);- g_app->audio.unload(id);- return JS_UNDEFINED;-}--// es_audioPlay(bufferId, volume, pan, loop, rate) -> voiceId (-1 if unknown).-JSValue js_audioPlay(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {- int32_t buf = 0; JS_ToInt32(ctx, &buf, argv[0]);- double vol = 1, pan = 0, rate = 1;- if (argc > 1) JS_ToFloat64(ctx, &vol, argv[1]);- if (argc > 2) JS_ToFloat64(ctx, &pan, argv[2]);- const bool loop = argc > 3 && JS_ToBool(ctx, argv[3]);- if (argc > 4) JS_ToFloat64(ctx, &rate, argv[4]);- return JS_NewInt32(ctx, g_app->audio.play(buf, (f32)vol, (f32)pan, loop, (f32)rate));-}--// The voice-scoped commands all take the voice id as argv[0].-int32_t voiceArg(JSContext* ctx, JSValueConst* argv) {- int32_t v = 0; JS_ToInt32(ctx, &v, argv[0]); return v;-}-JSValue js_audioStop(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {- g_app->audio.stop(voiceArg(ctx, argv)); return JS_UNDEFINED;-}-JSValue js_audioPause(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {- g_app->audio.pause(voiceArg(ctx, argv)); return JS_UNDEFINED;-}-JSValue js_audioResume(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {- g_app->audio.resume(voiceArg(ctx, argv)); return JS_UNDEFINED;-}-JSValue js_audioSetVolume(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {- double v = 1; JS_ToFloat64(ctx, &v, argv[1]);- g_app->audio.setVolume(voiceArg(ctx, argv), (f32)v); return JS_UNDEFINED;-}-JSValue js_audioSetPan(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {- double p = 0; JS_ToFloat64(ctx, &p, argv[1]);- g_app->audio.setPan(voiceArg(ctx, argv), (f32)p); return JS_UNDEFINED;-}-JSValue js_audioSetLoop(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {- g_app->audio.setLoop(voiceArg(ctx, argv), JS_ToBool(ctx, argv[1]) != 0); return JS_UNDEFINED;-}-JSValue js_audioSetRate(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {- double r = 1; JS_ToFloat64(ctx, &r, argv[1]);- g_app->audio.setRate(voiceArg(ctx, argv), (f32)r); return JS_UNDEFINED;-}--// es_audioVoiceState(voiceId) -> { playing, currentTime } | null (null once ended).-JSValue js_audioVoiceState(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {- auto st = g_app->audio.voiceState(voiceArg(ctx, argv));- if (!st.valid) return JS_NULL;- JSValue o = JS_NewObject(ctx);- JS_SetPropertyStr(ctx, o, "playing", JS_NewBool(ctx, st.playing));- JS_SetPropertyStr(ctx, o, "currentTime", JS_NewFloat64(ctx, st.currentTime));- return o;-}-JSValue js_audioSuspendAll(JSContext* ctx, JSValueConst, int, JSValueConst*) {- g_app->audio.suspendAll(); return JS_UNDEFINED;-}-JSValue js_audioResumeAll(JSContext* ctx, JSValueConst, int, JSValueConst*) {- g_app->audio.resumeAll(); return JS_UNDEFINED;-}--// console.* — QuickJS ships no console at all, so without this a game script's-// first console.log is a ReferenceError and every rejected promise is silent.-JSValue jsConsoleWrite(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv, bool error) {- std::string line;- for (int i = 0; i < argc; ++i) {- const char* s = JS_ToCString(ctx, argv[i]);- if (!s) continue;- if (!line.empty()) line += ' ';- line += s;- JS_FreeCString(ctx, s);- }- hostLog(error, "%s", line.c_str());- return JS_UNDEFINED;-}-JSValue js_consoleLog(JSContext* ctx, JSValueConst t, int argc, JSValueConst* argv) {- return jsConsoleWrite(ctx, t, argc, argv, false);-}-JSValue js_consoleError(JSContext* ctx, JSValueConst t, int argc, JSValueConst* argv) {- return jsConsoleWrite(ctx, t, argc, argv, true);-}--JSValue jsAddTimer(JSContext* ctx, int argc, JSValueConst* argv, bool repeat) {- if (argc < 1 || !JS_IsFunction(ctx, argv[0])) return JS_NewInt64(ctx, 0);- double delay = 0;- if (argc > 1) JS_ToFloat64(ctx, &delay, argv[1]);- if (!(delay >= 0)) delay = 0; // also catches NaN- App& a = *g_app;- const int64_t id = a.next_timer_id++;- // A zero-delay interval would fire forever within one pump; clamp as browsers do.- a.timers.push_back(Timer{id, nowMs() + delay, repeat ? (delay > 1 ? delay : 1) : 0,- JS_DupValue(ctx, argv[0])});- return JS_NewInt64(ctx, id);-}-JSValue js_setTimeout(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {- return jsAddTimer(ctx, argc, argv, false);-}-JSValue js_setInterval(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {- return jsAddTimer(ctx, argc, argv, true);-}-JSValue js_clearTimer(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {- int64_t id = 0;- if (argc > 0) JS_ToInt64(ctx, &id, argv[0]);- App& a = *g_app;- for (auto it = a.timers.begin(); it != a.timers.end(); ++it) {- if (it->id != id) continue;- JS_FreeValue(a.js, it->fn);- a.timers.erase(it);- break;- }- return JS_UNDEFINED;-}--JSValue js_performanceNow(JSContext* ctx, JSValueConst, int, JSValueConst*) {- return JS_NewFloat64(ctx, nowMs());-}--// The host's writable store, under Platform::cacheDir(). Backs both the-// hot-update offline cache and (through it) key-value storage. Keys are-// content hashes or plain names; anything else is refused rather than escaping-// the directory.-std::string cachePathFor(const char* key) {- if (!key || !*key || g_app->cacheDir.empty()) return {};- for (const char* c = key; *c; ++c) {- const bool ok = (*c >= 'a' && *c <= 'z') || (*c >= 'A' && *c <= 'Z')- || (*c >= '0' && *c <= '9') || *c == '.' || *c == '_' || *c == '-';- if (!ok) return {};- }- return g_app->cacheDir + "/" + key;-}--// es_readCacheFile(key) -> ArrayBuffer | null.-JSValue js_readCacheFile(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {- const char* key = JS_ToCString(ctx, argv[0]);- const std::string path = cachePathFor(key);- if (key) JS_FreeCString(ctx, key);- if (path.empty()) return JS_NULL;- FILE* f = fopen(path.c_str(), "rb");- if (!f) return JS_NULL;- fseek(f, 0, SEEK_END);- const long size = ftell(f);- fseek(f, 0, SEEK_SET);- std::vector<u8> bytes(size > 0 ? (size_t)size : 0);- if (!bytes.empty() && fread(bytes.data(), 1, bytes.size(), f) != bytes.size()) bytes.clear();- fclose(f);- if (bytes.empty()) return JS_NULL;- return JS_NewArrayBufferCopy(ctx, bytes.data(), bytes.size());-}--// es_writeCacheFile(key, ArrayBuffer | TypedArray | string) -> bool. A string is-// written as UTF-8, so script-side JSON needs no TextEncoder.-JSValue js_writeCacheFile(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {- if (argc < 2) return JS_FALSE;- const char* key = JS_ToCString(ctx, argv[0]);- const std::string path = cachePathFor(key);- if (key) JS_FreeCString(ctx, key);- if (path.empty()) return JS_FALSE;- std::vector<u8> bytes;- if (JS_IsString(argv[1])) {- size_t len = 0;- if (const char* text = JS_ToCStringLen(ctx, &len, argv[1])) {- bytes.assign(text, text + len);- JS_FreeCString(ctx, text);- }- } else {- readByteSource(ctx, argv[1], bytes);- }- FILE* f = fopen(path.c_str(), "wb");- if (!f) return JS_FALSE;- const bool ok = bytes.empty() || fwrite(bytes.data(), 1, bytes.size(), f) == bytes.size();- fclose(f);- return ok ? JS_TRUE : JS_FALSE;-}--// es_utf8Decode(ArrayBuffer | TypedArray) -> string. Backs the TextDecoder the-// platform layer uses to read packaged JSON (manifests, scenes); QuickJS parses-// UTF-8 natively, so this beats decoding byte-by-byte in script.-JSValue js_utf8Decode(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {- if (argc < 1) return JS_NewString(ctx, "");- size_t size = 0;- if (uint8_t* raw = JS_GetArrayBuffer(ctx, &size, argv[0])) {- return JS_NewStringLen(ctx, reinterpret_cast<const char*>(raw), size);- }- JS_FreeValue(ctx, JS_GetException(ctx)); // not an ArrayBuffer — try a view- size_t offset = 0, length = 0, bytesPerEl = 0;- JSValue ab = JS_GetTypedArrayBuffer(ctx, argv[0], &offset, &length, &bytesPerEl);- if (JS_IsException(ab)) { JS_FreeValue(ctx, JS_GetException(ctx)); return JS_NewString(ctx, ""); }- uint8_t* base = JS_GetArrayBuffer(ctx, &size, ab);- JSValue out = (base && offset + length <= size)- ? JS_NewStringLen(ctx, reinterpret_cast<const char*>(base + offset), length)- : JS_NewString(ctx, "");- JS_FreeValue(ctx, ab);- return out;-}--void logJsError(JSContext* ctx, const char* where) {- JSValue e = JS_GetException(ctx);- const char* s = JS_ToCString(ctx, e);- LOGE("JS error in %s: %s", where, s ? s : "?");- if (s) JS_FreeCString(ctx, s);- // The stack too: a bare message ("Maximum call stack size exceeded") says- // nothing about which SDK path produced it, and a device is where you find out.- JSValue stack = JS_GetPropertyStr(ctx, e, "stack");- if (!JS_IsUndefined(stack) && !JS_IsException(stack)) {- const char* st = JS_ToCString(ctx, stack);- if (st) { LOGE(" stack: %s", st); JS_FreeCString(ctx, st); }- }- JS_FreeValue(ctx, stack);- JS_FreeValue(ctx, e);-}-void evalJs(App& a, const char* src, const char* name) {- JSValue r = JS_Eval(a.js, src, strlen(src), name, JS_EVAL_TYPE_GLOBAL);- if (JS_IsException(r)) logJsError(a.js, name);- JS_FreeValue(a.js, r);-}-void callJs(App& a, const char* fn, int argc, JSValue* argv) {- JSValue global = JS_GetGlobalObject(a.js);- JSValue f = JS_GetPropertyStr(a.js, global, fn);- if (JS_IsFunction(a.js, f)) {- JSValue r = JS_Call(a.js, f, global, argc, argv);- if (JS_IsException(r)) logJsError(a.js, fn);- JS_FreeValue(a.js, r);- }- JS_FreeValue(a.js, f);- JS_FreeValue(a.js, global);-}--// ---- HTTP: es_fetch over the platform's native networking ---------------------std::string fetchStrProp(JSContext* ctx, JSValueConst obj, const char* key, const char* dflt) {- JSValue v = JS_GetPropertyStr(ctx, obj, key);- std::string out = dflt ? dflt : "";- if (JS_IsString(v)) {- if (const char* s = JS_ToCString(ctx, v)) { out = s; JS_FreeCString(ctx, s); }- }- JS_FreeValue(ctx, v);- return out;-}--void readFetchHeaders(JSContext* ctx, JSValueConst obj, eshost::FetchRequest& req) {- JSValue h = JS_GetPropertyStr(ctx, obj, "headers");- if (JS_IsObject(h)) {- JSPropertyEnum* tab = nullptr;- uint32_t len = 0;- if (JS_GetOwnPropertyNames(ctx, &tab, &len, h, JS_GPN_STRING_MASK | JS_GPN_ENUM_ONLY) == 0) {- for (uint32_t i = 0; i < len; ++i) {- const char* key = JS_AtomToCString(ctx, tab[i].atom);- JSValue val = JS_GetProperty(ctx, h, tab[i].atom);- const char* vs = JS_ToCString(ctx, val);- if (key && vs) req.headers.emplace_back(key, vs);- if (vs) JS_FreeCString(ctx, vs);- if (key) JS_FreeCString(ctx, key);- JS_FreeValue(ctx, val);- }- JS_FreePropertyEnum(ctx, tab, len);- }- }- JS_FreeValue(ctx, h);-}--// es_fetch(request, callback): request = { url, method?, headers?, body?,-// responseType? }. Runs the request off the main thread and calls back with-// { ok, status, statusText, headers, arrayBuffer | text, error? }. The bridge-// wraps this in a Promise. responseType 'text' returns a string; everything else-// returns an ArrayBuffer (the bridge decodes text/json from it on demand).-JSValue js_fetch(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {- if (argc < 2 || !JS_IsObject(argv[0]) || !JS_IsFunction(ctx, argv[1])) return JS_UNDEFINED;- eshost::FetchRequest req;- req.id = g_app->nextFetchId++;- req.url = fetchStrProp(ctx, argv[0], "url", "");- req.method = fetchStrProp(ctx, argv[0], "method", "GET");- req.wantText = fetchStrProp(ctx, argv[0], "responseType", "arraybuffer") == "text";- readFetchHeaders(ctx, argv[0], req);- JSValue body = JS_GetPropertyStr(ctx, argv[0], "body");- if (JS_IsString(body)) {- size_t len = 0;- if (const char* s = JS_ToCStringLen(ctx, &len, body)) {- req.body.assign(s, s + len);- JS_FreeCString(ctx, s);- }- } else if (!JS_IsUndefined(body) && !JS_IsNull(body)) {- readByteSource(ctx, body, req.body);- }- JS_FreeValue(ctx, body);-- g_app->fetchCallbacks[req.id] = JS_DupValue(ctx, argv[1]);- if (req.url.empty()) {- eshost::FetchResult err;- err.id = req.id;- err.error = "es_fetch: missing url";- eshost::deliverFetch(std::move(err));- } else {- g_app->platform->startFetch(req);- }- return JS_UNDEFINED;-}--JSValue makeFetchResult(App& a, const eshost::FetchResult& r) {- JSValue o = JS_NewObject(a.js);- JS_SetPropertyStr(a.js, o, "ok", JS_NewBool(a.js, r.ok));- JS_SetPropertyStr(a.js, o, "status", JS_NewInt32(a.js, r.status));- JS_SetPropertyStr(a.js, o, "statusText", JS_NewString(a.js, r.statusText.c_str()));- if (!r.error.empty()) JS_SetPropertyStr(a.js, o, "error", JS_NewString(a.js, r.error.c_str()));- JSValue h = JS_NewObject(a.js);- for (const auto& kv : r.headers) {- JS_SetPropertyStr(a.js, h, kv.first.c_str(), JS_NewString(a.js, kv.second.c_str()));- }- JS_SetPropertyStr(a.js, o, "headers", h);- if (r.isText) {- JS_SetPropertyStr(a.js, o, "text",- JS_NewStringLen(a.js, reinterpret_cast<const char*>(r.body.data()), r.body.size()));- } else {- JS_SetPropertyStr(a.js, o, "arrayBuffer",- JS_NewArrayBufferCopy(a.js, r.body.data(), r.body.size()));- }- return o;-}--// Run the JS callbacks for HTTP replies that arrived since the last frame — JS-// thread only. deliverFetch queued them (POD) from the completion thread.-void drainFetches(App& a) {- std::queue<eshost::FetchResult> done;- { std::lock_guard<std::mutex> lk(g_fetchMutex); done.swap(g_fetchQueue); }- while (!done.empty()) {- const eshost::FetchResult r = std::move(done.front());- done.pop();- auto it = a.fetchCallbacks.find(r.id);- if (it == a.fetchCallbacks.end()) continue; // never happens, but stay safe- JSValue cb = it->second;- a.fetchCallbacks.erase(it);- JSValue arg = makeFetchResult(a, r);- JSValue ret = JS_Call(a.js, cb, JS_UNDEFINED, 1, &arg);- if (JS_IsException(ret)) logJsError(a.js, "es_fetch callback");- JS_FreeValue(a.js, ret);- JS_FreeValue(a.js, arg);- JS_FreeValue(a.js, cb);- }-}--// Drain QuickJS's microtask queue. app.tick() is async: its synchronous prefix-// (finishPlugins, resource inserts) runs on call, but the systems run in jobs.-void pumpJobs(App& a) {- JSContext* c;- while (JS_ExecutePendingJob(a.rt, &c) > 0) { /* ran a job */ }-}--// Fire the timers that came due. Callbacks may add or clear timers, so they run-// off a snapshot rather than while iterating.-void pumpTimers(App& a) {- const double now = nowMs();- std::vector<Timer> due;- for (auto it = a.timers.begin(); it != a.timers.end();) {- if (it->due > now) { ++it; continue; }- due.push_back(*it);- if (it->interval > 0) { it->due = now + it->interval; ++it; }- else it = a.timers.erase(it);- }- for (Timer& t : due) {- JSValue r = JS_Call(a.js, t.fn, JS_UNDEFINED, 0, nullptr);- if (JS_IsException(r)) logJsError(a.js, "timer callback");- JS_FreeValue(a.js, r);- if (t.interval <= 0) JS_FreeValue(a.js, t.fn); // the erased entry's reference- }-}--/// One turn of the host's event loop: microtasks, then timers, then whatever-/// microtasks those timers queued.-void pumpJs(App& a) {- pumpJobs(a);- pumpTimers(a);- pumpJobs(a);-}--void bindGlobal(App& a, JSValue global, const char* name, JSCFunction* fn, int argc) {- JS_SetPropertyStr(a.js, global, name, JS_NewCFunction(a.js, fn, name, argc));-}--double nowMs() {- struct timespec ts;- clock_gettime(CLOCK_MONOTONIC, &ts);- return ts.tv_sec * 1000.0 + ts.tv_nsec / 1e6;-}--// FNV-1a of the bundle — a changed SDK invalidates its bytecode cache.-uint64_t hashBytes(const char* p, size_t n) {- uint64_t h = 1469598103934665603ull;- for (size_t i = 0; i < n; i++) { h ^= (uint8_t)p[i]; h *= 1099511628211ull; }- return h;-}--// Evaluate a global script, reusing a cached bytecode compile. QuickJS is an-// interpreter: parsing the ~700 KB SDK bundle costs ~8 s every launch. So compile-// once (JS_WriteObject the bytecode, tagged with the bundle hash), and on later-// launches JS_ReadObject it — skipping the parse. The same QuickJS build writes and-// reads it, so the format always matches; the hash guards against a stale bundle,-// and a bad read just recompiles. Cache file: [8-byte hash][bytecode].-JSValue evalCachedScript(App& a, const char* src, size_t srcLen, const char* filename,- const std::string& cachePath) {- const uint64_t want = hashBytes(src, srcLen);-- if (!cachePath.empty()) {- FILE* f = fopen(cachePath.c_str(), "rb");- if (f) {- uint64_t got = 0;- std::vector<u8> bc;- if (fread(&got, sizeof(got), 1, f) == 1 && got == want) {- fseek(f, 0, SEEK_END);- long sz = ftell(f);- fseek(f, (long)sizeof(got), SEEK_SET);- if (sz > (long)sizeof(got)) {- bc.resize((size_t)sz - sizeof(got));- if (fread(bc.data(), 1, bc.size(), f) != bc.size()) bc.clear();- }- }- fclose(f);- if (!bc.empty()) {- JSValue obj = JS_ReadObject(a.js, bc.data(), bc.size(), JS_READ_OBJ_BYTECODE);- if (!JS_IsException(obj)) {- LOGI("SDK bundle: loaded from bytecode cache");- return JS_EvalFunction(a.js, obj);- }- JSValue e = JS_GetException(a.js); JS_FreeValue(a.js, e); // stale/corrupt -> recompile- }- }- }-- // Parse once (slow), cache the bytecode, run.- JSValue fn = JS_Eval(a.js, src, srcLen, filename, JS_EVAL_TYPE_GLOBAL | JS_EVAL_FLAG_COMPILE_ONLY);- if (JS_IsException(fn)) return fn;- if (!cachePath.empty()) {- size_t bcLen = 0;- uint8_t* bc = JS_WriteObject(a.js, &bcLen, fn, JS_WRITE_OBJ_BYTECODE);- if (bc) {- FILE* f = fopen(cachePath.c_str(), "wb");- if (f) { fwrite(&want, sizeof(want), 1, f); fwrite(bc, 1, bcLen, f); fclose(f); }- js_free(a.js, bc);- LOGI("SDK bundle: compiled + cached bytecode (%zu bytes)", bcLen);- }- }- return JS_EvalFunction(a.js, fn); // consumes fn-}--void initJS(App& a) {- const double t0 = nowMs();- a.rt = JS_NewRuntime();- a.js = JS_NewContext(a.rt);- JSValue global = JS_GetGlobalObject(a.js);-- JS_SetPropertyStr(a.js, global, "W", JS_NewFloat64(a.js, a.w));- JS_SetPropertyStr(a.js, global, "H", JS_NewFloat64(a.js, a.h));- JS_SetPropertyStr(a.js, global, "S", JS_NewFloat64(a.js, a.w < a.h ? a.w : a.h));-- // The host environment the SDK expects but QuickJS (a language, not a runtime)- // does not provide: console, timers and a monotonic clock. Without them a- // rejected promise is silent and the asset cache's setTimeout throws.- JSValue console = JS_NewObject(a.js);- for (const char* name : {"log", "info", "debug", "trace"}) {- JS_SetPropertyStr(a.js, console, name, JS_NewCFunction(a.js, js_consoleLog, name, 1));- }- for (const char* name : {"warn", "error"}) {- JS_SetPropertyStr(a.js, console, name, JS_NewCFunction(a.js, js_consoleError, name, 1));- }- JS_SetPropertyStr(a.js, global, "console", console);-- bindGlobal(a, global, "setTimeout", js_setTimeout, 2);- bindGlobal(a, global, "setInterval", js_setInterval, 2);- bindGlobal(a, global, "clearTimeout", js_clearTimer, 1);- bindGlobal(a, global, "clearInterval", js_clearTimer, 1);- JSValue perf = JS_NewObject(a.js);- JS_SetPropertyStr(a.js, perf, "now", JS_NewCFunction(a.js, js_performanceNow, "now", 0));- JS_SetPropertyStr(a.js, global, "performance", perf);- bindGlobal(a, global, "es_utf8Decode", js_utf8Decode, 1);- bindGlobal(a, global, "es_readCacheFile", js_readCacheFile, 1);- bindGlobal(a, global, "es_writeCacheFile", js_writeCacheFile, 2);- bindGlobal(a, global, "es_fetch", js_fetch, 2);-- // Entity + hierarchy (base Registry surface).- bindGlobal(a, global, "es_createEntity", js_createEntity, 0);- bindGlobal(a, global, "es_destroyEntity", js_destroyEntity, 1);- bindGlobal(a, global, "es_setParent", js_setParent, 2);- bindGlobal(a, global, "es_hasParent", js_hasParent, 1);- bindGlobal(a, global, "es_removeParent", js_removeParent, 1);- bindGlobal(a, global, "es_hasChildren", js_hasChildren, 1);- bindGlobal(a, global, "es_getChildren", js_getChildren, 1);- // Resources + clear + asset reads. es_createTexture / es_releaseTexture /- // es_getTextureDimensions are the native ResourceManager contract the SDK's- // createNativeResourceManager binds to (the asset pipeline's texture backend).- bindGlobal(a, global, "es_setClear", js_setClear, 3);- bindGlobal(a, global, "es_createTexture", js_createTexture, 3);- bindGlobal(a, global, "es_createTextureKTX2", js_createTextureKTX2, 2);- bindGlobal(a, global, "es_releaseTexture", js_releaseTexture, 1);- bindGlobal(a, global, "es_getTextureDimensions", js_getTextureDimensions, 1);- bindGlobal(a, global, "es_readAsset", js_readAsset, 1);- bindGlobal(a, global, "es_loadImagePixels", js_loadImagePixels, 1);- // Text (es_rasterizeGlyph + es_submitTextBatch + the two texture calls the- // glyph atlas needs): the SDK's TEXT_BINDINGS, all-or-nothing. The device has- // no 2D canvas to rasterize on and no wasm heap to submit through; everything- // between those two — atlas, layout, batching — is the SDK's own code.- bindGlobal(a, global, "es_rasterizeGlyph", js_rasterizeGlyph, 1);- bindGlobal(a, global, "es_submitTextBatch", js_submitTextBatch, 9);- bindGlobal(a, global, "es_updateTextureSubregion", js_updateTextureSubregion, 6);- bindGlobal(a, global, "es_getTextureRenderId", js_getTextureRenderId, 1);- // The frame: es_renderer_* (and every other binding entry point) comes from- // esn_register_functions below — generated from the declarations embind- // registers on the web. Only what has no web counterpart is bound by hand.- bindGlobal(a, global, "es_renderer_surfaceSize", js_renderer_surfaceSize, 0);- bindGlobal(a, global, "es_registry_getCameraEntities", js_registry_getCameraEntities, 0);- // Audio (es_audio*): bound only when a device came up, so the SDK's- // hasAudioBindings() gates the native audio backend on real availability —- // a host with no sound device binds none and falls back to the Null backend.- if (a.audio.ready()) {- bindGlobal(a, global, "es_audioLoad", js_audioLoad, 1);- bindGlobal(a, global, "es_audioUnload", js_audioUnload, 1);- bindGlobal(a, global, "es_audioPlay", js_audioPlay, 5);- bindGlobal(a, global, "es_audioStop", js_audioStop, 1);- bindGlobal(a, global, "es_audioPause", js_audioPause, 1);- bindGlobal(a, global, "es_audioResume", js_audioResume, 1);- bindGlobal(a, global, "es_audioSetVolume", js_audioSetVolume, 2);- bindGlobal(a, global, "es_audioSetPan", js_audioSetPan, 2);- bindGlobal(a, global, "es_audioSetLoop", js_audioSetLoop, 2);- bindGlobal(a, global, "es_audioSetRate", js_audioSetRate, 2);- bindGlobal(a, global, "es_audioVoiceState", js_audioVoiceState, 1);- bindGlobal(a, global, "es_audioSuspendAll", js_audioSuspendAll, 0);- bindGlobal(a, global, "es_audioResumeAll", js_audioResumeAll, 0);- }- // Per-component bindings (EHT-generated): es_set_<C> / es_<C>_buffer / _has / _remove.- esn_register(a.js, global);- // The engine's binding entry points (EHT-generated from the same declarations- // embind registers): es_renderer_*, es_uiLayout_*, es_particle_*, … The SDK- // calls them by the same names its wasm path calls the module by.- esn_register_functions(a.js, global);- JS_FreeValue(a.js, global);-- // Layers: the real SDK bundle (engine, embedded) installs ESEngine; the host- // bootstrap (host platform glue) installs the NativeBridge; the game (a- // packaged asset, developer content) authors on top.- const double tCtx = nowMs();- std::string bcPath = a.cacheDir.empty() ? std::string() : (a.cacheDir + "/esengine.native.bc");- JSValue br = evalCachedScript(a, kSdkBundleJS, strlen(kSdkBundleJS), "esengine.native.js", bcPath);- if (JS_IsException(br)) logJsError(a.js, "SDK bundle");- JS_FreeValue(a.js, br);- const double tBundle = nowMs();- evalJs(a, kBootstrapJS, "bootstrap.js");- // An exported project (game.config.json + manifests + cooked assets) boots- // through the bootstrap's default init/update. Its own scripts must register- // their components BEFORE the scene loads. Without that config the package is- // a hand-written game.js, which replaces init/update outright.- const bool exported = !readAsset(a, "game.config.json").empty();- if (exported) {- std::vector<u8> scripts = readAsset(a, "scripts.js");- if (!scripts.empty()) {- evalJs(a, std::string(reinterpret_cast<const char*>(scripts.data()), scripts.size()).c_str(),- "scripts.js");- }- } else {- std::vector<u8> game = readAsset(a, "game.js");- if (game.empty()) {- LOGE("nothing to run: the package has neither game.config.json (an export) nor game.js");- return;- }- evalJs(a, std::string(reinterpret_cast<const char*>(game.data()), game.size()).c_str(), "game.js");- }- const double tGame = nowMs();- callJs(a, "init", 0, nullptr);- pumpJs(a);- const double tInit = nowMs();- LOGI("boot ms — qjs ctx: %.0f | SDK bundle eval: %.0f | bootstrap+game: %.0f | init(): %.0f | total JS: %.0f",- tCtx - t0, tBundle - tCtx, tGame - tBundle, tInit - tGame, tInit - t0);- LOGI("%s init() ran on the real SDK App", exported ? "exported project" : "game.js");-}--} // namespace--namespace eshost {--bool bindSurface() {- App& a = *g_app;- u32 w = 0, h = 0;- a.platform->surfaceSize(w, h);- a.w = (f32)w;- a.h = (f32)h;- if (!a.gfx->configureSurface(a.platform->surface(), w, h)) {- LOGE("configureSurface failed");- return false;- }- a.surfaceReady = true;- return true;-}--void surfaceLost() {- if (g_app) g_app->surfaceReady = false;-}--bool booted() { return g_app && g_app->ready; }--bool surfaceBound() { return g_app && g_app->surfaceReady; }--bool boot(Platform& platform) {- static App app;- g_app = &app;- App& a = app;- a.platform = &platform;- a.cacheDir = platform.cacheDir();-- const double te0 = nowMs();- WGPUInstanceFeatureName feats[] = {WGPUInstanceFeatureName_TimedWaitAny};- WGPUInstanceDescriptor idesc = {};- idesc.requiredFeatureCount = 1;- idesc.requiredFeatures = feats;- a.instance = wgpuCreateInstance(&idesc);- WGPURequestAdapterOptions opts = {};- opts.backendType = platform.backend();- auto onA = [](WGPURequestAdapterStatus s, WGPUAdapter ad, WGPUStringView, void* u, void*) {- if (s == WGPURequestAdapterStatus_Success) *static_cast<WGPUAdapter*>(u) = ad; };- WGPURequestAdapterCallbackInfo aci = {};- aci.mode = WGPUCallbackMode_WaitAnyOnly; aci.callback = onA; aci.userdata1 = &a.adapter;- WGPUFutureWaitInfo af = {wgpuInstanceRequestAdapter(a.instance, &opts, aci), 0};- wgpuInstanceWaitAny(a.instance, 1, &af, UINT64_MAX);- if (!a.adapter) { LOGE("no adapter"); return false; }- auto onD = [](WGPURequestDeviceStatus s, WGPUDevice d, WGPUStringView, void* u, void*) {- if (s == WGPURequestDeviceStatus_Success) *static_cast<WGPUDevice*>(u) = d; };- // Enable the block-compression families this adapter supports (ETC2/ASTC/BC)- // so the engine can create KTX2 textures; a device rejects a format it did not- // opt into, even when the adapter advertises it.- WGPUFeatureName compFeats[3];- size_t compCount = 0;- for (WGPUFeatureName f : {WGPUFeatureName_TextureCompressionETC2,- WGPUFeatureName_TextureCompressionASTC,- WGPUFeatureName_TextureCompressionBC}) {- if (wgpuAdapterHasFeature(a.adapter, f)) compFeats[compCount++] = f;- }- WGPUDeviceDescriptor dd = {};- dd.requiredFeatureCount = compCount;- dd.requiredFeatures = compCount ? compFeats : nullptr;- WGPURequestDeviceCallbackInfo dci = {};- dci.mode = WGPUCallbackMode_WaitAnyOnly; dci.callback = onD; dci.userdata1 = &a.device;- WGPUFutureWaitInfo df = {wgpuAdapterRequestDevice(a.adapter, &dd, dci), 0};- wgpuInstanceWaitAny(a.instance, 1, &df, UINT64_MAX);- if (!a.device) { LOGE("no device"); return false; }-- auto device = makeUnique<WebGPUDevice>(a.device, a.instance, a.adapter);- a.gfx = device.get();- if (!bindSurface()) return false;- static EstellaContext context;- a.ctx = &context;- // The binding entry points (the generated es_* wrappers call the same ones- // embind does) reach the engine through activeCtx(); install ours, exactly as- // the web entry does at initRenderer. Without this they would act on the- // fallback context and render into a different engine than the host presents.- g_activeContext = &context;- context.state().viewport_width = (i32)a.w;- context.state().viewport_height = (i32)a.h;- if (!context.init(std::move(device))) { LOGE("context.init failed"); return false; }- static ecs::Registry registry;- a.registry = ®istry;- LOGI("boot ms — Dawn instance/adapter/device + EstellaContext: %.0f", nowMs() - te0);- LOGI("audio: %s", a.audio.init() ? "native engine up (miniaudio)" : "no device — silent");- initJS(a);- a.ready = true;- LOGI("real SDK up (%dx%d) — esengine World over native Dawn", (int)a.w, (int)a.h);- return true;-}--// Has the SDK's render pipeline taken over the frame? It declares itself through-// `es_jsOwnsFrame` (see HOST_FLAGS in the SDK's nativeBindings) once installed.-bool jsOwnsFrame(App& a) {- JSValue global = JS_GetGlobalObject(a.js);- JSValue v = JS_GetPropertyStr(a.js, global, "es_jsOwnsFrame");- const bool owns = JS_ToBool(a.js, v) != 0;- JS_FreeValue(a.js, v);- JS_FreeValue(a.js, global);- return owns;-}--void frame() {- if (!g_app || !g_app->ready || !g_app->surfaceReady) return;- App& a = *g_app;- auto& ctx = *a.ctx;- JSValue dt = JS_NewFloat64(a.js, 1.0 / 60.0);- callJs(a, "update", 1, &dt);- JS_FreeValue(a.js, dt);- pumpJs(a); // run the App tick's async systems and any timers they set-- // Notify JS of voices that ended on their own (the audio thread never touches- // QuickJS; we poll on this thread and push, like touch). onEnd handlers may- // start new sounds synchronously — safe, pumpEnded iterates a snapshot.- a.audio.pumpEnded([&a](int voiceId) {- JSValue arg = JS_NewInt32(a.js, voiceId);- callJs(a, "es_onNativeAudioEnded", 1, &arg);- JS_FreeValue(a.js, arg);- });-- // Run the callbacks for any HTTP replies that landed since last frame, then- // let their .then() continuations run.- drainFetches(a);- pumpJs(a);-- // The frame itself belongs to the SDK: app.tick above ran its render system,- // which resolved the scene's cameras and drove RenderFrame through the- // es_renderer_* bindings — the same code path the web build takes. What is- // left here is what only a host can do: flip the swapchain.- //- // A game script that predates those bindings (or a host that has not bound- // them) still gets a frame: fall back to one full-viewport pass. The SDK says- // which it is by declaring es_jsOwnsFrame when its pipeline is installed —- // both drawing would mean the host's pass clears over the SDK's.- if (!jsOwnsFrame(a)) {- ctx.require<RenderContext>().setFrameTime((f32)a.frame / 60.0f, (u32)a.w, (u32)a.h);- World world{*a.registry, ctx.services(), 1.0f / 60.0f};- ctx.require<ecs::TransformSystem>().update(world);- const glm::mat4 vp = glm::ortho(0.0f, a.w, 0.0f, a.h);- auto& rf = ctx.require<RenderFrame>();- rf.begin(vp, 0, RenderFrame::PassClear{true, true, a.clear});- rf.collectAll(*a.registry);- rf.flush();- rf.end();- }- a.gfx->present();- if (++a.frame % 120 == 0) LOGI("real-SDK frame %llu", (unsigned long long)a.frame);-}--// Push one host touch to the game's es_onNativeTouch(type,id,x,y), which fans it-// out to the NativeBridge's registered listener.-void touch(int type, int id, float x, float y) {- if (!g_app || !g_app->ready) return;- App& a = *g_app;- JSValue global = JS_GetGlobalObject(a.js);- JSValue fn = JS_GetPropertyStr(a.js, global, "es_onNativeTouch");- if (JS_IsFunction(a.js, fn)) {- JSValue args[4] = {- JS_NewInt32(a.js, type), JS_NewInt32(a.js, id),- JS_NewFloat64(a.js, x), JS_NewFloat64(a.js, y),- };- JSValue r = JS_Call(a.js, fn, global, 4, args);- if (JS_IsException(r)) logJsError(a.js, "es_onNativeTouch");- JS_FreeValue(a.js, r);- for (JSValue& v : args) JS_FreeValue(a.js, v);- }- JS_FreeValue(a.js, fn);- JS_FreeValue(a.js, global);-}--// The app went to background (visible=false) or returned. Suspend/resume the-// audio device at the native layer — correct even while the JS tick is paused —-// then push the signal to JS, where the Lifecycle plugin auto-pauses the game.-void setVisible(bool visible) {- if (!g_app || !g_app->ready) return;- App& a = *g_app;- if (visible) a.audio.resumeAll(); else a.audio.suspendAll();- JSValue arg = JS_NewBool(a.js, visible);- callJs(a, "es_onNativeVisibility", 1, &arg);- JS_FreeValue(a.js, arg);- pumpJs(a);-}--// OS memory pressure — let the SDK's residency caches drop evictable entries-// (the audio buffer cache trims). Held buffers keep playing; only re-fetch cost-// returns for evicted ones.-void memoryWarning() {- if (!g_app || !g_app->ready) return;- callJs(*g_app, "es_onNativeMemoryWarning", 0, nullptr);- pumpJs(*g_app);-}--// Thread-safe: the platform's HTTP completion (any thread) queues its reply here;-// the frame loop drains it on the JS thread (drainFetches). No JS is touched here.-void deliverFetch(FetchResult result) {- std::lock_guard<std::mutex> lk(g_fetchMutex);- g_fetchQueue.push(std::move(result));-}--} // namespace eshostdiff --git a/native/host_js/logo.png b/native/host_js/logo.pngdeleted file mode 100644index 4166e60d7..000000000Binary files a/native/host_js/logo.png and /dev/null differdiff --git a/native/ios/Content/.gitkeep b/native/ios/Content/.gitkeepindex 06eda5a47..907f29482 100644--- a/native/ios/Content/.gitkeep+++ b/native/ios/Content/.gitkeep@@ -1,4 +1,4 @@Exported project content lands here (cli native --target ios --content <dir>) andships as a folder reference, so its subdirectories survive into the app bundle.-Committed empty: xcodegen needs the directory to exist, and the built-in demo-reads from the bundle root instead.+Committed empty: xcodegen needs the directory to exist before an export has been+staged into it.diff --git a/native/ios/project.yml b/native/ios/project.ymlindex 829da7e45..9821cae1c 100644--- a/native/ios/project.yml+++ b/native/ios/project.yml@@ -4,8 +4,8 @@## brew install xcodegen && cd native/ios && xcodegen && open EstellaiOS.xcodeproj#-# Then pick your Team under Signing & Capabilities and Run on a device. The game-# (game.js) and its content ship as bundle resources, the way the APK ships them+# Then pick your Team under Signing & Capabilities and Run on a device. An+# exported project's content ships as bundle resources, the way the APK ships it# under assets/ — the host reads both through the same project-relative paths.name: EstellaiOS@@ -21,18 +21,6 @@ targets:platform: iOSsources:- path: App- - path: ../host_js/game.js- buildPhase: resources- type: file- - path: ../host_js/logo.png- buildPhase: resources- type: file- - path: ../host_js/beep.wav- buildPhase: resources- type: file- - path: ../host_js/green.ktx2- buildPhase: resources- type: file# An exported project, staged by `cli native --target ios --content <dir>`.# A folder reference (not a group) so cooked subdirectories keep their# shape — the host reads Content/ first, the bundle root second.diff --git a/sdk/src/ecs/nativeBindings.ts b/sdk/src/ecs/nativeBindings.tsindex bc5225920..2c7843779 100644--- a/sdk/src/ecs/nativeBindings.ts+++ b/sdk/src/ecs/nativeBindings.ts@@ -13,6 +13,14 @@** These constants are the one spelling. The call sites read them, and* {@link assertNativeBindings} checks the whole set at boot.+ *+ * A name starting `es_rm_` or `es_renderer_` is GENERATED: the host binds+ * it from the same `bindings/*.hpp` declaration embind registers on the+ * web, so both platforms run one implementation of that entry point (and+ * both get its BoundarySpan validation). The rest are the host's own —+ * either native-only (KTX2 transcode, glyph rasterization) or a shape the+ * generator cannot marshal (an `emscripten::val` result). Those, and only+ * those, are hand-written in `native/host/bindings/`.*//** Entity + hierarchy — the base Registry surface the SDK's World drives. */@@ -26,11 +34,19 @@ export const REGISTRY_BINDINGS = {getChildren: 'es_getChildren',} as const;-/** The native ResourceManager surface the asset pipeline uploads through. */+/**+ * The native ResourceManager surface the asset pipeline uploads through.+ *+ * `createTexture` and `releaseTexture` are the engine's own `rm_*` entry points,+ * generated — the same ones embind exposes as methods on the web ResourceManager,+ * so a texture is created by one implementation on both platforms. The other two+ * cannot be: KTX2 transcoding is native-only (the web path is WebGL2 + a wasm+ * transcoder), and the dimensions query returns an `emscripten::val`.+ */export const RESOURCE_BINDINGS = {- createTexture: 'es_createTexture',+ createTexture: 'es_rm_createTextureEx',createTextureKTX2: 'es_createTextureKTX2',- releaseTexture: 'es_releaseTexture',+ releaseTexture: 'es_rm_releaseTexture',getTextureDimensions: 'es_getTextureDimensions',} as const;@@ -41,15 +57,20 @@ export const RESOURCE_BINDINGS = {* between those two calls — atlas, layout, batching — is the same SDK code the* web runs.*+ * Only the glyph source is genuinely the host's: rasterization has no engine entry+ * point to generate from, because on the web a 2D canvas does it. The other three+ * ARE engine entry points, generated — the submit even regains the boundary+ * validation a hand-written copy used to skip.+ ** OPTIONAL, like {@link AUDIO_BINDINGS}: a host that has not bound its font stack* simply draws no text, rather than failing to boot. {@link hasTextBindings} is* the gate.*/export const TEXT_BINDINGS = {rasterizeGlyph: 'es_rasterizeGlyph',- submitTextBatch: 'es_submitTextBatch',- updateTextureSubregion: 'es_updateTextureSubregion',- getTextureRenderId: 'es_getTextureRenderId',+ submitTextBatch: 'es_renderer_submitTextBatch',+ updateTextureSubregion: 'es_rm_updateTextureSubregion',+ getTextureRenderId: 'es_rm_getTextureGLId',} as const;/** Whether a host bound the whole text surface — all-or-nothing, so a partiallydiff --git a/sdk/src/ecs/nativeResourceManager.ts b/sdk/src/ecs/nativeResourceManager.tsindex 904b5334d..c65dc9720 100644--- a/sdk/src/ecs/nativeResourceManager.ts+++ b/sdk/src/ecs/nativeResourceManager.ts@@ -8,15 +8,22 @@//// The one wasm-specific op in the texture path — marshal RGBA into the wasm heap,// then call embind createTexture(ptr) — becomes createTextureFromBytes here: the-// native core has no wasm heap, so the host uploads the JS-owned bytes directly-// (es_createTexture). This mirrors how createNativeRegistry composes the ECS over-// es_* host globals; the same single generated/marshalling philosophy, one more-// backend. The upload helpers (runtimeAssets, TextureLoader) prefer this byte-// method when present, so web (embind, no such method) stays byte-identical.+// native core has no wasm heap, so the JS-owned bytes go straight to the same+// engine entry point (rm_createTextureEx), whose QuickJS wrapper copies them and+// hands the binding a real pointer. This mirrors how createNativeRegistry composes+// the ECS over es_* host globals; the same single generated/marshalling+// philosophy, one more backend. The upload helpers (runtimeAssets, TextureLoader)+// prefer this byte method when present, so web (embind, no such method) stays+// byte-identical.import type { CppResourceManager } from '../wasm';import { RESOURCE_BINDINGS, TEXT_BINDINGS } from './nativeBindings';+/** `rm_createTextureEx` filter/wrap codes, for the case with no import settings.+ * They spell out what the plain `rm_createTexture` path does, so the two agree. */+const FILTER_LINEAR = 1;+const WRAP_CLAMP_TO_EDGE = 1;+/** Invoke a host-provided global by name; throws if the host did not bind it* (these are part of the native ResourceManager contract). */function hostCall(scope: Record<string, unknown>, name: string, args: unknown[]): unknown {@@ -39,10 +46,12 @@ function hostCallOpt(scope: Record<string, unknown>, name: string, args: unknown* Build the CppResourceManager over the host's native texture bindings. `scope`* holds the globals (the QuickJS global object on a device; a plain object in* tests): the host binds- * * es_createTexture(w, h, pixels, format, flip, filter?, wrap?) -> handle- * * es_releaseTexture(handle)+ * * es_rm_createTextureEx(w, h, pixels, len, format, flip, filter, wrap) -> handle+ * * es_rm_releaseTexture(handle)* * es_getTextureDimensions(handle) -> { width, height } | null- * and optionally es_updateTextureSubregion / es_setTextureBudget.+ * and optionally es_rm_updateTextureSubregion / es_setTextureBudget. The `rm_`+ * names are the engine's own entry points, generated for QuickJS from the same+ * declarations embind registers — see {@link RESOURCE_BINDINGS}.** Only the methods the native asset path actually calls are implemented; the* wasm-specific ones (heap-pointer createTexture, registerExternalTexture,@@ -54,12 +63,18 @@ export function createNativeResourceManager(scope: Record<string, unknown> = globalThis as unknown as Record<string, unknown>,): CppResourceManager {const rm: Partial<CppResourceManager> = {- // The module-free upload the SDK prefers on native (no wasm heap).+ // The module-free upload the SDK prefers on native (no wasm heap). The+ // engine entry point is the web's `rm_createTextureEx`: it takes a byte+ // COUNT beside the buffer, because on the web the buffer is a heap offset.+ // Absent import settings mean the defaults the plain `rm_createTexture`+ // path applies — Linear filtering, ClampToEdge wrap (Texture::create's+ // pixel overload) — so a texture with no settings uploads identically.createTextureFromBytes: (width, height, pixels, format, flipY, filterMode, wrapMode,): number =>hostCall(scope, RESOURCE_BINDINGS.createTexture,- [width, height, pixels, format, flipY, filterMode, wrapMode]) as number,+ [width, height, pixels, pixels.length, format, flipY,+ filterMode ?? FILTER_LINEAR, wrapMode ?? WRAP_CLAMP_TO_EDGE]) as number,// The host transcodes KTX2 (basis) and uploads the compressed blocks; it// returns { id, width, height } — expose it as { handle, ... }.@@ -70,7 +85,8 @@ export function createNativeResourceManager(},updateTextureSubregionFromBytes: (handle, x, y, width, height, pixels): void => {- hostCallOpt(scope, TEXT_BINDINGS.updateTextureSubregion, [handle, x, y, width, height, pixels]);+ hostCallOpt(scope, TEXT_BINDINGS.updateTextureSubregion,+ [handle, x, y, width, height, pixels, pixels.length]);},// The id a draw command binds a texture by. Named for GL because that isdiff --git a/sdk/src/ecs/nativeRuntime.ts b/sdk/src/ecs/nativeRuntime.tsindex 0f6beb283..bbb290e53 100644--- a/sdk/src/ecs/nativeRuntime.ts+++ b/sdk/src/ecs/nativeRuntime.ts@@ -166,12 +166,18 @@ function installNativeRenderer(app: App, scope: Record<string, unknown>): void {function installNativeUI(app: App, scope: Record<string, unknown>): void {if (!hasTextBindings(scope)) return;+ // The engine's own renderer_submitTextBatch, generated for QuickJS: same+ // argument list as the wasm call in ui/text/submit.ts, because it IS that+ // call — the typed arrays stand in for the heap pointers, and the entry+ // point's BoundarySpan check runs on the far side either way.const submit = scope[TEXT_BINDINGS.submitTextBatch] as (- vertices: Float32Array, vertexCount: number, indices: Uint16Array, textureId: number,- transform: Float32Array, entity: number, layer: number, depth: number, sdf: boolean,+ vertices: Float32Array, vertexCount: number, indices: Uint16Array, indexCount: number,+ textureId: number, transform: Float32Array, entity: number, layer: number,+ depth: number, sdf: number,) => void;setNativeTextSubmit((vertices, vertexCount, indices, textureId, transform, entity, layer, depth, sdf) => {- submit(vertices, vertexCount, indices, textureId, transform, entity, layer, depth, sdf);+ submit(vertices, vertexCount, indices, indices.length, textureId, transform,+ entity, layer, depth, sdf ? 1 : 0);});app.addPlugin(uiPlugin);}diff --git a/sdk/tests/native-assets.test.ts b/sdk/tests/native-assets.test.tsindex 8d429932b..d066c9142 100644--- a/sdk/tests/native-assets.test.ts+++ b/sdk/tests/native-assets.test.ts@@ -4,7 +4,7 @@* @file native-assets.test.ts* @brief The native asset channel (Stage B): the SAME `Assets` class + loaders* the web build uses, over the native core. A mock host scope stands in- * for the QuickJS globals (es_createTexture / es_releaseTexture /+ * for the QuickJS globals (es_rm_createTextureEx / es_rm_releaseTexture /* es_getTextureDimensions) and a mock NativeBridge decodes images, so* `Assets.loadTexture` flows end-to-end — TextureLoader -> pixel decode ->* native ResourceManager createTextureFromBytes — with no wasm module,@@ -23,17 +23,22 @@ import type { NativeBridge } from '../src/platform/native/bridge';function makeTextureScope() {const textures = new Map<number, { width: number; height: number; pixels: Uint8Array; format: number; flip: boolean }>();let nextHandle = 1;+ // The engine's own rm_createTextureEx, as its generated QuickJS wrapper binds+ // it: a byte COUNT beside the buffer (a heap offset on the web), and explicit+ // filter/wrap codes.const createSpy = vi.fn(- (width: number, height: number, pixels: Uint8Array, format: number, flip: boolean) => {+ (width: number, height: number, pixels: Uint8Array, pixelsLen: number,+ format: number, flip: boolean, filter: number, wrap: number) => {const handle = nextHandle++;textures.set(handle, { width, height, pixels, format, flip });+ void pixelsLen; void filter; void wrap;return handle;},);const releaseSpy = vi.fn((handle: number) => { textures.delete(handle); });const scope: Record<string, unknown> = {- es_createTexture: createSpy,- es_releaseTexture: releaseSpy,+ es_rm_createTextureEx: createSpy,+ es_rm_releaseTexture: releaseSpy,es_getTextureDimensions: (handle: number) => {const t = textures.get(handle);return t ? { width: t.width, height: t.height } : null;@@ -79,14 +84,16 @@ afterEach(() => {});describe('createNativeResourceManager', () => {- it('uploads bytes through es_createTexture and reads dims / releases', () => {+ it('uploads bytes through es_rm_createTextureEx and reads dims / releases', () => {const { scope, createSpy, releaseSpy } = makeTextureScope();const rm = createNativeResourceManager(scope);const px = new Uint8Array([1, 2, 3, 4]);const handle = rm.createTextureFromBytes!(1, 1, px, 1, true);expect(handle).toBe(1);- expect(createSpy).toHaveBeenCalledWith(1, 1, px, 1, true, undefined, undefined);+ // Byte count beside the buffer, and the plain path's defaults where the+ // caller gave no import settings (filter Linear, wrap ClampToEdge).+ expect(createSpy).toHaveBeenCalledWith(1, 1, px, px.length, 1, true, 1, 1);expect(rm.getTextureDimensions(handle)).toEqual({ width: 1, height: 1 });rm.releaseTexture(handle);@@ -116,11 +123,14 @@ describe('native Assets.loadTexture', () => {expect(tex.width).toBe(4);expect(tex.height).toBe(2);- // The bytes reached es_createTexture: 4×2 RGBA, format 1 (gamma), flip=true.+ // The bytes reached the engine entry point: 4×2 RGBA, format 1 (gamma),+ // flip=true, and — with no import settings on this texture — the defaults+ // the plain rm_createTexture path applies (Linear filter, ClampToEdge wrap).expect(createSpy).toHaveBeenCalledTimes(1);- const [w, h, pixels, format, flip] = createSpy.mock.calls[0];- expect([w, h, format, flip]).toEqual([4, 2, 1, true]);+ const [w, h, pixels, pixelsLen, format, flip, filter, wrap] = createSpy.mock.calls[0];+ expect([w, h, format, flip, filter, wrap]).toEqual([4, 2, 1, true, 1, 1]);expect((pixels as Uint8Array).length).toBe(4 * 2 * 4);+ expect(pixelsLen).toBe(4 * 2 * 4);// A second load hits the cache — no second upload.const again = await assets.loadTexture('logo.png');diff --git a/sdk/tests/native-host-bridge.test.ts b/sdk/tests/native-host-bridge.test.tsindex 3cc33b65e..6e1aa8e1c 100644--- a/sdk/tests/native-host-bridge.test.ts+++ b/sdk/tests/native-host-bridge.test.ts@@ -162,7 +162,7 @@ describe('assertNativeHost', () => {delete scope[REGISTRY_BINDINGS.setParent];delete scope[RESOURCE_BINDINGS.createTexture];expect(() => assertNativeHost(scope)).toThrow(/es_setParent/);- expect(() => assertNativeHost(scope)).toThrow(/es_createTexture/);+ expect(() => assertNativeHost(scope)).toThrow(new RegExp(RESOURCE_BINDINGS.createTexture));});it('checks the JS environment before the bindings', () => {diff --git a/sdk/tests/native-text.test.ts b/sdk/tests/native-text.test.tsindex 47d5d89de..1864c0c31 100644--- a/sdk/tests/native-text.test.ts+++ b/sdk/tests/native-text.test.ts@@ -75,22 +75,23 @@ function makeHostScope() {}));const submitSpy = vi.fn();const scope: Record<string, unknown> = {- es_createTexture: (width: number, height: number) => {+ es_rm_createTextureEx: (width: number, height: number) => {const handle = nextHandle++;textures.set(handle, { width, height });return handle;},- es_releaseTexture: (handle: number) => { textures.delete(handle); },+ es_rm_releaseTexture: (handle: number) => { textures.delete(handle); },es_getTextureDimensions: (handle: number) => textures.get(handle) ?? null,// The atlas page id: the host answers with the engine's render id for the// handle. A distinct number here proves the id that reaches the batch is// this one, not the ResourceManager handle.- es_getTextureRenderId: (handle: number) => handle + 100,- es_updateTextureSubregion: (handle: number, x: number, y: number, w: number, h: number, pixels: Uint8Array) => {- uploads.push({ handle, x, y, w, h, bytes: pixels.length });+ es_rm_getTextureGLId: (handle: number) => handle + 100,+ es_rm_updateTextureSubregion: (handle: number, x: number, y: number, w: number, h: number,+ pixels: Uint8Array, pixelsLen: number) => {+ uploads.push({ handle, x, y, w, h, bytes: pixels.length, len: pixelsLen });},es_rasterizeGlyph: rasterizeSpy,- es_submitTextBatch: (...args: unknown[]) => { calls.push('text'); submitSpy(...args); },+ es_renderer_submitTextBatch: (...args: unknown[]) => { calls.push('text'); submitSpy(...args); },// The frame surface: the SDK's camera plugin + pipeline drive these, and// the order they arrive in is what the host's frame depends on.es_renderer_resize: () => { calls.push('resize'); },@@ -217,18 +218,23 @@ describe('a frame on the native core', () => {// Each glyph landed in the atlas page as an 8×8 RGBA sub-region upload.expect(uploads).toHaveLength(2);- expect(uploads[0]).toMatchObject({ handle: 1, w: 8, h: 8, bytes: 8 * 8 * 4 });+ expect(uploads[0]).toMatchObject({ handle: 1, w: 8, h: 8, bytes: 8 * 8 * 4, len: 8 * 8 * 4 });// One batch for the one page, bound by the host's render id (handle + 100),// carrying two quads: 4 vertices and 6 indices each.expect(submitSpy).toHaveBeenCalledTimes(1);- const [vertices, vertexCount, indices, textureId, transform, ent, , , sdf] = submitSpy.mock.calls[0];+ // The argument list is the engine entry point's, not a host-shaped one:+ // renderer_submitTextBatch(vertices, vertexCount, indices, indexCount,+ // textureId, transform, entity, layer, depth, sdf).+ const [vertices, vertexCount, indices, indexCount, textureId, transform, ent, , , sdf] =+ submitSpy.mock.calls[0];expect(textureId).toBe(101);expect(ent).toBe(entity);- expect(sdf).toBe(true);+ expect(sdf).toBe(1);expect(vertexCount).toBe(8);expect((vertices as Float32Array).length).toBe(8 * TEXT_VERTEX_FLOATS);expect((indices as Uint16Array).length).toBe(12);+ expect(indexCount).toBe(12);expect((transform as Float32Array).length).toBe(16);});diff --git a/src/esengine/bindings/ResourceManagerBindings.cpp b/src/esengine/bindings/ResourceManagerBindings.cppindex d19022b44..0c303f046 100644--- a/src/esengine/bindings/ResourceManagerBindings.cpp+++ b/src/esengine/bindings/ResourceManagerBindings.cpp@@ -9,7 +9,9 @@#include "../core/Types.hpp"#include "../core/Log.hpp"+#ifdef __EMSCRIPTEN__#include <emscripten/val.h>+#endifnamespace esengine {@@ -129,6 +131,7 @@ u32 rm_trimTextureCache(resource::ResourceManager& rm) {return static_cast<u32>(rm.trimTextureCache());}+#ifdef __EMSCRIPTEN__emscripten::val rm_getResourceStats(resource::ResourceManager& rm) {const auto st = rm.getStats();auto result = emscripten::val::object();@@ -143,6 +146,7 @@ emscripten::val rm_getResourceStats(resource::ResourceManager& rm) {result.set("textureEvictableCount", static_cast<f64>(st.textureEvictableCount));return result;}+#endif // __EMSCRIPTEN__void rm_releaseShader(resource::ResourceManager& rm, u32 handleId) {rm.releaseShader(resource::ShaderHandle(handleId));@@ -157,6 +161,7 @@ u32 rm_getTextureGLId(resource::ResourceManager& rm, u32 handleId) {return tex ? tex->getId() : 0;}+#ifdef __EMSCRIPTEN__emscripten::val rm_getTextureDimensions(resource::ResourceManager& rm, u32 handleId) {auto* tex = rm.getTexture(resource::TextureHandle(handleId));if (!tex) {@@ -167,6 +172,7 @@ emscripten::val rm_getTextureDimensions(resource::ResourceManager& rm, u32 handlresult.set("height", tex->getHeight());return result;}+#endif // __EMSCRIPTEN__#ifdef ES_ENABLE_BITMAP_TEXTu32 rm_loadBitmapFont(resource::ResourceManager& rm, const std::string& fntContent,@@ -193,6 +199,7 @@ u32 rm_getBitmapFontRefCount(resource::ResourceManager& rm, u32 handleId) {return rm.getBitmapFontRefCount(resource::BitmapFontHandle(handleId));}+#ifdef __EMSCRIPTEN__emscripten::val rm_measureBitmapText(resource::ResourceManager& rm, u32 fontHandle,const std::string& text, f32 fontSize, f32 spacing) {auto* font = rm.getBitmapFont(resource::BitmapFontHandle(fontHandle));@@ -208,7 +215,8 @@ emscripten::val rm_measureBitmapText(resource::ResourceManager& rm, u32 fontHandresult.set("height", metrics.height);return result;}-#endif+#endif // __EMSCRIPTEN__+#endif // ES_ENABLE_BITMAP_TEXTvoid rm_updateTextureSubregion(resource::ResourceManager& rm, u32 handleId,u32 x, u32 y, u32 width, u32 height,diff --git a/src/esengine/bindings/ResourceManagerBindings.hpp b/src/esengine/bindings/ResourceManagerBindings.hppindex 87e20e125..3df1cac10 100644--- a/src/esengine/bindings/ResourceManagerBindings.hpp+++ b/src/esengine/bindings/ResourceManagerBindings.hpp@@ -7,9 +7,14 @@#include "../resource/ResourceManager.hpp"#include <string>+// The value type embind returns for array/object results. Web-only: a native+// build compiles this same TU (see cmake/ESEngineSources.cmake) and simply does+// not carry the entry points that return one.+#ifdef __EMSCRIPTEN__namespace emscripten {class val;}+#endifnamespace esengine {@@ -31,11 +36,15 @@ void rm_setTextureBudget(resource::ResourceManager& rm, u32 bytes);u32 rm_acquireTextureByPath(resource::ResourceManager& rm, const std::string& path);bool rm_invalidateTexturePath(resource::ResourceManager& rm, const std::string& path);u32 rm_trimTextureCache(resource::ResourceManager& rm);+#ifdef __EMSCRIPTEN__emscripten::val rm_getResourceStats(resource::ResourceManager& rm);+#endifvoid rm_releaseShader(resource::ResourceManager& rm, u32 handleId);u32 rm_getShaderRefCount(resource::ResourceManager& rm, u32 handleId);u32 rm_getTextureGLId(resource::ResourceManager& rm, u32 handleId);+#ifdef __EMSCRIPTEN__emscripten::val rm_getTextureDimensions(resource::ResourceManager& rm, u32 handleId);+#endif#ifdef ES_ENABLE_BITMAP_TEXTu32 rm_loadBitmapFont(resource::ResourceManager& rm, const std::string& fntContent,u32 textureHandle, u32 texWidth, u32 texHeight);@@ -44,9 +53,11 @@ u32 rm_createLabelAtlasFont(resource::ResourceManager& rm, u32 textureHandle,u32 charWidth, u32 charHeight);void rm_releaseBitmapFont(resource::ResourceManager& rm, u32 handleId);u32 rm_getBitmapFontRefCount(resource::ResourceManager& rm, u32 handleId);+#ifdef __EMSCRIPTEN__emscripten::val rm_measureBitmapText(resource::ResourceManager& rm, u32 fontHandle,const std::string& text, f32 fontSize, f32 spacing);#endif+#endifvoid rm_updateTextureSubregion(resource::ResourceManager& rm, u32 handleId,u32 x, u32 y, u32 width, u32 height,uintptr_t pixelsPtr, u32 pixelsLen);diff --git a/tools/eht/generators/native_functions.py b/tools/eht/generators/native_functions.pyindex 1e2f08eaa..2eb226b24 100644--- a/tools/eht/generators/native_functions.py+++ b/tools/eht/generators/native_functions.py@@ -16,8 +16,9 @@ platforms run the same implementation; only the registration differs.The mapping is small because the declarations are:- ``ecs::Registry&`` the host has exactly one registry, so it is implicit and- consumes no JS argument+ engine singletons ``ecs::Registry&`` / ``resource::ResourceManager&``: the+ host has exactly one of each, so they are implicit and+ consume no JS argument (see ``_IMPLICIT_REFS``)scalars u32/i32/f32/f64/bool/int/float/double``uintptr_t`` ptr a JS ArrayBuffer / typed array; the wrapper copies thebytes and passes a real pointer (the same BoundarySpan@@ -39,6 +40,21 @@ _FLOAT_TYPES = {'f32', 'f64', 'float', 'double'}_BOOL_TYPES = {'bool'}_VOID = 'void'+# Reference parameters the host answers for itself: it runs exactly one registry+# and one resource manager, so these consume no JS argument and the wrapper passes+# the shim's accessor. Everything else taken by reference is a genuine object the+# boundary cannot marshal, and is skipped.+_IMPLICIT_REFS = {+ 'ecs::Registry&': 'esn_reg()',+ 'resource::ResourceManager&': 'esn_rm()',+}++# How a declaration spells each of them, matched on the type's last segment.+_IMPLICIT_SUFFIXES = {+ 'Registry': 'ecs::Registry&',+ 'ResourceManager': 'resource::ResourceManager&',+}+# `void name(args);` on one or more lines, inside the header's namespace._DECL = re.compile(r'^(?P<ret>[A-Za-z_][\w:]*(?:\s*\*)?)\s+(?P<name>[A-Za-z_]\w*)\s*\((?P<args>[^;{]*)\)\s*;',@@ -150,9 +166,12 @@ def _parse_params(args: str) -> Tuple[List[Param], Optional[str]]:if not decl:continueparts = decl.replace('&', ' & ').split()- # `ecs::Registry ®istry` → the host's one registry, no JS argument.- if parts[0].endswith('Registry') and '&' in decl:- params.append(Param('ecs::Registry&', parts[-1]))+ # `ecs::Registry ®istry` / `resource::ResourceManager &rm` → the host's+ # one of each, no JS argument.+ implicit = next((t for suffix, t in _IMPLICIT_SUFFIXES.items()+ if parts[0].endswith(suffix)), None) if '&' in decl else None+ if implicit:+ params.append(Param(implicit, parts[-1]))continueif '&' in decl or '*' in decl:return params, f'takes {decl}'@@ -190,7 +209,7 @@ class NativeFunctionsGenerator:self.emitted: List[str] = []def _wrapper(self, fn: Function) -> List[str]:- js_params = [p for p in fn.params if p.cpp_type != 'ecs::Registry&']+ js_params = [p for p in fn.params if p.cpp_type not in _IMPLICIT_REFS]out = [f'#ifdef {g}' for g in fn.guards]out.append(f'static JSValue es_{fn.name}(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {{')if js_params:@@ -200,8 +219,8 @@ class NativeFunctionsGenerator:call_args: List[str] = []js_index = 0for param in fn.params:- if param.cpp_type == 'ecs::Registry&':- call_args.append('esn_reg()')+ if param.cpp_type in _IMPLICIT_REFS:+ call_args.append(_IMPLICIT_REFS[param.cpp_type])continuelocal = f'a{js_index}'if param.cpp_type == 'uintptr_t':@@ -249,7 +268,7 @@ class NativeFunctionsGenerator:def _ts_type(cpp: str) -> str:if cpp in _BOOL_TYPES:return 'boolean'- if cpp == 'ecs::Registry&':+ if cpp in _IMPLICIT_REFS:return 'unknown'return 'number'@@ -301,13 +320,13 @@ class NativeFunctionsGenerator:' if (typeof fn !== \'function\') return;',' const call = fn as (...a: unknown[]) => unknown;',' api[name] = dropFirst',- ' ? (_registry: unknown, ...args: unknown[]) => call(...args)',+ ' ? (_implicit: unknown, ...args: unknown[]) => call(...args)',' : (...args: unknown[]) => call(...args);',' };',])for fn in functions:- takes_registry = any(p.cpp_type == 'ecs::Registry&' for p in fn.params)- lines.append(f" bind('{fn.name}', 'es_{fn.name}', {str(takes_registry).lower()});")+ takes_implicit = any(p.cpp_type in _IMPLICIT_REFS for p in fn.params)+ lines.append(f" bind('{fn.name}', 'es_{fn.name}', {str(takes_implicit).lower()});")lines.extend([' return api as NativeEngineApi;','}',@@ -348,7 +367,7 @@ class NativeFunctionsGenerator:lines.append('void esn_register_functions(JSContext* ctx, JSValue global) {')for fn in sorted(functions, key=lambda f: f.name):- js_arity = len([p for p in fn.params if p.cpp_type != 'ecs::Registry&'])+ js_arity = len([p for p in fn.params if p.cpp_type not in _IMPLICIT_REFS])lines.extend(f'#ifdef {g}' for g in fn.guards)lines.append(f' JS_SetPropertyStr(ctx, global, "es_{fn.name}", 'f'JS_NewCFunction(ctx, es_{fn.name}, "es_{fn.name}", {js_arity}));')