Skip to content

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.

refactor(native): one JS host with a platform seam, not one per OS

esenginef0ec870d0530
diff --git a/native/CMakeLists.txt b/native/CMakeLists.txt
index c50dcfe32..a1a4780b8 100644
--- a/native/CMakeLists.txt
+++ b/native/CMakeLists.txt
@@ -88,9 +88,11 @@ if(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).
+ # js/host_core.cpp is the platform-independent host; each platform adds its own
+ # glue TU (the event loop, the window, the packaged assets).
+ add_library(estella_js_host SHARED js/host_core.cpp js/main_android.cpp "${NATIVE_BINDINGS}")
+ # 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.
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)
diff --git a/native/js/main.cpp b/native/js/host_core.cpp
similarity index 77%
rename from native/js/main.cpp
rename to native/js/host_core.cpp
index 30f31ee4f..a5d117a9e 100644
--- a/native/js/main.cpp
+++ b/native/js/host_core.cpp
@@ -1,28 +1,28 @@
-// Estella native JS host — a thin C++ shell that runs the REAL SDK. Three layers,
-// only this one is C++:
-// 1. This host (native/js/main.cpp): boots Dawn, installs the es_* native
-// bindings as globals, feeds Android touch to JS, reads the APK, and renders.
-// 2. The SDK bundle (dist/index.native.bundled.js, embedded): the actual esengine
-// TS SDK — createNativeApp / World / Input — installed as `ESEngine`. Not here.
-// 3. The game (assets/game.js, an APK asset loaded at runtime): developer content.
-// It calls ESEngine.createNativeApp(__esNativeBridge) and authors the scene.
-// NOT compiled into the host — it ships as an asset, like a real game.
-//
-// 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 are the native Entity's raw u32 (round-tripped via
-// Entity::fromRaw), so hierarchy queries return ids the SDK recognises.
-
-#include <android_native_app_glue.h>
-#include <android/log.h>
-#include <android/input.h>
-#include <android/asset_manager.h>
-#include <android/native_window.h>
+// 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
@@ -33,7 +33,6 @@
#include "esengine/ecs/components/Hierarchy.hpp" // Parent / Children
#include "esengine/renderer/RenderContext.hpp"
#include "esengine/renderer/RenderFrame.hpp"
-#include "esengine/renderer/webgpu/WebGPUDevice.hpp"
#include "esengine/resource/ResourceManager.hpp"
#include "esengine/resource/ShaderParser.hpp" // linearColorSpace() — texture format at the JS boundary
@@ -44,6 +43,7 @@
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
+#include <cstdarg>
#include <cstdint>
#include <cstdio>
#include <cstring>
@@ -51,15 +51,11 @@
#include <string>
#include <vector>
-#define LOG_TAG "EstellaSDK"
-#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;
// Host platform bootstrap — HOST code, not game. It fans host touch out to the SDK
// listener and builds the NativeBridge from the host's es_* capabilities. The game
-// (game.js, loaded from the APK's assets/) then calls createNativeApp(__esNativeBridge).
+// (game.js, a packaged asset) then calls createNativeApp(__esNativeBridge).
static const char* kBootstrapJS = R"JS(
globalThis.es_onNativeTouch = function (type, id, x, y) {
var l = globalThis.__esInputListener;
@@ -93,6 +89,7 @@ globalThis.__esNativeBridge = {
namespace {
struct App {
+ eshost::Platform* platform = nullptr;
WGPUInstance instance = nullptr;
WGPUAdapter adapter = nullptr;
WGPUDevice device = nullptr;
@@ -101,7 +98,6 @@ struct App {
ecs::Registry* registry = nullptr;
JSRuntime* rt = nullptr;
JSContext* js = nullptr;
- AAssetManager* assets = nullptr; // APK assets/ — the game + its content
std::string cacheDir; // app private dir — SDK bytecode cache
glm::vec4 clear{0.07f, 0.08f, 0.12f, 1.0f};
f32 w = 0, h = 0;
@@ -112,8 +108,20 @@ struct App {
App* g_app = nullptr;
+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; }
@@ -284,20 +292,8 @@ JSValue js_getTextureDimensions(JSContext* ctx, JSValueConst, int, JSValueConst*
return obj;
}
-// Read an APK asset (assets/<path>) fully into a buffer; empty if missing. This is
-// the native NativeBridge.readFile capability — a packaged (project-relative) file.
std::vector<u8> readAsset(App& a, const char* path) {
- std::vector<u8> out;
- if (!a.assets) return out;
- AAsset* asset = AAssetManager_open(a.assets, path, AASSET_MODE_BUFFER);
- if (!asset) return out;
- off_t len = AAsset_getLength(asset);
- if (len > 0) {
- out.resize((size_t)len);
- AAsset_read(asset, out.data(), (size_t)len);
- }
- AAsset_close(asset);
- return out;
+ return a.platform ? a.platform->readAsset(path) : std::vector<u8>{};
}
// es_readAsset(path) -> ArrayBuffer | null. Backs the bridge's readFile.
@@ -311,7 +307,7 @@ JSValue js_readAsset(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {
}
// es_loadImagePixels(path) -> { width, height, pixels: ArrayBuffer(RGBA) } | null.
-// Decodes an APK image asset to top-first RGBA via stb_image — the native
+// 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]);
@@ -362,25 +358,6 @@ void pumpJobs(App& a) {
while (JS_ExecutePendingJob(a.rt, &c) > 0) { /* ran a job */ }
}
-// Push one Android touch to the game's es_onNativeTouch(type,id,x,y), which fans it
-// out to the NativeBridge's registered listener. type: 0 start / 1 move / 2 end / 3 cancel.
-void dispatchTouch(App& a, int type, int id, float x, float y) {
- 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);
-}
-
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));
}
@@ -482,8 +459,8 @@ void initJS(App& a) {
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 (an APK
- // asset, developer content) authors on top.
+ // 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);
@@ -492,7 +469,7 @@ void initJS(App& a) {
const double tBundle = nowMs();
evalJs(a, kBootstrapJS, "bootstrap.js");
std::vector<u8> game = readAsset(a, "game.js");
- if (game.empty()) { LOGE("game.js asset missing from the APK"); return; }
+ if (game.empty()) { LOGE("game.js asset missing from the app package"); return; }
std::string src(reinterpret_cast<const char*>(game.data()), game.size());
evalJs(a, src.c_str(), "game.js");
const double tGame = nowMs();
@@ -501,39 +478,20 @@ void initJS(App& 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("game.js (APK asset) init() ran on the real SDK App");
+ LOGI("game.js (packaged asset) init() ran on the real SDK App");
}
-void renderScene(App& a) {
- if (!a.ready || !a.surfaceReady) 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);
- pumpJobs(a); // run the App tick's async systems
+} // namespace
- 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);
-}
+namespace eshost {
-// Bind (or re-bind) the render surface to a window. Called on first boot and again
-// on APP_CMD_INIT_WINDOW after a screen-off/on, which destroys + recreates the
-// window (configureSurface is re-entrant: it drops the old surface first).
-bool configureForWindow(App& a, ANativeWindow* window) {
- a.w = (f32)ANativeWindow_getWidth(window);
- a.h = (f32)ANativeWindow_getHeight(window);
- if (!a.gfx->configureSurface(
- WebGPUDevice::NativeSurface{WebGPUDevice::NativeWindowKind::AndroidWindow, window},
- (u32)a.w, (u32)a.h)) {
+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;
}
@@ -541,7 +499,21 @@ bool configureForWindow(App& a, ANativeWindow* window) {
return true;
}
-void initEngine(App& a, ANativeWindow* window) {
+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 = {};
@@ -549,14 +521,14 @@ void initEngine(App& a, ANativeWindow* window) {
idesc.requiredFeatures = feats;
a.instance = wgpuCreateInstance(&idesc);
WGPURequestAdapterOptions opts = {};
- opts.backendType = WGPUBackendType_Vulkan;
+ 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; }
+ 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; };
WGPUDeviceDescriptor dd = {};
@@ -564,86 +536,66 @@ void initEngine(App& a, ANativeWindow* window) {
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; }
+ if (!a.device) { LOGE("no device"); return false; }
- a.w = (f32)ANativeWindow_getWidth(window);
- a.h = (f32)ANativeWindow_getHeight(window);
auto device = makeUnique<WebGPUDevice>(a.device, a.instance);
a.gfx = device.get();
- if (!configureForWindow(a, window)) return;
+ if (!bindSurface()) return false;
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; }
+ if (!context.init(std::move(device))) { LOGE("context.init failed"); return false; }
static ecs::Registry registry;
a.registry = &registry;
LOGI("boot ms — Dawn instance/adapter/device + EstellaContext: %.0f", nowMs() - te0);
initJS(a);
a.ready = true;
LOGI("real SDK up (%dx%d) — esengine World over native Dawn", (int)a.w, (int)a.h);
+ return true;
}
-int32_t onInput(android_app* app, AInputEvent* ev) {
- App* a = static_cast<App*>(app->userData);
- if (!a->ready || AInputEvent_getType(ev) != AINPUT_EVENT_TYPE_MOTION) return 0;
- const int32_t action = AMotionEvent_getAction(ev) & AMOTION_EVENT_ACTION_MASK;
- const float x = AMotionEvent_getX(ev, 0);
- const float y = AMotionEvent_getY(ev, 0);
- int type;
- switch (action) {
- case AMOTION_EVENT_ACTION_DOWN:
- case AMOTION_EVENT_ACTION_POINTER_DOWN: type = 0; break;
- case AMOTION_EVENT_ACTION_MOVE: type = 1; break;
- case AMOTION_EVENT_ACTION_UP:
- case AMOTION_EVENT_ACTION_POINTER_UP: type = 2; break;
- default: type = 3; break;
- }
- dispatchTouch(*a, type, 0, x, y);
- return 1;
-}
-
-void onAppCmd(android_app* app, int32_t cmd) {
- App* a = static_cast<App*>(app->userData);
- switch (cmd) {
- case APP_CMD_INIT_WINDOW:
- // First time: boot the engine. Afterwards (screen-on): just rebind the
- // new window surface — the engine + JS World stay alive.
- if (app->window) {
- if (!a->ready) initEngine(*a, app->window);
- else configureForWindow(*a, app->window);
- }
- break;
- case APP_CMD_TERM_WINDOW:
- // Screen-off / backgrounded: the window is gone, stop presenting to it.
- a->surfaceReady = false;
- break;
- default:
- break;
- }
-}
+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);
+ pumpJobs(a); // run the App tick's async systems
-} // namespace
+ 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);
+}
-void android_main(android_app* app) {
- App a;
- g_app = &a;
- a.assets = app->activity->assetManager; // APK assets/ (game.js + content)
- if (app->activity->internalDataPath) a.cacheDir = app->activity->internalDataPath;
- app->userData = &a;
- app->onAppCmd = onAppCmd;
- app->onInputEvent = onInput;
- while (true) {
- int events;
- android_poll_source* source;
- // Poll (0) while we can render; block (-1) when there's no surface (screen
- // off) so we wait for the next window event instead of spinning.
- int timeoutMs = (a.ready && a.surfaceReady) ? 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);
+// 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);
}
+
+} // namespace eshost
diff --git a/native/js/host_core.hpp b/native/js/host_core.hpp
new file mode 100644
index 000000000..2f0561c34
--- /dev/null
+++ b/native/js/host_core.hpp
@@ -0,0 +1,87 @@
+// 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.
+ * @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).
+ *
+ * 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.
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the Apache License, Version 2.0.
+ */
+#pragma once
+
+#include <string>
+#include <vector>
+
+#include "esengine/core/Types.hpp"
+#include "esengine/renderer/webgpu/WebGPUDevice.hpp"
+
+namespace eshost {
+
+/**
+ * @brief The platform seam: what the host needs that Android and iOS answer
+ * differently. The glue implements it; host_core owns everything else.
+ */
+struct Platform {
+ virtual ~Platform() = default;
+
+ /** A packaged, project-relative file — the APK's `assets/` on Android, the
+ * app bundle on iOS. Empty when missing. Backs NativeBridge.readFile. */
+ virtual std::vector<esengine::u8> readAsset(const char* path) = 0;
+
+ /** Writable private directory for the SDK bytecode cache; empty disables it. */
+ virtual std::string cacheDir() = 0;
+
+ /** The backend Dawn must pick: Vulkan on Android, Metal on iOS. */
+ virtual WGPUBackendType backend() const = 0;
+
+ /** The live window (`ANativeWindow*` / `CAMetalLayer*`) and its pixel size. */
+ virtual esengine::WebGPUDevice::NativeSurface surface() = 0;
+ virtual void surfaceSize(esengine::u32& width, esengine::u32& height) = 0;
+
+ virtual void log(bool error, const char* message) = 0;
+};
+
+/** @brief Boots Dawn, EstellaContext, QuickJS, the SDK bundle and game.js. 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);
+
+/** @brief (Re)binds the swapchain to Platform::surface(). Needed on first boot and
+ * again whenever the window is recreated — an Android screen-off/on
+ * destroys it, an iOS layer resize invalidates its size. */
+bool bindSurface();
+
+/** @brief The window is gone (backgrounded / screen off); stop presenting until
+ * the next bindSurface(). The engine and the JS World stay alive. */
+void surfaceLost();
+
+/** @brief Runs the game's update + one rendered, presented frame. No-op until
+ * boot() has succeeded and a surface is bound. */
+void frame();
+
+/** @brief Feeds one touch to the game. @p type: 0 start / 1 move / 2 end / 3 cancel.
+ * Coordinates are in surface pixels, top-left origin (as on the web). */
+void touch(int type, int id, float x, float y);
+
+bool booted();
+
+/** Whether a surface is currently bound — false while the window is gone, which is
+ * when an event loop should block for events instead of spinning on frames. */
+bool surfaceBound();
+
+} // namespace eshost
diff --git a/native/js/main_android.cpp b/native/js/main_android.cpp
new file mode 100644
index 000000000..ad75e5099
--- /dev/null
+++ b/native/js/main_android.cpp
@@ -0,0 +1,131 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file main_android.cpp
+ * @brief The Android glue for the JS host: NativeActivity, the APK's assets,
+ * Vulkan-backed Dawn, touch, and the ALooper frame loop.
+ * @details Everything else — Dawn bring-up, the es_* bindings, the SDK bundle and
+ * the frame — is in host_core.cpp, shared with the iOS glue.
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the Apache License, Version 2.0.
+ */
+#include <android_native_app_glue.h>
+#include <android/log.h>
+#include <android/input.h>
+#include <android/asset_manager.h>
+#include <android/native_window.h>
+
+#include "host_core.hpp"
+
+#define LOG_TAG "EstellaSDK"
+
+using esengine::u32;
+using esengine::u8;
+using esengine::WebGPUDevice;
+
+namespace {
+
+struct AndroidPlatform final : eshost::Platform {
+ AAssetManager* assets = nullptr; // APK assets/ — the game + its content
+ ANativeWindow* window = nullptr;
+ std::string cache; // app private dir — SDK bytecode cache
+
+ // Read an APK asset (assets/<path>) fully into a buffer; empty if missing.
+ std::vector<u8> readAsset(const char* path) override {
+ std::vector<u8> out;
+ if (!assets) return out;
+ AAsset* asset = AAssetManager_open(assets, path, AASSET_MODE_BUFFER);
+ if (!asset) return out;
+ off_t len = AAsset_getLength(asset);
+ if (len > 0) {
+ out.resize((size_t)len);
+ AAsset_read(asset, out.data(), (size_t)len);
+ }
+ AAsset_close(asset);
+ return out;
+ }
+
+ std::string cacheDir() override { return cache; }
+
+ WGPUBackendType backend() const override { return WGPUBackendType_Vulkan; }
+
+ WebGPUDevice::NativeSurface surface() override {
+ return {WebGPUDevice::NativeWindowKind::AndroidWindow, window};
+ }
+
+ void surfaceSize(u32& width, u32& height) override {
+ width = window ? (u32)ANativeWindow_getWidth(window) : 0;
+ height = window ? (u32)ANativeWindow_getHeight(window) : 0;
+ }
+
+ void log(bool error, const char* message) override {
+ __android_log_print(error ? ANDROID_LOG_ERROR : ANDROID_LOG_INFO, LOG_TAG, "%s", message);
+ }
+};
+
+AndroidPlatform g_platform;
+
+int32_t onInput(android_app*, AInputEvent* ev) {
+ if (!eshost::booted() || AInputEvent_getType(ev) != AINPUT_EVENT_TYPE_MOTION) return 0;
+ const int32_t action = AMotionEvent_getAction(ev) & AMOTION_EVENT_ACTION_MASK;
+ const float x = AMotionEvent_getX(ev, 0);
+ const float y = AMotionEvent_getY(ev, 0);
+ int type;
+ switch (action) {
+ case AMOTION_EVENT_ACTION_DOWN:
+ case AMOTION_EVENT_ACTION_POINTER_DOWN: type = 0; break;
+ case AMOTION_EVENT_ACTION_MOVE: type = 1; break;
+ case AMOTION_EVENT_ACTION_UP:
+ case AMOTION_EVENT_ACTION_POINTER_UP: type = 2; break;
+ default: type = 3; break;
+ }
+ eshost::touch(type, 0, x, y);
+ return 1;
+}
+
+void onAppCmd(android_app* app, int32_t cmd) {
+ switch (cmd) {
+ case APP_CMD_INIT_WINDOW:
+ // First time: boot the engine. Afterwards (screen-on): just rebind the
+ // new window surface — the engine + JS World stay alive.
+ if (app->window) {
+ g_platform.window = app->window;
+ if (!eshost::booted()) eshost::boot(g_platform);
+ else eshost::bindSurface();
+ }
+ break;
+ case APP_CMD_TERM_WINDOW:
+ // Screen-off / backgrounded: the window is gone, stop presenting to it.
+ eshost::surfaceLost();
+ g_platform.window = nullptr;
+ break;
+ default:
+ break;
+ }
+}
+
+} // namespace
+
+void android_main(android_app* app) {
+ g_platform.assets = app->activity->assetManager; // APK assets/ (game.js + content)
+ if (app->activity->internalDataPath) g_platform.cache = app->activity->internalDataPath;
+ app->onAppCmd = onAppCmd;
+ app->onInputEvent = onInput;
+ while (true) {
+ int events;
+ android_poll_source* source;
+ // Poll (0) while we can render; block (-1) when there's no surface (screen
+ // off) so we wait for the next window event instead of spinning.
+ int timeoutMs = (eshost::booted() && eshost::surfaceBound()) ? 0 : -1;
+ while (ALooper_pollOnce(timeoutMs, nullptr, &events, (void**)&source) >= 0) {
+ if (source) source->process(app, source);
+ if (app->destroyRequested) return;
+ timeoutMs = 0;
+ }
+ eshost::frame();
+ }
+}