Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(sdk): the open data domain is a capability, and a leaderboard is a package

yhh5855492715a4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 31950ea1c..d6bd2abfa 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,6 +14,40 @@ published separately; it ships inside the editor.
## [Unreleased]
+### Changed
+
+- **The friends leaderboard is a package, not an engine service.** It moved to
+ `estella-plugin-minigame-services` alongside share and payment, and with it the
+ open data context it draws in. The engine keeps what only it can offer — the
+ capabilities the board is built from — so a third-party board is built the same
+ way ours is.
+
+ Removed from `esengine` (all `@experimental`): `Leaderboard`, `LeaderboardAPI`,
+ `createLocalLeaderboard`, `LeaderboardOptions`, `LeaderboardProvider`,
+ `LeaderboardScope`, `LeaderboardStyle`, `LocalLeaderboardOptions`. Import them
+ from the package instead, and add `open-data/index.ts` to the project with one
+ line — `import 'estella-plugin-minigame-services/open-data';` — which is what a
+ mini-game export now bundles as the context. A project that had no
+ `open-data/` directory was getting the engine's board by default; it needs that
+ file to keep one.
+
+### Added
+
+- **Host capabilities a package can reach**: `platformCanOpenData`,
+ `platformOpenDataPostMessage`, `platformOpenDataCanvas`,
+ `platformSetCloudKeyValues`, `platformCreateCanvas`, `platformDevicePixelRatio`,
+ and `createCanvasTexture` — a texture whose content is a canvas something else
+ draws on. Exported because a shipped plugin holds each one up.
+
+- **A plugin can put a button on the editor's activity bar** —
+ `ctx.activityBar.register({ id, title, icon, run })`, with the glyph as the
+ plugin's own inline SVG. The audio mixer uses it, which is how it got back the
+ rail entry it had before it became a plugin.
+
+- **`registerAction` takes a declaration**, not only a bare function — the form
+ the docs already taught, and what turns an editor text box into typed controls
+ for a game's own action.
+
## [0.51.0] - 2026-08-13
### Added
diff --git a/desktop/electron/exportMiniGame.ts b/desktop/electron/exportMiniGame.ts
index 8b98afa34..778d7cd5f 100644
--- a/desktop/electron/exportMiniGame.ts
+++ b/desktop/electron/exportMiniGame.ts
@@ -374,16 +374,13 @@ export async function exportMiniGame(profile: MiniGameExportProfile, opts: {
// the `esengine` alias is deliberately WITHHELD here: a context that
// imports the engine fails to resolve at export instead of throwing on a
// device, which is the only place that mistake would otherwise surface.
- // The project's own context wins; absent, the engine's built-in
- // leaderboard ships instead (sdk `dist/open-data.js`, already bundled to
- // one file with no imports — see sdk/src/opendata). Shipping it by default
- // is the difference between a capability and a capability someone else
- // still has to build: the context is the hardest part of a mini-game to
- // write, and a game that just wants a friends board should not have to.
+ //
+ // The project owns this file and a package may be what it imports
+ // (`estella-plugin-minigame-services/open-data` is a friends board in one
+ // line). No directory, no context — which is what asking for none means.
const openDataEntry = ['index.ts', 'index.js']
.map((f) => path.join(opts.root, OPEN_DATA_DIR, f))
- .find((f) => existsSync(f))
- ?? [path.join(opts.sdkDir, 'open-data.js')].find((f) => existsSync(f));
+ .find((f) => existsSync(f));
if (openDataEntry) {
progress({ phase: 'Bundling open data context' });
try {
diff --git a/desktop/src/playHost.ts b/desktop/src/playHost.ts
index e958d936d..8f09a7860 100644
--- a/desktop/src/playHost.ts
+++ b/desktop/src/playHost.ts
@@ -14,7 +14,7 @@
* Everything is same-origin estella:// (host, sdk, bundle, wasm, assets),
* sidestepping the custom-scheme cross-fetch ban.
*/
-import { uiPickWorld, uiWorldToScreen, screenToUiWorld, uiNodeWorldBox, createWebApp, setEditorMode, setPlayMode, enableSceneOrigins, sceneOriginOf, entityWorldBox, entityBoxCorners, CameraView, layerOrderOf, quaternionToAngle2D, initPlayRealmRuntime, getComponent, clearUserComponents, getUserComponentFingerprint, probeRegistrations, Net, MessagePortTransport, Assets, Ads, createMockAdProvider, Leaderboard, createLocalLeaderboard, registerPackagedSideModules, Input, inputEventCallbacks, isEntityVisible, setEntityVisible, hasVisibility, takeCensus } from 'esengine';
+import { uiPickWorld, uiWorldToScreen, screenToUiWorld, uiNodeWorldBox, createWebApp, setEditorMode, setPlayMode, enableSceneOrigins, sceneOriginOf, entityWorldBox, entityBoxCorners, CameraView, layerOrderOf, quaternionToAngle2D, initPlayRealmRuntime, getComponent, clearUserComponents, getUserComponentFingerprint, probeRegistrations, Net, MessagePortTransport, Assets, Ads, createMockAdProvider, registerPackagedSideModules, Input, inputEventCallbacks, isEntityVisible, setEntityVisible, hasVisibility, takeCensus } from 'esengine';
import type { App, SceneData, InputState, UICameraData } from 'esengine';
import type { ESEngineModule } from 'esengine/wasm';
import { PLAY_PROTOCOL_VERSION } from './engine/playProtocol';
@@ -581,15 +581,6 @@ async function buildAppAndRun(msg: InitMessage): Promise<void> {
// pause/audio ceremony and just skips the video.
app.getResource(Ads)?.setProvider(createMockAdProvider());
- // Same reason, harder problem: a friends leaderboard is drawn by a second JS
- // runtime that exists only on a mini-game host, so without this there is
- // nowhere to look at one until the game is on a phone. The local board runs
- // the ENGINE'S OWN renderer — the one that ships inside that runtime —
- // against an offscreen canvas and obviously-invented friends, so what you see
- // here is what will be drawn there. What it cannot stand in for is the part
- // that is genuinely the host's: real friends.
- app.getResource(Leaderboard)?.setProvider(createLocalLeaderboard());
-
// Role first, runtime second: initPlayRealmRuntime ends in app.run(), and by
// then the Net role must already be decided (see beginNet).
const netReady = beginNet(msg);
@@ -622,6 +613,12 @@ async function buildAppAndRun(msg: InitMessage): Promise<void> {
achievements: msg.achievements,
enableStats: true, // editor profiler: per-phase / per-system frame timing
});
+
+ // A friends board, rehearsed as the ad above is. AFTER the runtime init, which
+ // is where the game's own plugins install — and by NAME, because a board is a
+ // package the editor does not depend on.
+ (app.getResourceByName('Leaderboard') as { rehearse?(): void } | undefined)?.rehearse?.();
+
// Realm-local debug handle for automation/diagnostics (mirrors the headless
// host's __estellaHeadless): the editor can't reach into this OOPIF except by
// main-process frame eval, and the eval needs SOMETHING to query. getComponent
diff --git a/desktop/tests/export-wechat.test.ts b/desktop/tests/export-wechat.test.ts
index 3f1585986..0cd17717e 100644
--- a/desktop/tests/export-wechat.test.ts
+++ b/desktop/tests/export-wechat.test.ts
@@ -522,10 +522,8 @@ describe('exportGame (wechat)', () => {
describe('exportGame (wechat) — open data context', () => {
const roots: string[] = [];
- /** A minimal exportable project: one scene, one texture, stub SDK + runtime.
- * `builtIn` puts the engine's own context bundle in the stub SDK dir, the way
- * a real `dist/` carries it. */
- function scaffold(openDataSource?: string, builtIn?: string): { root: string; out: string } {
+ /** A minimal exportable project: one scene, one texture, stub SDK + runtime. */
+ function scaffold(openDataSource?: string): { root: string; out: string } {
const dir = mkdtempSync(path.join(tmpdir(), 'estella-export-opendata-'));
roots.push(dir);
mkdirSync(path.join(dir, 'assets'), { recursive: true });
@@ -539,7 +537,6 @@ describe('exportGame (wechat) — open data context', () => {
writeFileSync(path.join(dir, 'scenes', 'main.esscene.meta'), meta(SCN, 'scene'));
mkdirSync(path.join(dir, '_sdk'), { recursive: true });
writeFileSync(path.join(dir, '_sdk', 'index.wechat.js'), 'export function initWeChatRuntime(){return Promise.resolve();}\n');
- if (builtIn !== undefined) writeFileSync(path.join(dir, '_sdk', 'open-data.js'), builtIn);
mkdirSync(path.join(dir, '_wxwasm'), { recursive: true });
writeFileSync(path.join(dir, '_wxwasm', 'esengine.js'), 'module.exports = () => Promise.resolve({});');
writeFileSync(path.join(dir, '_wxwasm', 'esengine.wasm'), 'wasmbytes');
@@ -590,27 +587,22 @@ describe('exportGame (wechat) — open data context', () => {
expect(code).not.toContain('?.');
}, 60_000);
- it('ships the engine\'s built-in board when the project wrote none', async () => {
- // The context is the hardest part of a mini-game to write, and a game that
- // just wants a friends board should not have to. So the capability arrives
- // working rather than as a directory you are expected to fill.
- const { root: r, out: o } = scaffold(undefined, '/* built-in board */ globalThis.__ESTELLA_BOARD__ = 1;\n');
- const res = await exportIt(r, o);
- expect(res.ok).toBe(true);
- expect(readFileSync(path.join(o, 'open-data', 'index.js'), 'utf8')).toContain('__ESTELLA_BOARD__');
- expect(JSON.parse(readFileSync(path.join(o, 'game.json'), 'utf8')).openDataContext).toBe('open-data');
- }, 60_000);
+ it('a package can be the context, through the one line the project writes', async () => {
+ // Which is how a friends board ships without the engine carrying one: the
+ // project owns the file, a dependency owns the code, and the bundler
+ // resolves it like any other import.
+ const { root: r, out: o } = scaffold("import 'estella-plugin-fake/open-data';\n");
+ const pkg = path.join(r, 'node_modules', 'estella-plugin-fake');
+ mkdirSync(pkg, { recursive: true });
+ writeFileSync(path.join(pkg, 'package.json'), JSON.stringify({
+ name: 'estella-plugin-fake', version: '1.0.0', exports: { './open-data': './od.js' },
+ }));
+ writeFileSync(path.join(pkg, 'od.js'), 'globalThis.__PACKAGE_BOARD__ = 1;\n');
- it('the project\'s own context wins over the built-in', async () => {
- const { root: r, out: o } = scaffold(
- 'declare const wx: { onMessage(cb: (m: unknown) => void): void };\nwx.onMessage(() => { (globalThis as Record<string, unknown>).__MINE__ = 1; });\n',
- '/* built-in board */ globalThis.__ESTELLA_BOARD__ = 1;\n',
- );
const res = await exportIt(r, o);
expect(res.ok).toBe(true);
- const code = readFileSync(path.join(o, 'open-data', 'index.js'), 'utf8');
- expect(code).toContain('__MINE__');
- expect(code).not.toContain('__ESTELLA_BOARD__');
+ expect(readFileSync(path.join(o, 'open-data', 'index.js'), 'utf8')).toContain('__PACKAGE_BOARD__');
+ expect(JSON.parse(readFileSync(path.join(o, 'game.json'), 'utf8')).openDataContext).toBe('open-data');
}, 60_000);
it('a context that imports the engine fails the export, not the device', async () => {
diff --git a/docs/astro/src/content/docs/publishing/ads-sharing.mdx b/docs/astro/src/content/docs/publishing/ads-sharing.mdx
index 56b59ffdf..995e135f4 100644
--- a/docs/astro/src/content/docs/publishing/ads-sharing.mdx
+++ b/docs/astro/src/content/docs/publishing/ads-sharing.mdx
@@ -119,10 +119,21 @@ host starts beside your game, with no engine, no WebGL and no wasm in it — and
there is no channel back from that runtime to yours. So the board is drawn
*over there* and arrives here as pixels.
-The API says that out loud rather than hiding it:
+It ships as a package rather than in the engine, because a game that never opens
+one should not carry a renderer for it:
+
+```bash
+npm install estella-plugin-minigame-services
+```
+
+The API says the host's constraint out loud rather than hiding it:
```typescript
-import { defineSystem, Res, Leaderboard, UIVisual } from 'esengine';
+import { UIVisual } from 'esengine';
+import { miniGameServicesPlugin, Leaderboard } from 'estella-plugin-minigame-services';
+
+addPlugin(miniGameServicesPlugin);
+const leaderboard = app.getResource(Leaderboard);
// Your half: write your own row. It is the one cloud operation the game
// itself may do — reading anyone's, including your own, belongs to the context.
@@ -142,30 +153,37 @@ leaderboard.hide(); // clears the board and stops sampling
any package that declares none. Hide the button rather than open a panel that
stays blank.
-### What ships by default
+### The other half
+
+The project owns the context directory; the package supplies what goes in it:
+
+```typescript title="open-data/index.ts"
+import 'estella-plugin-minigame-services/open-data';
+```
-Nothing to write: the engine's own board is bundled into every mini-game export
-that does not supply one, and `Leaderboard.show()` draws it. Rows are ranked,
-the player's own row is emphasised, and a friend who has never played is left
-off rather than shown as zero.
+That is the whole file. The exporter bundles `open-data/` separately and names
+it in `game.json`; a project without one ships no context, and `available` says
+so rather than a board failing on a device.
-Style it through `show({ style })` — colours, row height, font size, whether to
-draw avatars. The canvas is a fixed size and **cannot scroll**: no pointer or
-key event reaches that runtime, so `limit` is how many rows fit, not a page.
+What arrives is a board with the rows ranked, the player's own row emphasised,
+and a friend who has never played left off rather than shown as zero. Style it
+through `show({ style })` — colours, row height, font size, avatars. The canvas
+is a fixed size and **cannot scroll**: no pointer or key event reaches that
+runtime, so `limit` is how many rows fit, not a page.
### Your own board
-Put an `open-data/index.ts` in the project and the exporter bundles that
-instead. It runs in the context, so it may **not import `esengine`** — the
-export fails if it does, which is better than finding out on a device. Inside,
-you have a 2D canvas from `wx.getSharedCanvas()`, `wx.getFriendCloudStorage()`,
-and `wx.onMessage()` carrying whatever `show()` sent.
+Write the file yourself instead of importing the package's. It runs in the
+context, so it may **not import `esengine`** — the export fails if it does,
+which is better than finding out on a device. Inside, you have a 2D canvas from
+`wx.getSharedCanvas()`, `wx.getFriendCloudStorage()`, and `wx.onMessage()`
+carrying whatever `show()` sent.
### At your desk
-Play mode installs a local board: the engine's own renderer, the same code that
+Play mode has no context at all, so the board rehearses: the same renderer that
ships inside the context, drawn on an offscreen canvas with obviously-invented
-friends. So the panel can be laid out and styled without packaging anything.
+friends. The panel can be laid out and styled without packaging anything.
What it cannot rehearse is the part that is genuinely the host's — real friends
and the sandbox they live in. Check that on a device before you ship.
diff --git a/docs/astro/src/content/docs/zh-cn/publishing/ads-sharing.mdx b/docs/astro/src/content/docs/zh-cn/publishing/ads-sharing.mdx
index 08c17d6cd..e98a17879 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
@@ -108,10 +108,21 @@ share.share({ title: '来加入我的游戏' }); // 或一次性卡片
WebGL、也没有 wasm——而且它没有回到你这边的通道。所以榜是**在那边画的**,到你
这边时已经是像素。
-API 把这件事直说,而不是遮掩:
+它以**包**的形式发布而不是待在引擎里:一个从不开排行榜的游戏,不该背着一份榜的
+渲染器。
+
+```bash
+npm install estella-plugin-minigame-services
+```
+
+API 把宿主的这条约束直说,而不是遮掩:
```typescript
-import { defineSystem, Res, Leaderboard, UIVisual } from 'esengine';
+import { UIVisual } from 'esengine';
+import { miniGameServicesPlugin, Leaderboard } from 'estella-plugin-minigame-services';
+
+addPlugin(miniGameServicesPlugin);
+const leaderboard = app.getResource(Leaderboard);
// 你这一半:写自己的那一行。这是游戏本身唯一能做的云操作——
// 读任何人的(包括你自己的)都属于开放数据域。
@@ -130,28 +141,35 @@ leaderboard.hide(); // 清空并停止采样
没有开放数据域的地方 `Leaderboard.available` 是 `false`——网页、原生,以及任何
没有声明开放数据域的包。**把按钮藏起来**,别打开一个永远空白的面板。
-### 默认就带的那份
+### 另外那一半
+
+开放数据域这个目录属于项目,里面放什么由包提供:
+
+```typescript title="open-data/index.ts"
+import 'estella-plugin-minigame-services/open-data';
+```
-不用写任何东西:引擎自带的排行榜会被打进每一个没有自备开放数据域的小游戏导出包,
-`Leaderboard.show()` 直接就能画。行会排名,玩家自己那一行会加重,**从没玩过的
-好友不会以 0 分出现**,而是不出现。
+整个文件就这一行。导出器会把 `open-data/` 单独打一个包并写进 `game.json`;项目
+里没有这个目录就不带开放数据域,`available` 会如实说没有,而不是让一块榜到设备
+上才画不出来。
-样式走 `show({ style })`——颜色、行高、字号、画不画头像。画布尺寸固定且
-**不能滚动**:没有任何指针或按键事件能到达那个运行时,所以 `limit` 是「放得下
+带来的这块榜:行会排名,玩家自己那一行会加重,**从没玩过的好友不会以 0 分出现**,
+而是不出现。样式走 `show({ style })`——颜色、行高、字号、画不画头像。画布尺寸固定
+且**不能滚动**:没有任何指针或按键事件能到达那个运行时,所以 `limit` 是「放得下
几行」,不是分页。
### 自己写一份
-在项目里放一个 `open-data/index.ts`,导出器就会改用它。它运行在开放数据域里,
-所以**不允许 import `esengine`**——真这么写会导出失败,这比到设备上才发现要好。
-在里面你有 `wx.getSharedCanvas()` 给的 2D 画布、`wx.getFriendCloudStorage()`,
-以及 `wx.onMessage()` 收到的 `show()` 发过去的内容。
+不 import 包的那份,自己写这个文件就行。它运行在开放数据域里,所以**不允许
+import `esengine`**——真这么写会导出失败,这比到设备上才发现要好。在里面你有
+`wx.getSharedCanvas()` 给的 2D 画布、`wx.getFriendCloudStorage()`,以及
+`wx.onMessage()` 收到的 `show()` 发过去的内容。
### 在你自己的桌面上
-Play 模式会装一块本地榜:跑的是**引擎自己的渲染器**,和开放数据域里那份是同一段
-代码,画在离屏画布上,用一眼就看得出是假的好友数据。所以面板的排版和配色不打包
-就能调。
+Play 模式里根本没有开放数据域,所以榜会**排演**:跑的是和开放数据域里那份同一段
+渲染代码,画在离屏画布上,用一眼就看得出是假的好友数据。所以面板的排版和配色不
+打包就能调。
它替代不了的是真正属于宿主的那部分——真实好友,以及它们所在的沙箱。发版前请在
真机上过一眼。
diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.json
index 954a0fa85..bf7d5d309 100644
--- a/docs/astro/src/data/apiStability.generated.json
+++ b/docs/astro/src/data/apiStability.generated.json
@@ -3,10 +3,10 @@
"counts": {
"public": 112,
"beta": 60,
- "experimental": 1499,
+ "experimental": 1500,
"deprecated": 3
},
- "total": 1671,
+ "total": 1672,
"subsystems": [
{
"id": "ecs",
diff --git a/plugins/minigame-services/README.md b/plugins/minigame-services/README.md
index 898ec546d..c83dde9ce 100644
--- a/plugins/minigame-services/README.md
+++ b/plugins/minigame-services/README.md
@@ -1,8 +1,9 @@
# estella-plugin-minigame-services
-The mini-game host's **share sheet** and **in-game purchase**, as Estella
-services. Both used to ship inside the engine; they live here because most games
-never open either, and because a service is exactly the shape a plugin should be.
+The mini-game host's **share sheet**, **in-game purchase** and **friends
+leaderboard**, as Estella services. All three used to ship inside the engine;
+they live here because most games open none of them, and because a service is
+exactly the shape a plugin should be.
```bash
npm install estella-plugin-minigame-services
@@ -10,7 +11,7 @@ npm install estella-plugin-minigame-services
```ts title="src/main.ts"
import { addPlugin } from 'esengine';
-import { miniGameServicesPlugin, Share, Payment } from 'estella-plugin-minigame-services';
+import { miniGameServicesPlugin, Share, Payment, Leaderboard } from 'estella-plugin-minigame-services';
addPlugin(miniGameServicesPlugin);
```
@@ -49,12 +50,48 @@ Failures reject with the host's own message and `code`, untranslated: vendors
number them differently, and a mapping invented here would be a guess your game
then branches on.
+## Leaderboard
+
+A friends board has two halves in two JS runtimes, and this package is both.
+
+**The game's half** asks for the board and wears its pixels:
+
+```ts
+const board = app.getResource(Leaderboard);
+
+// Hide the button where the host has no open data context (web, native).
+if (board.available) showLeaderboardButton();
+
+board.submit(score); // your own cloud row — the one write allowed here
+board.show({ limit: 10 }); // a REQUEST to draw; no rows ever come back
+uiVisual.texture = board.texture; // what it drew, as an engine texture handle
+board.hide();
+```
+
+**The context's half** runs in the second runtime, which has no engine, no WebGL
+and no DOM. The project owns that file; this package supplies what goes in it:
+
+```ts title="open-data/index.ts"
+import 'estella-plugin-minigame-services/open-data';
+```
+
+That directory is what the exporter bundles separately and names in `game.json`.
+Without it the host has no context, and `available` says so rather than a board
+failing on a device.
+
+In the editor's play mode there is no context at all, so the board draws against
+invented friends — the same renderer that ships, on an offscreen canvas. It is
+`rehearse()`, the editor calls it for you, and a real host always wins.
+
## Built on the public API
-Only `esengine`'s public surface: `defineResource`, the `Plugin` interface, and
-the host capability functions (`platformShare`, `platformCanShare`,
-`platformOnShareRequest`, `platformCanPay`, `platformRequestPayment`). Declare
-`esengine` a **peer** dependency if you write one of these — a copy vendored
-inside the package would be a second engine whose resources nothing can read.
+Only `esengine`'s public surface: `defineResource`, the `Plugin` interface,
+`createCanvasTexture`, and the host capability functions (`platformShare`,
+`platformCanShare`, `platformOnShareRequest`, `platformCanPay`,
+`platformRequestPayment`, `platformCanOpenData`, `platformOpenDataPostMessage`,
+`platformOpenDataCanvas`, `platformSetCloudKeyValues`, `platformCreateCanvas`,
+`platformDevicePixelRatio`). Declare `esengine` a **peer** dependency if you
+write one of these — a copy vendored inside the package would be a second engine
+whose resources nothing can read.
Apache-2.0.
diff --git a/plugins/minigame-services/package.json b/plugins/minigame-services/package.json
index 515ac3592..6885f2e93 100644
--- a/plugins/minigame-services/package.json
+++ b/plugins/minigame-services/package.json
@@ -1,14 +1,17 @@
{
"name": "estella-plugin-minigame-services",
"version": "0.1.0",
- "description": "The mini-game host's share sheet and in-game purchase, as Estella services.",
+ "description": "The mini-game host's share sheet, in-game purchase and friends leaderboard, as Estella services.",
"license": "Apache-2.0",
"type": "module",
"main": "./src/index.ts",
"types": "./src/index.ts",
- "exports": { ".": "./src/index.ts" },
+ "exports": {
+ ".": "./src/index.ts",
+ "./open-data": "./src/opendata/index.ts"
+ },
"files": ["src", "README.md"],
- "keywords": ["estella", "estella-plugin", "minigame", "wechat", "share", "payment"],
+ "keywords": ["estella", "estella-plugin", "minigame", "wechat", "share", "payment", "leaderboard"],
"scripts": { "test": "vitest run" },
"peerDependencies": { "esengine": ">=0.51" },
"devDependencies": { "esengine": "workspace:*", "vitest": "^2.1.9" }
diff --git a/plugins/minigame-services/src/index.ts b/plugins/minigame-services/src/index.ts
index 0f2bc2a91..6de451083 100644
--- a/plugins/minigame-services/src/index.ts
+++ b/plugins/minigame-services/src/index.ts
@@ -1,17 +1,25 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
- * @file index.ts — the share sheet and the purchase, as a plugin.
+ * @file index.ts — the share sheet, the purchase and the friends board.
*
- * Two resources and nothing per frame: both services are façades over host
- * capabilities, so what they cost is what the host charges when you call them.
+ * Share and payment are façades over host capabilities and cost nothing per
+ * frame. The leaderboard costs one boolean: the canvas it shows is drawn by
+ * another runtime on its own schedule, so while a board is up it has to be
+ * re-taken, and nothing can tell us when it changed.
*/
-import type { App, Plugin } from 'esengine';
+import { Schedule, defineSystem, type App, type Plugin } from 'esengine';
import { Share, ShareAPI } from './share';
import { Payment, PaymentAPI } from './payment';
+import { Leaderboard, LeaderboardAPI } from './leaderboard';
export { Share, ShareAPI, type ShareCard } from './share';
export { Payment, PaymentAPI, type PaymentRequest, type PaymentFailure } from './payment';
+export {
+ Leaderboard, LeaderboardAPI, createLocalLeaderboard,
+ type LeaderboardOptions, type LeaderboardProvider, type LeaderboardScope,
+ type LeaderboardStyle, type LocalLeaderboardOptions, type CloudPlayer,
+} from './leaderboard';
export class MiniGameServicesPlugin implements Plugin {
name = 'MiniGameServices';
@@ -19,6 +27,18 @@ export class MiniGameServicesPlugin implements Plugin {
build(app: App): void {
app.insertResource(Share, new ShareAPI());
app.insertResource(Payment, new PaymentAPI());
+ // The App is resolved per call, not captured: the wasm module is attached
+ // after the plugins have built.
+ const board = new LeaderboardAPI(() => app);
+ app.insertResource(Leaderboard, board);
+
+ // Last in the frame: the other runtime draws on its own schedule, so the
+ // freshest canvas is the one that exists after everything else has run.
+ app.addSystemToSchedule(Schedule.Last, defineSystem(
+ [],
+ () => { board.sample(); },
+ { name: 'LeaderboardSample' },
+ ));
}
}
diff --git a/sdk/src/services/leaderboard.ts b/plugins/minigame-services/src/leaderboard.ts
similarity index 82%
rename from sdk/src/services/leaderboard.ts
rename to plugins/minigame-services/src/leaderboard.ts
index 42985d8fc..a82982a26 100644
--- a/sdk/src/services/leaderboard.ts
+++ b/plugins/minigame-services/src/leaderboard.ts
@@ -2,7 +2,7 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
* @file leaderboard.ts
- * @brief The friends leaderboard as an engine service.
+ * @brief The friends leaderboard, as a package.
*
* The shape of this API is not a design choice; it is the host's constraint
* made visible. A player's friends can be READ only inside the open data
@@ -19,20 +19,22 @@
*
* An API that returned `Promise<Row[]>` would be the honest-looking one, and it
* is the one no host can implement.
+ *
+ * The other half — what draws inside the context — is `./opendata`, which this
+ * file must never import: that runtime has no engine, and the package a project
+ * points its `open-data/index.ts` at is bundled on its own.
*/
-import { defineResource } from '../ecs/resource';
import {
- platformCanOpenData, platformOpenDataCanvas, platformOpenDataPostMessage, platformSetCloudKeyValues,
- platformDevicePixelRatio, platformCreateCanvas,
-} from '../platform';
-import type { ESEngineModule } from '../wasm';
-import type { PlatformCanvas } from '../platform/types';
-import { createCanvasTexture, type CanvasTexture } from '../asset/canvasTexture';
-import type { LeaderboardScope, LeaderboardStyle, ShowMessage } from '../opendata/protocol';
-import { createBoard, type CloudPlayer, type HostCanvas } from '../opendata/board';
-import { log } from '../util/logger';
-
-export type { LeaderboardScope, LeaderboardStyle };
+ defineResource, log,
+ platformCanOpenData, platformOpenDataCanvas, platformOpenDataPostMessage,
+ platformSetCloudKeyValues, platformDevicePixelRatio, platformCreateCanvas,
+ createCanvasTexture,
+ type App, type CanvasTexture, type PlatformCanvas,
+} from 'esengine';
+import { createBoard, type CloudPlayer, type HostCanvas } from './opendata/board';
+import type { LeaderboardScope, LeaderboardStyle, ShowMessage } from './opendata/protocol';
+
+export type { LeaderboardScope, LeaderboardStyle, CloudPlayer };
/** What to draw, and how. Everything has a default a game can ignore. */
export interface LeaderboardOptions {
@@ -70,7 +72,7 @@ export class LeaderboardAPI {
private key_ = DEFAULT_KEY;
private provider_: LeaderboardProvider | null = null;
- constructor(private readonly module_: () => ESEngineModule | null) {}
+ constructor(private readonly app_: () => App | null) {}
/** Whether SOME board exists here — the host's context, or an installed
* provider. What a menu reads to hide its leaderboard button honestly. */
@@ -78,11 +80,22 @@ export class LeaderboardAPI {
return this.provider_ !== null || platformCanOpenData();
}
+ /**
+ * Draw against invented friends where this host has no open data context.
+ *
+ * The editor's play realm calls it, so a board can be looked at before the
+ * game is on a phone; a game may call it too (a web demo). A no-op where a
+ * real context exists — the real thing always wins.
+ */
+ rehearse(options?: LocalLeaderboardOptions): void {
+ if (this.available) return;
+ this.setProvider(createLocalLeaderboard(options));
+ }
+
/**
* Install (or clear with null) a {@link LeaderboardProvider} that answers
- * INSTEAD of the platform. The editor's play mode installs the local one,
- * so a board can be looked at without a device. Clearing drops the texture
- * — the canvas behind it is going away.
+ * INSTEAD of the platform — a board to look at where the host has none.
+ * Clearing drops the texture: the canvas behind it is going away.
*/
setProvider(provider: LeaderboardProvider | null): void {
if (provider === this.provider_) return;
@@ -152,15 +165,15 @@ export class LeaderboardAPI {
this.texture_?.update();
}
- /** Re-take the context's canvas. Called by the service system, once a frame
- * and only while the board is up. @internal */
+ /** Re-take the context's canvas. Called by the plugin's system, once a frame
+ * and only while the board is up. */
sample(): void {
if (!this.shown_) return;
if (!this.texture_) this.ensureTexture_();
this.texture_?.update();
}
- /** Release the GL texture. @internal */
+ /** Release the GL texture. The handle is dead afterwards. */
dispose(): void {
this.texture_?.destroy();
this.texture_ = null;
@@ -177,11 +190,11 @@ export class LeaderboardAPI {
if (this.texture_) return;
const canvas = this.provider_ ? this.provider_.canvas() : platformOpenDataCanvas();
if (!canvas) return;
- this.texture_ = createCanvasTexture(this.module_(), canvas);
+ this.texture_ = createCanvasTexture(this.app_(), canvas);
if (!this.texture_) {
// Said once, where it is actionable: the board will be a blank quad
// and nothing else explains why.
- log.warn('services', 'leaderboard: no WebGL2 context to sample the open data canvas with');
+ log.warn('leaderboard', 'no WebGL2 context to sample the open data canvas with');
}
}
}
@@ -210,15 +223,10 @@ const REHEARSAL_FRIENDS: readonly CloudPlayer[] = [
/**
* A board you can look at without a device.
*
- * It runs the ENGINE'S OWN board — the same `createBoard` that ships inside the
- * open data context — against an offscreen 2D canvas and invented friends. That
- * is the whole point: a rehearsal that drew its own approximation would tell
- * you nothing about the thing that ships. What it cannot rehearse is the part
+ * It runs the SAME board this package ships into the context, against an
+ * offscreen canvas and invented friends — a rehearsal that drew its own
+ * approximation would rehearse nothing. What it cannot stand in for is the part
* that is genuinely the host's: real friends, and the sandbox they live in.
- *
- * The cloud read answers SYNCHRONOUSLY here, where a host answers over IPC. The
- * board treats both the same (it repaints from the callback either way), and a
- * fake delay would only be a number nobody chose.
*/
export function createLocalLeaderboard(options: LocalLeaderboardOptions = {}): LeaderboardProvider {
const friends = options.friends ?? REHEARSAL_FRIENDS;
diff --git a/sdk/src/opendata/board.ts b/plugins/minigame-services/src/opendata/board.ts
similarity index 100%
rename from sdk/src/opendata/board.ts
rename to plugins/minigame-services/src/opendata/board.ts
diff --git a/sdk/src/opendata/index.ts b/plugins/minigame-services/src/opendata/index.ts
similarity index 100%
rename from sdk/src/opendata/index.ts
rename to plugins/minigame-services/src/opendata/index.ts
diff --git a/sdk/src/opendata/protocol.ts b/plugins/minigame-services/src/opendata/protocol.ts
similarity index 100%
rename from sdk/src/opendata/protocol.ts
rename to plugins/minigame-services/src/opendata/protocol.ts
diff --git a/plugins/minigame-services/tests/leaderboard.test.ts b/plugins/minigame-services/tests/leaderboard.test.ts
new file mode 100644
index 000000000..2c5237af7
--- /dev/null
+++ b/plugins/minigame-services/tests/leaderboard.test.ts
@@ -0,0 +1,254 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file The leaderboard façade over a fake host.
+ *
+ * What is worth pinning here is the shape the host forces: `show` is a request
+ * with no answer, the rows never come back, and a platform without a context
+ * says so instead of pretending. Drawing is the other runtime's job and is
+ * tested in opendata.test.ts.
+ */
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+/** The capabilities `esengine` publishes, as a host that records what it was
+ * asked. Mocked rather than installed: a platform adapter is the engine's own
+ * seam, and a package sees only what the engine exports. */
+const host = {
+ context: true as boolean,
+ cloudStore: true as boolean,
+ dpr: 2,
+ sent: [] as Record<string, unknown>[],
+ cloud: [] as Array<Readonly<Record<string, string>>>,
+ canvas: null as unknown,
+ makeCanvas: (w: number, h: number) => ({ width: w, height: h, getContext: () => null }) as unknown,
+};
+
+vi.mock('esengine', () => ({
+ defineResource: (value: unknown, name: string) => ({ value, name }),
+ log: { warn: () => {}, info: () => {}, error: () => {} },
+ platformCanOpenData: () => host.context,
+ platformOpenDataPostMessage: (message: Record<string, unknown>) => {
+ if (!host.context) return false;
+ host.sent.push(message);
+ return true;
+ },
+ platformOpenDataCanvas: () => (host.context ? host.canvas : null),
+ platformSetCloudKeyValues: (entries: Readonly<Record<string, string>>) => {
+ if (!host.cloudStore) return false;
+ host.cloud.push(entries);
+ return true;
+ },
+ platformDevicePixelRatio: () => host.dpr,
+ platformCreateCanvas: (w: number, h: number) => host.makeCanvas(w, h),
+ // No WebGL in a unit test — which is itself worth exercising: the service must
+ // stay usable and just report texture 0.
+ createCanvasTexture: () => null,
+}));
+
+const { LeaderboardAPI, createLocalLeaderboard } = await import('../src/leaderboard');
+
+beforeEach(() => {
+ host.context = true;
+ host.cloudStore = true;
+ host.dpr = 2;
+ host.sent = [];
+ host.cloud = [];
+ host.canvas = { width: 512, height: 512, getContext: () => null };
+ host.makeCanvas = (w: number, h: number) => ({ width: w, height: h, getContext: () => null });
+});
+
+const api = () => new LeaderboardAPI(() => null);
+
+describe('Leaderboard.available', () => {
+ it('is true where the host has a context', () => {
+ expect(api().available).toBe(true);
+ });
+
+ it('is false where the package declares none', () => {
+ host.context = false;
+ expect(api().available).toBe(false);
+ });
+});
+
+describe('submit', () => {
+ it('writes the score under the default key', () => {
+ expect(api().submit(4200)).toBe(true);
+ expect(host.cloud).toEqual([{ 'es.score': '4200' }]);
+ });
+
+ it('carries extra rows alongside, without letting them shadow the score', () => {
+ api().submit(7, { extra: { level: '3', 'es.score': '0' } });
+ expect(host.cloud[0]).toEqual({ level: '3', 'es.score': '7' });
+ });
+
+ it('says so when there was nowhere to write', () => {
+ host.cloudStore = false;
+ expect(api().submit(1)).toBe(false);
+ });
+
+ it('remembers the key it wrote, so show reads the same one', () => {
+ const l = api();
+ l.submit(10, { key: 'best.time' });
+ l.show();
+ expect(host.sent[0]).toMatchObject({ key: 'best.time' });
+ });
+});
+
+describe('show / hide', () => {
+ it('asks the context to draw, with the defaults spelled out', () => {
+ expect(api().show()).toBe(true);
+ expect(host.sent).toEqual([{
+ kind: 'show', key: 'es.score', scope: 'friends', limit: 20, order: 'desc', style: {}, dpr: 2,
+ }]);
+ });
+
+ it('passes the caller\'s choices through', () => {
+ api().show({ key: 'k', scope: 'group', limit: 5, order: 'asc', style: { color: '#f00' } });
+ expect(host.sent[0]).toMatchObject({ key: 'k', scope: 'group', limit: 5, order: 'asc', style: { color: '#f00' } });
+ });
+
+ it('carries the device pixel ratio, which that runtime cannot ask for', () => {
+ host.dpr = 3;
+ api().show();
+ expect(host.sent[0]).toMatchObject({ dpr: 3 });
+ });
+
+ it('is false, and sends nothing, where there is no context', () => {
+ host.context = false;
+ expect(api().show()).toBe(false);
+ expect(host.sent).toEqual([]);
+ });
+
+ it('tracks whether the board is up', () => {
+ const l = api();
+ expect(l.visible).toBe(false);
+ l.show();
+ expect(l.visible).toBe(true);
+ l.hide();
+ expect(l.visible).toBe(false);
+ });
+
+ it('hide is a no-op when nothing was shown — not a stray message', () => {
+ api().hide();
+ expect(host.sent).toEqual([]);
+ });
+
+ it('tells the context to clear', () => {
+ const l = api();
+ l.show();
+ l.hide();
+ expect(host.sent[1]).toEqual({ kind: 'hide' });
+ });
+});
+
+/**
+ * The rehearsal board. Its value is entirely in being the SAME renderer that
+ * ships inside the open data context — an approximation drawn here would tell
+ * you nothing about what appears on a phone — so what these pin is that it
+ * really does draw, and that it stands in for the platform everywhere.
+ */
+describe('the local board', () => {
+ /** A 2D context that records what was drawn on it. */
+ function recordingCanvas() {
+ const calls: Array<{ op: string; args: unknown[] }> = [];
+ const ctx = new Proxy({} as Record<string, unknown>, {
+ get: (_t, prop: string) => {
+ if (prop === 'measureText') return (s: string) => ({ width: s.length * 7 });
+ if (prop === 'canvas') return undefined;
+ return (...args: unknown[]) => { calls.push({ op: prop, args }); };
+ },
+ set: () => true,
+ });
+ return { calls, ctx };
+ }
+
+ /** 1:1 and wide enough that nothing is clipped: the clipping rule has its own
+ * test, and letting it fire here would only make this one assert the wrong thing. */
+ function drawnOn() {
+ const rec = recordingCanvas();
+ host.dpr = 1;
+ host.makeCanvas = (w: number, h: number) => ({ width: w, height: h, getContext: () => rec.ctx });
+ return rec;
+ }
+
+ it('draws the rows through the same renderer that ships', () => {
+ const rec = drawnOn();
+ host.context = false; // no open data context at all — the provider is the whole board
+ const l = api();
+ l.setProvider(createLocalLeaderboard({ width: 640 }));
+ expect(l.available).toBe(true);
+ expect(l.show()).toBe(true);
+
+ const texts = rec.calls.filter((c) => c.op === 'fillText').map((c) => String(c.args[0]));
+ // The invented friends, ranked — and the one who never played is absent,
+ // the same rule the shipped board follows because it IS that board.
+ expect(texts).toContain('Player One');
+ expect(texts).toContain('18400');
+ expect(texts).not.toContain('Never Played');
+ });
+
+ it('re-keys the invented rows to whatever key the game asked for', () => {
+ // A game with its own key would otherwise rehearse against an empty board
+ // and reasonably read that as "this is broken".
+ const rec = drawnOn();
+ const l = api();
+ l.setProvider(createLocalLeaderboard({ width: 640 }));
+ l.show({ key: 'my.own.key' });
+ expect(rec.calls.some((c) => c.op === 'fillText' && c.args[0] === '18400')).toBe(true);
+ });
+
+ it('answers `available` where the platform cannot', () => {
+ host.context = false;
+ const l = api();
+ expect(l.available).toBe(false);
+ l.setProvider(createLocalLeaderboard());
+ expect(l.available).toBe(true);
+ l.setProvider(null);
+ expect(l.available).toBe(false);
+ });
+
+ it('rehearses only where the host has nothing, and only once', () => {
+ const l = api();
+ l.rehearse();
+ // A real context wins: nothing was installed, so `show` still goes to it.
+ l.show();
+ expect(host.sent).toHaveLength(1);
+
+ host.context = false;
+ const off = api();
+ off.rehearse();
+ expect(off.available).toBe(true);
+ const board = off;
+ off.rehearse(); // second call keeps the first board
+ expect(board.available).toBe(true);
+ });
+
+ it('clears the board when the provider is swapped out', () => {
+ const l = api();
+ l.setProvider(createLocalLeaderboard());
+ l.show();
+ expect(l.visible).toBe(true);
+ // The canvas behind the texture is going away with the provider.
+ l.setProvider(null);
+ expect(l.visible).toBe(false);
+ expect(l.texture).toBe(0);
+ });
+});
+
+describe('the texture', () => {
+ it('is 0 until there is one, and the service still works', () => {
+ const l = api();
+ expect(l.texture).toBe(0);
+ expect(l.show()).toBe(true); // no WebGL2 here; the request still goes
+ expect(l.texture).toBe(0);
+ expect(() => l.sample()).not.toThrow();
+ });
+
+ it('samples nothing while the board is down', () => {
+ const l = api();
+ // Nothing to assert but the absence of a throw and of a canvas read — the
+ // point is that the per-frame system costs one boolean.
+ expect(() => l.sample()).not.toThrow();
+ expect(l.visible).toBe(false);
+ });
+});
diff --git a/sdk/tests/opendata.test.ts b/plugins/minigame-services/tests/opendata.test.ts
similarity index 100%
rename from sdk/tests/opendata.test.ts
rename to plugins/minigame-services/tests/opendata.test.ts
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index f0e37c5de..6f7221f5e 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: 112 public · 53 beta · 1384 experimental · 3 deprecated
+Symbols: 112 public · 53 beta · 1385 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -1574,6 +1574,15 @@ matchWidthOrHeight: number
scaleMode: number
```
+## CanvasTexture — interface @experimental
+```
+destroy: () => void
+handle: number
+height: number
+update: () => void
+width: number
+```
+
## CapsuleCollider — const @experimental
```
BuiltinComponentDef<CapsuleColliderData>
@@ -3239,6 +3248,11 @@ static prototype: GestureDetector
@internal _type: "get_world"
```
+## GlImageSource — type @experimental
+```
+PlatformImage | PlatformCanvas | ImageBitmap
+```
+
## GpAxis — const @public
```
(axis: number, pad?: number, scale?: number) => Binding
@@ -3667,58 +3681,6 @@ getVisibleRange: (viewport: Rect, count: number) => [start: number, end: number]
ReadableWorld & Pick<World, 'getCppRegistry' | 'getWasmModule'>
```
-## Leaderboard — const @experimental
-```
-ResourceDef<LeaderboardAPI>
-```
-
-## LeaderboardAPI — class @experimental
-```
-@internal dispose: () => void
-@internal sample: () => void
-available: boolean
-hide: () => void
-setProvider: (provider: LeaderboardProvider | null) => void
-show: (options?: LeaderboardOptions) => boolean
-submit: (score: number, options?: { key?: string; extra?: Readonly<Record<string, string>>; }) => boolean
-texture: number
-visible: boolean
-static new (module_: () => ESEngineModule | null): LeaderboardAPI
-static prototype: LeaderboardAPI
-```
-
-## LeaderboardOptions — interface @experimental
-```
-key: string | undefined
-limit: number | undefined
-order: "desc" | "asc" | undefined
-scope: LeaderboardScope | undefined
-style: LeaderboardStyle | undefined
-```
-
-## LeaderboardProvider — interface @experimental
-```
-canvas: () => PlatformCanvas | null
-post: (message: Record<string, unknown>) => void
-```
-
-## LeaderboardScope — type @experimental
-```
-'friends' | 'group'
-```
-
-## LeaderboardStyle — interface @experimental
-```
-avatars: boolean | undefined
-background: string | undefined
-color: string | undefined
-fontFamily: string | undefined
-fontSize: number | undefined
-lineColor: string | undefined
-rowHeight: number | undefined
-selfColor: string | undefined
-```
-
## Lifecycle — const @experimental
```
ResourceDef<LifecycleManager>
@@ -3927,13 +3889,6 @@ spacing: number
textureHandle: number
```
-## LocalLeaderboardOptions — interface @experimental
-```
-friends: readonly CloudPlayer[] | undefined
-height: number | undefined
-width: number | undefined
-```
-
## LocalTransform — const @experimental @deprecated
```
BuiltinComponentDef<TransformData>
@@ -9200,6 +9155,11 @@ Plugin
(opts: ButtonOptions): ButtonHandle
```
+## createCanvasTexture — function @experimental
+```
+(app: App | null | undefined, source: GlImageSource): CanvasTexture | null
+```
+
## createDialog — function @experimental
```
(opts: DialogOptions): DialogHandle
@@ -9240,11 +9200,6 @@ Plugin
(): AchievementProvider
```
-## createLocalLeaderboard — function @experimental
-```
-(options?: LocalLeaderboardOptions): LeaderboardProvider
-```
-
## createMemoryTransportPair — function @experimental
```
(options?: MemoryTransportOptions): [MemoryTransport, MemoryTransport]
@@ -10410,6 +10365,11 @@ ParticlePlugin
PerceptionPlugin
```
+## platformCanOpenData — function @experimental
+```
+(): boolean
+```
+
## platformCanPay — function @experimental
```
(): boolean
@@ -10420,6 +10380,16 @@ PerceptionPlugin
(): boolean
```
+## platformCreateCanvas — function @experimental
+```
+(width: number, height: number): PlatformCanvas
+```
+
+## platformDevicePixelRatio — function @experimental
+```
+(): number
+```
+
## platformFetch — function @experimental
```
(url: string, options?: PlatformRequestOptions): Promise<PlatformResponse>
@@ -10440,6 +10410,16 @@ PerceptionPlugin
(provide: () => PlatformShareOptions): boolean
```
+## platformOpenDataCanvas — function @experimental
+```
+(): PlatformCanvas | null
+```
+
+## platformOpenDataPostMessage — function @experimental
+```
+(message: Record<string, unknown>): boolean
+```
+
## platformReadFile — function @experimental
```
(path: string): Promise<ArrayBuffer>
@@ -10455,6 +10435,11 @@ PerceptionPlugin
(request: PlatformPaymentRequest): Promise<void>
```
+## platformSetCloudKeyValues — function @experimental
+```
+(entries: Readonly<Record<string, string>>): boolean
+```
+
## platformShare — function @experimental
```
(options: PlatformShareOptions): boolean
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index e7f09cf2e..616805c4d 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: 112 public · 58 beta · 1403 experimental · 3 deprecated
+Symbols: 112 public · 58 beta · 1404 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -1574,6 +1574,15 @@ matchWidthOrHeight: number
scaleMode: number
```
+## CanvasTexture — interface @experimental
+```
+destroy: () => void
+handle: number
+height: number
+update: () => void
+width: number
+```
+
## CapsuleCollider — const @experimental
```
BuiltinComponentDef<CapsuleColliderData>
@@ -3247,6 +3256,11 @@ static prototype: GestureDetector
@internal _type: "get_world"
```
+## GlImageSource — type @experimental
+```
+PlatformImage | PlatformCanvas | ImageBitmap
+```
+
## GpAxis — const @public
```
(axis: number, pad?: number, scale?: number) => Binding
@@ -3675,58 +3689,6 @@ getVisibleRange: (viewport: Rect, count: number) => [start: number, end: number]
ReadableWorld & Pick<World, 'getCppRegistry' | 'getWasmModule'>
```
-## Leaderboard — const @experimental
-```
-ResourceDef<LeaderboardAPI>
-```
-
-## LeaderboardAPI — class @experimental
-```
-@internal dispose: () => void
-@internal sample: () => void
-available: boolean
-hide: () => void
-setProvider: (provider: LeaderboardProvider | null) => void
-show: (options?: LeaderboardOptions) => boolean
-submit: (score: number, options?: { key?: string; extra?: Readonly<Record<string, string>>; }) => boolean
-texture: number
-visible: boolean
-static new (module_: () => ESEngineModule | null): LeaderboardAPI
-static prototype: LeaderboardAPI
-```
-
-## LeaderboardOptions — interface @experimental
-```
-key: string | undefined
-limit: number | undefined
-order: "desc" | "asc" | undefined
-scope: LeaderboardScope | undefined
-style: LeaderboardStyle | undefined
-```
-
-## LeaderboardProvider — interface @experimental
-```
-canvas: () => PlatformCanvas | null
-post: (message: Record<string, unknown>) => void
-```
-
-## LeaderboardScope — type @experimental
-```
-'friends' | 'group'
-```
-
-## LeaderboardStyle — interface @experimental
-```
-avatars: boolean | undefined
-background: string | undefined
-color: string | undefined
-fontFamily: string | undefined
-fontSize: number | undefined
-lineColor: string | undefined
-rowHeight: number | undefined
-selfColor: string | undefined
-```
-
## Lifecycle — const @experimental
```
ResourceDef<LifecycleManager>
@@ -3935,13 +3897,6 @@ spacing: number
textureHandle: number
```
-## LocalLeaderboardOptions — interface @experimental
-```
-friends: readonly CloudPlayer[] | undefined
-height: number | undefined
-width: number | undefined
-```
-
## LocalTransform — const @experimental @deprecated
```
BuiltinComponentDef<TransformData>
@@ -9408,6 +9363,11 @@ Plugin
(opts: ButtonOptions): ButtonHandle
```
+## createCanvasTexture — function @experimental
+```
+(app: App | null | undefined, source: GlImageSource): CanvasTexture | null
+```
+
## createDialog — function @experimental
```
(opts: DialogOptions): DialogHandle
@@ -9453,11 +9413,6 @@ Plugin
(): AchievementProvider
```
-## createLocalLeaderboard — function @experimental
-```
-(options?: LocalLeaderboardOptions): LeaderboardProvider
-```
-
## createMemoryTransportPair — function @experimental
```
(options?: MemoryTransportOptions): [MemoryTransport, MemoryTransport]
@@ -10653,6 +10608,11 @@ ParticlePlugin
PerceptionPlugin
```
+## platformCanOpenData — function @experimental
+```
+(): boolean
+```
+
## platformCanPay — function @experimental
```
(): boolean
@@ -10663,6 +10623,16 @@ PerceptionPlugin
(): boolean
```
+## platformCreateCanvas — function @experimental
+```
+(width: number, height: number): PlatformCanvas
+```
+
+## platformDevicePixelRatio — function @experimental
+```
+(): number
+```
+
## platformFetch — function @experimental
```
(url: string, options?: PlatformRequestOptions): Promise<PlatformResponse>
@@ -10683,6 +10653,16 @@ PerceptionPlugin
(provide: () => PlatformShareOptions): boolean
```
+## platformOpenDataCanvas — function @experimental
+```
+(): PlatformCanvas | null
+```
+
+## platformOpenDataPostMessage — function @experimental
+```
+(message: Record<string, unknown>): boolean
+```
+
## platformReadFile — function @experimental
```
(path: string): Promise<ArrayBuffer>
@@ -10698,6 +10678,11 @@ PerceptionPlugin
(request: PlatformPaymentRequest): Promise<void>
```
+## platformSetCloudKeyValues — function @experimental
+```
+(entries: Readonly<Record<string, string>>): boolean
+```
+
## platformShare — function @experimental
```
(options: PlatformShareOptions): boolean
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index e06a7513c..59fd2d4c0 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: 112 public · 55 beta · 1383 experimental · 3 deprecated
+Symbols: 112 public · 55 beta · 1384 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -1569,6 +1569,15 @@ matchWidthOrHeight: number
scaleMode: number
```
+## CanvasTexture — interface @experimental
+```
+destroy: () => void
+handle: number
+height: number
+update: () => void
+width: number
+```
+
## CapsuleCollider — const @experimental
```
BuiltinComponentDef<CapsuleColliderData>
@@ -3234,6 +3243,11 @@ static prototype: GestureDetector
@internal _type: "get_world"
```
+## GlImageSource — type @experimental
+```
+PlatformImage | PlatformCanvas | ImageBitmap
+```
+
## GpAxis — const @public
```
(axis: number, pad?: number, scale?: number) => Binding
@@ -3662,58 +3676,6 @@ getVisibleRange: (viewport: Rect, count: number) => [start: number, end: number]
ReadableWorld & Pick<World, 'getCppRegistry' | 'getWasmModule'>
```
-## Leaderboard — const @experimental
-```
-ResourceDef<LeaderboardAPI>
-```
-
-## LeaderboardAPI — class @experimental
-```
-@internal dispose: () => void
-@internal sample: () => void
-available: boolean
-hide: () => void
-setProvider: (provider: LeaderboardProvider | null) => void
-show: (options?: LeaderboardOptions) => boolean
-submit: (score: number, options?: { key?: string; extra?: Readonly<Record<string, string>>; }) => boolean
-texture: number
-visible: boolean
-static new (module_: () => ESEngineModule | null): LeaderboardAPI
-static prototype: LeaderboardAPI
-```
-
-## LeaderboardOptions — interface @experimental
-```
-key: string | undefined
-limit: number | undefined
-order: "desc" | "asc" | undefined
-scope: LeaderboardScope | undefined
-style: LeaderboardStyle | undefined
-```
-
-## LeaderboardProvider — interface @experimental
-```
-canvas: () => PlatformCanvas | null
-post: (message: Record<string, unknown>) => void
-```
-
-## LeaderboardScope — type @experimental
-```
-'friends' | 'group'
-```
-
-## LeaderboardStyle — interface @experimental
-```
-avatars: boolean | undefined
-background: string | undefined
-color: string | undefined
-fontFamily: string | undefined
-fontSize: number | undefined
-lineColor: string | undefined
-rowHeight: number | undefined
-selfColor: string | undefined
-```
-
## Lifecycle — const @experimental
```
ResourceDef<LifecycleManager>
@@ -3922,13 +3884,6 @@ spacing: number
textureHandle: number
```
-## LocalLeaderboardOptions — interface @experimental
-```
-friends: readonly CloudPlayer[] | undefined
-height: number | undefined
-width: number | undefined
-```
-
## LocalTransform — const @experimental @deprecated
```
BuiltinComponentDef<TransformData>
@@ -9195,6 +9150,11 @@ Plugin
(opts: ButtonOptions): ButtonHandle
```
+## createCanvasTexture — function @experimental
+```
+(app: App | null | undefined, source: GlImageSource): CanvasTexture | null
+```
+
## createDialog — function @experimental
```
(opts: DialogOptions): DialogHandle
@@ -9235,11 +9195,6 @@ Plugin
(): AchievementProvider
```
-## createLocalLeaderboard — function @experimental
-```
-(options?: LocalLeaderboardOptions): LeaderboardProvider
-```
-
## createMemoryTransportPair — function @experimental
```
(options?: MemoryTransportOptions): [MemoryTransport, MemoryTransport]
@@ -10415,6 +10370,11 @@ ParticlePlugin
PerceptionPlugin
```
+## platformCanOpenData — function @experimental
+```
+(): boolean
+```
+
## platformCanPay — function @experimental
```
(): boolean
@@ -10425,6 +10385,16 @@ PerceptionPlugin
(): boolean
```
+## platformCreateCanvas — function @experimental
+```
+(width: number, height: number): PlatformCanvas
+```
+
+## platformDevicePixelRatio — function @experimental
+```
+(): number
+```
+
## platformFetch — function @experimental
```
(url: string, options?: PlatformRequestOptions): Promise<PlatformResponse>
@@ -10445,6 +10415,16 @@ PerceptionPlugin
(provide: () => PlatformShareOptions): boolean
```
+## platformOpenDataCanvas — function @experimental
+```
+(): PlatformCanvas | null
+```
+
+## platformOpenDataPostMessage — function @experimental
+```
+(message: Record<string, unknown>): boolean
+```
+
## platformReadFile — function @experimental
```
(path: string): Promise<ArrayBuffer>
@@ -10460,6 +10440,11 @@ PerceptionPlugin
(request: PlatformPaymentRequest): Promise<void>
```
+## platformSetCloudKeyValues — function @experimental
+```
+(entries: Readonly<Record<string, string>>): boolean
+```
+
## platformShare — function @experimental
```
(options: PlatformShareOptions): boolean
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 8b9d131fd..3d01fd08f 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: 112 public · 53 beta · 1404 experimental · 3 deprecated
+Symbols: 112 public · 53 beta · 1405 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -1569,6 +1569,15 @@ matchWidthOrHeight: number
scaleMode: number
```
+## CanvasTexture — interface @experimental
+```
+destroy: () => void
+handle: number
+height: number
+update: () => void
+width: number
+```
+
## CapsuleCollider — const @experimental
```
BuiltinComponentDef<CapsuleColliderData>
@@ -3234,6 +3243,11 @@ static prototype: GestureDetector
@internal _type: "get_world"
```
+## GlImageSource — type @experimental
+```
+PlatformImage | PlatformCanvas | ImageBitmap
+```
+
## GpAxis — const @public
```
(axis: number, pad?: number, scale?: number) => Binding
@@ -3662,58 +3676,6 @@ getVisibleRange: (viewport: Rect, count: number) => [start: number, end: number]
ReadableWorld & Pick<World, 'getCppRegistry' | 'getWasmModule'>
```
-## Leaderboard — const @experimental
-```
-ResourceDef<LeaderboardAPI>
-```
-
-## LeaderboardAPI — class @experimental
-```
-@internal dispose: () => void
-@internal sample: () => void
-available: boolean
-hide: () => void
-setProvider: (provider: LeaderboardProvider | null) => void
-show: (options?: LeaderboardOptions) => boolean
-submit: (score: number, options?: { key?: string; extra?: Readonly<Record<string, string>>; }) => boolean
-texture: number
-visible: boolean
-static new (module_: () => ESEngineModule | null): LeaderboardAPI
-static prototype: LeaderboardAPI
-```
-
-## LeaderboardOptions — interface @experimental
-```
-key: string | undefined
-limit: number | undefined
-order: "desc" | "asc" | undefined
-scope: LeaderboardScope | undefined
-style: LeaderboardStyle | undefined
-```
-
-## LeaderboardProvider — interface @experimental
-```
-canvas: () => PlatformCanvas | null
-post: (message: Record<string, unknown>) => void
-```
-
-## LeaderboardScope — type @experimental
-```
-'friends' | 'group'
-```
-
-## LeaderboardStyle — interface @experimental
-```
-avatars: boolean | undefined
-background: string | undefined
-color: string | undefined
-fontFamily: string | undefined
-fontSize: number | undefined
-lineColor: string | undefined
-rowHeight: number | undefined
-selfColor: string | undefined
-```
-
## Lifecycle — const @experimental
```
ResourceDef<LifecycleManager>
@@ -3922,13 +3884,6 @@ spacing: number
textureHandle: number
```
-## LocalLeaderboardOptions — interface @experimental
-```
-friends: readonly CloudPlayer[] | undefined
-height: number | undefined
-width: number | undefined
-```
-
## LocalTransform — const @experimental @deprecated
```
BuiltinComponentDef<TransformData>
@@ -9440,6 +9395,11 @@ Plugin
(opts: ButtonOptions): ButtonHandle
```
+## createCanvasTexture — function @experimental
+```
+(app: App | null | undefined, source: GlImageSource): CanvasTexture | null
+```
+
## createDialog — function @experimental
```
(opts: DialogOptions): DialogHandle
@@ -9480,11 +9440,6 @@ Plugin
(): AchievementProvider
```
-## createLocalLeaderboard — function @experimental
-```
-(options?: LocalLeaderboardOptions): LeaderboardProvider
-```
-
## createMemoryTransportPair — function @experimental
```
(options?: MemoryTransportOptions): [MemoryTransport, MemoryTransport]
@@ -10665,6 +10620,11 @@ ParticlePlugin
PerceptionPlugin
```
+## platformCanOpenData — function @experimental
+```
+(): boolean
+```
+
## platformCanPay — function @experimental
```
(): boolean
@@ -10675,6 +10635,16 @@ PerceptionPlugin
(): boolean
```
+## platformCreateCanvas — function @experimental
+```
+(width: number, height: number): PlatformCanvas
+```
+
+## platformDevicePixelRatio — function @experimental
+```
+(): number
+```
+
## platformFetch — function @experimental
```
(url: string, options?: PlatformRequestOptions): Promise<PlatformResponse>
@@ -10695,6 +10665,16 @@ PerceptionPlugin
(provide: () => PlatformShareOptions): boolean
```
+## platformOpenDataCanvas — function @experimental
+```
+(): PlatformCanvas | null
+```
+
+## platformOpenDataPostMessage — function @experimental
+```
+(message: Record<string, unknown>): boolean
+```
+
## platformReadFile — function @experimental
```
(path: string): Promise<ArrayBuffer>
@@ -10710,6 +10690,11 @@ PerceptionPlugin
(request: PlatformPaymentRequest): Promise<void>
```
+## platformSetCloudKeyValues — function @experimental
+```
+(entries: Readonly<Record<string, string>>): boolean
+```
+
## platformShare — function @experimental
```
(options: PlatformShareOptions): boolean
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index db786884a..43560aa5a 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: 112 public · 53 beta · 1394 experimental · 3 deprecated
+Symbols: 112 public · 53 beta · 1395 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -1569,6 +1569,15 @@ matchWidthOrHeight: number
scaleMode: number
```
+## CanvasTexture — interface @experimental
+```
+destroy: () => void
+handle: number
+height: number
+update: () => void
+width: number
+```
+
## CapsuleCollider — const @experimental
```
BuiltinComponentDef<CapsuleColliderData>
@@ -3234,6 +3243,11 @@ static prototype: GestureDetector
@internal _type: "get_world"
```
+## GlImageSource — type @experimental
+```
+PlatformImage | PlatformCanvas | ImageBitmap
+```
+
## GpAxis — const @public
```
(axis: number, pad?: number, scale?: number) => Binding
@@ -3669,58 +3683,6 @@ getVisibleRange: (viewport: Rect, count: number) => [start: number, end: number]
ReadableWorld & Pick<World, 'getCppRegistry' | 'getWasmModule'>
```
-## Leaderboard — const @experimental
-```
-ResourceDef<LeaderboardAPI>
-```
-
-## LeaderboardAPI — class @experimental
-```
-@internal dispose: () => void
-@internal sample: () => void
-available: boolean
-hide: () => void
-setProvider: (provider: LeaderboardProvider | null) => void
-show: (options?: LeaderboardOptions) => boolean
-submit: (score: number, options?: { key?: string; extra?: Readonly<Record<string, string>>; }) => boolean
-texture: number
-visible: boolean
-static new (module_: () => ESEngineModule | null): LeaderboardAPI
-static prototype: LeaderboardAPI
-```
-
-## LeaderboardOptions — interface @experimental
-```
-key: string | undefined
-limit: number | undefined
-order: "desc" | "asc" | undefined
-scope: LeaderboardScope | undefined
-style: LeaderboardStyle | undefined
-```
-
-## LeaderboardProvider — interface @experimental
-```
-canvas: () => PlatformCanvas | null
-post: (message: Record<string, unknown>) => void
-```
-
-## LeaderboardScope — type @experimental
-```
-'friends' | 'group'
-```
-
-## LeaderboardStyle — interface @experimental
-```
-avatars: boolean | undefined
-background: string | undefined
-color: string | undefined
-fontFamily: string | undefined
-fontSize: number | undefined
-lineColor: string | undefined
-rowHeight: number | undefined
-selfColor: string | undefined
-```
-
## Lifecycle — const @experimental
```
ResourceDef<LifecycleManager>
@@ -3929,13 +3891,6 @@ spacing: number
textureHandle: number
```
-## LocalLeaderboardOptions — interface @experimental
-```
-friends: readonly CloudPlayer[] | undefined
-height: number | undefined
-width: number | undefined
-```
-
## LocalTransform — const @experimental @deprecated
```
BuiltinComponentDef<TransformData>
@@ -9222,6 +9177,11 @@ Plugin
(opts: ButtonOptions): ButtonHandle
```
+## createCanvasTexture — function @experimental
+```
+(app: App | null | undefined, source: GlImageSource): CanvasTexture | null
+```
+
## createDialog — function @experimental
```
(opts: DialogOptions): DialogHandle
@@ -9262,11 +9222,6 @@ Plugin
(): AchievementProvider
```
-## createLocalLeaderboard — function @experimental
-```
-(options?: LocalLeaderboardOptions): LeaderboardProvider
-```
-
## createMemoryTransportPair — function @experimental
```
(options?: MemoryTransportOptions): [MemoryTransport, MemoryTransport]
@@ -10437,6 +10392,11 @@ ParticlePlugin
PerceptionPlugin
```
+## platformCanOpenData — function @experimental
+```
+(): boolean
+```
+
## platformCanPay — function @experimental
```
(): boolean
@@ -10447,6 +10407,16 @@ PerceptionPlugin
(): boolean
```
+## platformCreateCanvas — function @experimental
+```
+(width: number, height: number): PlatformCanvas
+```
+
+## platformDevicePixelRatio — function @experimental
+```
+(): number
+```
+
## platformFetch — function @experimental
```
(url: string, options?: PlatformRequestOptions): Promise<PlatformResponse>
@@ -10467,6 +10437,16 @@ PerceptionPlugin
(provide: () => PlatformShareOptions): boolean
```
+## platformOpenDataCanvas — function @experimental
+```
+(): PlatformCanvas | null
+```
+
+## platformOpenDataPostMessage — function @experimental
+```
+(message: Record<string, unknown>): boolean
+```
+
## platformReadFile — function @experimental
```
(path: string): Promise<ArrayBuffer>
@@ -10482,6 +10462,11 @@ PerceptionPlugin
(request: PlatformPaymentRequest): Promise<void>
```
+## platformSetCloudKeyValues — function @experimental
+```
+(entries: Readonly<Record<string, string>>): boolean
+```
+
## platformShare — function @experimental
```
(options: PlatformShareOptions): boolean
diff --git a/sdk/rolldown.config.js b/sdk/rolldown.config.js
index e392fd810..e96fc9d59 100644
--- a/sdk/rolldown.config.js
+++ b/sdk/rolldown.config.js
@@ -91,17 +91,6 @@ export default defineConfig([
plugins: [preserveViteIgnore()],
treeshake,
},
- {
- // The built-in leaderboard, for the open data context — a SECOND JS
- // runtime with no WebGL, no wasm and almost none of the host API. It
- // ships as its own single file because the exporter bundles it into the
- // game package separately, and because nothing here may reach the
- // engine: one file with no imports is the shape that cannot.
- input: 'src/opendata/index.ts',
- output: { file: 'dist/open-data.js', format: 'cjs', sourcemap: false, minify },
- plugins: [preserveViteIgnore()],
- treeshake,
- },
{
input: 'src/index.node.ts',
output: { file: 'dist/index.node.js', format: 'esm', sourcemap: true, minify },
diff --git a/sdk/src/asset/canvasTexture.ts b/sdk/src/asset/canvasTexture.ts
index 40455064d..be22640ea 100644
--- a/sdk/src/asset/canvasTexture.ts
+++ b/sdk/src/asset/canvasTexture.ts
@@ -18,7 +18,7 @@
* (nothing tiles a leaderboard), and `update()`.
*/
import { requireResourceManager } from '../wasm/resourceManager';
-import type { ESEngineModule } from '../wasm';
+import type { App } from '../app/app';
import { findWebGL2Context } from './loaders/TextureLoader';
import { uploadBoundTextureImage, applyBoundTextureSampling, type GlImageSource } from './glTextureUpload';
@@ -39,15 +39,16 @@ export interface CanvasTexture {
/**
* Wrap `source` in an engine texture and take its content once.
*
- * Returns null where there is no WebGL2 context to upload through — the native
- * backend and any host still booting. That is a real answer, not a failure: the
- * only caller is a leaderboard, which has already asked whether this platform
- * has an open data context at all.
+ * Null where there is no WebGL2 context to upload through (the native backend,
+ * a host still booting) — an answer, not a failure. Takes the App because the
+ * module behind it is engine-internal, and a service that samples someone
+ * else's canvas has an App and should need nothing more.
*/
export function createCanvasTexture(
- module: ESEngineModule | null | undefined,
+ app: App | null | undefined,
source: GlImageSource,
): CanvasTexture | null {
+ const module = app?.wasmModule;
const gl = findWebGL2Context(module?.GL);
if (!gl || !module) return null;
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.ts
index 54f133ba3..d9245dd41 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -103,6 +103,12 @@ export {
export { setTextureBudget, getResourceStats, trimTextureCache, type ResourceStats } from './wasm/resourceManager';
+/** A texture whose content is a canvas SOMETHING ELSE draws on, re-taken on
+ * demand — the seam a service outside the engine needs to put another
+ * runtime's pixels (an open data context, a host overlay) on a quad. */
+export { createCanvasTexture, type CanvasTexture } from './asset/canvasTexture';
+export type { GlImageSource } from './asset/glTextureUpload';
+
// =============================================================================
// Scene
// =============================================================================
@@ -427,13 +433,11 @@ export {
export {
Achievements, AchievementsAPI, createLocalAchievements,
Ads, AdsAPI, createMockAdProvider, createTakeover,
- Leaderboard, LeaderboardAPI, createLocalLeaderboard,
Identity, IdentityAPI,
ServicesPlugin, servicesPlugin,
type AchievementProvider,
type AdProvider, type MockAdProviderOptions, type Takeover, type TakeoverHost,
- type LeaderboardOptions, type LeaderboardProvider, type LeaderboardScope,
- type LeaderboardStyle, type LocalLeaderboardOptions, type LoginResult,
+ type LoginResult,
} from './services';
// =============================================================================
diff --git a/sdk/src/core-sys.ts b/sdk/src/core-sys.ts
index 025b71405..3a0a72790 100644
--- a/sdk/src/core-sys.ts
+++ b/sdk/src/core-sys.ts
@@ -116,6 +116,15 @@ export {
platformOnShareRequest,
platformCanPay,
platformRequestPayment,
+ // The open data domain: the runtime holding the player's friends, the canvas
+ // it draws on, the one-way channel to it, and this player's own cloud row —
+ // what a friends leaderboard is made of, and unreachable from a package.
+ platformCanOpenData,
+ platformOpenDataPostMessage,
+ platformOpenDataCanvas,
+ platformSetCloudKeyValues,
+ platformCreateCanvas,
+ platformDevicePixelRatio,
} from './platform';
export type { PlatformShareOptions, PlatformPaymentRequest } from './platform/types';
diff --git a/sdk/src/services/index.ts b/sdk/src/services/index.ts
index a9fbca9ac..6f48b4b4f 100644
--- a/sdk/src/services/index.ts
+++ b/sdk/src/services/index.ts
@@ -5,11 +5,6 @@ export {
type AdProvider, type MockAdProviderOptions,
} from './ads';
export { createTakeover, type Takeover, type TakeoverHost } from './takeover';
-export {
- Leaderboard, LeaderboardAPI, createLocalLeaderboard,
- type LeaderboardOptions, type LeaderboardProvider, type LeaderboardScope,
- type LeaderboardStyle, type LocalLeaderboardOptions,
-} from './leaderboard';
export {
Achievements, AchievementsAPI, createLocalAchievements, type AchievementProvider,
} from './achievements';
diff --git a/sdk/src/services/servicesPlugin.ts b/sdk/src/services/servicesPlugin.ts
index e92cf95b6..dfb029ee4 100644
--- a/sdk/src/services/servicesPlugin.ts
+++ b/sdk/src/services/servicesPlugin.ts
@@ -2,14 +2,12 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
* @file servicesPlugin.ts
- * @brief Installs the platform-services resources (Ads, Share, Leaderboard).
+ * @brief Installs the platform-services resources (Ads, Achievements, Identity).
*
- * Resources, and one system that does nothing until it has to. Ads and Share
- * cost nothing per frame; the leaderboard has to re-take the open data
- * context's canvas while it is on screen, because that canvas is drawn by
- * another runtime and the engine has no way to be told it changed. So it is
- * sampled — but only between `show` and `hide`, which on every other frame is
- * one boolean.
+ * What is here is what the ENGINE owes a game on every platform. A service that
+ * only some hosts have — a share sheet, a purchase, a friends board — is a
+ * package (`estella-plugin-minigame-services`), built on the same platform
+ * capabilities this file uses.
*
* The ads service is handed the app's clock and the audio device as two narrow
* hooks, so a fullscreen takeover can pause the game it covers without the
@@ -17,9 +15,7 @@
*/
import type { App, Plugin } from '../app/app';
import { Audio } from '../audio';
-import { Schedule, defineSystem } from '../ecs/system';
import { Ads, AdsAPI } from './ads';
-import { Leaderboard, LeaderboardAPI } from './leaderboard';
import { Achievements, AchievementsAPI } from './achievements';
import { Identity, IdentityAPI } from './identity';
import { createTakeover } from './takeover';
@@ -51,18 +47,6 @@ export class ServicesPlugin implements Plugin {
});
app.insertResource(Achievements, new AchievementsAPI());
app.insertResource(Identity, new IdentityAPI());
- // Resolved per call rather than captured: the module is attached by
- // connectCpp, which can run after the plugins have built.
- app.insertResource(Leaderboard, new LeaderboardAPI(() => app.wasmModule));
-
- // Last in the frame: the other runtime draws on its own schedule, so
- // the freshest canvas is the one that exists after everything else has
- // run. Costs one boolean on a frame with no board up.
- app.addSystemToSchedule(Schedule.Last, defineSystem(
- [],
- () => { app.getResource(Leaderboard)?.sample(); },
- { name: 'LeaderboardSample' },
- ));
}
}
diff --git a/sdk/tests/canvas-texture.test.ts b/sdk/tests/canvas-texture.test.ts
index e7d6fe388..dd126162a 100644
--- a/sdk/tests/canvas-texture.test.ts
+++ b/sdk/tests/canvas-texture.test.ts
@@ -12,6 +12,7 @@ import { initResourceManager, shutdownResourceManager } from '../src/wasm/resour
import { setLinearColorSpace } from '../src/ecs/env';
import { createCanvasTexture } from '../src/asset/canvasTexture';
import type { ESEngineModule } from '../src/wasm';
+import type { App } from '../src/app/app';
const SRGB8_ALPHA8 = 0x8c43;
const RGBA = 0x1908;
@@ -41,9 +42,10 @@ function makeGl() {
};
}
-/** A module whose GL registry hands out ids, with `gl` as the live context. */
-function makeModule(gl: ReturnType<typeof makeGl>): ESEngineModule {
- return {
+/** An App whose module's GL registry hands out ids, with `gl` as the live
+ * context — the App is what a caller has, so it is what this takes. */
+function makeApp(gl: ReturnType<typeof makeGl>): App {
+ const module = {
GL: {
currentContext: { GLctx: gl },
contexts: [],
@@ -51,6 +53,7 @@ function makeModule(gl: ReturnType<typeof makeGl>): ESEngineModule {
textures: {} as Record<number, WebGLTexture>,
},
} as unknown as ESEngineModule;
+ return { wasmModule: module } as unknown as App;
}
/** A stand-in for the shared canvas: something with a size that can change. */
@@ -71,7 +74,7 @@ afterEach(() => {
describe('createCanvasTexture', () => {
it('takes the source once and registers it as an engine texture', () => {
const gl = makeGl();
- const tex = createCanvasTexture(makeModule(gl), makeSource(256, 128))!;
+ const tex = createCanvasTexture(makeApp(gl), makeSource(256, 128))!;
expect(tex.handle).toBe(42);
expect(tex.width).toBe(256);
expect(tex.height).toBe(128);
@@ -81,7 +84,7 @@ describe('createCanvasTexture', () => {
it('keeps the handle across a re-take — a component is holding it', () => {
const gl = makeGl();
- const tex = createCanvasTexture(makeModule(gl), makeSource(64, 64))!;
+ const tex = createCanvasTexture(makeApp(gl), makeSource(64, 64))!;
const before = tex.handle;
tex.update();
tex.update();
@@ -93,7 +96,7 @@ describe('createCanvasTexture', () => {
it('follows the source when it is resized', () => {
const gl = makeGl();
const source = makeSource(64, 64) as { width: number; height: number };
- const tex = createCanvasTexture(makeModule(gl), source as never)!;
+ const tex = createCanvasTexture(makeApp(gl), source as never)!;
source.width = 320;
source.height = 200;
tex.update();
@@ -103,7 +106,7 @@ describe('createCanvasTexture', () => {
it('uploads in the engine\'s orientation, un-premultiplied, and leaves the flag off', () => {
const gl = makeGl();
- createCanvasTexture(makeModule(gl), makeSource(8, 8));
+ createCanvasTexture(makeApp(gl), makeSource(8, 8));
const flips = gl.pixelStorei.mock.calls.filter((c) => c[0] === UNPACK_FLIP_Y_WEBGL);
// Set for the upload, then restored — every other uploader shares this
// context and none of them asks for a flip they did not set.
@@ -112,18 +115,18 @@ describe('createCanvasTexture', () => {
it('is sRGB-encoded in the linear pipeline and plain RGBA in gamma', () => {
const gamma = makeGl();
- createCanvasTexture(makeModule(gamma), makeSource(8, 8));
+ createCanvasTexture(makeApp(gamma), makeSource(8, 8));
expect(gamma.texImage2D.mock.calls[0][2]).toBe(RGBA);
setLinearColorSpace(true);
const linear = makeGl();
- createCanvasTexture(makeModule(linear), makeSource(8, 8));
+ createCanvasTexture(makeApp(linear), makeSource(8, 8));
expect(linear.texImage2D.mock.calls[0][2]).toBe(SRGB8_ALPHA8);
});
it('has no mipmaps and does not tile — a chain per frame is waste, and nothing tiles a panel', () => {
const gl = makeGl();
- createCanvasTexture(makeModule(gl), makeSource(8, 8));
+ createCanvasTexture(makeApp(gl), makeSource(8, 8));
expect(gl.generateMipmap).not.toHaveBeenCalled();
const minFilter = gl.texParameteri.mock.calls.find((c) => c[1] === TEXTURE_MIN_FILTER);
expect(minFilter?.[2]).toBe(LINEAR);
@@ -134,7 +137,7 @@ describe('createCanvasTexture', () => {
it('sets sampler state once, not on every re-take', () => {
const gl = makeGl();
- const tex = createCanvasTexture(makeModule(gl), makeSource(8, 8))!;
+ const tex = createCanvasTexture(makeApp(gl), makeSource(8, 8))!;
const afterCreate = gl.texParameteri.mock.calls.length;
tex.update();
expect(gl.texParameteri.mock.calls.length).toBe(afterCreate);
@@ -147,11 +150,12 @@ describe('createCanvasTexture', () => {
it('releases the GL texture on destroy, and a re-take afterwards is a no-op', () => {
const gl = makeGl();
- const module = makeModule(gl);
- const tex = createCanvasTexture(module, makeSource(8, 8))!;
+ const app = makeApp(gl);
+ const tex = createCanvasTexture(app, makeSource(8, 8))!;
tex.destroy();
expect(gl.deleteTexture).toHaveBeenCalledTimes(1);
- expect((module.GL as unknown as { textures: Record<number, unknown> }).textures[7]).toBeUndefined();
+ const gpu = app.wasmModule!.GL as unknown as { textures: Record<number, unknown> };
+ expect(gpu.textures[7]).toBeUndefined();
const uploads = gl.texImage2D.mock.calls.length;
tex.update();
tex.destroy();
diff --git a/sdk/tests/leaderboard.test.ts b/sdk/tests/leaderboard.test.ts
deleted file mode 100644
index 400a13b3c..000000000
--- a/sdk/tests/leaderboard.test.ts
+++ /dev/null
@@ -1,239 +0,0 @@
-// SPDX-License-Identifier: Apache-2.0
-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-/**
- * @file The leaderboard façade over a fake host.
- *
- * What is worth pinning here is the shape the host forces: `show` is a request
- * with no answer, the rows never come back, and a platform without a context
- * says so instead of pretending. Drawing is the other runtime's job and is
- * tested in opendata.test.ts.
- */
-import { describe, it, expect, beforeEach, vi } from 'vitest';
-import { LeaderboardAPI, createLocalLeaderboard } from '../src/services/leaderboard';
-import { setPlatform } from '../src/platform/base';
-import type { PlatformAdapter } from '../src/platform/types';
-
-/** A platform with — or without — an open data context. */
-function platform(over: Partial<PlatformAdapter> = {}): {
- sent: Record<string, unknown>[];
- cloud: Array<Readonly<Record<string, string>>>;
-} {
- const sent: Record<string, unknown>[] = [];
- const cloud: Array<Readonly<Record<string, string>>> = [];
- setPlatform({
- name: 'wechat',
- family: 'minigame',
- devicePixelRatio: () => 2,
- openDataPostMessage: (m: Record<string, unknown>) => { sent.push(m); },
- openDataCanvas: () => ({ width: 512, height: 512, getContext: () => null }),
- createCanvas: (w: number, h: number) => ({ width: w, height: h, getContext: () => null }),
- setCloudKeyValues: (kv: Readonly<Record<string, string>>) => { cloud.push(kv); return true; },
- ...over,
- } as unknown as PlatformAdapter);
- return { sent, cloud };
-}
-
-// No wasm module in a unit test, so no texture is ever created — which is
-// itself worth exercising: the service must stay usable and just report 0.
-const api = (): LeaderboardAPI => new LeaderboardAPI(() => null);
-
-describe('Leaderboard.available', () => {
- beforeEach(() => { vi.restoreAllMocks(); });
-
- it('is true where the host hands back a canvas', () => {
- platform();
- expect(api().available).toBe(true);
- });
-
- it('is false where the package declares no context', () => {
- platform({ openDataCanvas: () => null });
- expect(api().available).toBe(false);
- });
-
- it('is false on a platform with no such capability at all', () => {
- platform({ openDataPostMessage: undefined, openDataCanvas: undefined });
- expect(api().available).toBe(false);
- });
-});
-
-describe('submit', () => {
- it('writes the score under the default key', () => {
- const { cloud } = platform();
- expect(api().submit(4200)).toBe(true);
- expect(cloud).toEqual([{ 'es.score': '4200' }]);
- });
-
- it('carries extra rows alongside, without letting them shadow the score', () => {
- const { cloud } = platform();
- api().submit(7, { extra: { level: '3', 'es.score': '0' } });
- expect(cloud[0]).toEqual({ level: '3', 'es.score': '7' });
- });
-
- it('says so when there was nowhere to write', () => {
- platform({ setCloudKeyValues: undefined });
- expect(api().submit(1)).toBe(false);
- });
-
- it('remembers the key it wrote, so show reads the same one', () => {
- const { sent } = platform();
- const l = api();
- l.submit(10, { key: 'best.time' });
- l.show();
- expect(sent[0]).toMatchObject({ key: 'best.time' });
- });
-});
-
-describe('show / hide', () => {
- it('asks the context to draw, with the defaults spelled out', () => {
- const { sent } = platform();
- expect(api().show()).toBe(true);
- expect(sent).toEqual([{
- kind: 'show', key: 'es.score', scope: 'friends', limit: 20, order: 'desc', style: {}, dpr: 2,
- }]);
- });
-
- it('passes the caller\'s choices through', () => {
- const { sent } = platform();
- api().show({ key: 'k', scope: 'group', limit: 5, order: 'asc', style: { color: '#f00' } });
- expect(sent[0]).toMatchObject({ key: 'k', scope: 'group', limit: 5, order: 'asc', style: { color: '#f00' } });
- });
-
- it('carries the device pixel ratio, which that runtime cannot ask for', () => {
- const { sent } = platform({ devicePixelRatio: () => 3 });
- api().show();
- expect(sent[0]).toMatchObject({ dpr: 3 });
- });
-
- it('is false, and sends nothing, where there is no context', () => {
- const { sent } = platform({ openDataCanvas: () => null });
- expect(api().show()).toBe(false);
- expect(sent).toEqual([]);
- });
-
- it('tracks whether the board is up', () => {
- platform();
- const l = api();
- expect(l.visible).toBe(false);
- l.show();
- expect(l.visible).toBe(true);
- l.hide();
- expect(l.visible).toBe(false);
- });
-
- it('hide is a no-op when nothing was shown — not a stray message', () => {
- const { sent } = platform();
- api().hide();
- expect(sent).toEqual([]);
- });
-
- it('tells the context to clear', () => {
- const { sent } = platform();
- const l = api();
- l.show();
- l.hide();
- expect(sent[1]).toEqual({ kind: 'hide' });
- });
-});
-
-/**
- * The rehearsal board. Its value is entirely in being the SAME renderer that
- * ships inside the open data context — an approximation drawn here would tell
- * you nothing about what appears on a phone — so what these pin is that it
- * really does draw, and that it stands in for the platform everywhere.
- */
-describe('the local board', () => {
- /** A 2D context that records what was drawn on it. */
- function recordingCanvas() {
- const calls: Array<{ op: string; args: unknown[] }> = [];
- const ctx = new Proxy({} as Record<string, unknown>, {
- get: (_t, prop: string) => {
- if (prop === 'measureText') return (s: string) => ({ width: s.length * 7 });
- if (prop === 'canvas') return undefined;
- return (...args: unknown[]) => { calls.push({ op: prop, args }); };
- },
- set: () => true,
- });
- return { calls, ctx };
- }
-
- it('draws the rows through the engine\'s own renderer', () => {
- const rec = recordingCanvas();
- platform({
- // No open data context here at all — the provider is the whole board.
- openDataPostMessage: undefined,
- openDataCanvas: undefined,
- // 1:1, and wide enough that nothing is clipped: the clipping rule has
- // its own test, and letting it fire here would only make this one
- // assert the wrong thing.
- devicePixelRatio: () => 1,
- createCanvas: (w: number, h: number) => ({ width: w, height: h, getContext: () => rec.ctx }),
- });
- const l = api();
- l.setProvider(createLocalLeaderboard({ width: 640 }));
- expect(l.available).toBe(true);
- expect(l.show()).toBe(true);
-
- const texts = rec.calls.filter((c) => c.op === 'fillText').map((c) => String(c.args[0]));
- // The invented friends, ranked — and the one who never played is absent,
- // the same rule the shipped board follows because it IS that board.
- expect(texts).toContain('Player One');
- expect(texts).toContain('18400');
- expect(texts).not.toContain('Never Played');
- });
-
- it('re-keys the invented rows to whatever key the game asked for', () => {
- // A game with its own key would otherwise rehearse against an empty
- // board and reasonably read that as "this is broken".
- const rec = recordingCanvas();
- platform({
- devicePixelRatio: () => 1,
- createCanvas: (w: number, h: number) => ({ width: w, height: h, getContext: () => rec.ctx }),
- });
- const l = api();
- l.setProvider(createLocalLeaderboard({ width: 640 }));
- l.show({ key: 'my.own.key' });
- expect(rec.calls.some((c) => c.op === 'fillText' && c.args[0] === '18400')).toBe(true);
- });
-
- it('answers `available` where the platform cannot', () => {
- platform({ openDataPostMessage: undefined, openDataCanvas: undefined });
- const l = api();
- expect(l.available).toBe(false);
- l.setProvider(createLocalLeaderboard());
- expect(l.available).toBe(true);
- l.setProvider(null);
- expect(l.available).toBe(false);
- });
-
- it('clears the board when the provider is swapped out', () => {
- platform();
- const l = api();
- l.setProvider(createLocalLeaderboard());
- l.show();
- expect(l.visible).toBe(true);
- // The canvas behind the texture is going away with the provider.
- l.setProvider(null);
- expect(l.visible).toBe(false);
- expect(l.texture).toBe(0);
- });
-});
-
-describe('the texture', () => {
- it('is 0 until there is one, and the service still works', () => {
- platform();
- const l = api();
- expect(l.texture).toBe(0);
- expect(l.show()).toBe(true); // no WebGL2 here; the request still goes
- expect(l.texture).toBe(0);
- expect(() => l.sample()).not.toThrow();
- });
-
- it('samples nothing while the board is down', () => {
- platform();
- const l = api();
- // Nothing to assert but the absence of a throw and of a canvas read —
- // the point is that the per-frame system costs one boolean.
- expect(() => l.sample()).not.toThrow();
- expect(l.visible).toBe(false);
- });
-});