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(sdk): a friends leaderboard, including the half that runs somewhere else
yhhd19aa69bb926
diff --git a/desktop/electron/exportMiniGame.ts b/desktop/electron/exportMiniGame.tsindex ccff77f10..1a539be6f 100644--- a/desktop/electron/exportMiniGame.ts+++ b/desktop/electron/exportMiniGame.ts@@ -343,9 +343,16 @@ 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.const openDataEntry = ['index.ts', 'index.js'].map((f) => path.join(opts.root, OPEN_DATA_DIR, f))- .find((f) => existsSync(f));+ .find((f) => existsSync(f))+ ?? [path.join(opts.sdkDir, 'open-data.js')].find((f) => existsSync(f));if (openDataEntry) {progress({ phase: 'Bundling open data context' });try {diff --git a/desktop/tests/export-wechat.test.ts b/desktop/tests/export-wechat.test.tsindex 8624e3efc..7452a54c1 100644--- a/desktop/tests/export-wechat.test.ts+++ b/desktop/tests/export-wechat.test.ts@@ -399,8 +399,10 @@ describe('exportGame (wechat)', () => {describe('exportGame (wechat) — open data context', () => {const roots: string[] = [];- /** A minimal exportable project: one scene, one texture, stub SDK + runtime. */- function scaffold(openDataSource?: string): { root: string; out: 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 } {const dir = mkdtempSync(path.join(tmpdir(), 'estella-export-opendata-'));roots.push(dir);mkdirSync(path.join(dir, 'assets'), { recursive: true });@@ -414,6 +416,7 @@ 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');@@ -464,6 +467,29 @@ 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('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__');+ }, 60_000);+it('a context that imports the engine fails the export, not the device', async () => {const { root: r, out: o } = scaffold("import { Assets } from 'esengine';\nAssets.toString();\n");const res = await exportIt(r, o);diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex e54121037..cafa262ae 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: 1411 stable · 17 beta · 1 deprecated+Symbols: 1416 stable · 17 beta · 1 deprecated## ANCHOR_AXES — const```@@ -3555,6 +3555,51 @@ getItemRect: (index: number) => RectgetVisibleRange: (viewport: Rect, count: number) => [start: number, end: number]```+## Leaderboard — const+```+ResourceDef<LeaderboardAPI>+```++## LeaderboardAPI — class+```+available: boolean+dispose: () => void+hide: () => void+sample: () => 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+```+key: string | undefined+limit: number | undefined+order: "desc" | "asc" | undefined+scope: LeaderboardScope | undefined+style: LeaderboardStyle | undefined+```++## LeaderboardScope — type+```+'friends' | 'group'+```++## LeaderboardStyle — interface+```+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```ResourceDef<LifecycleManager>diff --git a/sdk/rolldown.config.js b/sdk/rolldown.config.jsindex e96fc9d59..e392fd810 100644--- a/sdk/rolldown.config.js+++ b/sdk/rolldown.config.js@@ -91,6 +91,17 @@ 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/core-content.ts b/sdk/src/core-content.tsindex 93431911e..f4f6ba728 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -405,8 +405,10 @@ export {export {Ads, AdsAPI, createMockAdProvider,Share, ShareAPI,+ Leaderboard, LeaderboardAPI,ServicesPlugin, servicesPlugin,type AdProvider, type AdsHost, type MockAdProviderOptions, type ShareCard,+ type LeaderboardOptions, type LeaderboardScope, type LeaderboardStyle,} from './services';// =============================================================================diff --git a/sdk/src/opendata/index.ts b/sdk/src/opendata/index.tsnew file mode 100644index 000000000..069f5f8a0--- /dev/null+++ b/sdk/src/opendata/index.ts@@ -0,0 +1,244 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file opendata/index.ts+ * @brief The built-in leaderboard, as it runs INSIDE the open data context.+ *+ * This file is not part of the engine and must never import it. The context is+ * a second JS runtime with no WebGL, no wasm, no DOM and almost none of the+ * host API — it has a 2D canvas the main domain samples as a texture, a message+ * channel with no way back, and the one thing that exists nowhere else: the+ * player's friends. `opendata.test.ts` enforces the boundary, because the cost+ * of getting it wrong is a package that builds and then fails on a device.+ *+ * It ships as its own bundle (`dist/open-data.js`) and the exporter uses it+ * when a project supplies no `open-data/index.ts` of its own. Ship a+ * leaderboard people can use, and an escape hatch for the ones who cannot.+ *+ * Nothing here can be interactive: no pointer or key event reaches this+ * runtime, so there is no scrolling, no paging and no row you can tap. A board+ * that needs those is a board the host cannot give us, and pretending+ * otherwise would be a control that silently does nothing.+ */+import type { HideMessage, LeaderboardStyle, OpenDataMessage, ShowMessage } from './protocol';++// =============================================================================+// The host, as this runtime sees it+// =============================================================================++/** One player's cloud rows, as the host hands them over. */+interface CloudPlayer {+ avatarUrl?: string;+ nickname?: string;+ openid?: string;+ KVDataList?: Array<{ key: string; value: string }>;+}++/** The subset of the host global the context is given. Everything is optional:+ * a vendor missing one degrades to a board without that part, never a throw. */+interface OpenDataHost {+ onMessage?(cb: (message: unknown) => void): void;+ getSharedCanvas?(): OpenDataCanvas;+ getFriendCloudStorage?(opts: {+ keyList: string[];+ success?: (res: { data: CloudPlayer[] }) => void;+ fail?: (err: unknown) => void;+ }): void;+ createImage?(): { src: string; onload: (() => void) | null; onerror: (() => void) | null };+}++interface OpenDataCanvas {+ width: number;+ height: number;+ getContext(type: '2d'): CanvasRenderingContext2D | null;+}++const host = (globalThis as unknown as { wx?: OpenDataHost; tt?: OpenDataHost }).wx+ ?? (globalThis as unknown as { tt?: OpenDataHost }).tt;++// =============================================================================+// Drawing+// =============================================================================++const DEFAULTS: Required<Omit<LeaderboardStyle, 'background' | 'lineColor'>> & Pick<LeaderboardStyle, 'background' | 'lineColor'> = {+ background: undefined,+ color: '#e8e8e8',+ selfColor: '#ffffff',+ lineColor: '#ffffff14',+ rowHeight: 44,+ fontSize: 15,+ fontFamily: 'sans-serif',+ avatars: true,+};++/** A row as the board draws it: already sorted, already trimmed. */+interface Row {+ rank: number;+ name: string;+ score: number;+ avatarUrl?: string;+ self: boolean;+}++/**+ * Cloud rows → the rows to draw.+ *+ * Pure, and exported, because it is the half worth testing: which entries+ * survive, how they sort, and what a player with no score at all does (they are+ * dropped rather than drawn as zero — a friend who has not played is not last,+ * they are absent).+ */+export function rowsFrom(+ players: readonly CloudPlayer[],+ key: string,+ order: 'desc' | 'asc',+ limit: number,+ selfOpenId?: string,+): Row[] {+ const scored: Array<Omit<Row, 'rank'>> = [];+ for (const p of players) {+ const raw = p.KVDataList?.find((kv) => kv.key === key)?.value;+ if (raw === undefined) continue;+ const score = Number(raw);+ if (!Number.isFinite(score)) continue;+ scored.push({+ name: p.nickname ?? '',+ score,+ avatarUrl: p.avatarUrl,+ self: !!selfOpenId && p.openid === selfOpenId,+ });+ }+ scored.sort((a, b) => (order === 'asc' ? a.score - b.score : b.score - a.score));+ return scored.slice(0, Math.max(0, limit)).map((r, i) => ({ ...r, rank: i + 1 }));+}++/** Draw `rows` onto the shared canvas. */+function paint(canvas: OpenDataCanvas, rows: readonly Row[], style: LeaderboardStyle, dpr: number): void {+ const ctx = canvas.getContext('2d');+ if (!ctx) return;+ const s = { ...DEFAULTS, ...style };+ const w = canvas.width / dpr;+ const h = canvas.height / dpr;++ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);+ ctx.clearRect(0, 0, w, h);+ if (s.background) {+ ctx.fillStyle = s.background;+ ctx.fillRect(0, 0, w, h);+ }++ ctx.textBaseline = 'middle';+ const pad = 14;+ const avatarSize = Math.min(s.rowHeight - 12, 30);+ const nameLeft = pad + 34 + (s.avatars ? avatarSize + 10 : 0);++ rows.forEach((row, i) => {+ const y = i * s.rowHeight;+ const mid = y + s.rowHeight / 2;+ if (s.lineColor && i > 0) {+ ctx.fillStyle = s.lineColor;+ ctx.fillRect(pad, y, w - pad * 2, 1);+ }+ ctx.fillStyle = row.self ? s.selfColor : s.color;+ ctx.font = `${row.self ? '600 ' : ''}${s.fontSize}px ${s.fontFamily}`;++ ctx.textAlign = 'left';+ ctx.fillText(String(row.rank), pad, mid);++ const avatar = s.avatars ? avatarFor(row.avatarUrl) : null;+ if (avatar) {+ // Drawn only once it has actually loaded — an image mid-flight draws+ // nothing, and the load schedules the repaint that catches it.+ ctx.drawImage(avatar as unknown as CanvasImageSource, pad + 34, mid - avatarSize / 2, avatarSize, avatarSize);+ }++ // The name is what gets cut when the canvas is narrow, never the score:+ // a board whose numbers are missing is not a leaderboard.+ const scoreText = String(row.score);+ const scoreW = ctx.measureText(scoreText).width;+ ctx.fillText(clip(ctx, row.name, w - pad - nameLeft - scoreW - 12), nameLeft, mid);++ ctx.textAlign = 'right';+ ctx.fillText(scoreText, w - pad, mid);+ });+}++/** `text`, cut with an ellipsis to fit `max` px. */+function clip(ctx: CanvasRenderingContext2D, text: string, max: number): string {+ if (max <= 0) return '';+ if (ctx.measureText(text).width <= max) return text;+ let out = text;+ while (out.length > 0 && ctx.measureText(`${out}…`).width > max) out = out.slice(0, -1);+ return out.length ? `${out}…` : '';+}++// =============================================================================+// Avatars — loaded once, redrawn when they land+// =============================================================================++type LoadedImage = { src: string; onload: (() => void) | null; onerror: (() => void) | null };+const avatars = new Map<string, { img: LoadedImage; ready: boolean }>();+let repaint: (() => void) | null = null;++function avatarFor(url: string | undefined): LoadedImage | null {+ if (!url || !host?.createImage) return null;+ const have = avatars.get(url);+ if (have) return have.ready ? have.img : null;+ const img = host.createImage();+ const entry = { img, ready: false };+ avatars.set(url, entry);+ img.onload = () => { entry.ready = true; repaint?.(); };+ // A failed avatar is a row without a picture, not a row that is missing.+ img.onerror = () => { avatars.delete(url); };+ img.src = url;+ return null;+}++// =============================================================================+// The loop+// =============================================================================++let last: ShowMessage | null = null;++function show(msg: ShowMessage): void {+ last = msg;+ const canvas = host?.getSharedCanvas?.();+ const read = host?.getFriendCloudStorage;+ if (!canvas || !read) return;+ read.call(host, {+ keyList: [msg.key],+ success: (res) => {+ if (last !== msg) return; // a newer show already replaced this one+ const rows = rowsFrom(res.data ?? [], msg.key, msg.order, msg.limit);+ repaint = () => { if (last === msg) paint(canvas, rows, msg.style, msg.dpr); };+ repaint();+ },+ // Nothing to draw and nothing to say: this runtime has no channel back,+ // so an error here can only be a board that stays empty.+ fail: () => { if (last === msg) hide(); },+ });+}++function hide(_msg?: HideMessage): void {+ last = null;+ repaint = null;+ const canvas = host?.getSharedCanvas?.();+ const ctx = canvas?.getContext('2d');+ if (canvas && ctx) {+ ctx.setTransform(1, 0, 0, 1, 0, 0);+ ctx.clearRect(0, 0, canvas.width, canvas.height);+ }+}++/** Route one message. Exported so a test can drive it without a host. */+export function handle(message: unknown): void {+ const m = message as OpenDataMessage | undefined;+ // An older package can be running against a newer main domain, and a throw+ // in this runtime is invisible from the other one — so an unknown message is+ // ignored rather than trusted.+ if (!m || typeof m !== 'object') return;+ if (m.kind === 'show') show(m);+ else if (m.kind === 'hide') hide(m);+}++host?.onMessage?.call(host, handle);diff --git a/sdk/src/opendata/protocol.ts b/sdk/src/opendata/protocol.tsnew file mode 100644index 000000000..caac087b7--- /dev/null+++ b/sdk/src/opendata/protocol.ts@@ -0,0 +1,74 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file protocol.ts+ * @brief What the main domain says to the open data context.+ *+ * The two halves run in different JS runtimes and share nothing else — the+ * context has no engine, no wasm and no WebGL, and there is no channel back+ * from it. All they have is `postMessage`, so all they can agree on is a+ * message shape, and this file is that agreement.+ *+ * Types only, deliberately. It is imported by BOTH halves, and an import that+ * survived into the context's bundle would be the engine arriving in a runtime+ * that cannot run it — see the guard in `opendata.test.ts`.+ */++/** Which board to draw. `friends` is the only one every host has. */+export type LeaderboardScope = 'friends' | 'group';++/** How the built-in renderer should look. Everything optional: a game that+ * says nothing gets a board that matches the editor's own dark surface. */+export interface LeaderboardStyle {+ /** Page background. Transparent by default, so the board sits on the game. */+ background?: string;+ /** Row text. */+ color?: string;+ /** The row belonging to this player. */+ selfColor?: string;+ /** Row separators; absent draws none. */+ lineColor?: string;+ /** Row height in CSS px (the canvas is sized by the host). */+ rowHeight?: number;+ fontSize?: number;+ fontFamily?: string;+ /** Draw the player's avatar at the start of the row. */+ avatars?: boolean;+}++/**+ * Draw the board.+ *+ * `key` is the cloud-storage key the scores live under — the same one+ * `Leaderboard.submit` writes, which is why the service fills it in rather than+ * the game repeating it.+ */+export interface ShowMessage {+ kind: 'show';+ key: string;+ scope: LeaderboardScope;+ /** Rows to draw at most. The context's canvas is a fixed size and a board+ * that scrolls is a board that needs input it cannot receive. */+ limit: number;+ /** Sort descending (a high score) or ascending (a best time). */+ order: 'desc' | 'asc';+ style: LeaderboardStyle;+ /** Device pixel ratio, so text is not soft on a phone. The context cannot+ * ask — `getSystemInfoSync` is not one of the APIs it is given. */+ dpr: number;+}++/** Clear the canvas. The main domain stops sampling after this, so a context+ * that ignored it would leave the last frame on a texture nobody updates. */+export interface HideMessage {+ kind: 'hide';+}++/** Everything the main domain can send. A context that does not recognise a+ * message must ignore it: an older game package can be running against a+ * newer host, and a throw in that runtime is invisible from this one. */+export type OpenDataMessage = ShowMessage | HideMessage;++/** The channel's name in both directions of the codebase, so a search for it+ * finds the sender and the receiver. */+export const OPEN_DATA_CHANNEL = 'estella.leaderboard' as const;diff --git a/sdk/src/services/index.ts b/sdk/src/services/index.tsindex 290b29570..aa5b9c24b 100644--- a/sdk/src/services/index.ts+++ b/sdk/src/services/index.ts@@ -5,4 +5,8 @@ export {type AdProvider, type AdsHost, type MockAdProviderOptions,} from './ads';export { Share, ShareAPI, type ShareCard } from './share';+export {+ Leaderboard, LeaderboardAPI,+ type LeaderboardOptions, type LeaderboardScope, type LeaderboardStyle,+} from './leaderboard';export { ServicesPlugin, servicesPlugin } from './servicesPlugin';diff --git a/sdk/src/services/leaderboard.ts b/sdk/src/services/leaderboard.tsnew file mode 100644index 000000000..b02b511cc--- /dev/null+++ b/sdk/src/services/leaderboard.ts@@ -0,0 +1,154 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file leaderboard.ts+ * @brief The friends leaderboard as an engine service.+ *+ * 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+ * context — a second JS runtime with no engine — and there is no channel back+ * from it. So the two halves of a leaderboard live in different places and this+ * façade cannot hide that:+ *+ * `submit` is the MAIN domain's half. Writing your own row is the one cloud+ * operation a game may do here.+ * `show` is a request, not a question. It asks the context to draw, and+ * what comes back is pixels on a canvas — never rows, never a+ * count, never "did it work".+ * `texture` is those pixels, as an engine texture handle a UIVisual can wear.+ *+ * An API that returned `Promise<Row[]>` would be the honest-looking one, and it+ * is the one no host can implement.+ */+import { defineResource } from '../ecs/resource';+import {+ platformCanOpenData, platformOpenDataCanvas, platformOpenDataPostMessage, platformSetCloudKeyValues,+ platformDevicePixelRatio,+} from '../platform';+import type { ESEngineModule } from '../wasm';+import { createCanvasTexture, type CanvasTexture } from '../asset/canvasTexture';+import type { LeaderboardScope, LeaderboardStyle, ShowMessage } from '../opendata/protocol';+import { log } from '../util/logger';++export type { LeaderboardScope, LeaderboardStyle };++/** What to draw, and how. Everything has a default a game can ignore. */+export interface LeaderboardOptions {+ /** Cloud key the scores live under. Defaults to what {@link LeaderboardAPI.submit}+ * writes, so the two cannot disagree unless a game makes them. */+ key?: string;+ scope?: LeaderboardScope;+ /** Rows at most. The context's canvas is a fixed size and cannot scroll. */+ limit?: number;+ /** `desc` for a high score (default), `asc` for a best time. */+ order?: 'desc' | 'asc';+ style?: LeaderboardStyle;+}++/** The default cloud key. Named for the engine so two games in one host cannot+ * read each other's rows by accident. */+const DEFAULT_KEY = 'es.score';++export class LeaderboardAPI {+ private texture_: CanvasTexture | null = null;+ private shown_ = false;+ private key_ = DEFAULT_KEY;++ constructor(private readonly module_: () => ESEngineModule | null) {}++ /** Whether this host has an open data context at all — what a menu reads to+ * hide its leaderboard button honestly. False on web, on native, and in+ * any package that declares no context. */+ get available(): boolean {+ return platformCanOpenData();+ }++ /**+ * The board's pixels, as an engine texture handle, or 0 before there are+ * any. Stable across every redraw — a UIVisual set to it once keeps it.+ */+ get texture(): number {+ return this.texture_?.handle ?? 0;+ }++ /** Whether the board is currently being drawn. */+ get visible(): boolean {+ return this.shown_;+ }++ /**+ * Write this player's own score.+ *+ * Fire-and-forget past "was there a store": the hosts report a write's+ * outcome inconsistently, and the failure a game could act on (offline) is+ * not the one they distinguish. Returns whether there was anywhere to write.+ */+ submit(score: number, options?: { key?: string; extra?: Readonly<Record<string, string>> }): boolean {+ this.key_ = options?.key ?? this.key_;+ return platformSetCloudKeyValues({ ...options?.extra, [this.key_]: String(score) });+ }++ /**+ * Ask the context to draw the board, and start sampling what it draws.+ *+ * False where there is no context. The rows themselves never come back —+ * see the file header.+ */+ show(options: LeaderboardOptions = {}): boolean {+ const key = options.key ?? this.key_;+ this.key_ = key;+ const message: ShowMessage = {+ kind: 'show',+ key,+ scope: options.scope ?? 'friends',+ limit: options.limit ?? 20,+ order: options.order ?? 'desc',+ style: options.style ?? {},+ dpr: platformDevicePixelRatio(),+ };+ if (!platformOpenDataPostMessage(message as unknown as Record<string, unknown>)) return false;+ this.shown_ = true;+ this.ensureTexture_();+ return true;+ }++ /** Stop drawing, and stop sampling. The texture handle stays valid and+ * holds the last frame until the next {@link show}. */+ hide(): void {+ if (!this.shown_) return;+ this.shown_ = false;+ platformOpenDataPostMessage({ kind: 'hide' });+ // One last take, so what stays on the handle is the CLEARED canvas+ // rather than the board that was on it when we stopped looking.+ 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 */+ sample(): void {+ if (!this.shown_) return;+ if (!this.texture_) this.ensureTexture_();+ this.texture_?.update();+ }++ /** Release the GL texture. @internal */+ dispose(): void {+ this.texture_?.destroy();+ this.texture_ = null;+ this.shown_ = false;+ }++ private ensureTexture_(): void {+ if (this.texture_) return;+ const canvas = platformOpenDataCanvas();+ if (!canvas) return;+ this.texture_ = createCanvasTexture(this.module_(), 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');+ }+ }+}++export const Leaderboard = defineResource<LeaderboardAPI>(null!, 'Leaderboard');diff --git a/sdk/src/services/servicesPlugin.ts b/sdk/src/services/servicesPlugin.tsindex ba572e4fe..65ea35b7c 100644--- a/sdk/src/services/servicesPlugin.ts+++ b/sdk/src/services/servicesPlugin.ts@@ -2,16 +2,25 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team/*** @file servicesPlugin.ts- * @brief Installs the platform-services resources (Ads, Share).+ * @brief Installs the platform-services resources (Ads, Share, Leaderboard).*- * Resources only — no systems, no per-frame cost. 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 service knowing the App.+ * 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.+ *+ * 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+ * service knowing the App.*/import type { App, Plugin } from '../app/app';import { Audio } from '../audio';+import { Schedule, defineSystem } from '../ecs/system';import { Ads, AdsAPI } from './ads';import { Share, ShareAPI } from './share';+import { Leaderboard, LeaderboardAPI } from './leaderboard';export class ServicesPlugin implements Plugin {name = 'Services';@@ -27,6 +36,18 @@ export class ServicesPlugin implements Plugin {resumeAudio: () => app.getResource(Audio)?.resume(),}));app.insertResource(Share, new ShareAPI());+ // 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/leaderboard.test.ts b/sdk/tests/leaderboard.test.tsnew file mode 100644index 000000000..446b6555d--- /dev/null+++ b/sdk/tests/leaderboard.test.ts@@ -0,0 +1,155 @@+// 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 } 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 }),+ 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' });+ });+});++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);+ });+});diff --git a/sdk/tests/opendata.test.ts b/sdk/tests/opendata.test.tsnew file mode 100644index 000000000..d77a1105f--- /dev/null+++ b/sdk/tests/opendata.test.ts@@ -0,0 +1,117 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file The built-in leaderboard, and the boundary it lives behind.+ *+ * The open data context is a second JS runtime with no WebGL, no wasm and+ * almost none of the host API. The cost of forgetting that is not a compile+ * error — it is a package that builds, ships, and fails on a device — so the+ * boundary is a test rather than a comment at the top of the file.+ */+import { describe, it, expect } from 'vitest';+import { readFileSync, readdirSync } from 'node:fs';+import path from 'node:path';+import { rowsFrom } from '../src/opendata/index';++const DIR = path.join(__dirname, '..', 'src', 'opendata');++/**+ * The file with its comments removed.+ *+ * The guard below is about what the CODE reaches for, and these files talk at+ * length about the capabilities this runtime does not have — so a guard reading+ * the prose fails on the sentence explaining why it exists. Crude on purpose: a+ * `//` inside a string literal would be over-stripped, which can only make the+ * guard miss something, never invent a violation.+ */+const code = (src: string): string =>+ src.replace(/\/\*[\s\S]*?\*\//g, ' ').replace(/(^|[^:])\/\/.*$/gm, '$1');++describe('the boundary', () => {+ const sources = readdirSync(DIR).filter((f) => f.endsWith('.ts'));++ it('has files to check', () => {+ // A guard that silently checks nothing is worse than no guard.+ expect(sources.length).toBeGreaterThan(0);+ });++ it.each(sources)('%s imports nothing but its own protocol, and that only as a type', (file) => {+ const src = readFileSync(path.join(DIR, file), 'utf8');+ const imports = [...src.matchAll(/^\s*import\s+(type\s+)?[^;]*?from\s+'([^']+)'/gm)]+ .map((m) => ({ typeOnly: !!m[1], from: m[2] }));+ for (const im of imports) {+ // Relative and inside this folder: the two halves of the context.+ expect(im.from.startsWith('./'), `${file} imports "${im.from}" — the open data context has no engine to import`).toBe(true);+ // …and erased at build. A value import of anything, even a sibling,+ // is a runtime dependency this bundle would have to carry.+ expect(im.typeOnly, `${file} imports "${im.from}" as a VALUE; the context's bundle must carry no runtime dependency`).toBe(true);+ }+ });++ it.each(sources)('%s touches no browser or engine global', (file) => {+ const src = code(readFileSync(path.join(DIR, file), 'utf8'));+ // `document`/`window` do not exist there; WebGL and wasm are the two+ // capabilities the runtime is defined by NOT having.+ for (const banned of ['document.', 'window.', 'WebGL', 'WebAssembly', 'requestAnimationFrame']) {+ expect(src.includes(banned), `${file} uses \`${banned}\`, which the open data context does not have`).toBe(false);+ }+ });+});++describe('rowsFrom', () => {+ const p = (nickname: string, score?: string, openid?: string, avatarUrl?: string) => ({+ nickname, openid, avatarUrl,+ KVDataList: score === undefined ? [] : [{ key: 'best', value: score }],+ });++ it('ranks descending by default, from 1', () => {+ const rows = rowsFrom([p('a', '10'), p('b', '30'), p('c', '20')], 'best', 'desc', 10);+ expect(rows.map((r) => [r.rank, r.name, r.score])).toEqual([[1, 'b', 30], [2, 'c', 20], [3, 'a', 10]]);+ });++ it('ranks ascending for a best time', () => {+ const rows = rowsFrom([p('a', '10'), p('b', '30')], 'best', 'asc', 10);+ expect(rows.map((r) => r.name)).toEqual(['a', 'b']);+ });++ it('drops a friend who has never played rather than ranking them last', () => {+ // Zero is a score someone earned; absent is not a score at all, and+ // showing it as 0 puts people on a board they were never on.+ const rows = rowsFrom([p('a', '10'), p('never'), p('b', '0')], 'best', 'desc', 10);+ expect(rows.map((r) => r.name)).toEqual(['a', 'b']);+ });++ it('drops a value that is not a number', () => {+ const rows = rowsFrom([p('a', 'not-a-score'), p('b', '5')], 'best', 'desc', 10);+ expect(rows.map((r) => r.name)).toEqual(['b']);+ });++ it('reads only the key it was asked for', () => {+ const other = { nickname: 'a', KVDataList: [{ key: 'coins', value: '999' }] };+ expect(rowsFrom([other, p('b', '1')], 'best', 'desc', 10).map((r) => r.name)).toEqual(['b']);+ });++ it('trims to the limit — the canvas is a fixed size and cannot scroll', () => {+ const many = Array.from({ length: 40 }, (_, i) => p(`p${i}`, String(i)));+ expect(rowsFrom(many, 'best', 'desc', 5)).toHaveLength(5);+ });++ it('takes a limit of zero literally, and a negative one as zero', () => {+ expect(rowsFrom([p('a', '1')], 'best', 'desc', 0)).toEqual([]);+ expect(rowsFrom([p('a', '1')], 'best', 'desc', -3)).toEqual([]);+ });++ it('marks the player themselves, and only on an openid match', () => {+ const rows = rowsFrom([p('me', '9', 'oid-1'), p('them', '8', 'oid-2')], 'best', 'desc', 10, 'oid-1');+ expect(rows.map((r) => [r.name, r.self])).toEqual([['me', true], ['them', false]]);+ });++ it('marks nobody when the host did not say who we are', () => {+ const rows = rowsFrom([p('a', '9', 'oid-1')], 'best', 'desc', 10, undefined);+ expect(rows.every((r) => !r.self)).toBe(true);+ });++ it('survives a host that answers with nothing', () => {+ expect(rowsFrom([], 'best', 'desc', 10)).toEqual([]);+ });+});