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
perf(i18n): cache bounded plain translations with invalidation
yhhae7f30e4827a
diff --git a/examples/ui-localization-debug/README.md b/examples/ui-localization-debug/README.mdindex 3c5ebcd2c..41f965d5e 100644--- a/examples/ui-localization-debug/README.md+++ b/examples/ui-localization-debug/README.md@@ -164,3 +164,8 @@ GPU. Four update ratios and both width states compare all 421 nodes' localpositions and computed dimensions. Raw paired data is in`layout-cpu-web-2026-10-09.json`. This does not benchmark a fresh Yoga rebuild;the incremental-layout SDK regression separately compares against fresh registries.++In the Play fixture, L enables caption binding and switches English/Chinese;+P toggles length-stress preview and U replaces the active catalog entry.+These shortcuts exercise the actual localization binding helper and rendered+Text on Inside, including warmed-cache invalidation. Reopen Play to reset them.diff --git a/examples/ui-localization-debug/VALIDATION.md b/examples/ui-localization-debug/VALIDATION.mdindex 3d3900234..0bb8f0625 100644--- a/examples/ui-localization-debug/VALIDATION.md+++ b/examples/ui-localization-debug/VALIDATION.md@@ -456,3 +456,20 @@ snapshot; live-game-only dialogs and scripts need runtime acceptance separately.- No runtime optimization is claimed. End-to-end frame timing, changed-subtreescope optimization, shaping and device acceptance remain open; RM-009 remainsIn Progress. No local Electron/native runner launched.++## Plain translation cache — 2026-10-09++- Cache up to 256 parameter-free plain-string translations per LocalizationAPI.+ Language/fallback/catalog/preview edits clear the cache. Parameterized and+ plural messages stay uncached, preserving live parameters, externally changed+ plural forms and stateful selector behavior. Missing keys are not cached.+- Before caching, unchanged pseudo-localized UI labels repeatedly expand the+ same text every frame. Regression confirms 100 subsequent reads perform no+ additional expansion; invalidation, bounded eviction, parameter and plural+ behavior are covered. Twenty-five localization tests, SDK build and sixteen+ source/built API checks pass. No historical timing or FPS improvement claimed.+- Built-in browser Play host/SDK/WASM, actual Text binding helper: L switches+ Inside to 设置, then Settings; P shows expanded preview; U replaces the entry+ while preview is active; P restores Updated 更新. No stale translated label.+- This does not complete shaping, whole-frame performance or target-device+ acceptance. RM-009 stays In Progress. No Electron/native runner launched.diff --git a/sdk/src/i18n/Localization.ts b/sdk/src/i18n/Localization.tsindex 5bd9692db..77eca3635 100644--- a/sdk/src/i18n/Localization.ts+++ b/sdk/src/i18n/Localization.ts@@ -61,6 +61,7 @@ export class LocalizationAPI {private locale_: string;private fallback_: string;private pseudo_: PseudoLocalizationOptions | null = null;+ private readonly plainCache_ = new Map<string, string>();constructor(locale = 'en', fallback = 'en') {this.locale_ = locale;@@ -69,19 +70,21 @@ export class LocalizationAPI {/** Merge `entries` into a locale's catalog (later calls override keys). */addCatalog(locale: string, entries: LocaleCatalog): void {+ this.plainCache_.clear();let m = this.catalogs.get(locale);if (!m) { m = new Map(); this.catalogs.set(locale, m); }for (const k of Object.keys(entries)) m.set(k, entries[k]);}- setLocale(locale: string): void { this.locale_ = locale; }+ setLocale(locale: string): void { this.locale_ = locale; this.plainCache_.clear(); }get locale(): string { return this.locale_; }- setFallbackLocale(locale: string): void { this.fallback_ = locale; }+ setFallbackLocale(locale: string): void { this.fallback_ = locale; this.plainCache_.clear(); }get fallbackLocale(): string { return this.fallback_; }/** Opt-in length stress preview. Pass null to restore ordinary translation. */setPseudoLocalization(options: PseudoLocalizationOptions | null): void {+ this.plainCache_.clear();this.pseudo_ = options ? { ...options } : null;}@@ -106,9 +109,21 @@ export class LocalizationAPI {* (a visible, greppable fallback) rather than throwing.*/t(key: string, params?: TParams): string {+ if (params === undefined) {+ const cached = this.plainCache_.get(key);+ if (cached !== undefined) return cached;+ }const entry = this.lookup_(key);if (entry === undefined) return key;- if (typeof entry === 'string') return this.translate_(entry, params);+ if (typeof entry === 'string') {+ const translated = this.translate_(entry, params);+ if (params === undefined) {+ // Bound memory for projects that generate translation keys.+ if (this.plainCache_.size >= 256) this.plainCache_.delete(this.plainCache_.keys().next().value!);+ this.plainCache_.set(key, translated);+ }+ return translated;+ }const count = typeof params?.count === 'number' ? params.count : 0;const selector = this.selectors.get(this.locale_) ?? defaultPluralSelector;return this.translate_(selectPluralForm(entry, count, selector), params);diff --git a/sdk/tests/localization-cache.test.ts b/sdk/tests/localization-cache.test.tsnew file mode 100644index 000000000..0d826040e--- /dev/null+++ b/sdk/tests/localization-cache.test.ts@@ -0,0 +1,62 @@+// SPDX-License-Identifier: Apache-2.0+import { afterEach, expect, it, vi } from 'vitest';+import { LocalizationAPI } from '../src/i18n/Localization';+import * as preview from '../src/i18n/pseudo-localization';++afterEach(() => vi.restoreAllMocks());++it('avoids repeating preview expansion for unchanged plain UI labels', () => {+ const loc = new LocalizationAPI();+ loc.addCatalog('en', { label: 'Settings' });+ loc.setPseudoLocalization({ expansion: 1 });+ const expansion = vi.spyOn(preview, 'pseudoLocalize');+ const first = loc.t('label');+ for (let frame = 0; frame < 100; frame++) expect(loc.t('label')).toBe(first);+ expect(expansion).toHaveBeenCalledTimes(1);+});++it('updates warmed labels on locale, fallback, catalog and preview changes', () => {+ const loc = new LocalizationAPI();+ loc.addCatalog('en', { label: 'Settings' });+ loc.addCatalog('zh', { label: '设置' });+ expect(loc.t('label')).toBe('Settings');+ loc.setLocale('zh'); expect(loc.t('label')).toBe('设置');+ loc.setLocale('unknown'); expect(loc.t('label')).toBe('Settings');+ loc.setFallbackLocale('zh'); expect(loc.t('label')).toBe('设置');+ loc.addCatalog('zh', { label: '音量' }); expect(loc.t('label')).toBe('音量');+ loc.setPseudoLocalization({ expansion: 1, accents: false });+ expect(loc.t('label')).toBe(preview.pseudoLocalize('音量', { expansion: 1, accents: false }));+ loc.setPseudoLocalization(null); expect(loc.t('label')).toBe('音量');+ expect(loc.t('new')).toBe('new');+ loc.addCatalog('zh', { new: '新增' }); expect(loc.t('new')).toBe('新增');+ loc.addCatalog('zh', { label: { zero: '零项', other: '多个' } });+ expect(loc.t('label')).toBe('零项');+});++it('keeps parameters and externally stateful plural rules live', () => {+ const loc = new LocalizationAPI();+ const forms = { zero: 'zero', other: 'other' };+ loc.addCatalog('en', { greeting: 'Hello {name}', plural: forms });+ expect(loc.t('greeting')).toBe('Hello {name}');+ expect(loc.t('greeting', { name: 'Alice' })).toBe('Hello Alice');+ expect(loc.t('greeting', { name: 'Bob' })).toBe('Hello Bob');+ expect(loc.t('plural')).toBe('zero');+ forms.zero = 'updated'; expect(loc.t('plural')).toBe('updated');+ let category: 'one' | 'other' = 'one';+ loc.addCatalog('en', { dynamic: { one: 'one', other: 'other' } });+ loc.setPluralSelector('en', () => category);+ expect(loc.t('dynamic')).toBe('one');+ category = 'other'; expect(loc.t('dynamic')).toBe('other');+});++it('evicts old cached translations while keeping results correct', () => {+ const loc = new LocalizationAPI();+ loc.addCatalog('en', Object.fromEntries(Array.from({ length: 300 }, (_, i) => [`key${i}`, `Label ${i}`])));+ loc.setPseudoLocalization({ expansion: 0 });+ const expansion = vi.spyOn(preview, 'pseudoLocalize');+ for (let i = 0; i < 300; i++) loc.t(`key${i}`);+ expansion.mockClear();+ expect(loc.t('key299')).toBe(preview.pseudoLocalize('Label 299', { expansion: 0 }));+ expansion.mockClear(); loc.t('key299'); expect(expansion).not.toHaveBeenCalled();+ loc.t('key0'); expect(expansion).toHaveBeenCalledTimes(1);+});diff --git a/tools/ui-events-play-project.ts b/tools/ui-events-play-project.tsindex ba4d9704d..a32d7f56b 100644--- a/tools/ui-events-play-project.ts+++ b/tools/ui-events-play-project.ts@@ -1,6 +1,8 @@// SPDX-License-Identifier: Apache-2.0// Disposable browser game script: reactions are driven by real UI clicks.import { addSystemToSchedule, defineSystem, Schedule, Res, GetWorld, UIEvents, Text, UINode, Transform, UIVisual, Interactable, Focusable, px, Input, FocusManager, UIDialog, UIDisplay, createTextInput, Name, TextInput, type TextInputHandle, type InputState, type FocusManagerState, type Entity, type UIEventQueue, type World } from 'esengine';+import { LocalizationAPI, type TextData } from 'esengine';+import { applyTextLocalization } from '../sdk/src/ui/text/localize';const installed = new WeakMap<World, () => void>();addSystemToSchedule(Schedule.Update, defineSystem([Res(UIEvents), GetWorld(), Res(Input), Res(FocusManager)], (events: UIEventQueue, world: World, input: InputState, focus: FocusManagerState) => {const update = installed.get(world);@@ -12,9 +14,26 @@ addSystemToSchedule(Schedule.Update, defineSystem([Res(UIEvents), GetWorld(), Relet count = 0, dynamic: Entity | null = null, dialogHost: Entity | null = null, nested: Entity | null = null;let textField: TextInputHandle | null = null;const restore = new Set<Entity>();+ const locale = new LocalizationAPI();+ locale.addCatalog('en', { caption: 'Settings' });+ locale.addCatalog('zh', { caption: '设置' });+ let localized = false, preview = false;+ const boundText = { getEntitiesWithComponents: () => [inside],+ get: (entity: Entity) => world.get(entity, Text),+ insert: (entity: Entity, _component: unknown, data: unknown) => world.insert(entity, Text, data as TextData) };installed.set(world, () => {+ if (localized) applyTextLocalization(boundText, locale);// Fixture shortcuts must not react to letters typed into an engine field.if (focus.focusedEntity !== null && world.has(focus.focusedEntity, TextInput)) return;+ if (input.isKeyPressed('KeyL')) {+ localized = true;+ world.insert(inside, Text, { ...world.get(inside, Text), i18nKey: 'caption' });+ locale.setLocale(locale.locale === 'en' ? 'zh' : 'en');+ }+ if (input.isKeyPressed('KeyP') && localized) {+ preview = !preview; locale.setPseudoLocalization(preview ? { expansion: 1 } : null);+ }+ if (input.isKeyPressed('KeyU') && localized) locale.addCatalog(locale.locale, { caption: 'Updated 更新' });if (input.isKeyPressed('KeyK')) {const text = world.get(inside, Text);const first = text.content !== 'A|B';