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(i18n): scenes that bind Text.i18nKey localize themselves in every runtime

yhh1a8f8c402d9d
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index b9cf572af..dccdb4ada 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: 1123 stable · 17 beta · 1 deprecated
+Symbols: 1125 stable · 17 beta · 1 deprecated
## ABI_LAYOUT_HASH — const
```
@@ -4083,6 +4083,7 @@ fetch: (url: string, options?: PlatformRequestOptions) => Promise<PlatformRespon
fileExists: (path: string) => Promise<boolean>
getStorageItem: (key: string) => string | null
instantiateWasm: (pathOrBuffer: string | ArrayBuffer, imports: WebAssembly.Imports) => Promise<WasmInstantiateResult>
+language: (() => string) | undefined
loadImagePixels: (path: string) => Promise<ImageLoadResult>
loadSubpackage: ((name: string) => Promise<void>) | undefined
name: "web" | "wechat" | "node"
@@ -4862,6 +4863,7 @@ linearDamping: number
```
backend: Backend
decodePixels: (path: string, flip: boolean) => Promise<{ width: number; height: number; pixels: Uint8Array; }>
+listAssetPaths: (() => string[]) | undefined
resolveRef: ((ref: string) => string) | undefined
```
@@ -8007,6 +8009,11 @@ Logger
(world: World, entity: Entity, style: ThemeStyleData): void
```
+## matchLocale — function
+```
+(tag: string, available: readonly string[]): string | null
+```
+
## maxChildren — function
```
(type: BtNodeType): number
@@ -8417,6 +8424,11 @@ SafeAreaPlugin
Plugin
```
+## sceneUsesI18n — function
+```
+(sceneData: SceneData): boolean
+```
+
## screenToUiWorld — function
```
(camera: UICameraData, screenGLX: number, screenGLY: number): { x: number; y: number; }
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 1598c406e..9c1e8d849 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: 1122 stable · 19 beta · 1 deprecated
+Symbols: 1124 stable · 19 beta · 1 deprecated
## ANCHOR_AXES — const
```
@@ -4078,6 +4078,7 @@ fetch: (url: string, options?: PlatformRequestOptions) => Promise<PlatformRespon
fileExists: (path: string) => Promise<boolean>
getStorageItem: (key: string) => string | null
instantiateWasm: (pathOrBuffer: string | ArrayBuffer, imports: WebAssembly.Imports) => Promise<WasmInstantiateResult>
+language: (() => string) | undefined
loadImagePixels: (path: string) => Promise<ImageLoadResult>
loadSubpackage: ((name: string) => Promise<void>) | undefined
name: "web" | "wechat" | "node"
@@ -4857,6 +4858,7 @@ linearDamping: number
```
backend: Backend
decodePixels: (path: string, flip: boolean) => Promise<{ width: number; height: number; pixels: Uint8Array; }>
+listAssetPaths: (() => string[]) | undefined
resolveRef: ((ref: string) => string) | undefined
```
@@ -8007,6 +8009,11 @@ Logger
(world: World, entity: Entity, style: ThemeStyleData): void
```
+## matchLocale — function
+```
+(tag: string, available: readonly string[]): string | null
+```
+
## maxChildren — function
```
(type: BtNodeType): number
@@ -8422,6 +8429,11 @@ SafeAreaPlugin
Plugin
```
+## sceneUsesI18n — function
+```
+(sceneData: SceneData): boolean
+```
+
## screenToUiWorld — function
```
(camera: UICameraData, screenGLX: number, screenGLY: number): { x: number; y: number; }
diff --git a/sdk/etc/spine.api.md b/sdk/etc/spine.api.md
index 4c0dc1596..2cdd72766 100644
--- a/sdk/etc/spine.api.md
+++ b/sdk/etc/spine.api.md
@@ -56,6 +56,7 @@ spacing: number
```
backend: Backend
decodePixels: (path: string, flip: boolean) => Promise<{ width: number; height: number; pixels: Uint8Array; }>
+listAssetPaths: (() => string[]) | undefined
resolveRef: ((ref: string) => string) | undefined
```
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.ts
index fedf173cc..0194d5e79 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -205,6 +205,7 @@ export {
loadRuntimeScene,
createRuntimeSceneConfig,
initRuntime,
+ sceneUsesI18n,
type RuntimeAssetSource,
type LoadRuntimeSceneOptions,
type RuntimeInitConfig,
diff --git a/sdk/src/core-sys.ts b/sdk/src/core-sys.ts
index 85a8846a4..31be4d778 100644
--- a/sdk/src/core-sys.ts
+++ b/sdk/src/core-sys.ts
@@ -31,6 +31,7 @@ export {
selectPluralForm,
defaultPluralSelector,
parseLocaleTable,
+ matchLocale,
type LocaleTableAsset,
type LocalizationOptions,
type PluralCategory,
diff --git a/sdk/src/i18n/Localization.ts b/sdk/src/i18n/Localization.ts
index 13bff9a2f..ec7ea7867 100644
--- a/sdk/src/i18n/Localization.ts
+++ b/sdk/src/i18n/Localization.ts
@@ -137,6 +137,17 @@ export interface LocaleTableAsset {
const LOCALE_TABLE_VERSION = 1;
+/**
+ * Pick the best available locale for a platform tag: exact match first, else
+ * the first locale sharing the primary language ('zh-Hans-CN' → 'zh-CN'),
+ * else null — the caller keeps its current locale. Pure.
+ */
+export function matchLocale(tag: string, available: readonly string[]): string | null {
+ if (available.includes(tag)) return tag;
+ const lang = tag.split('-')[0].toLowerCase();
+ return available.find((l) => l.split('-')[0].toLowerCase() === lang) ?? null;
+}
+
/**
* Parse + validate `.eslocale` text. Fail-loud: a malformed table names the
* offending file and field instead of silently registering nothing. Pure.
diff --git a/sdk/src/i18n/index.ts b/sdk/src/i18n/index.ts
index 6a5f7ab82..aa6c18cf6 100644
--- a/sdk/src/i18n/index.ts
+++ b/sdk/src/i18n/index.ts
@@ -12,6 +12,7 @@ export {
selectPluralForm,
defaultPluralSelector,
parseLocaleTable,
+ matchLocale,
type LocaleTableAsset,
type PluralCategory,
type PluralForms,
diff --git a/sdk/src/platform/base.ts b/sdk/src/platform/base.ts
index 86f1b22a6..62eff90d2 100644
--- a/sdk/src/platform/base.ts
+++ b/sdk/src/platform/base.ts
@@ -135,3 +135,13 @@ export function platformDevicePixelRatio(): number {
}
return typeof window !== 'undefined' ? (window.devicePixelRatio || 1) : 1;
}
+
+/** The host's UI language as a BCP-47-ish tag ('zh-CN', 'en-US', …): the
+ * adapter's report (WeChat), else navigator.language (web), else 'en'.
+ * Underscore tags ('zh_CN') normalize to hyphens. Tolerates an
+ * uninitialized platform (tests). */
+export function platformLanguage(): string {
+ const raw = currentPlatform?.language?.()
+ ?? (typeof navigator !== 'undefined' ? navigator.language : undefined);
+ return (raw ?? 'en').replace(/_/g, '-');
+}
diff --git a/sdk/src/platform/index.ts b/sdk/src/platform/index.ts
index 87e04e519..8e609b4ba 100644
--- a/sdk/src/platform/index.ts
+++ b/sdk/src/platform/index.ts
@@ -36,6 +36,7 @@ export {
platformLoadSubpackage,
platformOnMemoryWarning,
platformDevicePixelRatio,
+ platformLanguage,
} from './base';
// Note: webAdapter is exported here for initialization
diff --git a/sdk/src/platform/types.ts b/sdk/src/platform/types.ts
index 23ad63a24..993068fb8 100644
--- a/sdk/src/platform/types.ts
+++ b/sdk/src/platform/types.ts
@@ -161,6 +161,11 @@ export interface PlatformAdapter {
* omit it. Residency caches subscribe to drop their evictable entries. */
onMemoryWarning?(callback: () => void): () => void;
+ /** The host's UI language tag ('zh-CN', 'en-US', …). WeChat reports
+ * 'zh_CN'-style tags — `platformLanguage()` normalizes underscores.
+ * Optional; web falls through to navigator.language. */
+ language?(): string;
+
devicePixelRatio(): number;
getStorageItem(key: string): string | null;
diff --git a/sdk/src/platform/wechat/index.ts b/sdk/src/platform/wechat/index.ts
index 36fabc7a8..7d4897890 100644
--- a/sdk/src/platform/wechat/index.ts
+++ b/sdk/src/platform/wechat/index.ts
@@ -210,6 +210,15 @@ class WeChatPlatformAdapter implements PlatformAdapter {
}
}
+ language(): string {
+ try {
+ // WeChat reports 'zh_CN'-style tags; platformLanguage() normalizes.
+ return wx.getSystemInfoSync?.()?.language ?? 'en';
+ } catch {
+ return 'en';
+ }
+ }
+
clearStorage(prefix: string): void {
try {
const { keys } = wx.getStorageInfoSync();
diff --git a/sdk/src/playRealmRuntime.ts b/sdk/src/playRealmRuntime.ts
index 837ac82bc..e4e7d4b14 100644
--- a/sdk/src/playRealmRuntime.ts
+++ b/sdk/src/playRealmRuntime.ts
@@ -134,6 +134,10 @@ function createPlayRealmSource(
backend,
decodePixels: (path) => fetchDecodePixels(backend.resolveUrl(path)),
resolveRef: (ref) => resolvePlayAssetRef(ref, manifest, assetBaseUrl, pathMap),
+ // Cooked builds: logical paths (the pathMap keys). Editor play: the
+ // manifest's resolved URLs — both keep the real extension, which is all
+ // the .eslocale discovery filters on.
+ listAssetPaths: () => (pathMap ? Object.keys(pathMap) : Object.values(manifest)),
};
}
diff --git a/sdk/src/playableRuntime.ts b/sdk/src/playableRuntime.ts
index 72fec9446..3348c4083 100644
--- a/sdk/src/playableRuntime.ts
+++ b/sdk/src/playableRuntime.ts
@@ -91,6 +91,9 @@ export async function initPlayableRuntime(config: PlayableRuntimeConfig): Promis
const source: RuntimeAssetSource = {
backend,
decodePixels: (path) => loadImagePixels(backend.resolveUrl(path)),
+ // Map keys are the shippable paths (logical aliases included) — the
+ // .eslocale discovery filters on extension, so aliases resolve fine.
+ listAssetPaths: () => Object.keys(assets),
};
if (app.hasResource(Audio)) {
diff --git a/sdk/src/runtimeAssets.ts b/sdk/src/runtimeAssets.ts
index a266ee4b7..6c6031c2f 100644
--- a/sdk/src/runtimeAssets.ts
+++ b/sdk/src/runtimeAssets.ts
@@ -30,6 +30,14 @@ export interface RuntimeAssetSource {
backend: Backend;
decodePixels(path: string, flip: boolean): Promise<{ width: number; height: number; pixels: Uint8Array }>;
resolveRef?(ref: string): string;
+ /**
+ * Every asset path this realm ships (logical, extension-bearing). Powers
+ * content-driven discovery of assets NO scene references — locale string
+ * tables (`.eslocale`), which Text binds by KEY, not path. Optional: a
+ * realm without it simply can't auto-load such assets (the runtime loader
+ * warns when a scene needs them).
+ */
+ listAssetPaths?(): string[];
}
export interface TextureParams {
diff --git a/sdk/src/runtimeLoader.ts b/sdk/src/runtimeLoader.ts
index 48ad03a96..d7f18cefb 100644
--- a/sdk/src/runtimeLoader.ts
+++ b/sdk/src/runtimeLoader.ts
@@ -24,7 +24,9 @@ import { SceneManager, type SceneConfig } from './sceneManager';
import { DEFAULT_GRAVITY, DEFAULT_FIXED_TIMESTEP } from './defaults';
import { SpriteAnimation } from './animation/SpriteAnimator';
import { Audio } from './audio/Audio';
-import { Localization } from './i18n/Localization';
+import { Localization, matchLocale } from './i18n/Localization';
+import { LocalizationPlugin } from './i18n/LocalizationPlugin';
+import { platformLanguage } from './platform';
import { flushPendingSystems } from './app';
import { requireResourceManager } from './resourceManager';
import { log } from './logger';
@@ -179,6 +181,20 @@ const PHYSICS_COMPONENT_TYPES = new Set([
'SegmentCollider', 'PolygonCollider', 'ChainCollider',
]);
+/** True if any Text binds its content to a localization key — the scene needs
+ * the Localization resource + the project's `.eslocale` tables to render as
+ * authored (an unbound key would show as the raw key string). */
+export function sceneUsesI18n(sceneData: SceneData): boolean {
+ for (const entity of sceneData.entities ?? []) {
+ for (const comp of entity.components ?? []) {
+ if (comp.type !== 'Text') continue;
+ const key = (comp.data as { i18nKey?: unknown } | undefined)?.i18nKey;
+ if (typeof key === 'string' && key.length > 0) return true;
+ }
+ }
+ return false;
+}
+
/** True if any entity carries a physics component, or a TilemapLayer that may spawn
* colliders at runtime — either baked collidable tile ids (legacy scenes) or a
* `.estileset` reference, whose collision shapes derive live at load and are
@@ -270,6 +286,35 @@ export async function loadRuntimeScene(options: LoadRuntimeSceneOptions): Promis
}
}
+ // Self-gating i18n, mirroring physics: a scene that binds Text.i18nKey needs
+ // the Localization resource + the shipped `.eslocale` tables — installed and
+ // loaded here so no runtime entry can forget. Tables come from the realm's
+ // OWN asset list (they're loaded by key, never referenced by the scene).
+ // Idempotent across scene switches: the resource persists, table loads hit
+ // the Assets cache, addCatalog merges. Awaited so the first frame renders
+ // words, not raw keys.
+ if (sceneUsesI18n(sceneData)) {
+ const autoInstalled = !app.hasResource(Localization);
+ if (autoInstalled) app.addPlugin(new LocalizationPlugin());
+ const tables = (source.listAssetPaths?.() ?? []).filter((p) => p.toLowerCase().endsWith('.eslocale'));
+ if (tables.length === 0) {
+ log.warn('i18n', 'scene binds Text.i18nKey but this realm lists no .eslocale tables — keys will render raw');
+ } else {
+ await Promise.all(tables.map((p) => sceneAssets.loadLocaleTable(p).catch((e: unknown) => {
+ log.error('i18n', `locale table ${p} failed to load: ${e instanceof Error ? e.message : String(e)}`);
+ })));
+ log.info('i18n', `installed — ${tables.length} locale table(s)`);
+ }
+ if (autoInstalled) {
+ // Auto-installed ⇒ nobody configured a locale: follow the player's
+ // system language when a shipped table matches. A game that installs
+ // the plugin itself (or calls setLocale later) is never overridden.
+ const i18n = app.getResource(Localization);
+ const picked = matchLocale(platformLanguage(), i18n.availableLocales());
+ if (picked) i18n.setLocale(picked);
+ }
+ }
+
const entityMap = loadSceneData(app.world, sceneData);
const cppRegistry = app.world.getCppRegistry();
diff --git a/sdk/src/wechatRuntime.ts b/sdk/src/wechatRuntime.ts
index 6896e8745..bca5d254b 100644
--- a/sdk/src/wechatRuntime.ts
+++ b/sdk/src/wechatRuntime.ts
@@ -157,6 +157,10 @@ export async function initWeChatRuntime(config: WeChatRuntimeConfig): Promise<vo
backend: new FileSystemBackend(),
decodePixels: (path) => platformLoadImagePixels(path),
resolveRef: resolvePath,
+ // Logical addresses where present (content-addressed packs rename the
+ // staged file), else the staged path — either keeps the extension the
+ // .eslocale discovery filters on.
+ listAssetPaths: () => manifestModel.allAssets().map((a) => a.address ?? a.path),
};
// The first scene loads eagerly (the game boots into it); every other
diff --git a/sdk/tests/locale-table.test.ts b/sdk/tests/locale-table.test.ts
index 0e1e9e51d..59df379fe 100644
--- a/sdk/tests/locale-table.test.ts
+++ b/sdk/tests/locale-table.test.ts
@@ -7,11 +7,13 @@
* `i18nKey` into live `content` and re-flows it on locale switch.
*/
import { describe, it, expect } from 'vitest';
-import { LocalizationApi, parseLocaleTable } from '../src/i18n/Localization';
+import { LocalizationApi, parseLocaleTable, matchLocale } from '../src/i18n/Localization';
import { LocaleAssetLoader } from '../src/asset/loaders/LocaleAssetLoader';
import type { LoadContext } from '../src/asset/AssetLoader';
import { applyTextLocalization, type TextWorldView } from '../src/ui/text/localize';
import { Text, type TextData } from '../src/ui/core/text';
+import { sceneUsesI18n } from '../src/runtimeLoader';
+import type { SceneData } from '../src/scene';
import type { Entity } from '../src/types';
// =============================================================================
@@ -58,6 +60,46 @@ describe('parseLocaleTable', () => {
});
});
+// =============================================================================
+// matchLocale (platform tag → shipped locale)
+// =============================================================================
+
+describe('matchLocale', () => {
+ const shipped = ['en', 'zh-CN'];
+ it('exact match wins', () => {
+ expect(matchLocale('zh-CN', shipped)).toBe('zh-CN');
+ });
+ it('falls back to the primary language (zh-Hans-CN / zh_CN-normalized → zh-CN)', () => {
+ expect(matchLocale('zh-Hans-CN', shipped)).toBe('zh-CN');
+ expect(matchLocale('zh', shipped)).toBe('zh-CN');
+ expect(matchLocale('en-US', shipped)).toBe('en');
+ });
+ it('null when nothing ships the language (caller keeps its default)', () => {
+ expect(matchLocale('ja-JP', shipped)).toBeNull();
+ expect(matchLocale('fr', [])).toBeNull();
+ });
+});
+
+// =============================================================================
+// sceneUsesI18n (the runtime loader's self-gating scan)
+// =============================================================================
+
+describe('sceneUsesI18n', () => {
+ const scene = (components: Array<{ type: string; data?: unknown }>): SceneData => ({
+ version: '1.0',
+ name: 's',
+ entities: [{ id: 1, name: 'E', parent: null, children: [], components }],
+ } as unknown as SceneData);
+
+ it('true only for a Text with a non-empty i18nKey', () => {
+ expect(sceneUsesI18n(scene([{ type: 'Text', data: { i18nKey: 'menu.play' } }]))).toBe(true);
+ expect(sceneUsesI18n(scene([{ type: 'Text', data: { i18nKey: '' } }]))).toBe(false);
+ expect(sceneUsesI18n(scene([{ type: 'Text', data: {} }]))).toBe(false);
+ expect(sceneUsesI18n(scene([{ type: 'Sprite', data: { i18nKey: 'x' } }]))).toBe(false);
+ expect(sceneUsesI18n(scene([]))).toBe(false);
+ });
+});
+
// =============================================================================
// LocaleAssetLoader
// =============================================================================