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(ui)!: project-declared widget theme + retire the Canvas2D-era inline-image machinery

esengine7589826f7a2d
diff --git a/desktop/src/engine/playProtocol.ts b/desktop/src/engine/playProtocol.ts
index 6d9e351d5..eb036fddf 100644
--- a/desktop/src/engine/playProtocol.ts
+++ b/desktop/src/engine/playProtocol.ts
@@ -59,6 +59,8 @@ export interface PlayPayload {
physicsConfig?: PhysicsPluginConfig;
/** Project mixer state (bus volumes / effects / duck rules) — forwarded. */
audioConfig?: AudioProjectConfig;
+ /** Project widget theme; absent = dark (the default). */
+ uiTheme?: 'light';
/** Bitmask of render layers (0..31) that y-sort within the layer — forwarded. */
ySortLayers?: number;
/** Project color space — 'linear' boots the realm on the linear-light pipeline. */
diff --git a/desktop/src/i18n/messages/project.ts b/desktop/src/i18n/messages/project.ts
index b2f5ec777..52a19fe4c 100644
--- a/desktop/src/i18n/messages/project.ts
+++ b/desktop/src/i18n/messages/project.ts
@@ -114,6 +114,7 @@ export const projectMessages = defineMessages({
'proj.savePlatformFailed': { en: 'Failed to save platform settings', zh: '保存平台设置失败' },
'proj.savePhysicsFailed': { en: 'Failed to save physics setting', zh: '保存物理设置失败' },
'proj.saveAudioFailed': { en: 'Failed to save audio setting', zh: '保存音频设置失败' },
+ 'proj.saveUiThemeFailed': { en: 'Failed to save UI theme', zh: '保存 UI 主题失败' },
'proj.startupScene': { en: 'Startup scene: {name}', zh: '启动场景:{name}' },
'proj.saveStartupSceneFailed': { en: 'Failed to save startup scene', zh: '保存启动场景失败' },
'proj.excludedFromExport': { en: 'Excluded from export: {name}', zh: '已从导出中排除:{name}' },
diff --git a/desktop/src/i18n/messages/settings.ts b/desktop/src/i18n/messages/settings.ts
index 9c38ded9c..2b059ac8f 100644
--- a/desktop/src/i18n/messages/settings.ts
+++ b/desktop/src/i18n/messages/settings.ts
@@ -36,6 +36,15 @@ export const settingsMessages = defineMessages({
'set.section.display': { en: 'Display', zh: '显示' },
'set.section.physics': { en: 'Physics', zh: '物理' },
'set.section.rendering': { en: 'Rendering', zh: '渲染' },
+ 'set.section.ui': { en: 'UI', zh: 'UI' },
+ 'set.group.uiTheme': { en: 'Widget Theme', zh: '控件主题' },
+ 'set.project.ui.theme': { en: 'Theme', zh: '主题' },
+ 'set.project.ui.theme.desc': {
+ en: 'Design-token palette for the built-in widgets. Applied when the game boots; themed widgets (including placed prefabs) re-resolve their colors.',
+ zh: '内置控件的设计令牌配色。游戏启动时应用;带主题标记的控件(包括摆放的预制体)会重新解析颜色。',
+ },
+ 'set.project.ui.theme.dark': { en: 'Dark', zh: '暗色' },
+ 'set.project.ui.theme.light': { en: 'Light', zh: '亮色' },
'set.section.packaging': { en: 'Packaging', zh: '打包' },
// — Group headers —
diff --git a/desktop/src/playHost.ts b/desktop/src/playHost.ts
index afa15e364..779c38e1d 100644
--- a/desktop/src/playHost.ts
+++ b/desktop/src/playHost.ts
@@ -211,6 +211,7 @@ async function buildAppAndRun(msg: InitMessage): Promise<void> {
physicsEnabled: msg.physicsEnabled,
physicsConfig: msg.physicsConfig,
audioConfig: msg.audioConfig,
+ uiTheme: msg.uiTheme,
enableStats: true, // editor profiler: per-phase / per-system frame timing
});
// Realm-local debug handle for automation/diagnostics (mirrors the headless
diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.ts
index 773c7b9f9..dfd8e84ed 100644
--- a/desktop/src/project/ProjectStore.ts
+++ b/desktop/src/project/ProjectStore.ts
@@ -1036,6 +1036,7 @@ class ProjectStoreImpl {
physicsEnabled?: boolean;
physicsConfig?: PhysicsPluginConfig;
audioConfig?: AudioProjectConfig;
+ uiTheme?: 'light';
ySortLayers?: number;
colorSpace?: 'gamma' | 'linear';
screenFit?: { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number };
@@ -1072,9 +1073,11 @@ class ProjectStoreImpl {
// Camera fit: only sent when the project opts in (scaleMode ≥ 0), so a played
// scene with no fit boots exactly as before.
const screenFit = this.screenFit();
+ const uiTheme = this.uiTheme();
return {
sceneData, assetManifest, physicsEnabled: f.enabled, physicsConfig,
...(audioConfig.buses ? { audioConfig } : {}),
+ ...(uiTheme === 'light' ? { uiTheme } : {}),
...(ySortLayers !== 0 ? { ySortLayers } : {}),
...(colorSpace === 'linear' ? { colorSpace } : {}),
...(screenFit.scaleMode >= 0 ? { screenFit } : {}),
@@ -1086,6 +1089,33 @@ class ProjectStoreImpl {
return this.state?.features?.audio ?? {};
}
+ /** The project's built-in widget theme (Project Settings → UI). */
+ uiTheme(): 'dark' | 'light' {
+ return this.state?.features?.ui?.theme === 'light' ? 'light' : 'dark';
+ }
+
+ /** Persist the widget theme; dark (the default) is expressed by absence. */
+ async setUiTheme(theme: 'dark' | 'light'): Promise<void> {
+ const st = this.state;
+ if (!st) return;
+ const ui = theme === 'light' ? { theme } : undefined;
+ const features: ProjectFeatures = { ...st.features };
+ if (ui) features.ui = ui;
+ else delete features.ui;
+ this.store.setState({ project: { ...st, features } });
+ try {
+ const raw = JSON.parse(await window.estella.fs.read(PROJECT_MANIFEST_FILE)) as Record<string, unknown>;
+ const rf = { ...(raw.features as Record<string, unknown> ?? {}) };
+ if (ui) rf.ui = ui;
+ else delete rf.ui;
+ raw.features = rf;
+ await window.estella.fs.write(PROJECT_MANIFEST_FILE, JSON.stringify(raw, null, 2) + '\n');
+ } catch (e) {
+ Toasts.push(t('proj.saveUiThemeFailed'), 'error');
+ console.error('[project] setUiTheme write failed', e);
+ }
+ }
+
/**
* Replace the project mixer state and persist to `project.esproject`. Rewrites
* the RAW manifest JSON so unmodeled fields survive; in-memory state first so
diff --git a/desktop/src/project/format.ts b/desktop/src/project/format.ts
index c28ed3fe8..f7600a295 100644
--- a/desktop/src/project/format.ts
+++ b/desktop/src/project/format.ts
@@ -101,6 +101,11 @@ export interface ProjectFeatures {
};
/** Project mixer state (bus volumes / custom buses / effects / duck rules). */
audio?: AudioProjectConfig;
+ ui?: {
+ /** Built-in widget theme. Only 'light' persists; dark (the default) is
+ * expressed by absence — like rendering.colorSpace. */
+ theme?: 'light';
+ };
}
export type ScreenOrientation = 'portrait' | 'landscape';
@@ -322,6 +327,10 @@ export function parseManifest(raw: unknown): ProjectManifest {
const audio = parseAudioProjectConfig(f.audio);
if (audio.buses) features.audio = audio;
}
+ if (f.ui && typeof f.ui === 'object') {
+ const u = f.ui as Record<string, unknown>;
+ if (u.theme === 'light') features.ui = { theme: 'light' };
+ }
if (Object.keys(features).length > 0) manifest.features = features;
}
if (o.packaging && typeof o.packaging === 'object') {
diff --git a/desktop/src/settings/projectSettings.ts b/desktop/src/settings/projectSettings.ts
index 088b4ac31..953278178 100644
--- a/desktop/src/settings/projectSettings.ts
+++ b/desktop/src/settings/projectSettings.ts
@@ -236,7 +236,29 @@ settingsRegistry.register({
});
// ── Packaging (per-platform Project Settings; read by the export, persisted to project.esproject) ──
-settingsRegistry.registerSection({ id: 'packaging', label: t('set.section.packaging'), category: 'project', order: 3 });
+settingsRegistry.registerSection({ id: 'ui', label: t('set.section.ui'), category: 'project', order: 3 });
+
+settingsRegistry.register({
+ id: 'project.ui.theme',
+ type: 'enum',
+ scope: 'project',
+ section: 'ui',
+ group: t('set.group.uiTheme'),
+ label: t('set.project.ui.theme'),
+ description: t('set.project.ui.theme.desc'),
+ default: 'dark',
+ segmented: true,
+ options: [
+ { value: 'dark', label: t('set.project.ui.theme.dark') },
+ { value: 'light', label: t('set.project.ui.theme.light') },
+ ],
+ bind: {
+ get: () => ProjectStore.uiTheme(),
+ set: (v) => { void ProjectStore.setUiTheme(v as 'dark' | 'light'); },
+ },
+});
+
+settingsRegistry.registerSection({ id: 'packaging', label: t('set.section.packaging'), category: 'project', order: 4 });
settingsRegistry.register({
id: 'project.packaging.wechat.appid',
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index e09f51482..df9512b3e 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: 1228 stable · 17 beta · 1 deprecated
+Symbols: 1223 stable · 17 beta · 1 deprecated
## ABI_LAYOUT_HASH — const
```
@@ -1850,20 +1850,6 @@ pixels: Uint8Array<ArrayBufferLike>
width: number
```
-## DefaultImageResolver — class
-```
-invalidate: (src: string) => void
-invalidateAll: () => void
-pendingEntities: Set<number>
-preload: (src: string) => void
-resolve: (src: string) => ResolvedImage | null
-retryFailed: () => void
-trackEntity: (entity: Entity, srcs: string[]) => void
-untrackEntity: (entity: Entity) => void
-static new (urlMapper: UrlMapper): DefaultImageResolver
-static prototype: DefaultImageResolver
-```
-
## DialogHandle — interface
```
close: () => void
@@ -2943,12 +2929,6 @@ number
number
```
-## ImageResolver — interface
-```
-pendingEntities: Set<number>
-resolve: (src: string) => ResolvedImage | null
-```
-
## ImageSegment — interface
```
height: number
@@ -3371,6 +3351,7 @@ sceneName: string | undefined
source: RuntimeAssetSource
spineManager: SpineManager | null | undefined
spineModule: SpineWasmModule | null | undefined
+uiTheme: "dark" | "light" | undefined
```
## LoadedTilemapLayer — interface
@@ -4397,6 +4378,7 @@ module: ESEngineModule
physicsConfig: PhysicsPluginConfig | undefined
physicsEnabled: boolean | undefined
sceneData: SceneData
+uiTheme: "dark" | "light" | undefined
wasmBaseUrl: string | undefined
```
@@ -4412,6 +4394,7 @@ manifest: AddressableManifest | null | undefined
module: ESEngineModule
physicsConfig: { gravity?: Vec2; fixedTimestep?: number; subStepCount?: number; } | undefined
scenes: { name: string; data: SceneData; }[]
+uiTheme: "dark" | "light" | undefined
ySortLayers: number | undefined
```
@@ -5018,11 +5001,6 @@ static new <T>(value: T, setter: (v: T) => void): ResMutInstance<T>
static prototype: ResMutInstance<any>
```
-## ResolvedImage — type
-```
-ImageBitmap | HTMLImageElement
-```
-
## ResolvedTileCollision — interface
```
density: number | undefined
@@ -5145,6 +5123,7 @@ scenes: { name: string; data?: SceneData; path?: string; }[]
source: RuntimeAssetSource
spineManager: SpineManager | null | undefined
spineModule: SpineWasmModule | null | undefined
+uiTheme: "dark" | "light" | undefined
```
## RuntimeOnly — const
@@ -8334,11 +8313,6 @@ FsmPlugin
(key: string): CompiledFsm | undefined
```
-## getImageResolver — function
-```
-(): ImageResolver | null
-```
-
## getLogger — function
```
(): Logger
@@ -9219,11 +9193,6 @@ Plugin
(enabled: boolean): void
```
-## setImageResolver — function
-```
-(resolver: ImageResolver | null): void
-```
-
## setInitial — function
```
(def: FsmDefinition, name: string): FsmDefinition
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 0182c7ee3..5b0e8e8b9 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: 1227 stable · 19 beta · 1 deprecated
+Symbols: 1222 stable · 19 beta · 1 deprecated
## ANCHOR_AXES — const
```
@@ -1845,20 +1845,6 @@ pixels: Uint8Array<ArrayBufferLike>
width: number
```
-## DefaultImageResolver — class
-```
-invalidate: (src: string) => void
-invalidateAll: () => void
-pendingEntities: Set<number>
-preload: (src: string) => void
-resolve: (src: string) => ResolvedImage | null
-retryFailed: () => void
-trackEntity: (entity: Entity, srcs: string[]) => void
-untrackEntity: (entity: Entity) => void
-static new (urlMapper: UrlMapper): DefaultImageResolver
-static prototype: DefaultImageResolver
-```
-
## DialogHandle — interface
```
close: () => void
@@ -2938,12 +2924,6 @@ number
number
```
-## ImageResolver — interface
-```
-pendingEntities: Set<number>
-resolve: (src: string) => ResolvedImage | null
-```
-
## ImageSegment — interface
```
height: number
@@ -3366,6 +3346,7 @@ sceneName: string | undefined
source: RuntimeAssetSource
spineManager: SpineManager | null | undefined
spineModule: SpineWasmModule | null | undefined
+uiTheme: "dark" | "light" | undefined
```
## LoadedTilemapLayer — interface
@@ -4392,6 +4373,7 @@ module: ESEngineModule
physicsConfig: PhysicsPluginConfig | undefined
physicsEnabled: boolean | undefined
sceneData: SceneData
+uiTheme: "dark" | "light" | undefined
wasmBaseUrl: string | undefined
```
@@ -4407,6 +4389,7 @@ manifest: AddressableManifest | null | undefined
module: ESEngineModule
physicsConfig: { gravity?: Vec2; fixedTimestep?: number; subStepCount?: number; } | undefined
scenes: { name: string; data: SceneData; }[]
+uiTheme: "dark" | "light" | undefined
ySortLayers: number | undefined
```
@@ -5013,11 +4996,6 @@ static new <T>(value: T, setter: (v: T) => void): ResMutInstance<T>
static prototype: ResMutInstance<any>
```
-## ResolvedImage — type
-```
-ImageBitmap | HTMLImageElement
-```
-
## ResolvedTileCollision — interface
```
density: number | undefined
@@ -5140,6 +5118,7 @@ scenes: { name: string; data?: SceneData; path?: string; }[]
source: RuntimeAssetSource
spineManager: SpineManager | null | undefined
spineModule: SpineWasmModule | null | undefined
+uiTheme: "dark" | "light" | undefined
```
## RuntimeOnly — const
@@ -8329,11 +8308,6 @@ FsmPlugin
(key: string): CompiledFsm | undefined
```
-## getImageResolver — function
-```
-(): ImageResolver | null
-```
-
## getLogger — function
```
(): Logger
@@ -9224,11 +9198,6 @@ Plugin
(enabled: boolean): void
```
-## setImageResolver — function
-```
-(resolver: ImageResolver | null): void
-```
-
## setInitial — function
```
(def: FsmDefinition, name: string): FsmDefinition
diff --git a/sdk/src/core-ui.ts b/sdk/src/core-ui.ts
index eb82842ee..6b820a1f8 100644
--- a/sdk/src/core-ui.ts
+++ b/sdk/src/core-ui.ts
@@ -27,12 +27,7 @@ export {
UILayoutGeneration,
UIMask,
textPlugin,
- DefaultImageResolver,
- setImageResolver,
- getImageResolver,
parseRichText,
- type ImageResolver,
- type ResolvedImage,
type RichTextRun,
type TextSegment,
type ImageSegment,
diff --git a/sdk/src/playRealmRuntime.ts b/sdk/src/playRealmRuntime.ts
index b6f9f23e9..c193ccd55 100644
--- a/sdk/src/playRealmRuntime.ts
+++ b/sdk/src/playRealmRuntime.ts
@@ -73,6 +73,8 @@ export interface PlayRealmRuntimeConfig {
/** Project-declared physics world config (gravity, solver tuning, collision-layer
* masks, sleep/continuous) from the editor's Project Settings. */
physicsConfig?: PhysicsPluginConfig;
+ /** Project-declared UI theme; 'light' re-skins ThemeStyle-tagged widgets at boot. */
+ uiTheme?: 'dark' | 'light';
/** Project-declared mixer state (bus volumes / effects / duck rules). */
audioConfig?: AudioProjectConfig;
/** Turn on per-phase / per-system frame timing (editor profiler; off in shipped games). */
@@ -182,6 +184,7 @@ export async function initPlayRealmRuntime(config: PlayRealmRuntimeConfig): Prom
aspectRatio: canvas.width / canvas.height,
physicsEnabled: config.physicsEnabled,
physicsConfig: config.physicsConfig,
+ uiTheme: config.uiTheme,
audioConfig: config.audioConfig,
// Physics (and spine) are acquired from app.sideModules — the fetch host
// createWebApp built from this realm's wasmBaseUrl.
diff --git a/sdk/src/playableRuntime.ts b/sdk/src/playableRuntime.ts
index 4ca1e4ef6..d6cb086de 100644
--- a/sdk/src/playableRuntime.ts
+++ b/sdk/src/playableRuntime.ts
@@ -38,6 +38,8 @@ export interface PlayableRuntimeConfig {
scenes: Array<{ name: string; data: SceneData }>;
firstScene: string;
physicsConfig?: { gravity?: Vec2; fixedTimestep?: number; subStepCount?: number };
+ /** Project-declared UI theme; 'light' re-skins ThemeStyle-tagged widgets at boot. */
+ uiTheme?: 'dark' | 'light';
/** Project-declared mixer state (bus volumes / effects / duck rules). */
audioConfig?: AudioProjectConfig;
/** Bitmask of render layers (0..31) that y-sort within the layer (Project Settings → Rendering). */
@@ -123,6 +125,7 @@ export async function initPlayableRuntime(config: PlayableRuntimeConfig): Promis
scenes,
firstScene,
physicsConfig: config.physicsConfig,
+ uiTheme: config.uiTheme,
audioConfig: config.audioConfig,
aspectRatio: config.canvas.width / config.canvas.height,
});
diff --git a/sdk/src/runtimeLoader.ts b/sdk/src/runtimeLoader.ts
index 29c52f81c..b9ac20ef5 100644
--- a/sdk/src/runtimeLoader.ts
+++ b/sdk/src/runtimeLoader.ts
@@ -7,6 +7,7 @@
import { SceneOwner } from './component';
import { loadSceneData, updateCameraAspectRatio, type SceneData } from './scene';
+import { switchTheme, LIGHT_TOKENS } from './ui';
import { discoverSceneAssets } from './asset/discoverAssets';
import type { ESEngineModule } from './wasm';
import type { SpineWasmModule } from './spine/SpineModuleLoader';
@@ -175,6 +176,10 @@ export interface LoadRuntimeSceneOptions {
* physics even for runtime-spawned bodies the static scene doesn't show.
* OR-combined with a content scan. */
physicsEnabled?: boolean;
+ /** Project-declared UI theme (Project Settings → UI). Dark is the default;
+ * 'light' switches the token set AND re-resolves already-instantiated
+ * ThemeStyle-tagged widgets (prefab instances carry dark baked values). */
+ uiTheme?: 'dark' | 'light';
sceneName?: string;
}
@@ -219,7 +224,7 @@ export function sceneUsesPhysics(sceneData: SceneData): boolean {
}
export async function loadRuntimeScene(options: LoadRuntimeSceneOptions): Promise<void> {
- const { app, module, sceneData, source, physicsConfig, physicsEnabled, sceneName } = options;
+ const { app, module, sceneData, source, physicsConfig, physicsEnabled, uiTheme, sceneName } = options;
// The SpineManager is owned by SpinePlugin (built from the realm's
// app.sideModules host); read it from there so every realm — play / playable /
@@ -326,6 +331,10 @@ export async function loadRuntimeScene(options: LoadRuntimeSceneOptions): Promis
const entityMap = loadSceneData(app.world, sceneData);
+ // Apply the project theme over the freshly instantiated scene: prefabs bake
+ // the dark palette, so a light project re-resolves every ThemeStyle tag.
+ if (uiTheme === 'light') switchTheme(app.world, LIGHT_TOKENS);
+
const cppRegistry = app.world.getCppRegistry();
if (cppRegistry) {
(module as ESEngineModule).transform_update(cppRegistry);
@@ -399,6 +408,8 @@ export interface RuntimeInitConfig {
/** Project-declared mixer state (bus volumes / custom buses / effects / duck
* rules) — threaded from the editor's audio config, applied once at boot. */
audioConfig?: AudioProjectConfig;
+ /** Project-declared UI theme; see {@link LoadRuntimeSceneOptions.uiTheme}. */
+ uiTheme?: 'dark' | 'light';
aspectRatio?: number;
}
@@ -427,6 +438,7 @@ export async function initRuntime(config: RuntimeInitConfig): Promise<void> {
physicsModule: config.physicsModule,
physicsConfig: config.physicsConfig,
physicsEnabled: config.physicsEnabled,
+ uiTheme: config.uiTheme,
};
const mgr = app.getResource(SceneManager);
diff --git a/sdk/src/ui/index.ts b/sdk/src/ui/index.ts
index 8ee194855..803834bf7 100644
--- a/sdk/src/ui/index.ts
+++ b/sdk/src/ui/index.ts
@@ -423,25 +423,6 @@ export {
type RichTextRun,
} from './text/rich-text-parser';
-export {
- createFontSet,
- layoutRichText,
- measureLayoutWidth,
- type FontSet,
- type PositionedRun,
- type TextPositionedRun,
- type ImagePositionedRun,
- type LayoutLine,
-} from './text/rich-text-layout';
-
-export {
- setImageResolver,
- getImageResolver,
- DefaultImageResolver,
- type ImageResolver,
- type ResolvedImage,
-} from './text/image-resolver';
-
// ─── SDF glyph-atlas text ───────────────────────────────────────────────────
export {
diff --git a/sdk/src/ui/text/image-resolver.ts b/sdk/src/ui/text/image-resolver.ts
deleted file mode 100644
index bd5a0118a..000000000
--- a/sdk/src/ui/text/image-resolver.ts
+++ /dev/null
@@ -1,131 +0,0 @@
-// SPDX-License-Identifier: Apache-2.0
-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-import type { Entity } from '../../types';
-
-export type ResolvedImage = ImageBitmap | HTMLImageElement;
-
-export interface ImageResolver {
- resolve(src: string): ResolvedImage | null;
- readonly pendingEntities: Set<Entity>;
-}
-
-let globalResolver: ImageResolver | null = null;
-
-export function setImageResolver(resolver: ImageResolver | null): void {
- globalResolver = resolver;
-}
-
-export function getImageResolver(): ImageResolver | null {
- return globalResolver;
-}
-
-type UrlMapper = (src: string) => string;
-
-const RETRY_INTERVAL_MS = 3000;
-
-export class DefaultImageResolver implements ImageResolver {
- readonly pendingEntities = new Set<Entity>();
- private cache_ = new Map<string, ResolvedImage>();
- private loading_ = new Set<string>();
- private failed_ = new Map<string, number>();
- private entitySrcMap_ = new Map<Entity, Set<string>>();
- private srcEntityMap_ = new Map<string, Set<Entity>>();
- private urlMapper_: UrlMapper;
-
- constructor(urlMapper: UrlMapper) {
- this.urlMapper_ = urlMapper;
- }
-
- resolve(src: string): ResolvedImage | null {
- return this.cache_.get(src) ?? null;
- }
-
- preload(src: string): void {
- if (this.cache_.has(src) || this.loading_.has(src)) return;
- const failedAt = this.failed_.get(src);
- if (failedAt !== undefined && Date.now() - failedAt < RETRY_INTERVAL_MS) return;
- this.loading_.add(src);
- this.failed_.delete(src);
- const url = this.urlMapper_(src);
- const img = new Image();
- img.crossOrigin = 'anonymous';
- img.onload = () => {
- this.cache_.set(src, img);
- this.loading_.delete(src);
- this.failed_.delete(src);
- const entities = this.srcEntityMap_.get(src);
- if (entities) {
- for (const e of entities) this.pendingEntities.add(e);
- }
- };
- img.onerror = () => {
- this.loading_.delete(src);
- this.failed_.set(src, Date.now());
- };
- img.src = url;
- }
-
- trackEntity(entity: Entity, srcs: string[]): void {
- let oldSrcs = this.entitySrcMap_.get(entity);
- if (oldSrcs) {
- for (const s of oldSrcs) {
- this.srcEntityMap_.get(s)?.delete(entity);
- }
- oldSrcs.clear();
- } else {
- oldSrcs = new Set();
- this.entitySrcMap_.set(entity, oldSrcs);
- }
- for (const src of srcs) {
- oldSrcs.add(src);
- let entities = this.srcEntityMap_.get(src);
- if (!entities) {
- entities = new Set();
- this.srcEntityMap_.set(src, entities);
- }
- entities.add(entity);
- this.preload(src);
- }
- }
-
- invalidate(src: string): void {
- this.cache_.delete(src);
- this.loading_.delete(src);
- this.failed_.delete(src);
- const entities = this.srcEntityMap_.get(src);
- if (entities) {
- for (const e of entities) this.pendingEntities.add(e);
- }
- }
-
- invalidateAll(): void {
- const allEntities = new Set<Entity>();
- for (const entities of this.srcEntityMap_.values()) {
- for (const e of entities) allEntities.add(e);
- }
- this.cache_.clear();
- this.loading_.clear();
- this.failed_.clear();
- for (const e of allEntities) this.pendingEntities.add(e);
- }
-
- retryFailed(): void {
- if (this.failed_.size === 0) return;
- const now = Date.now();
- for (const [src, failedAt] of this.failed_) {
- if (now - failedAt >= RETRY_INTERVAL_MS) {
- this.preload(src);
- }
- }
- }
-
- untrackEntity(entity: Entity): void {
- const srcs = this.entitySrcMap_.get(entity);
- if (srcs) {
- for (const s of srcs) {
- this.srcEntityMap_.get(s)?.delete(entity);
- }
- this.entitySrcMap_.delete(entity);
- }
- }
-}
diff --git a/sdk/src/ui/text/rich-text-layout.ts b/sdk/src/ui/text/rich-text-layout.ts
deleted file mode 100644
index 79e1693b7..000000000
--- a/sdk/src/ui/text/rich-text-layout.ts
+++ /dev/null
@@ -1,210 +0,0 @@
-// SPDX-License-Identifier: Apache-2.0
-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-import type { Color } from '../../types';
-import type { RichTextRun, ImageValign } from './rich-text-parser';
-import { isWordChar } from '../util/helpers';
-
-export interface FontSet {
- fonts: [string, string, string, string];
-}
-
-export interface TextPositionedRun {
- type: 'text';
- text: string;
- x: number;
- width: number;
- fontIndex: number;
- color: Color;
-}
-
-export interface ImagePositionedRun {
- type: 'image';
- src: string;
- x: number;
- width: number;
- height: number;
- valign: ImageValign;
- offsetX: number;
- offsetY: number;
- tint: Color | null;
-}
-
-export type PositionedRun = TextPositionedRun | ImagePositionedRun;
-
-export interface LayoutLine {
- runs: PositionedRun[];
- width: number;
- height?: number;
-}
-
-export function createFontSet(size: number, family: string): FontSet {
- return {
- fonts: [
- `${size}px ${family}`,
- `bold ${size}px ${family}`,
- `italic ${size}px ${family}`,
- `italic bold ${size}px ${family}`,
- ],
- };
-}
-
-export function fontIndex(bold: boolean, italic: boolean): number {
- return (bold ? 1 : 0) | (italic ? 2 : 0);
-}
-
-export function measureLayoutWidth(lines: LayoutLine[]): number {
- let max = 0;
- for (const line of lines) {
- if (line.width > max) max = line.width;
- }
- return max;
-}
-
-type Ctx = CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D;
-
-function appendTextRun(
- line: PositionedRun[], lineWidth: number,
- text: string, width: number, fi: number, color: Color,
-): number {
- line.push({ type: 'text', text, x: lineWidth, width, fontIndex: fi, color });
- return lineWidth + width;
-}
-
-function finishLine(runs: PositionedRun[], width: number): LayoutLine {
- return { runs, width };
-}
-
-function breakRun(
- ctx: Ctx, text: string, available: number,
-): { fit: string; rest: string } {
- if (ctx.measureText(text).width <= available) {
- return { fit: text, rest: '' };
- }
-
- let breakPos = 0;
- for (let j = 0; j < text.length; j++) {
- if (ctx.measureText(text.slice(0, j + 1)).width > available) break;
- breakPos = j + 1;
- }
-
- if (breakPos === 0) {
- return { fit: '', rest: text };
- }
-
- const charAfter = text.charCodeAt(breakPos);
- if (breakPos < text.length && isWordChar(charAfter)) {
- const lastFitChar = text.charCodeAt(breakPos - 1);
- if (isWordChar(lastFitChar)) {
- let wordBreak = -1;
- for (let j = breakPos - 1; j >= 0; j--) {
- if (!isWordChar(text.charCodeAt(j))) {
- wordBreak = j + 1;
- break;
- }
- }
- if (wordBreak > 0) {
- return { fit: text.slice(0, wordBreak), rest: text.slice(wordBreak) };
- }
- }
- }
-
- return { fit: text.slice(0, breakPos), rest: text.slice(breakPos) };
-}
-
-export function layoutRichText(
- ctx: Ctx,
- runs: RichTextRun[],
- fontSet: FontSet,
- baseColor: Color,
- maxWidth: number,
- fontSize: number = 16,
-): LayoutLine[] {
- const lines: LayoutLine[] = [];
- let currentRuns: PositionedRun[] = [];
- let lineWidth = 0;
- let lastFI = -1;
-
- let lineMaxImgH = 0;
-
- function emitLine(): void {
- const line = finishLine(currentRuns, lineWidth);
- if (lineMaxImgH > 0) line.height = lineMaxImgH;
- lines.push(line);
- currentRuns = [];
- lineWidth = 0;
- lineMaxImgH = 0;
- }
-
- for (const run of runs) {
- if (run.type === 'image') {
- const s = run.scale;
- const imgW = (run.width || fontSize) * s;
- const imgH = (run.height || fontSize) * s;
- if (maxWidth > 0 && lineWidth + imgW > maxWidth && currentRuns.length > 0) {
- emitLine();
- }
- currentRuns.push({
- type: 'image', src: run.src, x: lineWidth,
- width: imgW, height: imgH, valign: run.valign,
- offsetX: run.offsetX, offsetY: run.offsetY, tint: run.tint,
- });
- lineWidth += imgW;
- if (imgH > lineMaxImgH) lineMaxImgH = imgH;
- continue;
- }
- const fi = fontIndex(run.bold, run.italic);
- if (fi !== lastFI) {
- ctx.font = fontSet.fonts[fi];
- lastFI = fi;
- }
- const color = run.color ?? baseColor;
-
- const parts = run.text.split('\n');
- for (let p = 0; p < parts.length; p++) {
- if (p > 0) emitLine();
-
- const part = parts[p];
- if (!part) continue;
-
- if (maxWidth <= 0) {
- const w = ctx.measureText(part).width;
- lineWidth = appendTextRun(currentRuns, lineWidth, part, w, fi, color);
- continue;
- }
-
- let remaining = part;
- while (remaining) {
- const available = maxWidth - lineWidth;
- const { fit, rest } = breakRun(ctx, remaining, available);
-
- if (fit) {
- const w = ctx.measureText(fit).width;
- lineWidth = appendTextRun(currentRuns, lineWidth, fit, w, fi, color);
- }
-
- if (rest) {
- if (!fit && currentRuns.length === 0) {
- const oneChar = remaining[0];
- const w = ctx.measureText(oneChar).width;
- lineWidth = appendTextRun(currentRuns, lineWidth, oneChar, w, fi, color);
- remaining = remaining.slice(1);
- }
- emitLine();
- remaining = rest;
- if (fi !== lastFI) {
- ctx.font = fontSet.fonts[fi];
- lastFI = fi;
- }
- } else {
- remaining = '';
- }
- }
- }
- }
-
- if (currentRuns.length > 0 || lines.length === 0) {
- emitLine();
- }
-
- return lines;
-}
diff --git a/sdk/src/wechatRuntime.ts b/sdk/src/wechatRuntime.ts
index 68833f454..7c895c7e9 100644
--- a/sdk/src/wechatRuntime.ts
+++ b/sdk/src/wechatRuntime.ts
@@ -72,6 +72,8 @@ export interface WeChatRuntimeConfig {
firstScene: string;
runtimeConfig?: RuntimeBuildConfig;
physicsConfig?: { gravity?: Vec2; fixedTimestep?: number; subStepCount?: number };
+ /** Project-declared UI theme; 'light' re-skins ThemeStyle-tagged widgets at boot. */
+ uiTheme?: 'dark' | 'light';
/** Project-declared mixer state (routing labels only on WeChat — no DSP graph). */
audioConfig?: AudioProjectConfig;
/** Bitmask of render layers (0..31) that y-sort within the layer (Project Settings → Rendering). */
@@ -201,6 +203,7 @@ export async function initWeChatRuntime(config: WeChatRuntimeConfig): Promise<vo
scenes,
firstScene: config.firstScene,
physicsConfig: config.physicsConfig,
+ uiTheme: config.uiTheme,
audioConfig: config.audioConfig,
aspectRatio: canvas.width / canvas.height,
});
diff --git a/sdk/tests/RichTextLayout.test.ts b/sdk/tests/RichTextLayout.test.ts
deleted file mode 100644
index 2b281b043..000000000
--- a/sdk/tests/RichTextLayout.test.ts
+++ /dev/null
@@ -1,118 +0,0 @@
-// SPDX-License-Identifier: Apache-2.0
-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-import { describe, it, expect, beforeEach } from 'vitest';
-import { layoutRichText, createFontSet, type LayoutLine } from '../src/ui/text/rich-text-layout';
-import type { RichTextRun, ImageSegment } from '../src/ui/text/rich-text-parser';
-import type { Color } from '../src/types';
-
-const WHITE: Color = { r: 1, g: 1, b: 1, a: 1 };
-
-function createMockCtx() {
- const charWidth = 8;
- let currentFont = '';
- return {
- font: '',
- set _font(v: string) { currentFont = v; },
- get _currentFont() { return currentFont; },
- measureText(text: string) {
- return { width: text.length * charWidth };
- },
- } as unknown as OffscreenCanvasRenderingContext2D;
-}
-
-function img(src: string, width: number, height: number): ImageSegment {
- return { type: 'image', src, width, height, valign: 'baseline', offsetX: 0, offsetY: 0, scale: 1, tint: null };
-}
-
-describe('layoutRichText – image runs', () => {
- let ctx: OffscreenCanvasRenderingContext2D;
- let fontSet: ReturnType<typeof createFontSet>;
-
- beforeEach(() => {
- ctx = createMockCtx();
- fontSet = createFontSet(16, 'sans-serif');
- });
-
- it('image run occupies its width in the line', () => {
- const runs: RichTextRun[] = [
- { type: 'text', text: 'A', bold: false, italic: false, color: null },
- img('icon', 24, 24),
- { type: 'text', text: 'B', bold: false, italic: false, color: null },
- ];
- const lines = layoutRichText(ctx, runs, fontSet, WHITE, 0);
- expect(lines).toHaveLength(1);
-
- const imgRun = lines[0].runs.find(r => r.type === 'image');
- expect(imgRun).toBeDefined();
- expect(imgRun!.width).toBe(24);
-
- const bRun = lines[0].runs.find(r => r.type === 'text' && r.text === 'B');
- expect(bRun).toBeDefined();
- expect(bRun!.x).toBeGreaterThanOrEqual(imgRun!.x + 24);
- });
-
- it('image wraps to next line when it does not fit', () => {
- // 'AB' = 16px, image = 200px, maxWidth = 50
- const runs: RichTextRun[] = [
- { type: 'text', text: 'AB', bold: false, italic: false, color: null },
- img('big', 200, 32),
- ];
- const lines = layoutRichText(ctx, runs, fontSet, WHITE, 50);
- expect(lines.length).toBeGreaterThanOrEqual(2);
-
- const lastLine = lines[lines.length - 1];
- const imgRun = lastLine.runs.find(r => r.type === 'image');
- expect(imgRun).toBeDefined();
- });
-
- it('line height is expanded when image is taller than text', () => {
- const runs: RichTextRun[] = [
- { type: 'text', text: 'Hi', bold: false, italic: false, color: null },
- img('tall', 16, 48),
- ];
- const lines = layoutRichText(ctx, runs, fontSet, WHITE, 0);
- expect(lines).toHaveLength(1);
- expect(lines[0].height).toBe(48);
- });
-
- it('line records max image height even when small', () => {
- const runs: RichTextRun[] = [
- { type: 'text', text: 'Hi', bold: false, italic: false, color: null },
- img('small', 8, 8),
- ];
- const lines = layoutRichText(ctx, runs, fontSet, WHITE, 0);
- expect(lines).toHaveLength(1);
- expect(lines[0].height).toBe(8);
- });
-
- it('image does not wrap when wordWrap is disabled (maxWidth=0)', () => {
- const runs: RichTextRun[] = [
- { type: 'text', text: 'X', bold: false, italic: false, color: null },
- img('wide', 9999, 16),
- ];
- const lines = layoutRichText(ctx, runs, fontSet, WHITE, 0);
- expect(lines).toHaveLength(1);
- });
-
- it('single image wider than container still gets placed', () => {
- const runs: RichTextRun[] = [img('huge', 500, 32)];
- const lines = layoutRichText(ctx, runs, fontSet, WHITE, 100);
- expect(lines).toHaveLength(1);
- const imgRun = lines[0].runs[0];
- expect(imgRun.type).toBe('image');
- });
-
- it('consecutive images layout with correct x offsets', () => {
- const runs: RichTextRun[] = [
- img('a', 20, 16),
- img('b', 30, 16),
- img('c', 10, 16),
- ];
- const lines = layoutRichText(ctx, runs, fontSet, WHITE, 0);
- expect(lines).toHaveLength(1);
- expect(lines[0].runs[0].x).toBe(0);
- expect(lines[0].runs[1].x).toBe(20);
- expect(lines[0].runs[2].x).toBe(50);
- expect(lines[0].width).toBe(60);
- });
-});