A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(native): in-tree JS host (QuickJS), built by the orchestrated `cli native`
yhh6c8ade97099e
diff --git a/build-tools/cli.js b/build-tools/cli.jsindex 6910c16e4..5bd54880f 100644--- a/build-tools/cli.js+++ b/build-tools/cli.js@@ -162,6 +162,7 @@ program.description('Build the native (embedded-Dawn) host for Android arm64').option('--dawn <dir>', 'Dawn source dir (or ESTELLA_DAWN_DIR); see native/README.md').option('--dawn-build <dir>', 'Dawn arm64 build dir (or ESTELLA_DAWN_BUILD)')+ .option('--quickjs <dir>', 'QuickJS-ng source dir (or ESTELLA_QUICKJS_DIR); also builds the JS host').option('--abi <abi>', 'Android ABI', 'arm64-v8a').option('--platform <platform>', 'Android platform', 'android-33').option('-v, --verbose', 'Verbose output', false)@@ -171,6 +172,7 @@ programawait buildNative({dawn: options.dawn,dawnBuild: options.dawnBuild,+ quickjs: options.quickjs,abi: options.abi,platform: options.platform,});diff --git a/build-tools/tasks/native.js b/build-tools/tasks/native.jsindex be6676734..d843dfdfc 100644--- a/build-tools/tasks/native.js+++ b/build-tools/tasks/native.js@@ -8,11 +8,11 @@// paths via --dawn / --dawn-build or ESTELLA_DAWN_DIR / ESTELLA_DAWN_BUILD.import path from 'path';-import { existsSync, readdirSync } from 'fs';+import { existsSync, readdirSync, readFileSync, writeFileSync } from 'fs';import { mkdir } from 'fs/promises';import config from '../build.config.js';import * as logger from '../utils/logger.js';-import { runCommand, getCpuCount } from '../utils/emscripten.js';+import { runCommand, getCpuCount, resolvePython } from '../utils/emscripten.js';function androidSdk() {const sdk = process.env.ANDROID_HOME || process.env.ANDROID_SDK_ROOT;@@ -38,6 +38,56 @@ function sdkCmake(sdk) {return { cmake: path.join(bin, 'cmake' + exe), ninja: path.join(bin, 'ninja' + exe) };}+// Generate the native (QuickJS) ECS bindings from the SAME reflection source EHT+// uses for the web embind bindings — so the two surfaces can never drift. Written+// into the build tree (not committed); --native-only skips all embind/editor/TS+// work so no committed *.generated.* file is touched.+async function generateNativeBindings(rootDir, genDir, python) {+ const out = path.join(genDir, 'NativeBindings.generated.cpp');+ await runCommand(python, [+ path.join(rootDir, 'tools', 'eht.py'),+ '--input', path.join(rootDir, 'src', 'esengine', 'ecs', 'components'),+ '--native-output', out,+ '--native-shim', 'esn_shim.hpp',+ '--native-only',+ ], { cwd: rootDir });+ return out;+}++// Embed the REAL SDK sdk/src/ecs/ptrAccessors.generated.ts as plain JS the host+// evaluates in QuickJS. It's the exact file the web SDK marshals through — POD+// components are wasm32/arm64 layout-identical, so the accessors write native+// component memory unchanged (through the zero-copy es_<C>_buffer ArrayBuffer).+async function generatePtrAccessors(rootDir, genDir) {+ const tsSrc = path.join(rootDir, 'sdk', 'src', 'ecs', 'ptrAccessors.generated.ts');+ const tscBin = path.join(rootDir, 'sdk', 'node_modules', 'typescript', 'bin', 'tsc');+ if (!existsSync(tscBin)) {+ throw new Error(`tsc not found at ${tscBin}. Run 'npm install' in sdk/ first.`);+ }+ const tsOut = path.join(genDir, 'tsc-out');+ await mkdir(tsOut, { recursive: true });+ // Transpile TS -> plain JS (strip types); same bytes the web SDK uses.+ await runCommand('node', [tscBin, tsSrc, '--outDir', tsOut,+ '--module', 'es2020', '--target', 'es2020', '--skipLibCheck'], { cwd: rootDir });++ let js = readFileSync(path.join(tsOut, 'ptrAccessors.generated.js'), 'utf8');+ // Global eval hoists top-level `function` decls to globals but not `const`, so+ // drop the ESM `export`s (functions become globals) and expose the table.+ js = js.replace(/^export /gm, '');+ js += '\nglobalThis.PTR_ACCESSORS = PTR_ACCESSORS;\n';++ const header =+ '// The real SDK sdk/src/ecs/ptrAccessors.generated.ts, transpiled to plain JS.\n' ++ '// Generated by `cli native --quickjs` from the committed SDK file — DO NOT EDIT.\n' ++ '#pragma once\n' ++ 'static const char* kPtrAccessorsJS = R"PTRJS(\n' ++ js ++ ')PTRJS";\n';+ const headerPath = path.join(genDir, 'ptraccessors_js.h');+ writeFileSync(headerPath, header, 'utf8');+ return headerPath;+}+export async function buildNative(options = {}) {const { abi = 'arm64-v8a', platform = 'android-33' } = options;const rootDir = config.paths.root;@@ -59,6 +109,26 @@ export async function buildNative(options = {}) {const buildDir = path.join(rootDir, 'build-native');await mkdir(buildDir, { recursive: true });+ // JS host (opt-in): pass --quickjs <dir> (or ESTELLA_QUICKJS_DIR) to also build+ // the QuickJS host — a game script driving the engine through the generated+ // bindings + the real SDK ptrAccessors. Both generated artifacts go in the+ // build tree; nothing committed can drift from the reflection / SDK source.+ const quickjs = options.quickjs || process.env.ESTELLA_QUICKJS_DIR;+ let genDir = null;+ if (quickjs) {+ if (!existsSync(quickjs)) {+ throw new Error(`QuickJS source dir not found: ${quickjs}. Clone `+ + 'https://github.com/quickjs-ng/quickjs (see native/README.md).');+ }+ genDir = path.join(buildDir, 'gen');+ await mkdir(genDir, { recursive: true });+ const python = await resolvePython() ?? 'python3';+ logger.step('Generating native ECS bindings (EHT, single reflection source)...');+ await generateNativeBindings(rootDir, genDir, python);+ logger.step('Embedding the real SDK ptrAccessors (transpiled to JS)...');+ await generatePtrAccessors(rootDir, genDir);+ }+logger.step(`Configuring native host (${abi}, ${platform})...`);const configureArgs = ['-S', path.join(rootDir, 'native'),@@ -73,10 +143,19 @@ export async function buildNative(options = {}) {`-DESTELLA_DAWN_BUILD=${dawnBuild}`,];if (ninja) configureArgs.push(`-DCMAKE_MAKE_PROGRAM=${ninja}`);+ if (quickjs) {+ // CMake parses backslashes in -D string values as escapes (F:\estella -> \e),+ // so hand it forward-slash paths (valid on Windows too).+ const fwd = (p) => p.replace(/\\/g, '/');+ configureArgs.push(`-DESTELLA_QUICKJS_DIR=${fwd(quickjs)}`, `-DESTELLA_NATIVE_GEN_DIR=${fwd(genDir)}`);+ }await runCommand(cmake, configureArgs, { cwd: rootDir });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')}`);+ }}diff --git a/native/CMakeLists.txt b/native/CMakeLists.txtindex 0e5f72f96..c50dcfe32 100644--- a/native/CMakeLists.txt+++ b/native/CMakeLists.txt@@ -63,3 +63,36 @@ target_link_libraries(esengine PUBLIC glm yogacore webgpu_dawn)add_library(estella_host SHARED host/main.cpp)target_link_libraries(estella_host esengine native_app_glue android log)set_target_properties(estella_host PROPERTIES LINK_FLAGS "-u ANativeActivity_onCreate")++# 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.+if(ESTELLA_QUICKJS_DIR)+ if(NOT ESTELLA_NATIVE_GEN_DIR)+ set(ESTELLA_NATIVE_GEN_DIR "${CMAKE_BINARY_DIR}/gen")+ endif()+ set(NATIVE_BINDINGS "${ESTELLA_NATIVE_GEN_DIR}/NativeBindings.generated.cpp")+ if(NOT EXISTS "${NATIVE_BINDINGS}")+ message(FATAL_ERROR "ESTELLA_QUICKJS_DIR set but ${NATIVE_BINDINGS} is missing. "+ "Generate it (and ptraccessors_js.h) via `cli native --quickjs`, which runs "+ "`python -m eht --native-output ... --native-only`.")+ endif()++ # QuickJS-ng interpreter — core is just these four C files.+ add_library(qjs STATIC+ "${ESTELLA_QUICKJS_DIR}/quickjs.c" "${ESTELLA_QUICKJS_DIR}/libregexp.c"+ "${ESTELLA_QUICKJS_DIR}/libunicode.c" "${ESTELLA_QUICKJS_DIR}/dtoa.c")+ target_include_directories(qjs PUBLIC "${ESTELLA_QUICKJS_DIR}")+ target_compile_definitions(qjs PRIVATE _GNU_SOURCE)+ target_compile_options(qjs PRIVATE -Wno-unused -Wno-sign-compare)++ add_library(estella_js_host SHARED js/main.cpp "${NATIVE_BINDINGS}")+ # js/ holds esn_shim.hpp (the generated TU includes it); the gen dir holds+ # ptraccessors_js.h (main.cpp includes it).+ target_include_directories(estella_js_host PRIVATE+ "${CMAKE_CURRENT_SOURCE_DIR}/js" "${ESTELLA_NATIVE_GEN_DIR}")+ 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()diff --git a/native/README.md b/native/README.mdindex 4f4fb6e66..1d243cabd 100644--- a/native/README.md+++ b/native/README.md@@ -7,10 +7,17 @@ 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 is the reference host + build recipe. Dawn and QuickJS are **not-vendored** (multi-GB); the recipe fetches them, the way Dawn fetches its own deps.-Nothing here is compiled by the web/emscripten build or CI — it is inert until you-run the native build below.+This directory holds two reference hosts + the build recipe:++- **`host/`** — a pure-C++ host that renders one ECS scene (no JS). A smoke test+ for the engine core on native Dawn. Always built.+- **`js/`** — the JS host: a QuickJS game script drives the engine through the+ EHT-generated bindings + the real SDK `ptrAccessors`. Built when you pass+ `--quickjs` (this is the product-shaped runtime).++Dawn and QuickJS are **not vendored** (multi-GB / separate project); the recipe+fetches them, the way Dawn fetches its own deps. Nothing here is compiled by the+web/emscripten build or CI — it is inert until you run the native build below.## Why this works (the architecture, proven on device)@@ -28,9 +35,12 @@ the tree:## Build (Android arm64)Toolchain: Android SDK + NDK r28 (`android.toolchain.cmake`), SDK CMake ≥ 3.22.+`cli native` locates the SDK / NDK / CMake automatically (`ANDROID_HOME`, or+Android Studio's default install) and drives `native/CMakeLists.txt`.++**One-time: build Dawn for arm64** (Vulkan). Multi-GB; kept out of the tree.```sh-# 1) Fetch Dawn and build libwebgpu_dawn.so for arm64 (Vulkan).git clone --depth 1 https://github.com/google/dawn "$DAWN"python "$DAWN/tools/fetch_dawn_dependencies.py" --shallow # NOT depot_toolscmake -S "$DAWN" -B "$DAWN/out-android" -G Ninja \@@ -42,26 +52,33 @@ cmake -S "$DAWN" -B "$DAWN/out-android" -G Ninja \-DDAWN_BUILD_PROTOBUF=OFF -DTINT_BUILD_IR_BINARY=OFF \-DDAWN_BUILD_MONOLITHIC_LIBRARY=SHARED -DDAWN_FETCH_DEPENDENCIES=OFFcmake --build "$DAWN/out-android" --target webgpu_dawn+```-# 2) (JS host only) Fetch QuickJS-ng — core is dtoa/libregexp/libunicode/quickjs.c.-git clone --depth 1 https://github.com/quickjs-ng/quickjs "$QJS"--# 3) (JS host only) Generate the native bindings from the same reflection source.-python -m eht -i src/esengine/ecs/components \- --native-output "$BUILD/NativeBindings.generated.cpp" \- --native-components Transform,Sprite,ShapeRenderer,Light2D+**Build the hosts** through the orchestrated task:-# 4) Build the host (see CMakeLists.txt in this dir).-cmake -S native -B "$BUILD" -G Ninja \- -DCMAKE_TOOLCHAIN_FILE="$NDK/build/cmake/android.toolchain.cmake" \- -DANDROID_ABI=arm64-v8a -DANDROID_PLATFORM=android-33 -DANDROID_STL=c++_shared \- -DESTELLA_DAWN_DIR="$DAWN" -DESTELLA_DAWN_BUILD="$DAWN/out-android"-cmake --build "$BUILD"+```sh+# C++ host only.+node build-tools/cli.js native --dawn "$DAWN" --dawn-build "$DAWN/out-android"++# + JS host: clone QuickJS-ng (core is dtoa/libregexp/libunicode/quickjs.c) and+# pass --quickjs. The task then 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)+# * ptraccessors_js.h — the real SDK sdk/src/ecs/ptrAccessors.generated.ts,+# transpiled to JS and embedded+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"```-Package the APK by hand (no gradle): `aapt2 link` a manifest, inject-`lib/arm64-v8a/{libhost.so,libwebgpu_dawn.so,libc++_shared.so}` (strip Dawn with-`llvm-strip`), `zipalign -f 4`, `apksigner sign`.+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`.++Package the APK by hand (no gradle): `aapt2 link` the matching manifest+(`host/` or `js/AndroidManifest.xml`), inject+`lib/arm64-v8a/{libestella*_host.so,libwebgpu_dawn.so,libc++_shared.so}` (strip+Dawn with `llvm-strip`), `zipalign -f 4`, `apksigner sign`.## Gotchas (all resolved; each cost a build)@@ -79,5 +96,7 @@ Package the APK by hand (no gradle): `aapt2 link` a manifest, injectProven end-to-end on device (Snapdragon 8 Elite / Adreno 830, 120 fps): the fullengine renders an ECS scene, a QuickJS game script drives it through the generatedbindings, and the real SDK `ptrAccessors` write native component memory unchanged.-Remaining: load the full SDK bundle + a `BuiltinBridge` memory backend, more-system bindings, and the iOS shell (the Metal surface seam is already in place).+Both hosts are now in-tree and build from the orchestrated `cli native` task+(`js/` links a 24 MB arm64 `libestella_js_host.so`). Remaining: load the full SDK+bundle + a `BuiltinBridge` memory backend, more system bindings, and the iOS shell+(the Metal surface seam is already in place).diff --git a/native/js/AndroidManifest.xml b/native/js/AndroidManifest.xmlnew file mode 100644index 000000000..cc2a022f1--- /dev/null+++ b/native/js/AndroidManifest.xml@@ -0,0 +1,11 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.estella.jshost" 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="EstellaJS" android:hasCode="false" android:extractNativeLibs="true">+ <activity android:name="android.app.NativeActivity" android:label="EstellaJS" android:configChanges="orientation|keyboardHidden|screenSize|screenLayout|density" android:exported="true">+ <meta-data android:name="android.app.lib_name" android:value="estella_js_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/js/esn_shim.hpp b/native/js/esn_shim.hppnew file mode 100644index 000000000..333abb66f--- /dev/null+++ b/native/js/esn_shim.hpp@@ -0,0 +1,28 @@+// 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.+//+// NativeBindings.generated.cpp includes this header first, then self-includes+// each bound component's header — so the shim itself needs no component headers.+#pragma once++extern "C" {+#include "quickjs.h"+}++#include "esengine/ecs/Registry.hpp" // esengine::ecs::Registry + esengine::Entity++// --- provided by the host (js/main.cpp) --------------------------------------+esengine::ecs::Registry& esn_reg();+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);+// Read obj[key] as a truthy int into *out; returns true if present.+bool esn_getbool(JSContext* ctx, JSValueConst obj, const char* key, int* out);+// Read obj[key] as an array of n numbers into dst[0..n-1] (no-op if absent).+void esn_getvec(JSContext* ctx, JSValueConst obj, const char* key, float* dst, int n);+// Wrap [ptr, ptr+size) as a zero-copy JS ArrayBuffer (native owns the memory).+JSValue esn_arraybuffer(JSContext* ctx, void* ptr, size_t size);++// --- provided by the generated file (NativeBindings.generated.cpp) -----------+void esn_register(JSContext* ctx, JSValue global);diff --git a/native/js/main.cpp b/native/js/main.cppnew file mode 100644index 000000000..7f9320d66--- /dev/null+++ b/native/js/main.cpp@@ -0,0 +1,368 @@+// Estella native JS host — a QuickJS game script drives the native C++ engine.+//+// This is the arm64 sibling of the web runtime, and the architecture is+// single-sourced end to end:+//+// * es_set_<Component> / es_<Component>_buffer live in the generated+// NativeBindings.generated.cpp, emitted by EHT (tools/eht) from the SAME+// reflection that emits the web embind bindings — the two surfaces can't drift.+// * ptraccessors_js.h is the REAL SDK sdk/src/ecs/ptrAccessors.generated.ts,+// transpiled to plain JS. POD components are wasm32/arm64 layout-identical, so+// the SDK's marshalling code writes native component memory unchanged, through+// a zero-copy ArrayBuffer over the native component (the es_<C>_buffer path).+// * The engine C++ core is the same source the web build compiles to wasm; only+// the game script is interpreted (QuickJS), the engine runs native/full speed.+//+// QuickJS interprets init()/update(dt); native C++ renders via EstellaContext ->+// ECS Registry -> TransformSystem -> RenderFrame -> WebGPUDevice -> Dawn -> Vulkan.+// Device gets its surface from configureSurface(NativeSurface{AndroidWindow}).+//+// NOTE: kGameScript below is a self-contained reference script. The product path+// loads the real SDK bundle + the shipped game script through a NativeBridge+// (fs/asset plumbing); that arrives with the native SDK runtime.++#include <android_native_app_glue.h>+#include <android/log.h>+#include <android/native_window.h>++#include "esn_shim.hpp" // quickjs + the esn_* plumbing decls+#include "ptraccessors_js.h" // the real SDK ptrAccessors.generated.ts, as JS++#include "esengine/core/EstellaContext.hpp"+#include "esengine/core/World.hpp"+#include "esengine/ecs/TransformSystem.hpp"+#include "esengine/ecs/components/Sprite.hpp" // js_useWhiteTexture touches Sprite directly+#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>++#include <cstring>+#include <vector>++#define LOG_TAG "EstellaJS"+#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;++// Reference game script — composes the generated component setters the way the+// TS SDK does, and exercises the SDK fast path (ptrAccessors over a zero-copy+// ArrayBuffer). Replaced by the shipped bundle once the native SDK runtime lands.+static const char* kGameScript = R"JS(+function texSprite(x, y, size, tex) {+ var e = es_createEntity();+ es_set_Transform(e, { position: [x, y, 0] });+ es_set_Sprite(e, { texture: tex, color: [1, 1, 1, 1], size: [size, size], enabled: true });+ return e;+}+function litSprite(x, y, size) {+ var e = es_createEntity();+ es_set_Transform(e, { position: [x, y, 0] });+ es_set_Sprite(e, { color: [1, 1, 1, 1], size: [size, size], lit: true, enabled: true });+ es_useWhiteTexture(e);+ return e;+}+function circle(x, y, size, r, g, b) {+ var e = es_createEntity();+ es_set_Transform(e, { position: [x, y, 0] });+ es_set_ShapeRenderer(e, { shapeType: 0, color: [r, g, b, 1], size: [size, size], enabled: true });+ return e;+}+// The BuiltinBridge dispatch pattern with a NATIVE memory backend: on web the+// bridge writes via mod.HEAPF32 + a wasm ptr; here the backend hands it zero-copy+// views over the native component (the generated es_<Component>_buffer binding)+// and ptr 0. The dispatch (PTR_ACCESSORS[cppName].fill/write) is the REAL SDK+// table — generic for any component, no per-type code.+function nativeViews(cppName, e) {+ var buf = globalThis['es_' + cppName + '_buffer'](e);+ return { f32: new Float32Array(buf), u32: new Uint32Array(buf), u8: new Uint8Array(buf) };+}+function readComponent(cppName, e) { // ~ BuiltinBridge.resolvePtrGetter+ var acc = PTR_ACCESSORS[cppName];+ var v = nativeViews(cppName, e);+ var d = acc.create();+ acc.fill(v.f32, v.u32, v.u8, 0, d);+ return d;+}+function setComponent(cppName, e, data) { // ~ BuiltinBridge.resolvePtrSetter+ var acc = PTR_ACCESSORS[cppName];+ var v = nativeViews(cppName, e);+ acc.write(v.f32, v.u32, v.u8, 0, data);+}+function bufferSprite(x, y, size, tex, r, g, b) {+ var e = es_createEntity();+ es_set_Transform(e, { position: [x, y, 0] });+ var d = readComponent('Sprite', e); // real dispatch: fill from native+ d.texture = tex;+ d.color = { r: r, g: g, b: b, a: 1 };+ d.size = { x: size, y: size };+ setComponent('Sprite', e, d); // real dispatch: write to native+ return e;+}+var moving, orbit;+function init() {+ es_setClear(0.07, 0.08, 0.12);+ var tex = es_createTexture(2, 2, [+ 255, 0, 0, 255, 0, 255, 0, 255,+ 0, 0, 255, 255, 255, 255, 0, 255 ]);+ moving = texSprite(W * 0.5, H * 0.62, S * 0.42, tex);+ orbit = circle(W * 0.5, H * 0.42, S * 0.26, 1.0, 0.2, 0.9);+ var l = es_createEntity();+ es_set_Transform(l, { position: [W * 0.32, H * 0.30, 0] });+ es_set_Light2D(l, { type: 0, color: [1.0, 0.55, 0.15, 1], intensity: 1.6, radius: S * 0.7, enabled: true });+ var la = es_createEntity();+ es_set_Light2D(la, { type: 2, color: [1, 1, 1, 1], intensity: 0.25, enabled: true });+ litSprite(W * 0.32, H * 0.30, S * 0.26);+ bufferSprite(W * 0.68, H * 0.30, S * 0.26, tex, 0.2, 1.0, 0.5);+}+var t = 0.0;+function update(dt) {+ t += dt;+ es_set_Transform(moving, { position: [W * 0.5 + Math.sin(t * 1.6) * S * 0.55, H * 0.62, 0] });+ es_set_Transform(orbit, { position: [W * 0.5 + Math.cos(t * 1.2) * S * 0.30, H * 0.42 + Math.sin(t * 1.2) * S * 0.14, 0] });+}+)JS";++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;+ JSRuntime* rt = nullptr;+ JSContext* js = nullptr;+ std::vector<Entity> entities; // script entity id -> Entity+ resource::TextureHandle whiteTex{};+ glm::vec4 clear{0.07f, 0.08f, 0.12f, 1.0f};+ f32 w = 0, h = 0;+ bool ready = false;+ uint64_t frame = 0;+};++App* g_app = nullptr;++} // namespace++// ---- shim the generated bindings call (declared in esn_shim.hpp) ------------++ecs::Registry& esn_reg() { return *g_app->registry; }++Entity esn_entity(JSContext* ctx, JSValueConst v) {+ int32_t id = 0;+ JS_ToInt32(ctx, &id, v);+ return (id >= 0 && id < (int)g_app->entities.size()) ? g_app->entities[id] : Entity{};+}++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);+}+JSValue esn_arraybuffer(JSContext* ctx, void* ptr, size_t size) {+ // Native owns the memory (the ECS component) — no free callback, not shared.+ return JS_NewArrayBuffer(ctx, reinterpret_cast<uint8_t*>(ptr), size, nullptr, nullptr, false);+}++namespace {++// Hand-written bindings for the bits reflection can't spell: entity creation,+// clear colour, and binding a shared texture (a resource handle). These are the+// native analog of the web ResourceManagerBindings — resources aren't reflected.+JSValue js_createEntity(JSContext* ctx, JSValueConst, int, JSValueConst*) {+ g_app->entities.push_back(g_app->registry->create());+ return JS_NewInt32(ctx, (int)g_app->entities.size() - 1);+}+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;+}+JSValue js_useWhiteTexture(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {+ Entity e = esn_entity(ctx, argv[0]);+ if (auto* s = g_app->registry->tryGet<ecs::Sprite>(e)) s->texture = g_app->whiteTex;+ return JS_UNDEFINED;+}+JSValue js_createTexture(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {+ int32_t w = 0, h = 0;+ JS_ToInt32(ctx, &w, argv[0]);+ JS_ToInt32(ctx, &h, argv[1]);+ uint32_t len = 0;+ JSValue lv = JS_GetPropertyStr(ctx, argv[2], "length");+ JS_ToUint32(ctx, &len, lv);+ JS_FreeValue(ctx, lv);+ std::vector<u8> pixels(len);+ for (uint32_t i = 0; i < len; ++i) {+ JSValue el = JS_GetPropertyUint32(ctx, argv[2], i);+ int32_t v = 0;+ JS_ToInt32(ctx, &v, el);+ pixels[i] = (u8)v;+ JS_FreeValue(ctx, el);+ }+ auto handle = g_app->ctx->require<resource::ResourceManager>().createTexture(+ (u32)w, (u32)h, ConstSpan<u8>(pixels.data(), pixels.size()), TextureFormat::RGBA8, false);+ return JS_NewInt64(ctx, (int64_t)handle.id());+}++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);+ JS_FreeValue(ctx, e);+}+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);+}++void initJS(App& a) {+ 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));+ JS_SetPropertyStr(a.js, global, "es_createEntity", JS_NewCFunction(a.js, js_createEntity, "es_createEntity", 0));+ JS_SetPropertyStr(a.js, global, "es_setClear", JS_NewCFunction(a.js, js_setClear, "es_setClear", 3));+ JS_SetPropertyStr(a.js, global, "es_useWhiteTexture", JS_NewCFunction(a.js, js_useWhiteTexture, "es_useWhiteTexture", 1));+ JS_SetPropertyStr(a.js, global, "es_createTexture", JS_NewCFunction(a.js, js_createTexture, "es_createTexture", 3));+ esn_register(a.js, global); // the EHT-generated es_set_<Component> / es_<C>_buffer+ JS_FreeValue(a.js, global);++ // Load the REAL SDK ptrAccessors (writeSprite/fillSprite/createSpriteData, …)+ // as globals, so the game script drives native components through actual SDK code.+ JSValue pr = JS_Eval(a.js, kPtrAccessorsJS, strlen(kPtrAccessorsJS), "ptrAccessors.js", JS_EVAL_TYPE_GLOBAL);+ if (JS_IsException(pr)) logJsError(a.js, "ptrAccessors eval");+ JS_FreeValue(a.js, pr);++ JSValue r = JS_Eval(a.js, kGameScript, strlen(kGameScript), "game.js", JS_EVAL_TYPE_GLOBAL);+ if (JS_IsException(r)) logJsError(a.js, "eval");+ JS_FreeValue(a.js, r);+ callJs(a, "init", 0, nullptr);+ LOGI("game script init() ran via generated bindings — %zu entities", g_app->entities.size());+}++void renderScene(App& a) {+ if (!a.ready) return;+ auto& ctx = *a.ctx;+ JSValue dt = JS_NewFloat64(a.js, 1.0 / 60.0);+ callJs(a, "update", 1, &dt);+ JS_FreeValue(a.js, dt);++ 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("JS-driven 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.backendType = WGPUBackendType_Vulkan;+ 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; }+ auto onD = [](WGPURequestDeviceStatus s, WGPUDevice d, WGPUStringView, void* u, void*) {+ if (s == WGPURequestDeviceStatus_Success) *static_cast<WGPUDevice*>(u) = d; };+ WGPUDeviceDescriptor dd = {};+ 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; }++ 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;+ const u8 white[4] = {255, 255, 255, 255};+ a.whiteTex = context.require<resource::ResourceManager>().createTexture(+ 1, 1, ConstSpan<u8>(white, sizeof(white)), TextureFormat::RGBA8);+ initJS(a);+ a.ready = true;+ LOGI("JS host up (%dx%d) — QuickJS game script driving native Dawn", (int)a.w, (int)a.h);+}++void onAppCmd(android_app* app, int32_t cmd) {+ App* a = static_cast<App*>(app->userData);+ if (cmd == APP_CMD_INIT_WINDOW && app->window && !a->ready) initEngine(*a, app->window);+}++} // namespace++void android_main(android_app* app) {+ App a;+ g_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/tools/eht/__main__.py b/tools/eht/__main__.pyindex 2762ebb56..61d362201 100644--- a/tools/eht/__main__.py+++ b/tools/eht/__main__.py@@ -12,6 +12,20 @@ from .generators import ()+def _emit_native(components, enums, args) -> None:+ """Emit the opt-in native (QuickJS) bindings from the parsed reflection —+ the native sibling of WebBindings.generated.cpp, one reflection source."""+ only = None+ if args.native_components:+ only = {n.strip() for n in args.native_components.split(',') if n.strip()}+ args.native_output.parent.mkdir(parents=True, exist_ok=True)+ print(f"Generating: {args.native_output}")+ native_gen = NativeBindingsGenerator(+ components, enums, shim_header=args.native_shim, only=only,+ )+ args.native_output.write_text(native_gen.generate(), encoding='utf-8')++def main() -> int:parser = argparse.ArgumentParser(description='EHT - ESEngine Header Tool')parser.add_argument('--input', '-i', type=Path, nargs='+',@@ -32,6 +46,12 @@ def main() -> int:help='Comma-separated component names to emit (default: all)')parser.add_argument('--native-shim', type=str, default='esn_shim.hpp',help='Shim header the generated native TU includes')+ # With --native-output, emit ONLY the native bindings and skip the embind /+ # editor / TS generation. A native build just needs NativeBindings.generated.cpp;+ # this keeps that invocation single-purpose and from touching the committed+ # web/editor/TS *.generated.* files at all (no throwaway output dirs needed).+ parser.add_argument('--native-only', action='store_true',+ help='With --native-output: emit only the native bindings')args = parser.parse_args()print("EHT - ESEngine Header Tool")@@ -68,6 +88,17 @@ def main() -> int:print("Warning: No components found!")return 1+ # ── Native-only fast path ──+ # A native build needs just NativeBindings.generated.cpp, from the same+ # reflection — so skip all embind/editor/TS work and touch no committed files.+ if args.native_only:+ if args.native_output is None:+ print("[FAIL] --native-only requires --native-output.")+ return 1+ _emit_native(cpp_parser.components, cpp_parser.enums, args)+ print("[OK] Done (native bindings only)!")+ return 0+# ── Boundary ABI: single source of truth ──# Compute pointer layouts and the ABI hash first; both the C++ bindings and# the TS metadata embed the same hash so connect() can verify they match.@@ -96,16 +127,7 @@ def main() -> int:# ── Native QuickJS Bindings (opt-in) ──if args.native_output is not None:- only = None- if args.native_components:- only = {n.strip() for n in args.native_components.split(',') if n.strip()}- args.native_output.parent.mkdir(parents=True, exist_ok=True)- print(f"Generating: {args.native_output}")- native_gen = NativeBindingsGenerator(- cpp_parser.components, cpp_parser.enums,- shim_header=args.native_shim, only=only,- )- args.native_output.write_text(native_gen.generate(), encoding='utf-8')+ _emit_native(cpp_parser.components, cpp_parser.enums, args)# Resolve the TS source directory robustly. Callers historically pass either# the package root (`sdk`) or the source dir (`sdk/src`); detect which by