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(editor): a leaderboard you can look at before there is a phone
yhh9b1fa3e5d22a
diff --git a/desktop/src/playHost.ts b/desktop/src/playHost.tsindex 55996b494..8884c6574 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 { createWebApp, setEditorMode, setPlayMode, initPlayRealmRuntime, getComponent, clearUserComponents, getUserComponentFingerprint, probeRegistrations, Net, MessagePortTransport, Assets, Ads, createMockAdProvider } from 'esengine';+import { createWebApp, setEditorMode, setPlayMode, initPlayRealmRuntime, getComponent, clearUserComponents, getUserComponentFingerprint, probeRegistrations, Net, MessagePortTransport, Assets, Ads, createMockAdProvider, Leaderboard, createLocalLeaderboard } from 'esengine';import type { App, ESEngineModule, SceneData } from 'esengine';import { PLAY_PROTOCOL_VERSION } from './engine/playProtocol';import type { PlayOutbound, PlayInbound } from './engine/playProtocol';@@ -234,6 +234,15 @@ 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);diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex e7be3f087..26cd9bfe0 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: 1391 stable · 17 beta · 1 deprecated+Symbols: 1399 stable · 17 beta · 1 deprecated## ABI_LAYOUT_HASH — const```@@ -3560,6 +3560,58 @@ 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+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+```+key: string | undefined+limit: number | undefined+order: "desc" | "asc" | undefined+scope: LeaderboardScope | undefined+style: LeaderboardStyle | undefined+```++## LeaderboardProvider — interface+```+canvas: () => PlatformCanvas | null+post: (message: Record<string, unknown>) => void+```++## 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>@@ -3768,6 +3820,13 @@ spacing: numbertextureHandle: number```+## LocalLeaderboardOptions — interface+```+friends: readonly CloudPlayer[] | undefined+height: number | undefined+width: number | undefined+```+## LocalTransform — const```BuiltinComponentDef<TransformData>@@ -8778,6 +8837,11 @@ Plugin<T>(opts: CreateListViewOptions<T>): ListViewHandle<T>```+## createLocalLeaderboard — function+```+(options?: LocalLeaderboardOptions): LeaderboardProvider+```+## createMemoryTransportPair — function```(options?: MemoryTransportOptions): [MemoryTransport, MemoryTransport]diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex a7eeaf960..2925c0b6e 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: 1410 stable · 22 beta · 1 deprecated+Symbols: 1418 stable · 22 beta · 1 deprecated## ABI_LAYOUT_HASH — const```@@ -3568,6 +3568,58 @@ 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+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+```+key: string | undefined+limit: number | undefined+order: "desc" | "asc" | undefined+scope: LeaderboardScope | undefined+style: LeaderboardStyle | undefined+```++## LeaderboardProvider — interface+```+canvas: () => PlatformCanvas | null+post: (message: Record<string, unknown>) => void+```++## 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>@@ -3776,6 +3828,13 @@ spacing: numbertextureHandle: number```+## LocalLeaderboardOptions — interface+```+friends: readonly CloudPlayer[] | undefined+height: number | undefined+width: number | undefined+```+## LocalTransform — const```BuiltinComponentDef<TransformData>@@ -8964,6 +9023,11 @@ Plugin<T>(opts: CreateListViewOptions<T>): ListViewHandle<T>```+## createLocalLeaderboard — function+```+(options?: LocalLeaderboardOptions): LeaderboardProvider+```+## createMemoryTransportPair — function```(options?: MemoryTransportOptions): [MemoryTransport, MemoryTransport]diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 8015a267e..7395d2525 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: 1390 stable · 19 beta · 1 deprecated+Symbols: 1398 stable · 19 beta · 1 deprecated## ANCHOR_AXES — const```@@ -3555,6 +3555,58 @@ 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+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+```+key: string | undefined+limit: number | undefined+order: "desc" | "asc" | undefined+scope: LeaderboardScope | undefined+style: LeaderboardStyle | undefined+```++## LeaderboardProvider — interface+```+canvas: () => PlatformCanvas | null+post: (message: Record<string, unknown>) => void+```++## 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>@@ -3763,6 +3815,13 @@ spacing: numbertextureHandle: number```+## LocalLeaderboardOptions — interface+```+friends: readonly CloudPlayer[] | undefined+height: number | undefined+width: number | undefined+```+## LocalTransform — const```BuiltinComponentDef<TransformData>@@ -8773,6 +8832,11 @@ Plugin<T>(opts: CreateListViewOptions<T>): ListViewHandle<T>```+## createLocalLeaderboard — function+```+(options?: LocalLeaderboardOptions): LeaderboardProvider+```+## createMemoryTransportPair — function```(options?: MemoryTransportOptions): [MemoryTransport, MemoryTransport]diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex cafa262ae..305f136cc 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: 1416 stable · 17 beta · 1 deprecated+Symbols: 1419 stable · 17 beta · 1 deprecated## ANCHOR_AXES — const```@@ -3566,6 +3566,7 @@ available: booleandispose: () => voidhide: () => voidsample: () => void+setProvider: (provider: LeaderboardProvider | null) => voidshow: (options?: LeaderboardOptions) => booleansubmit: (score: number, options?: { key?: string; extra?: Readonly<Record<string, string>>; }) => booleantexture: number@@ -3583,6 +3584,12 @@ scope: LeaderboardScope | undefinedstyle: LeaderboardStyle | undefined```+## LeaderboardProvider — interface+```+canvas: () => PlatformCanvas | null+post: (message: Record<string, unknown>) => void+```+## LeaderboardScope — type```'friends' | 'group'@@ -3808,6 +3815,13 @@ spacing: numbertextureHandle: number```+## LocalLeaderboardOptions — interface+```+friends: readonly CloudPlayer[] | undefined+height: number | undefined+width: number | undefined+```+## LocalTransform — const```BuiltinComponentDef<TransformData>@@ -9046,6 +9060,11 @@ Plugin<T>(opts: CreateListViewOptions<T>): ListViewHandle<T>```+## createLocalLeaderboard — function+```+(options?: LocalLeaderboardOptions): LeaderboardProvider+```+## createMemoryTransportPair — function```(options?: MemoryTransportOptions): [MemoryTransport, MemoryTransport]diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 7526fbe89..dec2aa81f 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: 1401 stable · 17 beta · 1 deprecated+Symbols: 1409 stable · 17 beta · 1 deprecated## ANCHOR_AXES — const```@@ -3562,6 +3562,58 @@ 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+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+```+key: string | undefined+limit: number | undefined+order: "desc" | "asc" | undefined+scope: LeaderboardScope | undefined+style: LeaderboardStyle | undefined+```++## LeaderboardProvider — interface+```+canvas: () => PlatformCanvas | null+post: (message: Record<string, unknown>) => void+```++## 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>@@ -3770,6 +3822,13 @@ spacing: numbertextureHandle: number```+## LocalLeaderboardOptions — interface+```+friends: readonly CloudPlayer[] | undefined+height: number | undefined+width: number | undefined+```+## LocalTransform — const```BuiltinComponentDef<TransformData>@@ -8797,6 +8856,11 @@ Plugin<T>(opts: CreateListViewOptions<T>): ListViewHandle<T>```+## createLocalLeaderboard — function+```+(options?: LocalLeaderboardOptions): LeaderboardProvider+```+## createMemoryTransportPair — function```(options?: MemoryTransportOptions): [MemoryTransport, MemoryTransport]diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex f4f6ba728..a212137b3 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -405,10 +405,11 @@ export {export {Ads, AdsAPI, createMockAdProvider,Share, ShareAPI,- Leaderboard, LeaderboardAPI,+ Leaderboard, LeaderboardAPI, createLocalLeaderboard,ServicesPlugin, servicesPlugin,type AdProvider, type AdsHost, type MockAdProviderOptions, type ShareCard,- type LeaderboardOptions, type LeaderboardScope, type LeaderboardStyle,+ type LeaderboardOptions, type LeaderboardProvider, type LeaderboardScope,+ type LeaderboardStyle, type LocalLeaderboardOptions,} from './services';// =============================================================================diff --git a/sdk/src/opendata/board.ts b/sdk/src/opendata/board.tsnew file mode 100644index 000000000..0fecfd7f6--- /dev/null+++ b/sdk/src/opendata/board.ts@@ -0,0 +1,251 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file board.ts+ * @brief The built-in leaderboard's drawing, over whatever host it is given.+ *+ * Separated from the entry so the SAME code can run in two places: inside the+ * open data context on a device (index.ts hands it the host global), and in the+ * editor's play mode against an offscreen canvas and invented friends. A+ * rehearsal that drew a different board would rehearse nothing.+ *+ * Which is also why the host is a PARAMETER and the state is per board: two+ * boards sharing a module-level canvas and avatar cache is a bug that appears+ * only in the place that has two of them.+ *+ * Imports nothing but its own protocol, and that only as a type — see+ * `opendata.test.ts`. The runtime this ends up in has no engine to import.+ */+import type { HideMessage, LeaderboardStyle, OpenDataMessage, ShowMessage } from './protocol';++// =============================================================================+// The host, as this runtime sees it+// =============================================================================++/** One player's cloud rows, as a host hands them over. */+export interface CloudPlayer {+ avatarUrl?: string;+ nickname?: string;+ openid?: string;+ KVDataList?: Array<{ key: string; value: string }>;+}++/** An image the host can load. Deliberately not `HTMLImageElement`: there is no+ * DOM in the context, and the shape below is all the drawing needs. */+export interface HostImage {+ src: string;+ onload: (() => void) | null;+ onerror: (() => void) | null;+}++export interface HostCanvas {+ width: number;+ height: number;+ getContext(type: '2d'): CanvasRenderingContext2D | null;+}++/**+ * What a board needs from wherever it runs. Every member optional: a vendor+ * missing one degrades to a board without that part, never a throw.+ */+export interface BoardHost {+ getSharedCanvas?(): HostCanvas | null;+ getFriendCloudStorage?(opts: {+ keyList: string[];+ success?: (res: { data: CloudPlayer[] }) => void;+ fail?: (err: unknown) => void;+ }): void;+ createImage?(): HostImage;+ /** This player, so their row can be marked. Absent marks nobody. */+ selfOpenId?: string;+}++// =============================================================================+// Ranking+// =============================================================================++/** A row as the board draws it: already sorted, already trimmed. */+export 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 does — dropped, not+ * drawn as zero, since 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 }));+}++// =============================================================================+// Drawing+// =============================================================================++type Resolved = Required<Omit<LeaderboardStyle, 'background' | 'lineColor'>>+ & Pick<LeaderboardStyle, 'background' | 'lineColor'>;++const DEFAULTS: Resolved = {+ background: undefined,+ color: '#e8e8e8',+ selfColor: '#ffffff',+ lineColor: '#ffffff14',+ rowHeight: 44,+ fontSize: 15,+ fontFamily: 'sans-serif',+ avatars: true,+};++/** `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}…` : '';+}++/** A board bound to one host. */+export interface Board {+ /** Route one message from the main domain. Unknown kinds are ignored. */+ handle(message: unknown): void;+}++export function createBoard(host: BoardHost): Board {+ // Per board, not per module: see the file header.+ const avatars = new Map<string, { img: HostImage; ready: boolean }>();+ let last: ShowMessage | null = null;+ let repaint: (() => void) | null = null;++ const avatarFor = (url: string | undefined): HostImage | 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;+ };++ const paint = (canvas: HostCanvas, 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;+ // Drawn only once it has actually loaded — an image mid-flight draws+ // nothing, and its load schedules the repaint that catches it.+ if (avatar) {+ 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);+ });+ };++ const 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);+ }+ };++ const 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, host.selfOpenId);+ 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(); },+ });+ };++ return {+ handle(message: unknown): void {+ const m = message as OpenDataMessage | undefined;+ // An older package can run 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);+ },+ };+}diff --git a/sdk/src/opendata/index.ts b/sdk/src/opendata/index.tsindex 069f5f8a0..9e11c3425 100644--- a/sdk/src/opendata/index.ts+++ b/sdk/src/opendata/index.ts@@ -2,243 +2,32 @@// 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.+ * @brief The built-in leaderboard's ENTRY, as it runs inside the open data+ * context: find the host global, hand it to a board, subscribe.+ *+ * That is all this file does, because it is the only part that cannot run+ * anywhere else. Everything the board actually is lives in `board.ts`, where+ * the editor's play mode can run the same code against an offscreen canvas —+ * a rehearsal that drew a different board would rehearse nothing.** 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.+ * host API; `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.+ * when a project supplies no `open-data/index.ts` of its own.** 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.+ * runtime, so there is no scrolling, no paging and no row you can tap.*/-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-// =============================================================================+import { createBoard, type BoardHost } from './board';-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,-};+const host = (globalThis as unknown as { wx?: BoardHost; tt?: BoardHost }).wx+ ?? (globalThis as unknown as { tt?: BoardHost }).tt;-/** A row as the board draws it: already sorted, already trimmed. */-interface Row {- rank: number;- name: string;- score: number;- avatarUrl?: string;- self: boolean;+if (host) {+ const board = createBoard(host);+ (host as BoardHost & { onMessage?(cb: (m: unknown) => void): void })+ .onMessage?.call(host, (m) => { board.handle(m); });}--/**- * 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/services/index.ts b/sdk/src/services/index.tsindex aa5b9c24b..77ecdbcec 100644--- a/sdk/src/services/index.ts+++ b/sdk/src/services/index.ts@@ -6,7 +6,8 @@ export {} from './ads';export { Share, ShareAPI, type ShareCard } from './share';export {- Leaderboard, LeaderboardAPI,- type LeaderboardOptions, type LeaderboardScope, type LeaderboardStyle,+ Leaderboard, LeaderboardAPI, createLocalLeaderboard,+ type LeaderboardOptions, type LeaderboardProvider, type LeaderboardScope,+ type LeaderboardStyle, type LocalLeaderboardOptions,} from './leaderboard';export { ServicesPlugin, servicesPlugin } from './servicesPlugin';diff --git a/sdk/src/services/leaderboard.ts b/sdk/src/services/leaderboard.tsindex b02b511cc..42985d8fc 100644--- a/sdk/src/services/leaderboard.ts+++ b/sdk/src/services/leaderboard.ts@@ -23,11 +23,13 @@import { defineResource } from '../ecs/resource';import {platformCanOpenData, platformOpenDataCanvas, platformOpenDataPostMessage, platformSetCloudKeyValues,- platformDevicePixelRatio,+ 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 };@@ -49,18 +51,45 @@ export interface LeaderboardOptions {* read each other's rows by accident. */const DEFAULT_KEY = 'es.score';+/**+ * A stand-in for the open data context, for hosts that have none: the editor's+ * play mode, a web build, a test. Mirrors the two things the platform supplies+ * — somewhere to send a message, and a canvas to sample — so one seam serves+ * both. {@link createLocalLeaderboard} is the standard implementation.+ */+export interface LeaderboardProvider {+ /** The surface the board is drawn on. */+ canvas(): PlatformCanvas | null;+ /** Receive what the main domain would have posted into the context. */+ post(message: Record<string, unknown>): void;+}+export class LeaderboardAPI {private texture_: CanvasTexture | null = null;private shown_ = false;private key_ = DEFAULT_KEY;+ private provider_: LeaderboardProvider | null = null;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. */+ /** Whether SOME board exists here — the host's context, or an installed+ * provider. What a menu reads to hide its leaderboard button honestly. */get available(): boolean {- return platformCanOpenData();+ return this.provider_ !== null || platformCanOpenData();+ }++ /**+ * 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.+ */+ setProvider(provider: LeaderboardProvider | null): void {+ if (provider === this.provider_) return;+ this.provider_ = provider;+ this.texture_?.destroy();+ this.texture_ = null;+ this.shown_ = false;}/**@@ -106,7 +135,7 @@ export class LeaderboardAPI {style: options.style ?? {},dpr: platformDevicePixelRatio(),};- if (!platformOpenDataPostMessage(message as unknown as Record<string, unknown>)) return false;+ if (!this.post_(message as unknown as Record<string, unknown>)) return false;this.shown_ = true;this.ensureTexture_();return true;@@ -117,7 +146,7 @@ export class LeaderboardAPI {hide(): void {if (!this.shown_) return;this.shown_ = false;- platformOpenDataPostMessage({ kind: 'hide' });+ this.post_({ 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();@@ -138,9 +167,15 @@ export class LeaderboardAPI {this.shown_ = false;}+ /** An installed provider answers instead of the platform, both ways. */+ private post_(message: Record<string, unknown>): boolean {+ if (this.provider_) { this.provider_.post(message); return true; }+ return platformOpenDataPostMessage(message);+ }+private ensureTexture_(): void {if (this.texture_) return;- const canvas = platformOpenDataCanvas();+ const canvas = this.provider_ ? this.provider_.canvas() : platformOpenDataCanvas();if (!canvas) return;this.texture_ = createCanvasTexture(this.module_(), canvas);if (!this.texture_) {@@ -152,3 +187,60 @@ export class LeaderboardAPI {}export const Leaderboard = defineResource<LeaderboardAPI>(null!, 'Leaderboard');++/** How a rehearsal board is populated. */+export interface LocalLeaderboardOptions {+ /** The friends to invent. Defaults to a small, obviously-fake set — real+ * names would read as real data and hide that this is a rehearsal. */+ friends?: readonly CloudPlayer[];+ /** Canvas size in CSS px. */+ width?: number;+ height?: number;+}++/** Names that cannot be mistaken for a real friends list. */+const REHEARSAL_FRIENDS: readonly CloudPlayer[] = [+ { nickname: 'Player One', openid: 'local-self', KVDataList: [{ key: 'es.score', value: '18400' }] },+ { nickname: 'Sample Friend', openid: 'local-2', KVDataList: [{ key: 'es.score', value: '15250' }] },+ { nickname: 'Another Tester', openid: 'local-3', KVDataList: [{ key: 'es.score', value: '9870' }] },+ { nickname: 'Someone Else', openid: 'local-4', KVDataList: [{ key: 'es.score', value: '6120' }] },+ { nickname: 'Never Played', openid: 'local-5', KVDataList: [] },+];++/**+ * 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+ * 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;+ const canvas = platformCreateCanvas(options.width ?? 360, options.height ?? 260);+ const board = createBoard({+ getSharedCanvas: () => canvas as unknown as HostCanvas,+ getFriendCloudStorage: ({ keyList, success }) => {+ const key = keyList[0];+ success?.({+ data: friends.map((f) => ({+ ...f,+ // Re-keyed to whatever the game asked for, so a game with its+ // own key still sees the rehearsal rows rather than an empty+ // board it would reasonably read as "this is broken".+ KVDataList: (f.KVDataList ?? []).map((kv) => ({ ...kv, key })),+ })),+ });+ },+ selfOpenId: 'local-self',+ });+ return {+ canvas: () => canvas,+ post: (message) => { board.handle(message); },+ };+}diff --git a/sdk/tests/leaderboard.test.ts b/sdk/tests/leaderboard.test.tsindex 446b6555d..400a13b3c 100644--- a/sdk/tests/leaderboard.test.ts+++ b/sdk/tests/leaderboard.test.ts@@ -9,7 +9,7 @@* tested in opendata.test.ts.*/import { describe, it, expect, beforeEach, vi } from 'vitest';-import { LeaderboardAPI } from '../src/services/leaderboard';+import { LeaderboardAPI, createLocalLeaderboard } from '../src/services/leaderboard';import { setPlatform } from '../src/platform/base';import type { PlatformAdapter } from '../src/platform/types';@@ -26,6 +26,7 @@ function platform(over: Partial<PlatformAdapter> = {}): {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);@@ -134,6 +135,89 @@ describe('show / 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();diff --git a/sdk/tests/opendata.test.ts b/sdk/tests/opendata.test.tsindex d77a1105f..9cf5a513d 100644--- a/sdk/tests/opendata.test.ts+++ b/sdk/tests/opendata.test.ts@@ -9,9 +9,9 @@* 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 { existsSync, readFileSync, readdirSync } from 'node:fs';import path from 'node:path';-import { rowsFrom } from '../src/opendata/index';+import { rowsFrom } from '../src/opendata/board';const DIR = path.join(__dirname, '..', 'src', 'opendata');@@ -35,16 +35,23 @@ describe('the boundary', () => {expect(sources.length).toBeGreaterThan(0);});- it.each(sources)('%s imports nothing but its own protocol, and that only as a type', (file) => {+ it.each(sources)('%s imports nothing from outside this folder', (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);+ const imports = [...src.matchAll(/^\s*import\s+(?:type\s+)?[^;]*?from\s+'([^']+)'/gm)].map((m) => m[1]);+ for (const from of imports) {+ // The boundary is the FOLDER, not the import kind: files in here are+ // bundled together into the one file that ships to the context, so a+ // sibling costs nothing. What must never happen is an import that+ // leaves — `../` or a package name is the engine arriving in a+ // runtime that cannot run it.+ expect(+ from.startsWith('./') && !from.includes('..'),+ `${file} imports "${from}" — the open data context has no engine to import`,+ ).toBe(true);+ expect(+ existsSync(path.join(DIR, `${from.slice(2)}.ts`)),+ `${file} imports "${from}", which is not a file in this folder`,+ ).toBe(true);}});