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): a game calls its own Java or Objective-C by name - NativeChannel.call, has and on reach the handlers an app registers (NativeChannel.register on Android, EstellaNativeChannel on iOS) with JSON both ways, and Ads works on a device once that code answers ads.show; the engine links no ad SDK
yhh24769f81c591
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e3faefd42..bcba14b20 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,7 @@ published separately; it ships inside the editor.### Added+- **A game calls its own native code by name.** A packaged Android or iOS game can link an ad SDK, a store or a sign-in library, and had no way to reach it: the native host answered the engine's own calls and nothing else. `NativeChannel.call(method, args)` now runs a handler the app registered (`com.estella.host.NativeChannel.register` in Java, `EstellaNativeChannel` in Objective-C) and resolves with what it answered; `has` says whether a name is answered and `on` hears what the native side raises on its own. Values cross as JSON. `Ads` rides on it: once the app's code answers `ads.show`, `Ads.available` is true on a device and `showRewarded` works as it does in a mini-game. The engine links no ad SDK; which one is the project's choice. An exported Android Studio project keeps your Java under `app/src/game`, which a re-export leaves alone. Elsewhere `has` is false and nothing is called, so a game that asks first runs unchanged on the web.- **Text has letter spacing.** `Text.letterSpacing` is extra space after every glyph, in the same px as `fontSize`; a negative value draws the glyphs closer. The layout always took a spacing, and `measureText` did, but the component had no field for it and nothing handed one over, so a label could not be spaced. Wrapping, alignment, `Ellipsis` and `Shrink` measure with it, `Shrink` scales it with the type, and it is in the Details panel beside Line Height. The default, 0, is the text as it was.- **A cliff's beds can wander.** A terrain layer seen from the side is read by height, so the beds of a cliff texture lie level, and ran dead straight along a whole wall like lines on ruled paper. The Terrain Layers material's `u_strataWarp` is how far they wander up and down, by slow noise `u_strataSpan` wide. At 0, the default, they are straight as before.- **The tonemap has the fitted ACES curve too.** The `tonemap` effect ran one curve, the engine's (Narkowicz's fit). A picture made for the other ACES fit in wide use (Hill's RRT and ODT, what three.js calls ACES Filmic) came out with shadows about a third brighter at the same mid tones, and with the hue kept in bright colours that curve sends to white. **Fitted ACES** (`u_curve` 1) runs that fit; off, which is the default, nothing changes.diff --git a/build-tools/utils/gradleProject.js b/build-tools/utils/gradleProject.jsindex 2c16dd8fb..510b54a89 100644--- a/build-tools/utils/gradleProject.js+++ b/build-tools/utils/gradleProject.js@@ -133,6 +133,15 @@ android {}}+ // Your own Java or Kotlin, and its resources, live under src/game. Exporting+ // again rewrites src/main (the host's own classes among it) and never this.+ sourceSets {+ getByName("main") {+ java.srcDir("src/game/java")+ resources.srcDir("src/game/resources")+ }+ }+compileOptions {sourceCompatibility = JavaVersion.VERSION_17targetCompatibility = JavaVersion.VERSION_17@@ -183,6 +192,33 @@ Add the dependency in \`app/build.gradle.kts\` and whatever the SDK asks of themanifest. The game itself is native and starts from \`NativeActivity\`; a Java SDKthat needs an entry point can subclass it and name the subclass in the manifest.+## Calling your Java from the game++The game reaches your code by name through \`com.estella.host.NativeChannel\`.+Put your classes under \`app/src/game/java\` (a re-export leaves that folder+alone) and register what they answer from a plugin:++ package com.example.game;++ public final class GamePlugin implements com.estella.host.NativeChannel.Plugin {+ @Override public void register(android.app.Activity activity) {+ com.estella.host.NativeChannel.register("ads.show", (args, reply) -> {+ // show the ad with your SDK, then, when it has closed:+ reply.resolve("{\\"completed\\":true}");+ });+ }+ }++Name the plugin in \`app/src/game/resources/META-INF/services/com.estella.host.NativeChannel$Plugin\`+(one class name per line), which is how it is found before the first frame:++ com.example.game.GamePlugin++In the game, \`await NativeChannel.call('ads.show', { kind: 'rewarded', unitId })\`+runs the handler on the UI thread and resolves with what it answered. Answering+\`ads.show\` is also what makes the engine's own \`Ads\` service work on a device.+\`NativeChannel.emit(event, json)\` tells the game something it did not ask for.+## Re-exportingExporting again from Estella rewrites \`app/src/main/assets\`, the manifest, thediff --git a/build-tools/utils/iosProject.js b/build-tools/utils/iosProject.jsindex 4d808b513..3f4543053 100644--- a/build-tools/utils/iosProject.js+++ b/build-tools/utils/iosProject.js@@ -85,6 +85,10 @@ export async function emitIosXcodeProject(contentDir, app, sources, deploymentTaawait cp(sources.xcframework, frameworkDest, { recursive: true });await mkdir(appDir, { recursive: true });await cp(sources.mainM, path.join(appDir, 'main.m'));+ // What the app's own Objective-C or Swift includes to answer the game by name.+ if (sources.channelHeader && existsSync(sources.channelHeader)) {+ await cp(sources.channelHeader, path.join(appDir, 'EstellaNativeChannel.h'));+ }await writeIconCatalog(contentDir, icon ?? await readFile(sources.icon));diff --git a/build-tools/utils/nativeTemplate.js b/build-tools/utils/nativeTemplate.jsindex c50beb094..d361c479b 100644--- a/build-tools/utils/nativeTemplate.js+++ b/build-tools/utils/nativeTemplate.js@@ -190,6 +190,12 @@ export function templateLayout(platform, options = {}) {from: (ctx) => path.join(ctx.root, 'build/cmake/native-ios', 'Estella.xcframework'),},{ rel: 'App/main.m', from: (ctx) => path.join(ctx.root, 'native', 'ios', 'App', 'main.m') },+ // What an app target includes to answer the game from its own Objective-C+ // or Swift; the class is in the xcframework.+ {+ rel: 'App/EstellaNativeChannel.h',+ from: (ctx) => path.join(ctx.root, 'native', 'ios', 'App', 'EstellaNativeChannel.h'),+ },{ rel: 'App/Info.plist.in', from: (ctx) => path.join(ctx.root, 'native', 'ios', 'App', 'Info.plist.in') },{ rel: DEFAULT_ICON, from: (ctx) => path.join(ctx.root, 'native', 'icon.png') },// The same first-launch fix the Android template carries: without it the@@ -683,6 +689,7 @@ export function iosTemplateSources(dir) {return {xcframework: path.join(dir, 'Estella.xcframework'),mainM: path.join(dir, 'App', 'main.m'),+ channelHeader: path.join(dir, 'App', 'EstellaNativeChannel.h'),infoPlistIn: path.join(dir, 'App', 'Info.plist.in'),icon: path.join(dir, DEFAULT_ICON),bytecode: path.join(dir, 'assets', BYTECODE_FILE),diff --git a/docs/astro/src/content/docs/publishing/ads-sharing.mdx b/docs/astro/src/content/docs/publishing/ads-sharing.mdxindex 18f4d6a9a..f15fa07e0 100644--- a/docs/astro/src/content/docs/publishing/ads-sharing.mdx+++ b/docs/astro/src/content/docs/publishing/ads-sharing.mdx@@ -65,9 +65,10 @@ installed provider. Use it to hide the "watch ad" button honestly:- **The editor's Play mode** — a **mock provider** is installed automatically:`showRewarded` "plays" for a moment and resolves `completed: true`, with thereal pause/audio ceremony running. Your revive flow rehearses at your desk.-- **Plain web and native builds** — no ad system, `available` is `false`. A native- shell that integrates a mediation SDK installs it through the same door the- editor uses: `Ads.setProvider(...)`.+- **Android and iOS builds** — the ad SDK is your own native code, and the engine+ links none. `available` is `true` once that code answers `ads.show`+ (see [Calling your own native code](/publishing/android-ios/#ads)).+- **Plain web and desktop builds** — no ad system, `available` is `false`.## Sharingdiff --git a/docs/astro/src/content/docs/publishing/android-ios.mdx b/docs/astro/src/content/docs/publishing/android-ios.mdxindex e6f4d976d..6dbd10800 100644--- a/docs/astro/src/content/docs/publishing/android-ios.mdx+++ b/docs/astro/src/content/docs/publishing/android-ios.mdx@@ -255,6 +255,123 @@ play. Install this editor version's template from Package Project to fix it.If a future build ever *does* drop a subsystem, the export names it — with thescenes that use it — instead of quietly shipping a package missing half a scene.+## Calling your own native code++A packaged game is an ordinary app, so it can link an ad SDK, a store, a sign-in+or an analytics library. Those are Java, Kotlin, Objective-C or Swift, and they are+yours: the engine links none of them. `NativeChannel` is how a script reaches them.+The native side answers a name, the script calls the name, and values cross as JSON.++```typescript title="src/shop.ts"+import { NativeChannel } from 'esengine';++if (NativeChannel.has('store.buy')) {+ const receipt = await NativeChannel.call<{ token: string }>('store.buy', { sku: 'gems_100' });+}+const off = NativeChannel.on<{ sku: string }>('store.restored', (p) => grant(p.sku));+```++| Call | What it does |+| --- | --- |+| `NativeChannel.available` | Whether this platform has native code to reach. `false` on the web, in a mini-game and in the editor. |+| `NativeChannel.has(method)` | Whether a call to `method` would be answered. Ask before offering the feature. |+| `NativeChannel.call(method, args?)` | Runs the handler and resolves with what it answered. Rejects when nothing answers to the name, or with the reason the handler gave. |+| `NativeChannel.on(event, handler)` | Hears what the native side raises on its own. Returns the unsubscribe. |++A game that asks `has` first runs unchanged everywhere: where there is no native+code, `has` is `false` and nothing is called.++Every native build answers `app.info` itself: `{ os, osVersion, device, id, version, build }`+on Android and iOS (the package id and its version, which a script cannot otherwise+read), and `{ device }` on desktop.++### Android++Export an **Android Studio project** (your code has to be compiled into the app, so+the one-click APK cannot carry it). Put your classes under `app/src/game/java`,+which a re-export leaves alone, and register what they answer from a plugin:++```java title="app/src/game/java/com/example/game/GamePlugin.java"+package com.example.game;++import android.app.Activity;+import com.estella.host.NativeChannel;++public final class GamePlugin implements NativeChannel.Plugin {+ @Override public void register(Activity activity) {+ NativeChannel.register("store.buy", (args, reply) -> {+ // args is JSON text. Call your SDK, then answer once, from any thread:+ reply.resolve("{\"token\":\"abc\"}"); // or reply.reject("cancelled")+ });+ }+}+```++Name the plugin in `app/src/game/resources/META-INF/services/com.estella.host.NativeChannel$Plugin`,+one class name per line. That file is how the plugin is found before the first frame+(Java's `ServiceLoader`), so a library can bring its own and nothing in the manifest+names it.++A handler runs on the UI thread, where an SDK that shows anything has to be called.+`NativeChannel.emit("store.restored", json)` raises an event from any thread, and+`NativeChannel.activity()` is the game's activity for an SDK that needs one.++A project exported before this version has no `src/game` source set in its+`app/build.gradle.kts`, which is yours and is not rewritten. Add it by hand:++```kotlin title="app/build.gradle.kts"+android {+ sourceSets {+ getByName("main") {+ java.srcDir("src/game/java")+ resources.srcDir("src/game/resources")+ }+ }+}+```++### iOS++The exported Xcode project carries `App/EstellaNativeChannel.h`. Add your own source+file to the app target (outside `App/`, which a re-export rewrites) and register from+`+load`, which runs before the game starts:++```objc title="GamePlugin.m"+#import "App/EstellaNativeChannel.h"++@interface GamePlugin : NSObject+@end++@implementation GamePlugin++ (void)load {+ [EstellaNativeChannel registerMethod:@"store.buy"+ handler:^(NSString* args, EstellaNativeReply reply) {+ // Call your SDK, then answer once, from any thread:+ reply(@"{\"token\":\"abc\"}", nil); // or reply(nil, @"cancelled")+ }];+}+@end+```++`[EstellaNativeChannel emitEvent:@"store.restored" json:json]` raises an event.+A handler runs on the main thread.++### Ads++The engine's [`Ads` service](/publishing/ads-sharing/#rewarded-ads) works on a device+as soon as your native code answers two names. Nothing else changes in the game:+`Ads.available` becomes `true`, and `showRewarded` pauses the game, silences it and+resumes it around the ad as it does in a mini-game.++| Method | Args | Answer |+| --- | --- | --- |+| `ads.show` | `{ kind: "rewarded" \| "interstitial", unitId }` | Answer when the ad has **closed**. For a rewarded ad, `{ "completed": true }` when the reward was earned; anything else grants nothing. Reject when there is no ad to show. |+| `ads.preload` | the same | Optional. Answer when the ad is loaded. |++Which ad SDK that is (AdMob, Pangle, a mediation layer) is the project's choice,+with its own size, privacy terms and account, which is why the engine does not pick+one.+## What only bites on a deviceThese are the differences worth knowing before your first device build. Each onediff --git a/docs/astro/src/content/docs/zh-cn/publishing/ads-sharing.mdx b/docs/astro/src/content/docs/zh-cn/publishing/ads-sharing.mdxindex b321b2839..600f32e1e 100644--- a/docs/astro/src/content/docs/zh-cn/publishing/ads-sharing.mdx+++ b/docs/astro/src/content/docs/zh-cn/publishing/ads-sharing.mdx@@ -58,8 +58,9 @@ const reviveSystem = defineSystem([Res(Ads), GetWorld()], (ads, world) => {- **带广告的渠道 Web 导出**——Poki、CrazyGames 和 YouTube Playables 会安装各自的 provider(见下文)。- **编辑器 Play 模式**——自动安装 **mock provider**:`showRewarded`"播放"片刻后resolve `completed: true`,真实的暂停/音频仪式照常运行。复活流程在工位上就能排练。-- **普通 Web 与原生构建**——没有广告系统,`available` 为 false。接入聚合 SDK 的原生壳- 走编辑器同一扇门:`Ads.setProvider(...)`。+- **Android 与 iOS 构建**——广告 SDK 是你自己的原生代码,引擎一个都不链接。那段代码应答+ `ads.show` 之后 `available` 为 true(见[调用你自己的原生代码](/zh-cn/publishing/android-ios/#广告))。+- **普通 Web 与桌面构建**——没有广告系统,`available` 为 false。## 分享diff --git a/docs/astro/src/content/docs/zh-cn/publishing/android-ios.mdx b/docs/astro/src/content/docs/zh-cn/publishing/android-ios.mdxindex c82ec5648..ba2377cc9 100644--- a/docs/astro/src/content/docs/zh-cn/publishing/android-ios.mdx+++ b/docs/astro/src/content/docs/zh-cn/publishing/android-ios.mdx@@ -206,6 +206,115 @@ Android 上每个版本是一个单独的库(每个 ABI 0.2 到 1 MB)。导出万一将来某个构建*真的*砍掉了某个子系统,导出会点名它——连同用到它的场景——而不是悄悄发出一个缺了半个场景的包。+## 调用你自己的原生代码++打包后的游戏就是一个普通应用,可以链接广告 SDK、商店、登录或统计库。这些是 Java、+Kotlin、Objective-C 或 Swift,属于项目自己,引擎一个都不链接。脚本通过 `NativeChannel`+够到它们:原生侧应答一个名字,脚本调用这个名字,值以 JSON 传递。++```typescript title="src/shop.ts"+import { NativeChannel } from 'esengine';++if (NativeChannel.has('store.buy')) {+ const receipt = await NativeChannel.call<{ token: string }>('store.buy', { sku: 'gems_100' });+}+const off = NativeChannel.on<{ sku: string }>('store.restored', (p) => grant(p.sku));+```++| 调用 | 作用 |+| --- | --- |+| `NativeChannel.available` | 这个平台有没有原生代码可调。Web、小游戏和编辑器里是 `false`。 |+| `NativeChannel.has(method)` | 调用 `method` 会不会有人应答。提供功能之前先问。 |+| `NativeChannel.call(method, args?)` | 运行处理器,以它的应答 resolve。没有人应答这个名字时 reject,处理器给了失败原因时带着原因 reject。 |+| `NativeChannel.on(event, handler)` | 监听原生侧主动发出的事件。返回取消订阅函数。 |++先问 `has` 的游戏在所有平台上不用改:没有原生代码的地方 `has` 是 `false`,什么也不会被调用。++每个原生构建自己应答 `app.info`:Android 和 iOS 上是+`{ os, osVersion, device, id, version, build }`(包名和版本号,脚本没有别的办法读到),+桌面上是 `{ device }`。++### Android++导出 **Android Studio 工程**(你的代码要编进应用,一键 APK 带不了)。把类放在+`app/src/game/java` 下,重新导出不会动这个目录,然后从一个插件里注册它们应答什么:++```java title="app/src/game/java/com/example/game/GamePlugin.java"+package com.example.game;++import android.app.Activity;+import com.estella.host.NativeChannel;++public final class GamePlugin implements NativeChannel.Plugin {+ @Override public void register(Activity activity) {+ NativeChannel.register("store.buy", (args, reply) -> {+ // args 是 JSON 文本。调用你的 SDK,然后应答一次,哪个线程都可以:+ reply.resolve("{\"token\":\"abc\"}"); // 或 reply.reject("cancelled")+ });+ }+}+```++在 `app/src/game/resources/META-INF/services/com.estella.host.NativeChannel$Plugin`+里写上插件的类名,一行一个。插件靠这个文件在第一帧之前被找到(Java 的 `ServiceLoader`),+所以一个库可以自带插件,清单里不用点名。++处理器在 UI 线程上运行,要显示界面的 SDK 必须在那里调用。+`NativeChannel.emit("store.restored", json)` 可以从任何线程发出事件,+`NativeChannel.activity()` 是游戏的 Activity,给需要它的 SDK 用。++这个版本之前导出的工程,`app/build.gradle.kts` 里没有 `src/game` 源码集;这个文件归你,+不会被重写,手动加上:++```kotlin title="app/build.gradle.kts"+android {+ sourceSets {+ getByName("main") {+ java.srcDir("src/game/java")+ resources.srcDir("src/game/resources")+ }+ }+}+```++### iOS++导出的 Xcode 工程里带着 `App/EstellaNativeChannel.h`。把你自己的源文件加进应用 target+(放在 `App/` 之外,重新导出会重写那个目录),在 `+load` 里注册,它在游戏启动之前运行:++```objc title="GamePlugin.m"+#import "App/EstellaNativeChannel.h"++@interface GamePlugin : NSObject+@end++@implementation GamePlugin++ (void)load {+ [EstellaNativeChannel registerMethod:@"store.buy"+ handler:^(NSString* args, EstellaNativeReply reply) {+ // 调用你的 SDK,然后应答一次,哪个线程都可以:+ reply(@"{\"token\":\"abc\"}", nil); // 或 reply(nil, @"cancelled")+ }];+}+@end+```++`[EstellaNativeChannel emitEvent:@"store.restored" json:json]` 发出事件。处理器在主线程上运行。++### 广告++只要你的原生代码应答两个名字,引擎自带的 [`Ads` 服务](/zh-cn/publishing/ads-sharing/#激励视频)+在真机上就能用,游戏里别的都不用改:`Ads.available` 变成 `true`,`showRewarded`+像在小游戏里一样,在广告前后暂停游戏、静音、再恢复。++| 方法 | 参数 | 应答 |+| --- | --- | --- |+| `ads.show` | `{ kind: "rewarded" \| "interstitial", unitId }` | 广告**关闭**时应答。激励广告在奖励确实获得时应答 `{ "completed": true }`,其他任何应答都不发奖励。没有广告可放时 reject。 |+| `ads.preload` | 同上 | 可选。广告加载好时应答。 |++用哪家广告 SDK(AdMob、穿山甲、聚合层)由项目决定,体积、隐私条款和账号都是项目自己的,+所以引擎不替你选。+## 只在真机上才咬人的那些事这些是你第一次做真机构建前值得知道的差异。每一条都至少发过一次坏包,diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.jsonindex 857cd1b18..dfb785223 100644--- a/docs/astro/src/data/apiStability.generated.json+++ b/docs/astro/src/data/apiStability.generated.json@@ -1,12 +1,12 @@{"note": "Generated by tools/api-stability.mjs from sdk/etc/*.api.md — do not edit.","counts": {- "public": 115,+ "public": 117,"beta": 178,- "experimental": 3065,+ "experimental": 3068,"deprecated": 3},- "total": 3358,+ "total": 3363,"subsystems": [{"id": "mobile-controls",@@ -1192,6 +1192,30 @@"minigame"]},+ {+ "name": "NativeChannel",+ "kind": "const",+ "deprecated": false,+ "entries": [+ "index",+ "index.node",+ "index.native",+ "wechat",+ "minigame"+ ]+ },+ {+ "name": "NativeChannelApi",+ "kind": "interface",+ "deprecated": false,+ "entries": [+ "index",+ "index.node",+ "index.native",+ "wechat",+ "minigame"+ ]+ },{"name": "Parent","kind": "const",diff --git a/native/CMakeLists.txt b/native/CMakeLists.txtindex f4d4e895a..8b24b8734 100644--- a/native/CMakeLists.txt+++ b/native/CMakeLists.txt@@ -519,6 +519,7 @@ if(ESTELLA_QUICKJS_DIR)host/bindings/DeviceBindings.cpphost/net/WsClient.cpphost/bindings/TextEditorBindings.cpp+ host/bindings/ChannelBindings.cpphost/bindings/AotBindings.cpp# The name table a compiled system is dispatched through — generated# from the same reflection the component bindings above come from.diff --git a/native/android/java/com/estella/host/NativeChannel.java b/native/android/java/com/estella/host/NativeChannel.javanew file mode 100644index 000000000..e8fe7dadd--- /dev/null+++ b/native/android/java/com/estella/host/NativeChannel.java@@ -0,0 +1,187 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+package com.estella.host;++import android.app.Activity;+import android.content.pm.PackageInfo;+import android.os.Build;+import android.util.Log;++import org.json.JSONObject;++import java.nio.charset.StandardCharsets;+import java.util.ServiceLoader;+import java.util.concurrent.ConcurrentHashMap;+import java.util.concurrent.atomic.AtomicBoolean;++/**+ * The game's line to this app's own Java: methods a script calls by name, and+ * events Java raises for the script.+ *+ * The engine is native and knows nothing of an ad SDK, a store or a sign-in+ * library; those are Java, and they are the project's. A project answers a name+ * here and its script calls that name:+ *+ * <pre>+ * NativeChannel.register("ads.show", (args, reply) -> { ... reply.resolve("{\"completed\":true}"); });+ * </pre>+ * <pre>+ * const result = await NativeChannel.call('ads.show', { kind: 'rewarded', unitId });+ * </pre>+ *+ * Arguments and results are JSON text, so neither side needs the other's types.+ * A handler runs on the UI thread, which is where an SDK that shows anything has+ * to be called, and may answer later from any thread, once.+ *+ * Registration happens before the game's first frame through {@link Plugin}: a+ * class named in {@code META-INF/services/com.estella.host.NativeChannel$Plugin}+ * is constructed and asked to register, the way any Java library finds its+ * providers. A library can therefore bring its handlers with it, and nothing in+ * the manifest names them.+ */+public final class NativeChannel {++ /** How a handler answers. One of the two, once; a second answer is dropped. */+ public interface Reply {+ /** The call's result, as JSON text ({@code null} for no value). */+ void resolve(String json);+ /** The call failed: the script's promise rejects with this reason. */+ void reject(String reason);+ }++ /** What answers a method. Runs on the UI thread. */+ public interface Handler {+ void handle(String argsJson, Reply reply);+ }++ /** A provider of handlers, found through {@link ServiceLoader}. */+ public interface Plugin {+ /** Register what this plugin answers. On the game thread, before the first frame. */+ void register(Activity activity);+ }++ private static final String TAG = "EstellaSDK";+ private static final ConcurrentHashMap<String, Handler> handlers = new ConcurrentHashMap<>();+ private static volatile Activity activity;+ /** Set once the natives below are registered: before that there is nobody to tell. */+ private static volatile boolean attached;++ private NativeChannel() {}++ /** Answer {@code method} from now on; a later registration replaces an earlier one. */+ public static void register(String method, Handler handler) {+ if (method == null || handler == null) throw new IllegalArgumentException("method and handler are required");+ handlers.put(method, handler);+ }++ /** Stop answering {@code method}. */+ public static void unregister(String method) {+ if (method != null) handlers.remove(method);+ }++ /**+ * Tell the script something it did not ask for: every listener of {@code event}+ * hears {@code json} on the game's next frame. From any thread. Before the game+ * has started there is nobody to hear it, and it is dropped.+ */+ public static void emit(String event, String json) {+ if (event == null || !attached) return;+ nativeEvent(event, utf8(json == null ? "null" : json));+ }++ /** The game's activity, for an SDK that needs one. Null before the game starts. */+ public static Activity activity() {+ return activity;+ }++ // -- Called by the host (platform/android.cpp), on the game thread ---------++ static void attach(Activity host) {+ activity = host;+ attached = true;+ if (!handlers.containsKey("app.info")) register("app.info", new AppInfo(host));+ try {+ for (Plugin plugin : ServiceLoader.load(Plugin.class, host.getClassLoader())) {+ try {+ plugin.register(host);+ } catch (Throwable error) {+ Log.e(TAG, "native plugin " + plugin.getClass().getName() + " failed to register", error);+ }+ }+ } catch (Throwable error) {+ // A provider file naming a class that is not there: the rest still run.+ Log.e(TAG, "native plugins could not be listed", error);+ }+ }++ static boolean has(String method) {+ return method != null && handlers.containsKey(method);+ }++ /** Start {@code method}; false when nothing answers to the name. */+ static boolean call(final int id, String method, byte[] argsUtf8) {+ final String args = new String(argsUtf8 == null ? new byte[0] : argsUtf8, StandardCharsets.UTF_8);+ final Handler handler = method == null ? null : handlers.get(method);+ final Activity host = activity;+ if (handler == null || host == null) return false;+ final Once reply = new Once(id);+ host.runOnUiThread(new Runnable() {+ @Override public void run() {+ try {+ handler.handle(args, reply);+ } catch (Throwable error) {+ reply.reject(error.toString());+ }+ }+ });+ return true;+ }++ // Text crosses as UTF-8 bytes: a JNI string is modified UTF-8, which is not+ // what the script reads, and an emoji in a payload would arrive as two halves.+ private static native void nativeReply(int id, boolean ok, byte[] payloadUtf8);+ private static native void nativeEvent(String name, byte[] payloadUtf8);++ private static byte[] utf8(String text) {+ return text.getBytes(StandardCharsets.UTF_8);+ }++ /** A reply that reaches the script once, however many times it is given. */+ private static final class Once implements Reply {+ private final int id;+ private final AtomicBoolean answered = new AtomicBoolean();++ Once(int id) { this.id = id; }++ @Override public void resolve(String json) {+ if (answered.compareAndSet(false, true)) nativeReply(id, true, utf8(json == null ? "null" : json));+ }++ @Override public void reject(String reason) {+ if (answered.compareAndSet(false, true)) nativeReply(id, false, utf8(reason == null ? "" : reason));+ }+ }++ /** What the app is, which a script cannot otherwise read: its id and version. */+ private static final class AppInfo implements Handler {+ private final Activity host;++ AppInfo(Activity host) { this.host = host; }++ @Override public void handle(String argsJson, Reply reply) {+ try {+ PackageInfo info = host.getPackageManager().getPackageInfo(host.getPackageName(), 0);+ JSONObject out = new JSONObject();+ out.put("os", "android");+ out.put("osVersion", Build.VERSION.RELEASE);+ out.put("device", Build.MANUFACTURER + " " + Build.MODEL);+ out.put("id", host.getPackageName());+ out.put("version", info.versionName == null ? "" : info.versionName);+ out.put("build", String.valueOf(info.getLongVersionCode()));+ reply.resolve(out.toString());+ } catch (Throwable error) {+ reply.reject(error.toString());+ }+ }+ }+}diff --git a/native/host/Bindings.hpp b/native/host/Bindings.hppindex 20093a2c9..2616b8cdd 100644--- a/native/host/Bindings.hpp+++ b/native/host/Bindings.hpp@@ -70,6 +70,11 @@ void registerAotBindings(HostState& h, esjs::Val global);* exactly as it does audio. */void registerTextEditorBindings(HostState& h, esjs::Val global);+/** es_native_has / es_native_call: the game's own line to the app's Java or+ * Objective-C, by method name. Bound on every platform; a call nobody answers+ * is refused at the call. See ChannelBindings.cpp. */+void registerChannelBindings(HostState& h, esjs::Val 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);@@ -79,4 +84,9 @@ void drainSockets(HostState& h);* only; the deliverTextEditor* calls queued it from the platform's UI thread. */void drainTextEditor(HostState& h);+/** Hand JS the replies and events native code queued since the last frame. JS+ * thread only; deliverNativeReply / deliverNativeEvent queued them from whatever+ * thread an SDK called back on. */+void drainNativeChannel(HostState& h);+} // namespace eshostdiff --git a/native/host/Host.cpp b/native/host/Host.cppindex aa7e71b2e..cfbbdc8d7 100644--- a/native/host/Host.cpp+++ b/native/host/Host.cpp@@ -398,6 +398,7 @@ void frame(long long vsyncNanos) {drainFetches(h);drainSockets(h);drainTextEditor(h);+ drainNativeChannel(h);pumpJs(h);// app.tick above ran the SDK's render system, which resolved the scene'sdiff --git a/native/host/Host.hpp b/native/host/Host.hppindex a5adf5dc5..9020fddaf 100644--- a/native/host/Host.hpp+++ b/native/host/Host.hpp@@ -29,6 +29,7 @@#pragma once#include <chrono>+#include <functional>#include <string>#include <utility>#include <vector>@@ -294,6 +295,24 @@ struct Platform {virtual void textEditorBlur() {}virtual void textEditorWrite(const std::string& /*value*/, int /*selectionStart*/,int /*selectionEnd*/) {}++ /**+ * The app's own native code, by name: what a game's Java or Objective-C+ * registered to answer (an ad SDK, a store, a sign-in). A platform with such+ * a registry overrides both; the default has none.+ *+ * `nativeHas` is asked while the script decides what it can offer (whether+ * there are ads to show), so it must answer at once and from the frame loop.+ */+ virtual bool nativeHas(const std::string& /*method*/) { return false; }+ /**+ * Start the call and answer true, or answer false when nobody is registered+ * under @p method. The answer comes later through {@link deliverNativeReply}+ * with the same @p id, from any thread. @p args is JSON.+ */+ virtual bool nativeCall(int /*id*/, const std::string& /*method*/, const std::string& /*args*/) {+ return false;+ }};/** Deliver an HTTP reply for a {@link Platform::startFetch}. Thread-safe: the@@ -311,6 +330,24 @@ void deliverTextEditorSubmit();/** The keyboard was dismissed without committing (back gesture, done). Thread-safe. */void deliverTextEditorCancel();+/** The answer to a {@link Platform::nativeCall}: @p payload is JSON when @p ok,+ * otherwise the reason, which the script's promise rejects with. Thread-safe;+ * the script hears it on the next frame. */+void deliverNativeReply(int id, bool ok, std::string payload);+/** Something native code raises on its own (a purchase finished in the+ * background, a push arrived): every script listener of @p name receives the+ * JSON @p payload on the next frame. Thread-safe. */+void deliverNativeEvent(std::string name, std::string payload);++/** How a C++ handler answers; callable once, from any thread. */+using NativeReply = std::function<void(bool ok, std::string payload)>;+/** A method answered in C++ rather than by the platform's registry. Runs on the+ * frame-loop thread, inside the script's call. */+using NativeHandler = std::function<void(const std::string& args, NativeReply reply)>;+/** Answer @p method from C++; an empty handler removes it. The platform's own+ * registry is asked first. Thread-safe. */+void registerNativeHandler(std::string method, NativeHandler handler);+/** @brief Boots Dawn, EstellaContext, the JS engine, the SDK bundle and the packaged* project. Call once, when a window first exists; @p platform must* outlive the host.diff --git a/native/host/Runtime.cpp b/native/host/Runtime.cppindex 66cad2187..2b6ed5d32 100644--- a/native/host/Runtime.cpp+++ b/native/host/Runtime.cpp@@ -439,6 +439,7 @@ void initRuntime(HostState& h) {registerNetBindings(h, global);registerDeviceBindings(h, global);registerTextEditorBindings(h, global);+ registerChannelBindings(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 comediff --git a/native/host/bindings/ChannelBindings.cpp b/native/host/bindings/ChannelBindings.cppnew file mode 100644index 000000000..77f291299--- /dev/null+++ b/native/host/bindings/ChannelBindings.cpp@@ -0,0 +1,190 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file ChannelBindings.cpp+ * @brief es_native_* — the game's own line to native code, by name.+ * @details Every other binding here is one capability the engine needs of the OS,+ * written out call by call. This one is the capability a game needs that+ * the engine cannot name in advance: an ad SDK, a store, a sign-in, an+ * analytics library — code that exists in Java or Objective-C, belongs to+ * the project, and is different in every project. So it is one seam and+ * not many: a method name, a JSON argument, a JSON reply, and events the+ * native side raises on its own.+ *+ * A call is answered by the first of:+ * * the platform ({@link Platform::nativeCall}): the handlers the app's+ * Java or Objective-C registered;+ * * a handler registered here in C++ ({@link registerNativeHandler}).+ * One that nobody answers is refused at the call (es_native_call answers+ * false), so the script's promise rejects naming the method rather than+ * waiting on a reply that is not coming.+ *+ * Handlers answer from whatever thread their SDK calls back on, so a+ * reply is queued as POD and delivered in the frame loop, the shape+ * {@link deliverFetch} and the text editor use for the same reason.+ *+ * @author ESEngine Team+ * @date 2026+ *+ * @copyright Copyright (c) 2026 ESEngine Team+ * Licensed under the Apache License, Version 2.0.+ */+#include "Bindings.hpp"++#include <cstdio>+#include <mutex>+#include <queue>+#include <string>+#include <unordered_map>+#include <utility>++using namespace esengine;++namespace eshost {+namespace {++/** One thing native code said, as POD: what crosses the thread boundary. */+struct ChannelPush {+ bool reply = false; ///< a call's answer; otherwise an event+ int id = 0; ///< the call it answers+ bool ok = false;+ std::string name; ///< the event's name+ std::string payload; ///< JSON, or the reason a call failed+};++// Namespace-scope, so deliverNative* is safe before boot and after teardown alike.+std::mutex g_mutex;+std::queue<ChannelPush> g_queue;+std::unordered_map<std::string, NativeHandler> g_handlers;++void push(ChannelPush item) {+ std::lock_guard<std::mutex> lk(g_mutex);+ g_queue.push(std::move(item));+}++bool hasHandler(const std::string& method) {+ std::lock_guard<std::mutex> lk(g_mutex);+ return g_handlers.count(method) != 0;+}++std::string jsonString(const std::string& text) {+ std::string out = "\"";+ for (const unsigned char c : text) {+ switch (c) {+ case '"': out += "\\\""; break;+ case '\\': out += "\\\\"; break;+ case '\n': out += "\\n"; break;+ case '\r': out += "\\r"; break;+ case '\t': out += "\\t"; break;+ default:+ if (c < 0x20) {+ char escaped[8];+ std::snprintf(escaped, sizeof escaped, "\\u%04x", c);+ out += escaped;+ } else {+ out += static_cast<char>(c);+ }+ }+ }+ return out + "\"";+}++// es_native_has(method): whether a call to it would be answered.+esjs::Val js_native_has(const esjs::Args& a) {+ if (a.size() < 1 || !hostAlive()) return esjs::boolean(false);+ const std::string method = esjs::toString(a[0]);+ if (host().platform && host().platform->nativeHas(method)) return esjs::boolean(true);+ return esjs::boolean(hasHandler(method));+}++// es_native_call(id, method, argsJson): false when nobody answers to the name.+esjs::Val js_native_call(const esjs::Args& a) {+ if (a.size() < 3 || !hostAlive()) return esjs::boolean(false);+ const int id = esjs::toInt32(a[0]);+ const std::string method = esjs::toString(a[1]);+ const std::string args = esjs::toString(a[2]);+ if (host().platform && host().platform->nativeCall(id, method, args)) return esjs::boolean(true);++ NativeHandler handler;+ {+ std::lock_guard<std::mutex> lk(g_mutex);+ const auto it = g_handlers.find(method);+ if (it == g_handlers.end()) return esjs::boolean(false);+ handler = it->second; // a copy: the handler may register or remove one+ }+ handler(args, [id](bool ok, std::string payload) { deliverNativeReply(id, ok, std::move(payload)); });+ return esjs::boolean(true);+}++/** The push as the SDK's `es_onNativeMessage` reads it. */+esjs::Val makePush(const ChannelPush& item) {+ esjs::Val obj = esjs::object();+ if (item.reply) {+ esjs::set(obj, "kind", esjs::string("reply"));+ esjs::set(obj, "id", esjs::int32(item.id));+ esjs::set(obj, "ok", esjs::boolean(item.ok));+ } else {+ esjs::set(obj, "kind", esjs::string("event"));+ esjs::set(obj, "name", esjs::string(item.name));+ }+ esjs::set(obj, "payload", esjs::string(item.payload));+ return obj;+}++} // namespace++void drainNativeChannel(HostState& h) {+ std::queue<ChannelPush> pending;+ { std::lock_guard<std::mutex> lk(g_mutex); pending.swap(g_queue); }+ if (pending.empty()) return;+ (void)h;+ esjs::Enter enter;+ const esjs::Val fn = esjs::get(esjs::global(), "es_onNativeMessage");+ while (!pending.empty()) {+ const ChannelPush item = std::move(pending.front());+ pending.pop();+ if (!esjs::isFunction(fn)) continue; // the SDK has not installed it (yet)+ esjs::Scope scope;+ const esjs::Val arg = makePush(item);+ esjs::call(fn, esjs::undefined(), 1, &arg, "es_onNativeMessage");+ }+}++void registerChannelBindings(HostState& h, esjs::Val global) {+ // What the host itself answers on every platform, so a script can tell where+ // it is running without a handler of its own. A platform that knows more (the+ // package's id and version) answers the same name first.+ if (!hasHandler("app.info")) {+ const std::string device = h.platform ? h.platform->describe() : std::string();+ registerNativeHandler("app.info", [device](const std::string&, NativeReply reply) {+ reply(true, "{\"device\":" + jsonString(device) + "}");+ });+ }+ bindGlobal(global, "es_native_has", js_native_has, 1);+ bindGlobal(global, "es_native_call", js_native_call, 3);+}++void registerNativeHandler(std::string method, NativeHandler handler) {+ std::lock_guard<std::mutex> lk(g_mutex);+ if (handler) g_handlers[std::move(method)] = std::move(handler);+ else g_handlers.erase(method);+}++// Thread-safe: an SDK answers on its own thread, the frame loop delivers.+void deliverNativeReply(int id, bool ok, std::string payload) {+ ChannelPush item;+ item.reply = true;+ item.id = id;+ item.ok = ok;+ item.payload = std::move(payload);+ push(std::move(item));+}++void deliverNativeEvent(std::string name, std::string payload) {+ ChannelPush item;+ item.name = std::move(name);+ item.payload = std::move(payload);+ push(std::move(item));+}++} // namespace eshostdiff --git a/native/host/platform/android.cpp b/native/host/platform/android.cppindex 73fd94e48..c21e8375c 100644--- a/native/host/platform/android.cpp+++ b/native/host/platform/android.cpp@@ -474,6 +474,55 @@ struct AndroidPlatform final : eshost::Platform {env->ExceptionClear();}}++ // -- The app's own Java, by name: com.estella.host.NativeChannel -----------+ //+ // An ad SDK, a store, a sign-in library are Java and are the project's. The+ // class keeps the registry and does its own threading (a handler runs on the+ // UI thread and answers from wherever its SDK calls back), so these are plain+ // calls from the frame loop.++ jclass channel = nullptr; // global ref, set by attachJavaShims+ jmethodID channelHas = nullptr;+ jmethodID channelCall = nullptr;++ bool nativeHas(const std::string& method) override {+ bool known = false;+ withChannel([&](JNIEnv* env) {+ jstring name = env->NewStringUTF(method.c_str());+ known = env->CallStaticBooleanMethod(channel, channelHas, name) != JNI_FALSE;+ env->DeleteLocalRef(name);+ });+ return known;+ }++ bool nativeCall(int id, const std::string& method, const std::string& args) override {+ bool started = false;+ withChannel([&](JNIEnv* env) {+ jstring name = env->NewStringUTF(method.c_str());+ // As bytes: a JNI string is modified UTF-8, and JSON is not.+ jbyteArray json = env->NewByteArray((jsize)args.size());+ if (json) env->SetByteArrayRegion(json, 0, (jsize)args.size(), reinterpret_cast<const jbyte*>(args.data()));+ started = env->CallStaticBooleanMethod(channel, channelCall, (jint)id, name, json) != JNI_FALSE;+ env->DeleteLocalRef(json);+ env->DeleteLocalRef(name);+ });+ return started;+ }++ template <typename F>+ void withChannel(F&& body) {+ if (!channel || !vm) return;+ JNIEnv* env = nullptr;+ if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {+ if (vm->AttachCurrentThread(&env, nullptr) != JNI_OK || !env) return;+ }+ body(env);+ if (env->ExceptionCheck()) {+ env->ExceptionDescribe();+ env->ExceptionClear();+ }+ }};AndroidPlatform g_platform;@@ -581,6 +630,68 @@ void attachGlyphPainter(JNIEnv* env, ANativeActivity* activity) {env->DeleteLocalRef(cls);}+// -- The channel's answers, on whatever thread the app's SDK called back on ----+// Queued as POD; the frame loop hands them to JS (see ChannelBindings.cpp).++std::string jniBytes(JNIEnv* env, jbyteArray bytes) {+ if (!bytes) return {};+ const jsize size = env->GetArrayLength(bytes);+ std::string out(static_cast<size_t>(size), ' ');+ if (size > 0) env->GetByteArrayRegion(bytes, 0, size, reinterpret_cast<jbyte*>(out.data()));+ return out;+}++std::string jniName(JNIEnv* env, jstring text) {+ const char* utf8 = text ? env->GetStringUTFChars(text, nullptr) : nullptr;+ std::string out = utf8 ? utf8 : "";+ if (utf8) env->ReleaseStringUTFChars(text, utf8);+ return out;+}++void jniChannelReply(JNIEnv* env, jclass, jint id, jboolean ok, jbyteArray payload) {+ eshost::deliverNativeReply((int)id, ok != JNI_FALSE, jniBytes(env, payload));+}++void jniChannelEvent(JNIEnv* env, jclass, jstring name, jbyteArray payload) {+ eshost::deliverNativeEvent(jniName(env, name), jniBytes(env, payload));+}++/**+ * Load com.estella.host.NativeChannel, register its natives and let the app's+ * plugins register what they answer. Before boot, so that a script asking what+ * it can call during its own start is told the truth.+ */+void attachNativeChannel(JNIEnv* env, ANativeActivity* activity) {+ if (g_platform.channel) return;+ jclass cls = loadAppClass(env, activity, "com.estella.host.NativeChannel");+ if (!cls) {+ __android_log_print(ANDROID_LOG_WARN, LOG_TAG,+ "native channel: com.estella.host.NativeChannel not in the APK — the app's Java cannot be called");+ return;+ }+ const JNINativeMethod natives[] = {+ {"nativeReply", "(IZ[B)V", (void*)jniChannelReply},+ {"nativeEvent", "(Ljava/lang/String;[B)V", (void*)jniChannelEvent},+ };+ const jmethodID attach = env->GetStaticMethodID(cls, "attach", "(Landroid/app/Activity;)V");+ const jmethodID has = env->GetStaticMethodID(cls, "has", "(Ljava/lang/String;)Z");+ const jmethodID call = env->GetStaticMethodID(cls, "call", "(ILjava/lang/String;[B)Z");+ if (!attach || !has || !call || env->RegisterNatives(cls, natives, 2) != JNI_OK) {+ env->ExceptionClear();+ env->DeleteLocalRef(cls);+ return;+ }+ env->CallStaticVoidMethod(cls, attach, activity->clazz);+ if (env->ExceptionCheck()) {+ env->ExceptionDescribe();+ env->ExceptionClear();+ }+ g_platform.channelHas = has;+ g_platform.channelCall = call;+ g_platform.channel = (jclass)env->NewGlobalRef(cls);+ env->DeleteLocalRef(cls);+}+/** The APK's Java shims, loaded once on the frame-loop thread before boot binds what they answer. */void attachJavaShims(ANativeActivity* activity) {if (!activity->vm) return;@@ -588,6 +699,7 @@ void attachJavaShims(ANativeActivity* activity) {if (activity->vm->AttachCurrentThread(&env, nullptr) != JNI_OK || !env) return;attachTextEditor(env, activity);attachGlyphPainter(env, activity);+ attachNativeChannel(env, activity);}// The decoder's own copies of the MotionEvent constants, held against the NDK'sdiff --git a/native/host/platform/ios.mm b/native/host/platform/ios.mmindex a3e77bf84..048eb2124 100644--- a/native/host/platform/ios.mm+++ b/native/host/platform/ios.mm@@ -28,6 +28,7 @@#include "platform/apple_common.hpp" // Core Text + NSURLSession, shared with macOS#include "platform/touch_stream.hpp"#include "platform/ios_device.hpp"+#include "../../ios/App/EstellaNativeChannel.h" // the app-facing half of the channelusing esengine::u32;using esengine::u8;@@ -46,6 +47,12 @@ using esengine::WebGPUDevice;selectionEnd:(NSInteger)selectionEnd;@end+/** The host's own side of the channel: what the platform asks of the registry. */+@interface EstellaNativeChannel ()++ (BOOL)answers:(NSString*)method;++ (BOOL)call:(int)callId method:(NSString*)method args:(NSString*)args;+@end+namespace {struct IOSPlatform final : eshost::Platform {@@ -177,6 +184,16 @@ struct IOSPlatform final : eshost::Platform {return eshost::appleDrawGlyph(family, codepoint, style, pixelSize, supersample, padding, out);}+ // The app's own Objective-C or Swift, by name: see EstellaNativeChannel below.+ bool nativeHas(const std::string& method) override {+ return [EstellaNativeChannel answers:[NSString stringWithUTF8String:method.c_str()] ?: @""];+ }+ bool nativeCall(int id, const std::string& method, const std::string& args) override {+ return [EstellaNativeChannel call:id+ method:[NSString stringWithUTF8String:method.c_str()] ?: @""+ args:[NSString stringWithUTF8String:args.c_str()] ?: @"null"];+ }+void startFetch(const eshost::FetchRequest& req) override {eshost::appleStartFetch(req);}@@ -186,6 +203,91 @@ IOSPlatform g_platform;} // namespace+// -- The app's own native code, by name ----------------------------------------+//+// The registry an app's Objective-C or Swift fills (EstellaNativeChannel.h) and+// the frame loop asks. A handler runs on the main thread, where an SDK that+// presents anything has to be called, and answers from wherever that SDK calls+// back; the answer is queued and the script hears it on the next frame.++@implementation EstellaNativeChannel++/** The handlers, created on first use: an app registers from +load, which runs+ * before anything of the host's has. Guarded by the dictionary itself. */++ (NSMutableDictionary<NSString*, EstellaNativeHandler>*)handlers {+ static NSMutableDictionary<NSString*, EstellaNativeHandler>* handlers;+ static dispatch_once_t once;+ dispatch_once(&once, ^{+ handlers = [NSMutableDictionary dictionary];+ // What the app is, which a script cannot otherwise read: its id and version.+ handlers[@"app.info"] = [^(NSString* args, EstellaNativeReply reply) {+ NSBundle* bundle = NSBundle.mainBundle;+ NSDictionary* info = @{+ @"os": @"ios",+ @"osVersion": UIDevice.currentDevice.systemVersion ?: @"",+ @"device": UIDevice.currentDevice.model ?: @"",+ @"id": bundle.bundleIdentifier ?: @"",+ @"version": [bundle objectForInfoDictionaryKey:@"CFBundleShortVersionString"] ?: @"",+ @"build": [bundle objectForInfoDictionaryKey:@"CFBundleVersion"] ?: @"",+ };+ NSData* json = [NSJSONSerialization dataWithJSONObject:info options:0 error:nil];+ if (json) reply([[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding], nil);+ else reply(nil, @"app.info could not be written as JSON");+ } copy];+ });+ return handlers;+}+++ (void)registerMethod:(NSString*)method handler:(EstellaNativeHandler)handler {+ if (!method || !handler) return;+ NSMutableDictionary* handlers = [self handlers];+ @synchronized (handlers) { handlers[method] = [handler copy]; }+}+++ (void)unregisterMethod:(NSString*)method {+ if (!method) return;+ NSMutableDictionary* handlers = [self handlers];+ @synchronized (handlers) { [handlers removeObjectForKey:method]; }+}+++ (void)emitEvent:(NSString*)event json:(NSString*)json {+ if (!event) return;+ eshost::deliverNativeEvent(event.UTF8String ?: "", json.UTF8String ?: "null");+}+++ (BOOL)answers:(NSString*)method {+ NSMutableDictionary* handlers = [self handlers];+ @synchronized (handlers) { return handlers[method] != nil; }+}+++ (BOOL)call:(int)callId method:(NSString*)method args:(NSString*)args {+ EstellaNativeHandler handler = nil;+ NSMutableDictionary* handlers = [self handlers];+ @synchronized (handlers) { handler = handlers[method]; }+ if (!handler) return NO;+ // One answer reaches the script, however many times the handler gives one.+ NSObject* once = [NSObject new];+ __block BOOL answered = NO;+ EstellaNativeReply reply = ^(NSString* json, NSString* error) {+ @synchronized (once) {+ if (answered) return;+ answered = YES;+ }+ if (error) eshost::deliverNativeReply(callId, false, error.UTF8String ?: "");+ else eshost::deliverNativeReply(callId, true, json.UTF8String ?: "null");+ };+ dispatch_async(dispatch_get_main_queue(), ^{+ @try {+ handler(args, reply);+ } @catch (NSException* exception) {+ reply(nil, exception.reason ?: exception.name);+ }+ });+ return YES;+}++@end+/// A view whose backing layer is the CAMetalLayer Dawn renders into.@interface EstellaMetalView : UIView@enddiff --git a/native/ios/App/EstellaNativeChannel.h b/native/ios/App/EstellaNativeChannel.hnew file mode 100644index 000000000..acb36cfd2--- /dev/null+++ b/native/ios/App/EstellaNativeChannel.h@@ -0,0 +1,53 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+//+// The game's line to this app's own Objective-C or Swift: methods a script calls+// by name, and events native code raises for the script.+//+// The engine knows nothing of an ad SDK, a store or a sign-in library; those are+// the project's. A project answers a name here and its script calls that name:+//+// + (void)load {+// [EstellaNativeChannel registerMethod:@"ads.show"+// handler:^(NSString* args, EstellaNativeReply reply) {+// ...+// reply(@"{\"completed\":true}", nil);+// }];+// }+//+// const result = await NativeChannel.call('ads.show', { kind: 'rewarded', unitId });+//+// Arguments and results are JSON text, so neither side needs the other's types.+// A handler runs on the main thread and may answer later from any thread, once.+// Register before the game starts: a class's +load is early enough, and needs no+// entry point of its own.+//+// The class itself is in the engine library (Estella.xcframework); this header is+// all an app target needs to use it.++#import <Foundation/Foundation.h>++NS_ASSUME_NONNULL_BEGIN++/// How a handler answers: `json` for a result (nil for no value), or `error` for+/// a failure the script's promise rejects with. Once; a second answer is dropped.+typedef void (^EstellaNativeReply)(NSString* _Nullable json, NSString* _Nullable error);++/// What answers a method. Runs on the main thread. `argsJson` is JSON text.+typedef void (^EstellaNativeHandler)(NSString* argsJson, EstellaNativeReply reply);++@interface EstellaNativeChannel : NSObject++/// Answer `method` from now on; a later registration replaces an earlier one.++ (void)registerMethod:(NSString*)method handler:(EstellaNativeHandler)handler;++/// Stop answering `method`.++ (void)unregisterMethod:(NSString*)method;++/// Tell the script something it did not ask for: every listener of `event` hears+/// `json` on the game's next frame. From any thread.++ (void)emitEvent:(NSString*)event json:(nullable NSString*)json;++@end++NS_ASSUME_NONNULL_ENDdiff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex ba8f67926..fac8d7c22 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -1,7 +1,7 @@# API surface — esengine/index<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 166 beta · 2179 experimental · 3 deprecated+Symbols: 117 public · 166 beta · 2179 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -6656,6 +6656,19 @@ ComponentDef<NameData>value: string```+## NativeChannel — const @public+```+NativeChannelApi+```++## NativeChannelApi — interface @public+```+available: boolean+call: <T = unknown>(method: string, args?: unknown) => Promise<T>+has: (method: string) => boolean+on: <T = unknown>(event: string, handler: (data: T) => void) => () => void+```+## NestedPrefabRef — interface @experimental```overrides: PrefabOverride[]@@ -7734,6 +7747,7 @@ loadImagePixels: (path: string) => Promise<ImageLoadResult>loadSubpackage: ((name: string) => Promise<void>) | undefinedlogin: (() => Promise<string>) | undefinedname: PlatformName+nativeChannel: (() => PlatformNativeChannel | null) | undefinednow: () => numberonAppHide: ((callback: () => void) => () => void) | undefinedonAppShow: ((callback: () => void) => () => void) | undefineddiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 81737411c..bf4841c53 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.native<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 171 beta · 2199 experimental · 3 deprecated+Symbols: 117 public · 171 beta · 2199 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -6672,6 +6672,7 @@ value: string## NativeBridge — interface @beta```audio: NativeAudioBridge | undefined+channel: NativeChannelBridge | undefineddevice: (() => DeviceBackend) | undefineddeviceName: (() => string) | undefineddevicePixelRatio: () => number@@ -6703,6 +6704,19 @@ textEditor: NativeTextEditorBridge | undefinedwriteCacheFile: ((key: string, bytes: ArrayBuffer) => Promise<void>) | undefined```+## NativeChannel — const @public+```+NativeChannelApi+```++## NativeChannelApi — interface @public+```+available: boolean+call: <T = unknown>(method: string, args?: unknown) => Promise<T>+has: (method: string) => boolean+on: <T = unknown>(event: string, handler: (data: T) => void) => () => void+```+## NativeComponentBufferFn — type @experimental```(entity: number) => ArrayBuffer | null | undefined@@ -6758,6 +6772,8 @@ es_isHandheld: (() => boolean) | undefinedes_keepScreenOn: ((enabled: boolean) => boolean) | undefinedes_language: (() => string) | undefinedes_loadImagePixels: (pathOrBytes: string | ArrayBuffer) => { width: number; height: number; pixels: ArrayBuffer; } | null+es_native_call: ((id: number, method: string, args: string) => boolean) | undefined+es_native_has: ((method: string) => boolean) | undefinedes_pollGamepads: (() => { index: number; connected: boolean; buttons: number[]; axes: number[]; }[]) | undefinedes_pollMotion: (() => Pick<MotionSample, "timestamp" | "accelerationIncludingGravity" | "gyroscope"> | null) | undefinedes_rasterizeGlyph: ((request: PlatformGlyphRequest) => { pixels: ArrayBuffer; width: number; height: number; advance: number; bearingX: number; bearingY: number; } | null) | undefined@@ -6819,6 +6835,8 @@ clearStorage: (prefix: string) => voidcreateAudioBackend: (() => PlatformAudioBackend) | undefinedcreateCanvas: (_width: number, _height: number) => PlatformCanvascreateImage: () => PlatformImage+createInterstitialAd: ((adUnitId: string) => PlatformInterstitialAd | null) | undefined+createRewardedAd: ((adUnitId: string) => PlatformRewardedAd | null) | undefinedcreateSocket: (options: PlatformSocketOptions) => PlatformSocketcreateTextEditor: () => PlatformTextEditor | nullcreateVideoBackend: (ctx: VideoBackendContext) => PlatformVideoBackend@@ -6834,6 +6852,7 @@ isHandheld: () => booleanlanguage: () => stringloadImagePixels: (path: string) => Promise<ImageLoadResult>name: "native"+nativeChannel: () => PlatformNativeChannel | nullnow: () => numberonAppHide: (callback: () => void) => () => voidonAppShow: (callback: () => void) => () => void@@ -7941,6 +7960,7 @@ loadImagePixels: (path: string) => Promise<ImageLoadResult>loadSubpackage: ((name: string) => Promise<void>) | undefinedlogin: (() => Promise<string>) | undefinedname: PlatformName+nativeChannel: (() => PlatformNativeChannel | null) | undefinednow: () => numberonAppHide: ((callback: () => void) => () => void) | undefinedonAppShow: ((callback: () => void) => () => void) | undefineddiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex c9f58d8d7..5b614ac01 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.node<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 168 beta · 2178 experimental · 3 deprecated+Symbols: 117 public · 168 beta · 2178 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -6651,6 +6651,19 @@ ComponentDef<NameData>value: string```+## NativeChannel — const @public+```+NativeChannelApi+```++## NativeChannelApi — interface @public+```+available: boolean+call: <T = unknown>(method: string, args?: unknown) => Promise<T>+has: (method: string) => boolean+on: <T = unknown>(event: string, handler: (data: T) => void) => () => void+```+## NestedPrefabRef — interface @experimental```overrides: PrefabOverride[]@@ -7729,6 +7742,7 @@ loadImagePixels: (path: string) => Promise<ImageLoadResult>loadSubpackage: ((name: string) => Promise<void>) | undefinedlogin: (() => Promise<string>) | undefinedname: PlatformName+nativeChannel: (() => PlatformNativeChannel | null) | undefinednow: () => numberonAppHide: ((callback: () => void) => () => void) | undefinedonAppShow: ((callback: () => void) => () => void) | undefineddiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 7c275eccf..7121bffba 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -1,7 +1,7 @@# API surface — esengine/minigame<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 166 beta · 2200 experimental · 3 deprecated+Symbols: 117 public · 166 beta · 2200 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -6948,6 +6948,19 @@ ComponentDef<NameData>value: string```+## NativeChannel — const @public+```+NativeChannelApi+```++## NativeChannelApi — interface @public+```+available: boolean+call: <T = unknown>(method: string, args?: unknown) => Promise<T>+has: (method: string) => boolean+on: <T = unknown>(event: string, handler: (data: T) => void) => () => void+```+## NestedPrefabRef — interface @experimental```overrides: PrefabOverride[]@@ -8026,6 +8039,7 @@ loadImagePixels: (path: string) => Promise<ImageLoadResult>loadSubpackage: ((name: string) => Promise<void>) | undefinedlogin: (() => Promise<string>) | undefinedname: PlatformName+nativeChannel: (() => PlatformNativeChannel | null) | undefinednow: () => numberonAppHide: ((callback: () => void) => () => void) | undefinedonAppShow: ((callback: () => void) => () => void) | undefineddiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 37205402f..d86535086 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -1,7 +1,7 @@# API surface — esengine/wechat<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 166 beta · 2191 experimental · 3 deprecated+Symbols: 117 public · 166 beta · 2191 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -6658,6 +6658,19 @@ ComponentDef<NameData>value: string```+## NativeChannel — const @public+```+NativeChannelApi+```++## NativeChannelApi — interface @public+```+available: boolean+call: <T = unknown>(method: string, args?: unknown) => Promise<T>+has: (method: string) => boolean+on: <T = unknown>(event: string, handler: (data: T) => void) => () => void+```+## NestedPrefabRef — interface @experimental```overrides: PrefabOverride[]@@ -7736,6 +7749,7 @@ loadImagePixels: (path: string) => Promise<ImageLoadResult>loadSubpackage: ((name: string) => Promise<void>) | undefinedlogin: (() => Promise<string>) | undefinedname: PlatformName+nativeChannel: (() => PlatformNativeChannel | null) | undefinednow: () => numberonAppHide: ((callback: () => void) => () => void) | undefinedonAppShow: ((callback: () => void) => () => void) | undefineddiff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex b456c150f..0ac50f24b 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -752,13 +752,14 @@ export {} from './audio';// =============================================================================-// Platform services (ads, share, achievements)+// Platform services (ads, share, achievements, the app's own native code)// =============================================================================export {Achievements, AchievementsAPI, createLocalAchievements,Ads, AdsAPI, createMockAdProvider, createTakeover,Identity, IdentityAPI,+ NativeChannel, type NativeChannelApi,ServicesPlugin, servicesPlugin,type AchievementProvider,type AdProvider, type MockAdProviderOptions, type Takeover, type TakeoverHost,diff --git a/sdk/src/platform/base.ts b/sdk/src/platform/base.tsindex 3bb2e6912..1fbdd5b7d 100644--- a/sdk/src/platform/base.ts+++ b/sdk/src/platform/base.ts@@ -297,6 +297,13 @@ export function platformRemoveStorageItem(key: string): void {getPlatform().removeStorageItem(key);}+/** The app's own native code, or null where there is none to reach (the web, a+ * mini-game, a native host built before the channel, an uninitialized platform). */+export function platformNativeChannel(): import('./types').PlatformNativeChannel | null {+ if (!isPlatformInitialized()) return null;+ return getPlatform().nativeChannel?.() ?? null;+}+/** Whether this platform can mint ad units at all, without minting one (a* mini-game host materializes a real host object per created unit). */export function platformCanCreateAds(): boolean {@@ -304,7 +311,7 @@ export function platformCanCreateAds(): boolean {}/** One rewarded ad unit from the platform, or null where the platform has no ad- * system (web, native, playable, an uninitialized platform in tests). Null is+ * system (web, a native app whose own code answers for none, playable, an uninitialized platform in tests). Null is* an answer, not an error: the services layer substitutes its mock provider or* fails loud with the reason, which is a decision this layer cannot make. */export function platformCreateRewardedAd(adUnitId: string): import('./types').PlatformRewardedAd | null {diff --git a/sdk/src/platform/index.ts b/sdk/src/platform/index.tsindex ac17a38f5..5b587e20f 100644--- a/sdk/src/platform/index.ts+++ b/sdk/src/platform/index.ts@@ -61,6 +61,7 @@ export {platformCanCreateAds,platformCreateRewardedAd,platformCreateInterstitialAd,+ platformNativeChannel,platformCanShare,platformShare,platformOnShareRequest,diff --git a/sdk/src/platform/native/adapter.ts b/sdk/src/platform/native/adapter.tsindex 47dd80c1b..df3628773 100644--- a/sdk/src/platform/native/adapter.ts+++ b/sdk/src/platform/native/adapter.ts@@ -29,6 +29,9 @@ import type {PlatformTextEditor,PlatformSocket,PlatformSocketOptions,+ PlatformNativeChannel,+ PlatformRewardedAd,+ PlatformInterstitialAd,} from '../types';import { NativeSocket } from './socket';import { unavailableDevice } from '../../device/core';@@ -39,6 +42,9 @@ import { setPlatform } from '../base';import { createPrimaryPointer } from '../primaryPointer';import { NativeAudioBackend } from '../../audio/NativeAudioBackend';import { createNativeTextEditor } from './textEditor';+import {+ createNativeChannel, createNativeInterstitialAd, createNativeRewardedAd, nativeChannelHasAds,+} from './channel';import { browserLanguageTag } from './languageTag';import { createSteamAchievements } from './steamAchievements';import type { AchievementProvider } from '../../services/achievements';@@ -65,8 +71,31 @@ export class NativePlatformAdapter implements PlatformAdapter {const rasterize = bridge_.rasterizeGlyph.bind(bridge_);this.rasterizeGlyph = (request) => rasterize(request);}+ // The app's own native code, and ads over it. The ad factories exist only+ // when that code answers for ads, so `Ads.available` is the truth about+ // THIS app rather than about native hosts in general. Asked once, here:+ // the app's plugins registered before the script started.+ if (bridge_.channel) {+ const channel = createNativeChannel(bridge_.channel);+ this.channel_ = channel;+ if (nativeChannelHasAds(channel)) {+ this.createRewardedAd = (adUnitId) => createNativeRewardedAd(channel, adUnitId);+ this.createInterstitialAd = (adUnitId) => createNativeInterstitialAd(channel, adUnitId);+ }+ }}+ private channel_: PlatformNativeChannel | null = null;++ /** The app's own native code; null on a host built before the channel. */+ nativeChannel(): PlatformNativeChannel | null {+ return this.channel_;+ }++ /** Assigned in the constructor only when the app's native code answers for ads. */+ createRewardedAd?: (adUnitId: string) => PlatformRewardedAd | null;+ createInterstitialAd?: (adUnitId: string) => PlatformInterstitialAd | null;+/** Assigned in the constructor only when the host bound an audio engine. */createAudioBackend?: () => PlatformAudioBackend;diff --git a/sdk/src/platform/native/bridge.ts b/sdk/src/platform/native/bridge.tsindex 194c4e660..a169d504b 100644--- a/sdk/src/platform/native/bridge.ts+++ b/sdk/src/platform/native/bridge.ts@@ -166,6 +166,22 @@ export interface NativeAudioBridge {onEnded(callback: (voiceId: number) => void): () => void;}+/**+ * The host's line to the app's own native code. Text both ways: the host carries+ * a method name and JSON without knowing what either means (see channel.ts for+ * the side that does).+ */+export interface NativeChannelBridge {+ /** Whether anything answers to `method`. */+ has(method: string): boolean;+ /** Call `method` with JSON `args`. Resolves with the JSON it answered;+ * rejects when nothing answers, or with the reason the native side gave. */+ call(method: string, args: string): Promise<string>;+ /** The sink for events native code raises on its own (pushed, like touch):+ * the event's name and its JSON. Returns an unsubscribe. */+ subscribe(handler: (name: string, payload: string) => void): () => void;+}+/*** The host functions the native shell injects. Async where the call crosses to* the OS (files, network, image decode); sync where the native API is sync@@ -184,6 +200,10 @@ export interface NativeBridge {* route the play realm and WeChat also use). */loadImagePixels(path: string): Promise<ImageLoadResult>;+ /** The app's own Java or Objective-C, by method name. Optional: a host built+ * before the channel omits it, and the SDK then reports no native code. */+ channel?: NativeChannelBridge;+/** Rasterize one glyph — the device's answer to the 2D canvas the browser* path draws text on. Synchronous, because the dynamic glyph atlas fills* cells during the frame that needs them. Optional: a host that has notdiff --git a/sdk/src/platform/native/channel.ts b/sdk/src/platform/native/channel.tsnew file mode 100644index 000000000..25051e8f5--- /dev/null+++ b/sdk/src/platform/native/channel.ts@@ -0,0 +1,110 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file platform/native/channel.ts+ * @brief The app's own native code, by name, behind the platform's+ * {@link PlatformNativeChannel} contract; and ads over it.+ *+ * The host carries text both ways (a method name, JSON in, JSON out) so that it+ * needs no knowledge of what is being said. This is where that text becomes+ * values, and where a reason a call failed becomes an Error that names the call.+ *+ * Ads are the first thing said over the channel rather than a second bridge: an+ * ad SDK is the project's native code like any other, and the engine links none.+ * A project whose Java or Objective-C answers {@link NATIVE_ADS_SHOW} has ads;+ * one that does not has none, and `Ads.available` says so.+ */+import type {+ PlatformInterstitialAd, PlatformNativeChannel, PlatformRewardedAd, PlatformRewardedAdResult,+} from '../types';+import type { NativeChannelBridge } from './bridge';++/** Show one ad. Args `{ kind: 'rewarded' | 'interstitial', unitId }`; answers when+ * the ad has CLOSED, with `{ completed: boolean }` for a rewarded one. */+export const NATIVE_ADS_SHOW = 'ads.show';+/** Load one ad ahead of showing it. Same args; optional for a handler to answer. */+export const NATIVE_ADS_PRELOAD = 'ads.preload';++function decode(method: string, text: string): unknown {+ if (text === '') return undefined;+ try {+ return JSON.parse(text);+ } catch {+ throw new Error(`native "${method}" answered with something that is not JSON: ${text.slice(0, 120)}`);+ }+}++export function createNativeChannel(bridge: NativeChannelBridge): PlatformNativeChannel {+ const listeners = new Map<string, Set<(data: unknown) => void>>();+ let unsubscribe: (() => void) | null = null;++ const dispatch = (name: string, payload: string): void => {+ const set = listeners.get(name);+ if (!set || set.size === 0) return;+ let data: unknown;+ try {+ data = decode(name, payload);+ } catch (error) {+ // One malformed event must not stop the others in the same frame.+ console.error(error);+ return;+ }+ // A copy: a listener may remove itself, or add another, while it runs.+ for (const handler of [...set]) handler(data);+ };++ return {+ has: (method) => bridge.has(method),+ async call(method, args) {+ const text = await bridge.call(method, args === undefined ? 'null' : JSON.stringify(args));+ return decode(method, text);+ },+ on(event, handler) {+ let set = listeners.get(event);+ if (!set) listeners.set(event, set = new Set());+ set.add(handler);+ unsubscribe ??= bridge.subscribe(dispatch);+ return () => {+ set.delete(handler);+ if (set.size === 0) listeners.delete(event);+ if (listeners.size === 0 && unsubscribe) {+ unsubscribe();+ unsubscribe = null;+ }+ };+ },+ };+}++/** Whether this app's native code answers for ads at all. */+export function nativeChannelHasAds(channel: PlatformNativeChannel): boolean {+ return channel.has(NATIVE_ADS_SHOW);+}++function preload(channel: PlatformNativeChannel, kind: 'rewarded' | 'interstitial', unitId: string): Promise<void> {+ // Preloading is a courtesy: a handler that only shows loads when asked to show.+ if (!channel.has(NATIVE_ADS_PRELOAD)) return Promise.resolve();+ return channel.call(NATIVE_ADS_PRELOAD, { kind, unitId }).then(() => {});+}++export function createNativeRewardedAd(channel: PlatformNativeChannel, unitId: string): PlatformRewardedAd {+ return {+ preload: () => preload(channel, 'rewarded', unitId),+ async show(): Promise<PlatformRewardedAdResult> {+ const result = await channel.call(NATIVE_ADS_SHOW, { kind: 'rewarded', unitId });+ // The reward is the game's currency: only a handler that SAYS it was+ // earned grants it. A reply with no verdict is a handler that forgot.+ return { completed: (result as { completed?: unknown } | null | undefined)?.completed === true };+ },+ // The unit lives in the app's SDK, which keeps or frees it as it sees fit.+ destroy: () => {},+ };+}++export function createNativeInterstitialAd(channel: PlatformNativeChannel, unitId: string): PlatformInterstitialAd {+ return {+ preload: () => preload(channel, 'interstitial', unitId),+ show: () => channel.call(NATIVE_ADS_SHOW, { kind: 'interstitial', unitId }).then(() => {}),+ destroy: () => {},+ };+}diff --git a/sdk/src/platform/native/hostBridge.ts b/sdk/src/platform/native/hostBridge.tsindex bdc76b1ff..6580d09bc 100644--- a/sdk/src/platform/native/hostBridge.ts+++ b/sdk/src/platform/native/hostBridge.ts@@ -15,7 +15,7 @@import { log } from '../../util/logger';import type {NativeAudioBridge, NativeBridge, NativeFetchResult, NativeInputListener,- NativeTextEditorBridge, NativeTextEditorPush, NativeSocketEvent,+ NativeTextEditorBridge, NativeTextEditorPush, NativeSocketEvent, NativeChannelBridge,} from './bridge';import type { PlatformGlyph, PlatformGlyphRequest, PlatformRequestOptions } from '../types';import { assertHostEnvironment } from './hostEnvironment';@@ -136,6 +136,11 @@ export interface NativeHostBindings extends NativeDeviceHost {es_textEditor_blur?(): void;es_textEditor_write?(value: string, selectionStart: number, selectionEnd: number): void;+ // The app's own native code, by name (see ChannelBindings.cpp). Bound as a+ // pair; replies and events come back through es_onNativeMessage.+ es_native_has?(method: string): boolean;+ es_native_call?(id: number, method: string, args: string): boolean;+es_audioSpectrum?(bins: number): ArrayBuffer | null;es_audioLoad?(bytes: ArrayBuffer, stream?: boolean): { id: number; duration: number; bytes: number; streamed?: boolean } | null;es_audioUnload?(bufferId: number): void;@@ -198,6 +203,7 @@ export function createHostBridge(const storage = hostStorage(bindings);const audio = hostAudio(bindings, scope);const textEditor = hostTextEditor(bindings, scope);+ const channel = hostChannel(bindings, scope);const lifecycle = hostLifecycle(scope);let device: NativeDevice | null = null;@@ -295,6 +301,7 @@ export function createHostBridge(: {}),...(audio ? { audio } : {}),...(textEditor ? { textEditor } : {}),+ ...(channel ? { channel } : {}),...lifecycle,};}@@ -441,6 +448,56 @@ function hostTextEditor(};}+/** What the host pushes through `es_onNativeMessage`: a call's answer, or an event. */+type NativeChannelPush =+ | { kind: 'reply'; id: number; ok: boolean; payload: string }+ | { kind: 'event'; name: string; payload: string };++/**+ * The channel to the app's own native code, when the host bound it. A call is+ * numbered here and answered later through `es_onNativeMessage`; one the host+ * refuses at the door (nothing answers to the name) rejects at once, so no+ * promise is left waiting on a reply that cannot come.+ */+function hostChannel(+ bindings: NativeHostBindings,+ scope: Record<string, unknown>,+): NativeChannelBridge | undefined {+ if (!bindings.es_native_has || !bindings.es_native_call) return undefined;+ const pending = new Map<number, { method: string; resolve: (payload: string) => void; reject: (error: Error) => void }>();+ let subs: ((name: string, payload: string) => void)[] = [];+ let nextId = 1;+ scope.es_onNativeMessage = (push: NativeChannelPush): void => {+ if (push.kind === 'event') {+ for (const cb of subs) cb(push.name, push.payload);+ return;+ }+ const call = pending.get(push.id);+ if (!call) return; // answered twice, or a reply to a realm that is gone+ pending.delete(push.id);+ if (push.ok) call.resolve(push.payload);+ else call.reject(new Error(`native "${call.method}" failed: ${push.payload || 'no reason given'}`));+ };+ return {+ has: (method) => bindings.es_native_has!(method),+ call: (method, args) => new Promise<string>((resolve, reject) => {+ const id = nextId++;+ pending.set(id, { method, resolve, reject });+ let started = false;+ try {+ started = bindings.es_native_call!(id, method, args);+ } finally {+ if (!started) pending.delete(id);+ }+ if (!started) reject(new Error(`native "${method}": nothing in this app answers to that name`));+ }),+ subscribe: (handler) => {+ subs.push(handler);+ return () => { subs = subs.filter((s) => s !== handler); };+ },+ };+}+/*** The lifecycle signals the host pushes (like touch), each installed as an* `es_onNative*` entry the shell calls and exposed as a subscribe/unsubscribe ondiff --git a/sdk/src/platform/native/index.ts b/sdk/src/platform/native/index.tsindex 70320cfea..705215d93 100644--- a/sdk/src/platform/native/index.ts+++ b/sdk/src/platform/native/index.ts@@ -10,7 +10,8 @@*/export { NativePlatformAdapter, installNativePlatform } from './adapter';-export type { NativeBridge, NativeInputListener, NativeFetchResult } from './bridge';+export type { NativeBridge, NativeInputListener, NativeFetchResult, NativeChannelBridge } from './bridge';+export { NATIVE_ADS_SHOW, NATIVE_ADS_PRELOAD } from './channel';export { createHostBridge } from './hostBridge';export { assertHostEnvironment, assertNativeHost } from './hostEnvironment';export type { NativeHostBindings } from './hostBridge';diff --git a/sdk/src/platform/types.ts b/sdk/src/platform/types.tsindex 8537b75c6..83a43e7f3 100644--- a/sdk/src/platform/types.ts+++ b/sdk/src/platform/types.ts@@ -602,14 +602,22 @@ export interface PlatformAdapter {isHandheld?(): boolean;/** One rewarded ad unit. Mini-game hosts implement it over their- * RewardedVideoAd; platforms without an ad system (web, native until a- * mediation SDK is wired, playable — networks forbid nested ads) omit the+ * RewardedVideoAd; platforms without an ad system (web, a native app whose own+ * code answers for none, playable — networks forbid nested ads) omit the* method, and a family adapter whose PARTICULAR host lacks the capability* returns null. Both answers mean the same thing to the services layer:* substitute the mock provider or fail loud with the reason. */createRewardedAd?(adUnitId: string): PlatformRewardedAd | null;/** One interstitial ad unit — same availability story as rewarded. */createInterstitialAd?(adUnitId: string): PlatformInterstitialAd | null;+ /**+ * The app's own native code, reached by method name: the Java or Objective-C+ * a packaged game links beside the engine (an ad SDK, a store, a sign-in).+ * Present only on a native host; null there when the host binary predates+ * the channel. The web and mini-games omit it: a page has no native code,+ * and a mini-game's host API is the vendor's, not the project's.+ */+ nativeChannel?(): PlatformNativeChannel | null;/** Actively open the host's share sheet. Fire-and-forget: since 2021 no* mini-game host reports whether the player actually shared. */share?(options: PlatformShareOptions): void;@@ -692,6 +700,21 @@ export interface PlatformAdapter {// Monetization / share services// =============================================================================+/**+ * The app's own native code, by name. Values cross as JSON, so anything JSON+ * carries is an argument, a result or an event's data.+ */+export interface PlatformNativeChannel {+ /** Whether anything answers to `method`. Synchronous: it is asked while a+ * menu decides what to offer. */+ has(method: string): boolean;+ /** Call `method`. Rejects when nothing answers to the name, or with the+ * reason the native side gave. */+ call(method: string, args?: unknown): Promise<unknown>;+ /** Hear every `event` the native side raises. Returns the unsubscribe. */+ on(event: string, handler: (data: unknown) => void): () => void;+}+/** How a rewarded ad ended: `completed` is whether the reward was earned. */export interface PlatformRewardedAdResult {completed: boolean;diff --git a/sdk/src/services/index.ts b/sdk/src/services/index.tsindex 6f48b4b4f..27591a4a6 100644--- a/sdk/src/services/index.ts+++ b/sdk/src/services/index.ts@@ -10,3 +10,4 @@ export {} from './achievements';export { Identity, IdentityAPI, type LoginResult } from './identity';export { ServicesPlugin, servicesPlugin } from './servicesPlugin';+export { NativeChannel, type NativeChannelApi } from './nativeChannel';diff --git a/sdk/src/services/nativeChannel.ts b/sdk/src/services/nativeChannel.tsnew file mode 100644index 000000000..9cdb9a996--- /dev/null+++ b/sdk/src/services/nativeChannel.ts@@ -0,0 +1,63 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file nativeChannel.ts+ * @brief Call the app's own native code by name, and hear what it raises.+ *+ * A packaged Android or iOS game is an ordinary app: it can link an ad SDK, a+ * store, a sign-in or an analytics library, and that code is Java, Kotlin,+ * Objective-C or Swift. This is how a script reaches it. The native side answers+ * a method name (`NativeChannel.register` in Java, `EstellaNativeChannel` in+ * Objective-C); the script calls the name:+ *+ * ```ts+ * if (NativeChannel.has('store.buy')) {+ * const receipt = await NativeChannel.call<{ token: string }>('store.buy', { sku: 'gems_100' });+ * }+ * const off = NativeChannel.on<{ sku: string }>('store.restored', (p) => grant(p.sku));+ * ```+ *+ * Arguments, results and event data are anything JSON carries.+ *+ * Elsewhere (the web, a mini-game, the editor's play mode) there is no native+ * code to reach: `available` is false, `has` answers false, `call` rejects+ * naming the method, and `on` never fires. A game that asks `has` first runs+ * unchanged on every platform.+ */+import { platformNativeChannel } from '../platform';++/** @public */+export interface NativeChannelApi {+ /** Whether this platform has native code to reach at all. */+ readonly available: boolean;+ /** Whether a call to `method` would be answered. Cheap; ask before offering a feature. */+ has(method: string): boolean;+ /**+ * Call `method` in the app's native code. Resolves with what it answered;+ * rejects when nothing answers to the name, or with the reason the native+ * side gave. `args` is anything JSON carries.+ */+ call<T = unknown>(method: string, args?: unknown): Promise<T>;+ /** Hear every `event` the native side raises from now on. Returns the unsubscribe. */+ on<T = unknown>(event: string, handler: (data: T) => void): () => void;+}++/** @public */+export const NativeChannel: NativeChannelApi = {+ get available(): boolean {+ return platformNativeChannel() !== null;+ },+ has(method: string): boolean {+ return platformNativeChannel()?.has(method) ?? false;+ },+ call<T = unknown>(method: string, args?: unknown): Promise<T> {+ const channel = platformNativeChannel();+ if (!channel) {+ return Promise.reject(new Error(`native "${method}": this platform has no native code to call (check NativeChannel.has first)`));+ }+ return channel.call(method, args) as Promise<T>;+ },+ on<T = unknown>(event: string, handler: (data: T) => void): () => void {+ return platformNativeChannel()?.on(event, handler as (data: unknown) => void) ?? (() => {});+ },+};diff --git a/sdk/tests/native-channel.test.ts b/sdk/tests/native-channel.test.tsnew file mode 100644index 000000000..1f607f851--- /dev/null+++ b/sdk/tests/native-channel.test.ts@@ -0,0 +1,226 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file The channel to an app's own native code, from the host's two entry+ * points up to what a game calls. The host carries a name and JSON; these+ * hold what the SDK makes of that: a call that is answered, one that is+ * refused, one that fails, an event, and ads as the first thing said over it.+ */+import { afterEach, describe, it, expect } from 'vitest';+import { createHostBridge, NativePlatformAdapter, NATIVE_ADS_PRELOAD, NATIVE_ADS_SHOW } from '../src/platform/native';+import type { NativeBridge } from '../src/platform/native';+import { platformCanCreateAds, platformNativeChannel, setPlatform } from '../src/platform';+import { NativeChannel } from '../src/services';++type Push = { kind: 'reply'; id: number; ok: boolean; payload: string } | { kind: 'event'; name: string; payload: string };++/** A host whose native side answers the methods given, each with JSON or by throwing a reason. */+function host(handlers: Record<string, (args: unknown) => unknown> = {}) {+ const calls: Array<{ id: number; method: string; args: string }> = [];+ const scope: Record<string, unknown> = {+ console: { log: () => {}, error: () => {}, warn: () => {} },+ setTimeout: () => 0,+ clearTimeout: () => {},+ performance: { now: () => 0 },+ TextDecoder,+ es_readAsset: () => new ArrayBuffer(4),+ es_loadImagePixels: () => ({ width: 1, height: 1, pixels: new ArrayBuffer(4) }),+ es_native_has: (method: string) => method in handlers,+ es_native_call: (id: number, method: string, args: string) => {+ if (!(method in handlers)) return false;+ calls.push({ id, method, args });+ return true;+ },+ };+ const bridge = createHostBridge(scope);+ const push = (message: Push): void => (scope.es_onNativeMessage as (m: Push) => void)(message);+ /** Answer every call made so far, the way the frame loop drains a queue. */+ const drain = (): void => {+ for (const call of calls.splice(0)) {+ try {+ const result = handlers[call.method]!(JSON.parse(call.args));+ push({ kind: 'reply', id: call.id, ok: true, payload: result === undefined ? 'null' : JSON.stringify(result) });+ } catch (error) {+ push({ kind: 'reply', id: call.id, ok: false, payload: (error as Error).message });+ }+ }+ };+ return { scope, bridge, calls, push, drain };+}++afterEach(() => {+ setPlatform(null as never);+});++describe('the host side of the channel', () => {+ it('is absent on a host that bound neither entry point', () => {+ const scope: Record<string, unknown> = {+ console: { log: () => {}, error: () => {}, warn: () => {} }, setTimeout: () => 0, clearTimeout: () => {},+ performance: { now: () => 0 }, TextDecoder,+ es_readAsset: () => new ArrayBuffer(4),+ es_loadImagePixels: () => ({ width: 1, height: 1, pixels: new ArrayBuffer(4) }),+ };+ expect(createHostBridge(scope).channel).toBeUndefined();+ expect(new NativePlatformAdapter(createHostBridge(scope)).nativeChannel()).toBeNull();+ });++ it('resolves a call with what the native side answered', async () => {+ const h = host({ 'store.buy': (args) => ({ bought: (args as { sku: string }).sku }) });+ const answer = h.bridge.channel!.call('store.buy', '{"sku":"gems"}');+ expect(h.calls).toEqual([{ id: 1, method: 'store.buy', args: '{"sku":"gems"}' }]);+ h.drain();+ await expect(answer).resolves.toBe('{"bought":"gems"}');+ });++ it('rejects at once when nothing answers to the name', async () => {+ const h = host();+ await expect(h.bridge.channel!.call('nobody.home', 'null')).rejects.toThrow(/nobody\.home.*nothing in this app answers/);+ expect(h.calls).toEqual([]);+ });++ it('rejects with the reason the native side gave, naming the call', async () => {+ const h = host({ 'store.buy': () => { throw new Error('user cancelled'); } });+ const answer = h.bridge.channel!.call('store.buy', 'null');+ h.drain();+ await expect(answer).rejects.toThrow('native "store.buy" failed: user cancelled');+ });++ it('answers concurrent calls each with its own reply, in any order', async () => {+ const h = host({ echo: (args) => args });+ const first = h.bridge.channel!.call('echo', '1');+ const second = h.bridge.channel!.call('echo', '2');+ const [a, b] = h.calls.splice(0);+ h.push({ kind: 'reply', id: b!.id, ok: true, payload: 'two' });+ h.push({ kind: 'reply', id: a!.id, ok: true, payload: 'one' });+ await expect(first).resolves.toBe('one');+ await expect(second).resolves.toBe('two');+ });++ it('ignores a second answer to a call, and an answer to no call', async () => {+ const h = host({ echo: (args) => args });+ const answer = h.bridge.channel!.call('echo', '1');+ h.push({ kind: 'reply', id: 1, ok: true, payload: 'first' });+ expect(() => h.push({ kind: 'reply', id: 1, ok: false, payload: 'again' })).not.toThrow();+ expect(() => h.push({ kind: 'reply', id: 99, ok: true, payload: 'stray' })).not.toThrow();+ await expect(answer).resolves.toBe('first');+ });+});++describe('NativeChannel', () => {+ it('is unavailable where there is no native code, and says so in the rejection', async () => {+ expect(NativeChannel.available).toBe(false);+ expect(NativeChannel.has('ads.show')).toBe(false);+ await expect(NativeChannel.call('ads.show')).rejects.toThrow(/ads\.show.*no native code/);+ expect(() => NativeChannel.on('anything', () => {})()).not.toThrow();+ });++ it('carries values, not text', async () => {+ const h = host({ sum: (args) => ({ total: (args as number[]).reduce((a, b) => a + b, 0) }), nothing: () => undefined });+ setPlatform(new NativePlatformAdapter(h.bridge));+ expect(NativeChannel.available).toBe(true);+ expect(NativeChannel.has('sum')).toBe(true);+ expect(NativeChannel.has('difference')).toBe(false);+ const total = NativeChannel.call<{ total: number }>('sum', [1, 2, 3]);+ const nothing = NativeChannel.call('nothing');+ expect(h.calls.map((c) => c.args)).toEqual(['[1,2,3]', 'null']);+ h.drain();+ await expect(total).resolves.toEqual({ total: 6 });+ await expect(nothing).resolves.toBeNull();+ });++ it('rejects an answer that is not JSON, naming the method', async () => {+ const h = host({ broken: () => 0 });+ setPlatform(new NativePlatformAdapter(h.bridge));+ const answer = NativeChannel.call('broken');+ h.push({ kind: 'reply', id: h.calls[0]!.id, ok: true, payload: '{not json' });+ await expect(answer).rejects.toThrow(/native "broken" answered with something that is not JSON/);+ });++ it('delivers an event to its listeners and to no others, until they leave', () => {+ const h = host();+ setPlatform(new NativePlatformAdapter(h.bridge));+ const restored: unknown[] = [];+ const other: unknown[] = [];+ const off = NativeChannel.on('store.restored', (data) => restored.push(data));+ NativeChannel.on('push.received', (data) => other.push(data));+ h.push({ kind: 'event', name: 'store.restored', payload: '{"sku":"gems"}' });+ expect(restored).toEqual([{ sku: 'gems' }]);+ expect(other).toEqual([]);+ off();+ h.push({ kind: 'event', name: 'store.restored', payload: '{"sku":"again"}' });+ expect(restored).toEqual([{ sku: 'gems' }]);+ });++ it('lets a listener remove itself while it is being told', () => {+ const h = host();+ setPlatform(new NativePlatformAdapter(h.bridge));+ const heard: string[] = [];+ const off = NativeChannel.on('tick', () => { heard.push('once'); off(); });+ NativeChannel.on('tick', () => heard.push('always'));+ h.push({ kind: 'event', name: 'tick', payload: 'null' });+ h.push({ kind: 'event', name: 'tick', payload: 'null' });+ expect(heard).toEqual(['once', 'always', 'always']);+ });+});++describe('ads over the channel', () => {+ it('has no ad source when the app answers for none', () => {+ const h = host({ 'store.buy': () => null });+ const adapter = new NativePlatformAdapter(h.bridge);+ setPlatform(adapter);+ expect(platformNativeChannel()).not.toBeNull();+ expect(adapter.createRewardedAd).toBeUndefined();+ expect(platformCanCreateAds()).toBe(false);+ });++ it('shows a rewarded ad and grants only what the app says was earned', async () => {+ const seen: unknown[] = [];+ let verdict: unknown = { completed: true };+ const h = host({ [NATIVE_ADS_SHOW]: (args) => { seen.push(args); return verdict; } });+ const adapter = new NativePlatformAdapter(h.bridge);+ setPlatform(adapter);+ expect(platformCanCreateAds()).toBe(true);++ const ad = adapter.createRewardedAd!('unit-1')!;+ const earned = ad.show();+ h.drain();+ await expect(earned).resolves.toEqual({ completed: true });+ expect(seen).toEqual([{ kind: 'rewarded', unitId: 'unit-1' }]);++ for (verdict of [{ completed: false }, {}, null, { completed: 'yes' }]) {+ const result = ad.show();+ h.drain();+ await expect(result).resolves.toEqual({ completed: false });+ }+ });++ it('shows an interstitial and resolves when the app says it closed', async () => {+ const seen: unknown[] = [];+ const h = host({ [NATIVE_ADS_SHOW]: (args) => { seen.push(args); return null; } });+ const adapter = new NativePlatformAdapter(h.bridge);+ const shown = adapter.createInterstitialAd!('unit-2')!.show();+ h.drain();+ await expect(shown).resolves.toBeUndefined();+ expect(seen).toEqual([{ kind: 'interstitial', unitId: 'unit-2' }]);+ });++ it('preloads through the app when it answers, and is a no-op when it does not', async () => {+ const loaded: unknown[] = [];+ const withPreload = host({ [NATIVE_ADS_SHOW]: () => null, [NATIVE_ADS_PRELOAD]: (args) => { loaded.push(args); return null; } });+ const warm = new NativePlatformAdapter(withPreload.bridge).createRewardedAd!('unit-3')!.preload();+ withPreload.drain();+ await expect(warm).resolves.toBeUndefined();+ expect(loaded).toEqual([{ kind: 'rewarded', unitId: 'unit-3' }]);++ const without = host({ [NATIVE_ADS_SHOW]: () => null });+ await expect(new NativePlatformAdapter(without.bridge).createRewardedAd!('unit-3')!.preload()).resolves.toBeUndefined();+ expect(without.calls).toEqual([]);+ });++ it('passes a no-fill on as the rejection it is', async () => {+ const h = host({ [NATIVE_ADS_SHOW]: () => { throw new Error('no fill'); } });+ const shown = new NativePlatformAdapter(h.bridge).createRewardedAd!('unit-4')!.show();+ h.drain();+ await expect(shown).rejects.toThrow('native "ads.show" failed: no fill');+ });+});diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex cfc70eed6..fc73f44ad 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -4568,6 +4568,10 @@ export const NOTED = {{"note": "A tilemap layer can be lit."},"feat(text): Text has letter spacing - Text.letterSpacing is extra px after every glyph and a negative value draws them closer; the layout always took one and no path handed it over. Retained labels, the per-frame fallback and inline images read a Text through one derivation, which gives the fallback the underline it never drew":{"note": "Text has letter spacing."},+ "feat(native): a game calls its own Java or Objective-C by name - NativeChannel.call, has and on reach the handlers an app registers (NativeChannel.register on Android, EstellaNativeChannel on iOS) with JSON both ways, and Ads works on a device once that code answers ads.show; the engine links no ad SDK":+ {"note": "A game calls its own native code by name."},+ "fix(aot): the engine digest counts TilemapLayer.lit - the field landed without it, so a packaged native game refused its own compiled systems as built against a different engine; the digest and the two conformance files are regenerated":+ {"internal": "Repairs a field added since the last release: no released build refused its compiled systems."},"feat(sky): a sky of your own shades the ground under its clouds - defineSkyEffect takes groundShadow and a second function, skyShadow(world, sun), what is left of the light at a world position, and the sky pass multiplies every surface it finds by it, as Sky Atmosphere does with its own clouds":{"note": "A sky of your own shades the ground under its clouds."},"fix(terrain): a colour map and an occlusion map lie the way the heightmap does - Terrain.colorMap, Terrain.occlusionMap and Foliage.colorMap were sampled with their rows turned over, so a picture painted to match a heightmap, a splatmap or a density map came out mirrored north to south under them; an image over an area now has its first row along the least z whoever reads it":