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
fix(editor): a dropdown that arrives on time, and a field that survives a drag
yhh89b292c757db
diff --git a/desktop/electron/main.ts b/desktop/electron/main.tsindex 6b945d6a3..793bb166c 100644--- a/desktop/electron/main.ts+++ b/desktop/electron/main.ts@@ -9,6 +9,7 @@ import {openProject,readManifest,readInRoot,+ readOptionalInRoot,writeInRoot,readDirInRoot,listFilesInRoot,@@ -195,9 +196,11 @@ async function runScreenshot(w: BrowserWindow, out: string): Promise<void> {w.webContents.executeJavaScript(code, true).catch(() => undefined);// Pipe renderer console (all frames, incl. the play OOPIF) to the shot log —- // headless failures otherwise die silently inside the window.- w.webContents.on('console-message', (_e, level, message) => {- if (level >= 2) console.log(`[console:${level === 3 ? 'error' : 'warn'}]`, message);+ // headless failures otherwise die silently inside the window. Reads the event+ // OBJECT (`{ level, message }`, named severities): the positional+ // `(event, level, message)` form is deprecated and warns on every listener.+ w.webContents.on('console-message', ({ level, message }) => {+ if (level === 'error' || level === 'warning') console.log(`[console:${level}]`, message);// Surface engine diagnostics (e.g. the resolved GPU backend) in the dev terminal.else if (message.startsWith('[engine]')) console.log(message);});@@ -751,6 +754,7 @@ ipcMain.handle('project:thumbnail', async (_e, rect: { x: number; y: number; wid});ipcMain.handle('fs:read', (_e, relPath: string) => readInRoot(requireRoot(), relPath));+ipcMain.handle('fs:readOptional', (_e, relPath: string) => readOptionalInRoot(requireRoot(), relPath));ipcMain.handle('fs:write', (_e, relPath: string, contents: string) =>writeInRoot(requireRoot(), relPath, contents),);diff --git a/desktop/electron/preload.ts b/desktop/electron/preload.tsindex 3c545e9e6..7e6493055 100644--- a/desktop/electron/preload.ts+++ b/desktop/electron/preload.ts@@ -158,6 +158,10 @@ const api = {// Filesystem, scoped to the open project root (paths are project-relative).fs: {read: (relPath: string): Promise<string> => ipcRenderer.invoke('fs:read', relPath),+ /** Read a file that may legitimately not exist (optional project config) —+ * `null` when it isn't there, so "absent" never travels as a failed IPC call. */+ readOptional: (relPath: string): Promise<string | null> =>+ ipcRenderer.invoke('fs:readOptional', relPath),write: (relPath: string, contents: string): Promise<void> =>ipcRenderer.invoke('fs:write', relPath, contents),readDir: (relPath: string): Promise<DirEntry[]> => ipcRenderer.invoke('fs:readdir', relPath),diff --git a/desktop/electron/projectFs.ts b/desktop/electron/projectFs.tsindex b27145262..d04f4ebc4 100644--- a/desktop/electron/projectFs.ts+++ b/desktop/electron/projectFs.ts@@ -70,6 +70,25 @@ export function readInRoot(root: string, relPath: string): Promise<string> {return readFile(resolveInRoot(root, relPath), 'utf8');}+/**+ * Read a file that is allowed not to exist — `null` instead of a throw.+ *+ * Optional project config (delivery groups, build profiles) is absent in most+ * projects, and "absent" is an ANSWER there, not a failure. Asking `read` for it+ * and swallowing the rejection still crossed IPC as a rejected handler, which+ * Electron logs as `Error occurred in handler for 'fs:read'` — a stack trace on+ * every project open for a file nothing was missing. A read that genuinely fails+ * (permissions, a directory, a bad path) still throws.+ */+export async function readOptionalInRoot(root: string, relPath: string): Promise<string | null> {+ try {+ return await readFile(resolveInRoot(root, relPath), 'utf8');+ } catch (e) {+ if ((e as NodeJS.ErrnoException)?.code === 'ENOENT') return null;+ throw e;+ }+}+export async function writeInRoot(root: string, relPath: string, contents: string): Promise<void> {const abs = resolveInRoot(root, relPath);await mkdir(path.dirname(abs), { recursive: true });diff --git a/desktop/scripts/editor-mcp-host.mjs b/desktop/scripts/editor-mcp-host.mjsindex 09f448442..aa55b6c5c 100644--- a/desktop/scripts/editor-mcp-host.mjs+++ b/desktop/scripts/editor-mcp-host.mjs@@ -23,6 +23,7 @@ import { readFile } from 'node:fs/promises';import path from 'node:path';import { fileURLToPath } from 'node:url';import { createExecEndpoint } from './mcp-exec-endpoint.mjs';+import { onRendererConsole } from './rendererConsole.mjs';const DIST = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'dist');const TOKEN = process.env.ESTELLA_MCP_TOKEN;@@ -68,8 +69,7 @@ app.whenReady().then(async () => {const assets = await serveDist();const url = `http://127.0.0.1:${assets.address().port}/headless.html?w=${W}&h=${H}`;const win = new BrowserWindow({ show: false, width: W, height: H, webPreferences: { offscreen: false } });- win.webContents.on('console-message', (...args) => {- const msg = args.map((a) => (a && typeof a === 'object' ? a.message ?? '' : String(a))).join(' ');+ onRendererConsole(win.webContents, (msg) => {if (/error|fail|unwind|exception|webgl/i.test(msg)) log('[renderer]', msg.slice(0, 240));});await win.loadURL(url);diff --git a/desktop/scripts/engine-parity.mjs b/desktop/scripts/engine-parity.mjsindex 0a842e1c8..65fbff9eb 100644--- a/desktop/scripts/engine-parity.mjs+++ b/desktop/scripts/engine-parity.mjs@@ -19,6 +19,7 @@ import os from 'node:os';import { readFile } from 'node:fs/promises';import path from 'node:path';import { fileURLToPath } from 'node:url';+import { onRendererConsole } from './rendererConsole.mjs';try {os.setPriority(os.constants.priority.PRIORITY_BELOW_NORMAL);@@ -85,13 +86,11 @@ function serve() {async function runBackend(win, baseUrl, backend) {let framesOk = false;const errors = [];- const onMessage = (...args) => {- const msg = args.map((a) => (a && typeof a === 'object' ? a.message ?? '' : String(a))).join(' ');+ const stopConsole = onRendererConsole(win.webContents, (msg) => {if (/PARITY|error|warn/i.test(msg)) console.log(`[${backend}]`, msg.slice(0, 220));if (msg.includes('PARITY_FRAMES_OK')) framesOk = true;if (msg.includes('PARITY_FAIL') || msg.includes('PARITY_VALIDATION')) errors.push(msg);- };- win.webContents.on('console-message', onMessage);+ });try {await win.loadURL(`${baseUrl}?backend=${backend}`);@@ -109,7 +108,7 @@ async function runBackend(win, baseUrl, backend) {errors.push(`run failed: ${e.message}`);return { framesOk, errors, bitmap: Buffer.alloc(256 * 256 * 4), width: 256 };} finally {- win.webContents.removeListener('console-message', onMessage);+ stopConsole();}}diff --git a/desktop/scripts/headless-cooked-verify.mjs b/desktop/scripts/headless-cooked-verify.mjsindex c1ce5e992..cfecd05be 100644--- a/desktop/scripts/headless-cooked-verify.mjs+++ b/desktop/scripts/headless-cooked-verify.mjs@@ -14,6 +14,7 @@ import http from 'node:http';import { readFile } from 'node:fs/promises';import path from 'node:path';import { fileURLToPath } from 'node:url';+import { onRendererConsole } from './rendererConsole.mjs';const COOKED = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '.cooked-verify');const W = 256, H = 256;@@ -50,8 +51,7 @@ app.whenReady().then(async () => {server = await serve(COOKED);const url = `http://127.0.0.1:${server.address().port}/index.html?headless=1`;const win = new BrowserWindow({ show: false, width: W, height: H, webPreferences: { offscreen: false } });- win.webContents.on('console-message', (...a) => {- const m = a.map((x) => (x && typeof x === 'object' ? x.message ?? '' : String(x))).join(' ');+ onRendererConsole(win.webContents, (m) => {if (/error|fail|unwind|exception|webgl|basis|ktx/i.test(m)) diag.push(m.slice(0, 200));});await win.loadURL(url);diff --git a/desktop/scripts/headless-hotupdate-verify.mjs b/desktop/scripts/headless-hotupdate-verify.mjsindex 83bf49fd6..4fba1fea5 100644--- a/desktop/scripts/headless-hotupdate-verify.mjs+++ b/desktop/scripts/headless-hotupdate-verify.mjs@@ -15,6 +15,7 @@ import http from 'node:http';import { readFile } from 'node:fs/promises';import path from 'node:path';import { fileURLToPath } from 'node:url';+import { onRendererConsole } from './rendererConsole.mjs';const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '.hotupdate-verify');const BUILD = path.join(ROOT, 'build');@@ -59,8 +60,7 @@ app.whenReady().then(async () => {const base = `http://127.0.0.1:${server.address().port}`;const win = new BrowserWindow({ show: false, width: W, height: H, webPreferences: { offscreen: false } });- win.webContents.on('console-message', (...a) => {- const m = a.map((x) => (x && typeof x === 'object' ? x.message ?? '' : String(x))).join(' ');+ onRendererConsole(win.webContents, (m) => {if (/error|fail|unwind|exception|webgl|update|group|manifest/i.test(m)) diag.push(m.slice(0, 200));});await win.loadURL(`${base}/index.html?headless=1`);diff --git a/desktop/scripts/headless-verify.mjs b/desktop/scripts/headless-verify.mjsindex 1e91b1d6b..8dc5bbba3 100644--- a/desktop/scripts/headless-verify.mjs+++ b/desktop/scripts/headless-verify.mjs@@ -25,6 +25,7 @@ import os from 'node:os';import { readFile, writeFile } from 'node:fs/promises';import path from 'node:path';import { fileURLToPath } from 'node:url';+import { onRendererConsole } from './rendererConsole.mjs';// SwiftShader rasterizes on the CPU; run the whole electron tree below normal// priority (child processes inherit the class) so a verify never starves the@@ -120,8 +121,7 @@ app.whenReady().then(async () => {show: false, width: W, height: H, useContentSize: true,webPreferences: { offscreen: false },});- win.webContents.on('console-message', (...args) => {- const msg = args.map((a) => (a && typeof a === 'object' ? a.message ?? '' : String(a))).join(' ');+ onRendererConsole(win.webContents, (msg) => {if (/error|fail|unwind|exception|webgl/i.test(msg)) console.log('[renderer]', msg.slice(0, 240));});await win.loadURL(url);diff --git a/desktop/scripts/rendererConsole.mjs b/desktop/scripts/rendererConsole.mjsnew file mode 100644index 000000000..95d34989b--- /dev/null+++ b/desktop/scripts/rendererConsole.mjs@@ -0,0 +1,25 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file rendererConsole.mjs+ * @brief One way for a headless harness to read the renderer's console.+ *+ * Electron's `console-message` used to hand the listener positional arguments+ * (`event, level, message, line, sourceId`) and now hands it a single event+ * OBJECT (`{ level, message, lineNumber, sourceId, frame }`, with named+ * severities). Subscribing the old way logs a deprecation warning on every run.+ *+ * Every harness here wants the same thing — the message text, and sometimes how+ * bad it was — so the shape lives in one place instead of each script mashing+ * `...args` back into a string and quietly picking up whichever form it got.+ */++/**+ * Subscribe to a renderer's console. `onMessage(text, level)` — level is one of+ * `info` / `warning` / `error` / `debug`. Returns an unsubscribe.+ */+export function onRendererConsole(webContents, onMessage) {+ const listener = ({ message, level }) => onMessage(message, level);+ webContents.on('console-message', listener);+ return () => webContents.removeListener('console-message', listener);+}diff --git a/desktop/scripts/webgpu-bringup.mjs b/desktop/scripts/webgpu-bringup.mjsindex 78c86fcf3..d9b4b2456 100644--- a/desktop/scripts/webgpu-bringup.mjs+++ b/desktop/scripts/webgpu-bringup.mjs@@ -20,6 +20,7 @@ import os from 'node:os';import { readFile } from 'node:fs/promises';import path from 'node:path';import { fileURLToPath } from 'node:url';+import { onRendererConsole } from './rendererConsole.mjs';try {os.setPriority(os.constants.priority.PRIORITY_BELOW_NORMAL);@@ -84,8 +85,7 @@ app.whenReady().then(async () => {const win = new BrowserWindow({ show: false, width: 256, height: 256, useContentSize: true });let framesOk = false;const errors = [];- win.webContents.on('console-message', (...args) => {- const msg = args.map((a) => (a && typeof a === 'object' ? a.message ?? '' : String(a))).join(' ');+ onRendererConsole(win.webContents, (msg) => {if (/BRINGUP|error|warn/i.test(msg)) console.log('[page]', msg.slice(0, 200));if (msg.includes('BRINGUP_FRAMES_OK')) framesOk = true;if (msg.includes('BRINGUP_FAIL') || msg.includes('BRINGUP_VALIDATION')) errors.push(msg);diff --git a/desktop/src/ai/paramOptions.ts b/desktop/src/ai/paramOptions.tsindex bb8c7c29d..149ee209b 100644--- a/desktop/src/ai/paramOptions.ts+++ b/desktop/src/ai/paramOptions.ts@@ -8,16 +8,19 @@* A declared parameter can name a source instead of listing options, because the* real choices depend on the scene: which controllers the target entity resolves,* which pages the chosen controller has. This is the same shape (and for the same- * reason) as `registerDynamicEnum` for component fields — one keyed provider map,- * consulted by whoever renders the control. Kept out of the SDK registry on- * purpose: the sdk declares WHAT a parameter is, the editor knows what is on- * screen to choose from.+ * reason) as `setEnumSource` for component fields — one keyed provider map,+ * consulted by whoever renders the control. Separate because the context differs:+ * a field's source sees a component, an action's sees a row's target + sibling+ * parameters. Kept out of the SDK registry on purpose: the sdk declares WHAT a+ * parameter is, the editor knows what is on screen to choose from.*/import { resolveControllers } from '@/controller/controllerModel';-import type { DynamicEnumOption } from '@/engine/schema';import type { EntityId } from '@/types';import type { AiParamValue } from 'esengine';+/** One choice: the value stored, and the label shown when it reads differently. */+export interface AiParamOption { value: string; label?: string }+export interface AiParamOptionContext {/** The entity the action will run on — a row's resolved target, not its owner. */entityId: EntityId;@@ -25,7 +28,7 @@ export interface AiParamOptionContext {params: Readonly<Record<string, AiParamValue>>;}-export type AiParamOptionProvider = (ctx: AiParamOptionContext) => readonly (string | DynamicEnumOption)[];+export type AiParamOptionProvider = (ctx: AiParamOptionContext) => readonly (string | AiParamOption)[];const providers = new Map<string, AiParamOptionProvider>();@@ -34,7 +37,7 @@ export function registerAiParamOptions(source: string, provider: AiParamOptionPr}/** Options for an `optionsSource`, or null when unknown / nothing to offer. */-export function aiParamOptions(source: string, ctx: AiParamOptionContext): DynamicEnumOption[] | null {+export function aiParamOptions(source: string, ctx: AiParamOptionContext): AiParamOption[] | null {const opts = providers.get(source)?.(ctx);if (!opts || opts.length === 0) return null;return opts.map((o) => (typeof o === 'string' ? { value: o } : o));diff --git a/desktop/src/engine/EditorControlSurface.ts b/desktop/src/engine/EditorControlSurface.tsindex 3954d00b5..632ae2d94 100644--- a/desktop/src/engine/EditorControlSurface.ts+++ b/desktop/src/engine/EditorControlSurface.ts@@ -17,6 +17,7 @@*/import type {EntityId,+ EnumOption,InspectorComponent,InspectorFieldType,InspectorFieldValue,@@ -74,6 +75,10 @@ export function coerceFieldValue(declared: InspectorFieldType,key: string,value: InspectorFieldValue,+ /** The field's own options, when it has them — an enum whose options are NAMES+ * ("walk", "Dragon", see EnumOption) stores the name, so the option set is what+ * says whether a string is a legal value or a typo. */+ options?: readonly EnumOption[],): InspectorFieldValue {const fail = (expected: string): never => {throw new Error(`field "${key}" (${declared}) expects ${expected}, got ${JSON.stringify(value)}`);@@ -86,8 +91,19 @@ export function coerceFieldValue(}};switch (declared) {+ case 'enum': {+ // Name-valued options: accept the name (or a label spelling it), and refuse+ // anything the field cannot actually hold, rather than silently writing NaN.+ const named = options?.some((o) => typeof o.value === 'string');+ if (named) {+ const hit = options!.find((o) => o.value === value || o.label === value);+ if (hit) return hit.value;+ return fail(`one of: ${options!.map((o) => String(o.value)).join(', ')}`);+ }+ const n = Number(value);+ return Number.isFinite(n) ? n : fail('a number');+ }case 'number':- case 'enum':case 'flags':case 'entity': {// 'entity' is a source-id reference to another entity — a plain number.@@ -282,13 +298,14 @@ export class EditorControlSurfaceImpl {}// The enable toggle is surfaced in the component header, not in `fields` —// but it is still a writable bool field to automation.+ const field = comp.fields.find((f) => f.key === key);const declared: InspectorFieldType | undefined =- comp.fields.find((f) => f.key === key)?.type ?? (comp.enable?.key === key ? 'bool' : undefined);+ field?.type ?? (comp.enable?.key === key ? 'bool' : undefined);if (!declared) {const keys = [...comp.fields.map((f) => f.key), ...(comp.enable ? [comp.enable.key] : [])];throw new Error(`"${component}" has no field "${key}" (fields: ${keys.join(', ')})`);}- this.s.commands.setField(entity, component, key, declared, coerceFieldValue(declared, key, value));+ this.s.commands.setField(entity, component, key, declared, coerceFieldValue(declared, key, value, field?.options));}/** Add a component (by schema name) to an entity — the Details "Add Component" door. */addComponent(entity: EntityId, component: string): void {diff --git a/desktop/src/engine/EditorSession.ts b/desktop/src/engine/EditorSession.tsindex 23a639dbb..6ef1732a0 100644--- a/desktop/src/engine/EditorSession.ts+++ b/desktop/src/engine/EditorSession.ts@@ -8,7 +8,6 @@ import { SceneCommands, SceneCommandsImpl } from './SceneCommands';import { SceneQuery, SceneQueryImpl } from './SceneQuery';import { useSelection, createSelectionStore, type SelectionStore } from '@/store/selectionStore';import { EditorControlSurfaceImpl } from './EditorControlSurface';-import './spineEnums'; // side effect: register spine animation/skin dynamic enums/*** The single editor boundary. One instance ownsdiff --git a/desktop/src/engine/SceneCommands.ts b/desktop/src/engine/SceneCommands.tsindex 004dfc1f4..225f08d33 100644--- a/desktop/src/engine/SceneCommands.ts+++ b/desktop/src/engine/SceneCommands.ts@@ -13,6 +13,7 @@ import { setEntityClipboard, getEntityClipboard, remapClipboardEntities } from 'import {componentByName,componentDefaults,+ defaultDataFor,userSchema,angleZToQuat,hexToRgba,@@ -86,9 +87,14 @@ export function toModelValue(): unknown {switch (type) {case 'number':- case 'enum':case 'flags':return Number(value);+ case 'enum':+ // An enum option's value is a C++ ordinal OR a name read off a referenced+ // asset ("walk", "Dragon") — see EnumOption. The control writes the option's+ // own value, so its type is the answer; coercing everything through Number+ // turned every name into NaN, which read back as an empty dropdown.+ return typeof value === 'string' ? value : Number(value);case 'bool':return Boolean(value);case 'string':@@ -391,7 +397,15 @@ export class SceneCommandsImpl {const firstTouch = !this.gesture || !this.gesture.touched.has(k);const before = firstTouch ? structuredClone(cur[key]) : undefined;- const after = clampFieldValue(compName, key, toModelValue(cur, type, key, value));+ // Slice edits (one vec axis, one box edge) merge onto the field's CURRENT+ // value, which is the stored value *over its default* — scene data holds only+ // what was authored, so a field at its default simply isn't there. Merging onto+ // the raw stored data wrote a partial vector for those ({ x } with no y/z): the+ // World rejected it ("Missing field: y") and the inspector, unable to recognize+ // the shape, dropped the row. A UINode hit this every time — layout owns its+ // Transform.position, so the scene file never stores one.+ const effective = { ...defaultDataFor(compName), ...cur };+ const after = clampFieldValue(compName, key, toModelValue(effective, type, key, value));this.model.setField(sourceId, compName, key, after);if (this.gesture) {diff --git a/desktop/src/engine/SceneQuery.ts b/desktop/src/engine/SceneQuery.tsindex f9f1df5d8..0935a5743 100644--- a/desktop/src/engine/SceneQuery.ts+++ b/desktop/src/engine/SceneQuery.ts@@ -81,7 +81,7 @@ export function buildInspector(const cdata = (e.components.find((c) => c.type === name)?.data as Record<string, unknown>) ?? {};const enable = componentEnable(name, cdata) ?? undefined;// The enable field is promoted to the header checkbox — drop it from the body.- const fields = inspectorFields(name, cdata, baseOf?.(name)).filter((f) => f.key !== enable?.key);+ const fields = inspectorFields(name, cdata, baseOf?.(name), id).filter((f) => f.key !== enable?.key);out.push({ name, label, fields, enable, notice: componentNotice(name, e) ?? undefined });}return out;@@ -124,7 +124,7 @@ export function buildMultiInspector(const enable = enableBase? { ...enableBase, mixed: !datas.every((d) => (componentEnable(name, d)?.value ?? enableBase.value) === enableBase.value) }: undefined;- const fields = inspectorFields(name, datas[0], baseOf?.(name)).filter((f) => f.key !== enable?.key);+ const fields = inspectorFields(name, datas[0], baseOf?.(name), primary.id).filter((f) => f.key !== enable?.key);// A vector axis reads from either the raw {x,y,z,w} object or an array form.const VKEYS = ['x', 'y', 'z', 'w'] as const;const axisOf = (raw: unknown, i: number): unknown =>diff --git a/desktop/src/engine/dragonBonesNames.ts b/desktop/src/engine/dragonBonesNames.tsindex 0132953dd..37c6b3215 100644--- a/desktop/src/engine/dragonBonesNames.ts+++ b/desktop/src/engine/dragonBonesNames.ts@@ -10,7 +10,10 @@* A cold miss returns nothing, which the inspector already treats as* "leave the field plainly editable" — so the field works before the read* lands and improves after it, instead of stranding the value in an empty- * dropdown.+ * dropdown. A landed read POKES the panels: nothing else changes when a+ * background read finishes, so without it the inspector kept rendering the+ * cold answer until some unrelated edit repainted it (the dropdown only+ * appearing after a Play/Stop round trip).** A `.dbbin` yields nothing, on purpose. It is binary, naming what is* inside it would mean instantiating the runtime, and a free-text field@@ -19,6 +22,7 @@import { parseDragonBonesNames, type DragonBonesArmatureNames } from '../../../sdk/src/dragonbones/skeletonNames';import { ProjectStore } from '@/project/ProjectStore';import { setEnumSource } from './schema';+import { SceneStore } from './SceneStore';import type { EnumOption } from '@/types';/** ref → what that file declares; an empty array is a read that found nothing. */@@ -48,10 +52,18 @@ function warm(ref: string): void {inFlight.delete(ref);return;}- void window.estella.fs.read(path)+ // Optional: a ref can outlive the file it names (deleted, moved outside the+ // editor). Absent is an answer here — an empty list — not a failed IPC call.+ void window.estella.fs.readOptional(path).then((text) => cache.set(ref, text ? parseDragonBonesNames(text) : [])).catch(() => cache.set(ref, []))- .finally(() => inFlight.delete(ref));+ .finally(() => {+ inFlight.delete(ref);+ // Repaint whoever is showing this component: the read is the only thing+ // that changed, and an inspector re-renders off the scene revision.+ // Cached now, so the repaint's provider call cannot start another read.+ if (cache.get(ref)?.length) SceneStore.poke();+ });}function armaturesFor(data: Readonly<Record<string, unknown>>): DragonBonesArmatureNames[] {diff --git a/desktop/src/engine/schema.ts b/desktop/src/engine/schema.tsindex 86d76caaa..5efd0dd06 100644--- a/desktop/src/engine/schema.ts+++ b/desktop/src/engine/schema.ts@@ -2,7 +2,8 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamimport { getComponentRegistry, getUserComponents, getComponent, getComponentAssetFieldDescriptors, getComponentSkeletalFieldDescriptor, getComponentFieldMeta, Light2DType, usesStagger, isHexOrientation } from 'esengine';import type { App, SceneData } from 'esengine';-import type { NodeKind, InspectorField, EnumOption, GradientValue, CurveValue } from '@/types';+import type { NodeKind, EntityId, InspectorField, EnumOption, GradientValue, CurveValue } from '@/types';+import { t } from '@/i18n';type SceneEntityLike = SceneData['entities'][number];@@ -68,6 +69,20 @@ export function componentDefaults(def: AnyComp): Record<string, unknown> {return (def as unknown as { _default: Record<string, unknown> })._default;}+/**+ * A component's default field values BY NAME — the engine registry's `_default`,+ * else a project component's extracted schema, else `{}`.+ *+ * Scene data stores only what was authored, so a field can be absent from a+ * component's data and still have a value: its default. Anything reading "what+ * this field is right now" (the inspector's effective view, a slice write's merge+ * base) has to resolve through this, or it sees a hole where there is a value.+ */+export function defaultDataFor(compType: string): Record<string, unknown> {+ const def = componentByName(compType);+ return (def ? componentDefaults(def) : userSchema(compType)?.default) ?? {};+}+/** The component's entity-reference fields (source-id-valued in scene data), [] if none. */export function componentEntityFields(def: AnyComp | undefined): readonly string[] {return (def as unknown as { entityFields?: readonly string[] } | undefined)?.entityFields ?? [];@@ -357,30 +372,6 @@ export function readonlyFieldsFor(compType: string): readonly string[] {return getComponent(compType)?.readonlyFields ?? [];}-// — Per-entity dynamic enums —-// Some string fields are really a choice from a list that depends on the entity's-// runtime state, not a static enum (e.g. a spine animation/skin name from the loaded-// skeleton). A provider, keyed by `component|field`, yields the options for one-// entity; the inspector renders a dropdown when it returns any. An option may-// carry a display label distinct from the stored value (e.g. an i18n key with-// its translated preview); plain strings stay valid for label-less providers.-export interface DynamicEnumOption { value: string; label?: string }--const dynamicEnums = new Map<string, (sourceId: number) => readonly (string | DynamicEnumOption)[]>();--export function registerDynamicEnum(- component: string, field: string, provider: (sourceId: number) => readonly (string | DynamicEnumOption)[],-): void {- dynamicEnums.set(`${component}|${field}`, provider);-}--/** Dynamic enum options for a field on an entity, or null if the field has no provider / no options. */-export function dynamicEnumOptions(component: string, field: string, sourceId: number): DynamicEnumOption[] | null {- const opts = dynamicEnums.get(`${component}|${field}`)?.(sourceId);- if (!opts || !opts.length) return null;- return opts.map((o) => (typeof o === 'string' ? { value: o } : o));-}-// — Field presentation metadata (the SDK's UPROPERTY analog) —//// A component declares per-field editor policy (enum options, numeric range,@@ -505,16 +496,34 @@ export function setBitmaskSource(name: string, provider: (() => EnumOption[]) |else bitmaskSources.delete(name);}-// Editor-registered providers of dynamic enum options (e.g. project sorting-// layers). A field with `enumSource` becomes a dropdown when its source yields-// options, else a plain number — so free-int editing survives an empty set.+// — Dynamic enum sources —+//+// The ONE door for "this field's choices are not knowable at definition time".+// A component names a source on the field (`enum_source=` in its C++ declaration,+// `enumSource` in schemas.json); the editor registers what that name yields. The+// field becomes a dropdown while its source answers, and stays a plain editable+// field while it doesn't — so free editing survives a source that isn't warm yet+// (a skeleton still being read) or isn't installed at all (a headless host).+//+// Options are values, not indices: a sorting layer is an int, an animation name+// is the string itself (see EnumOption). Both flow through the same control and+// the same write path./**- * A provider is handed the component's own values, because some option sets are- * not global. Sorting layers are a project fact and ignore it; which armatures- * exist depends on which file THIS entity's `skeletonPath` points at, and two- * entities of one component type legitimately answer differently.+ * A provider is handed the component's own values AND the entity being inspected,+ * because option sets differ in where they come from:+ * - project facts ignore both (sorting layers);+ * - what an entity REFERENCES comes from the data (which armatures exist depends+ * on the file this component's `skeletonPath` points at, so two entities of one+ * component type legitimately answer differently);+ * - what an entity has LOADED comes from the id (a spine skeleton's animation+ * list lives in the runtime instance bound to that entity).+ *+ * `entity` is absent where no single entity is on screen (a prefab diff, a test).*/-export type EnumOptionProvider = (data: Readonly<Record<string, unknown>>) => EnumOption[];+export type EnumOptionProvider = (+ data: Readonly<Record<string, unknown>>,+ entity?: EntityId,+) => EnumOption[];const enumSources = new Map<string, EnumOptionProvider>();/** Register (or clear) a named source of dynamic enum options. */@@ -522,8 +531,12 @@ export function setEnumSource(name: string, provider: EnumOptionProvider | null)if (provider) enumSources.set(name, provider);else enumSources.delete(name);}-function enumSourceOptions(name: string, data: Readonly<Record<string, unknown>>): EnumOption[] {- return enumSources.get(name)?.(data) ?? [];+function enumSourceOptions(+ name: string,+ data: Readonly<Record<string, unknown>>,+ entity?: EntityId,+): EnumOption[] {+ return enumSources.get(name)?.(data, entity) ?? [];}/** The bit options for a bitmask field: its source's labels, else `Layer N`. */function bitmaskOptions(meta: { bits?: number; source?: string }): EnumOption[] {@@ -543,6 +556,7 @@ function fieldFor(value: unknown,isColor: boolean,data: Readonly<Record<string, unknown>> = {},+ entity?: EntityId,): InspectorField | null {const meta = fieldMetaFor(compType, key);const at = assetFieldType(compType, key) ?? spineSlotType(compType, key);@@ -576,8 +590,8 @@ function fieldFor(field = { key, label: prettyLabel(key), type: 'flags', value: Number(value) || 0, options: meta.flags.map((o) => ({ ...o })) };} else if (meta?.enum && meta.enum.length) {field = { key, label: prettyLabel(key), type: 'enum', value: Number(value) || 0, options: meta.enum.map((o) => ({ ...o })) };- } else if (meta?.enumSource && enumSourceOptions(meta.enumSource, data).length) {- const options = enumSourceOptions(meta.enumSource, data);+ } else if (meta?.enumSource && enumSourceOptions(meta.enumSource, data, entity).length) {+ const options = enumSourceOptions(meta.enumSource, data, entity);// A string-valued source names things; coercing through Number would turn// every option into NaN and the field into a broken 0.const stringly = typeof options[0].value === 'string';@@ -672,6 +686,9 @@ export function inspectorFields(compType: string,data: Record<string, unknown>,baseData?: Record<string, unknown>,+ /** The entity being inspected — reaches enum sources whose options come from+ * its LOADED runtime state (a spine skeleton's animations). */+ entity?: EntityId,): InspectorField[] {const def = componentByName(compType);const schema = def ? undefined : userSchema(compType);@@ -688,12 +705,12 @@ export function inspectorFields(if (DERIVED_FIELDS.has(key)) continue;if (isConditionallyHidden(compType, key, eff)) continue;const value = key in data ? data[key] : defaults?.[key];- const f = fieldFor(compType, key, value, colorKeys.has(key), eff);+ const f = fieldFor(compType, key, value, colorKeys.has(key), eff, entity);if (!f) continue;// Reset target: the prefab base for this key, else the registered default.const baseRaw = baseData && key in baseData ? baseData[key] : defaults?.[key];if (baseRaw !== undefined) {- const bf = fieldFor(compType, key, baseRaw, colorKeys.has(key), eff);+ const bf = fieldFor(compType, key, baseRaw, colorKeys.has(key), eff, entity);if (bf) f.defaultValue = bf.value;}fields.push(f);@@ -775,6 +792,18 @@ const POSITIONAL_LIGHT_TYPES = new Set([Light2DType.Point, Light2DType.Spot]);* explainable (e.g. the render path skips a positional light with no Transform).*/export function componentNotice(compType: string, entity: SceneEntityLike): string | null {+ // A UINode's placement is LAYOUT-owned: the layout pass writes the resolved box+ // into Transform.position every relayout, so editing it here holds only until the+ // next UI change and then snaps back. Said only once the scene actually CARRIES an+ // authored position — that dead value is the symptom someone is chasing ("I dragged+ // it and nothing moved"). Every well-formed UI node simply omits the field, and a+ // notice true of all of them would be noise on the card and in the diagnostics sweep.+ if (compType === 'Transform' && entity.components.some((c) => c.type === 'UINode')) {+ const d = entity.components.find((c) => c.type === 'Transform')?.data as+ | Record<string, unknown>+ | undefined;+ return d && d.position !== undefined ? t('det.noticeUILayoutOwnsPosition') : null;+ }// Text align/verticalAlign resolve against a layout box, which only a UINode (laid// out under a Canvas) provides. Without one the text anchors to the entity origin —// surfaced when the user has actually set an alignment, so the behavior is explained.@@ -783,8 +812,7 @@ export function componentNotice(compType: string, entity: SceneEntityLike): striconst d = entity.components.find((c) => c.type === 'Text')?.data as| { align?: number; verticalAlign?: number }| undefined;- if ((d?.align ?? 0) !== 0 || (d?.verticalAlign ?? 0) !== 0)- return 'No layout box — align anchors the text to the entity origin. To align within a fixed area, add a UINode and place this Text under a Canvas.';+ if ((d?.align ?? 0) !== 0 || (d?.verticalAlign ?? 0) !== 0) return t('det.noticeTextNoLayoutBox');}return null;}@@ -792,10 +820,9 @@ export function componentNotice(compType: string, entity: SceneEntityLike): striif (hasTransform) return null;if (compType === 'Light2D') {const data = entity.components.find((c) => c.type === compType)?.data as { type?: number } | undefined;- if (POSITIONAL_LIGHT_TYPES.has(Number(data?.type ?? 0)))- return 'Point / Spot lights need a Transform for their position — this light is skipped.';+ if (POSITIONAL_LIGHT_TYPES.has(Number(data?.type ?? 0))) return t('det.noticeLightNeedsTransform');}- if (compType === 'ShadowCaster2D') return 'Needs a Transform to place its shadow box — this caster is skipped.';+ if (compType === 'ShadowCaster2D') return t('det.noticeShadowNeedsTransform');return null;}diff --git a/desktop/src/engine/spineEnums.ts b/desktop/src/engine/spineEnums.tsindex cf7595559..844bf466e 100644--- a/desktop/src/engine/spineEnums.ts+++ b/desktop/src/engine/spineEnums.ts@@ -2,19 +2,28 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team/*** @file spineEnums.ts- * @brief Registers the spine animation/skin fields as per-entity dynamic enums, so- * the inspector offers the loaded skeleton's actual animation/skin names as a- * dropdown instead of a raw text field. Importing this performs the- * registration (side effect).+ * @brief Fills the spine animation/skin dropdowns from the skeleton LOADED on that+ * entity, so the inspector offers the names it can actually play instead of a+ * raw text field. Importing this performs the registration (side effect).+ *+ * @details Unlike DragonBones (which reads the file, see dragonBonesNames.ts), the+ * names here come from the live instance: a spine skeleton can be binary+ * (`.skel`) across four runtime versions, so the runtime that parsed it is+ * the only thing that can name what is inside. That is what the source's+ * `entity` argument is for. Nothing loaded yet ⇒ no options ⇒ the field+ * stays plainly editable, and the binding load pokes a repaint when it lands.*/-import { registerDynamicEnum } from './schema';+import { setEnumSource } from './schema';import { SceneModel } from './SceneModel';import { EngineHost } from './EngineHost';+import type { EnumOption } from '@/types';-const names = (sourceId: number, pick: (rt: number) => string[]): string[] => {- const rt = SceneModel.runtimeFor(sourceId);- return rt != null ? pick(rt) : [];+const options = (entity: number | undefined, pick: (rt: number) => string[]): EnumOption[] => {+ const rt = entity != null ? SceneModel.runtimeFor(entity) : undefined;+ return rt != null ? pick(rt).map((name) => ({ label: name, value: name })) : [];};-registerDynamicEnum('SpineAnimation', 'animation', (id) => names(id, (rt) => EngineHost.spineAnimations(rt)));-registerDynamicEnum('SpineAnimation', 'skin', (id) => names(id, (rt) => EngineHost.spineSkins(rt)));+export function installSpineEnumSources(): void {+ setEnumSource('spineAnimations', (_data, entity) => options(entity, (rt) => EngineHost.spineAnimations(rt)));+ setEnumSource('spineSkins', (_data, entity) => options(entity, (rt) => EngineHost.spineSkins(rt)));+}diff --git a/desktop/src/i18n/messages/details.ts b/desktop/src/i18n/messages/details.tsindex 5e25c5409..71f0e02e5 100644--- a/desktop/src/i18n/messages/details.ts+++ b/desktop/src/i18n/messages/details.ts@@ -8,6 +8,24 @@ import { defineMessages } from './types';export const detailsMessages = defineMessages({// — Shared field controls (enum/flags dropdowns, asset refs, gradients/curves) —+ // — Component notices: an entity state that leaves a component silently inert+ // or a field silently overwritten, said out loud on the component's card. —+ 'det.noticeUILayoutOwnsPosition': {+ en: 'UI layout owns this position — it is recomputed every relayout. Move this widget with the UI Node anchors / offsets instead.',+ zh: '该位置由 UI 布局决定 —— 每次重新布局都会重算。请改用 UI 节点的锚点 / 偏移来移动此控件。',+ },+ 'det.noticeTextNoLayoutBox': {+ en: 'No layout box — align anchors the text to the entity origin. To align within a fixed area, add a UINode and place this Text under a Canvas.',+ zh: '没有布局框 —— 对齐只会把文本吸附到实体原点。要在固定区域内对齐,请添加 UI 节点并把该文本放到画布下。',+ },+ 'det.noticeLightNeedsTransform': {+ en: 'Point / Spot lights need a Transform for their position — this light is skipped.',+ zh: '点光 / 聚光需要 Transform 提供位置 —— 该灯光被跳过。',+ },+ 'det.noticeShadowNeedsTransform': {+ en: 'Needs a Transform to place its shadow box — this caster is skipped.',+ zh: '需要 Transform 来放置阴影盒 —— 该投影体被跳过。',+ },'det.noMatch': { en: 'No match', zh: '无匹配项' },'det.none': { en: 'None', zh: '无' },'det.noneOption': { en: '(none)', zh: '(无)' },diff --git a/desktop/src/main.tsx b/desktop/src/main.tsxindex ca2628efc..47a3d3246 100644--- a/desktop/src/main.tsx+++ b/desktop/src/main.tsx@@ -66,8 +66,6 @@ import { assetTypeOf } from './project/assetTypes';import { initBackgroundThrottle } from './engine/backgroundThrottle';// Register the built-in settings (side effect) and replay persisted ones.import './settings';-// Register the Text.i18nKey picker's key index (side effect, like spineEnums).-import './project/localeKeys';import { applySettings } from './store/settingsStore';// Capture console (editor + SDK + wasm) into the Output Log panel from startup.diff --git a/desktop/src/panels/Details.tsx b/desktop/src/panels/Details.tsxindex 251a71988..d1d4bda02 100644--- a/desktop/src/panels/Details.tsx+++ b/desktop/src/panels/Details.tsx@@ -75,7 +75,7 @@ import { sourceById, createFromSource } from '@/engine/entitySources';import { PlayInspect } from '@/engine/PlayInspect';import { DimensionUnit, AnchorAxis, detectAnchorAxes, UIPositionType, FlexDirection, FlexWrap, JustifyContent, AlignItems, INTERACTION_CONTROLLER, INTERACTION_PAGES, parseLocaleTable, EasingType, BUILTIN_SHADER_TEMPLATES, INVALID_ENTITY } from 'esengine';import type { SceneData, InputMapAsset, ActionType, Binding, LocaleTableAsset, PluralCategory, GearValue, GearTween, MaterialAssetData } from 'esengine';-import { modelAddableComponentEntries, subscribeSchemas, getSchemaRevision, prettyLabel, hexToRgba, dynamicEnumOptions, boxGroupsFor, isRequiredEmpty, inspectorFields, type BoxGroupDef } from '@/engine/schema';+import { modelAddableComponentEntries, subscribeSchemas, getSchemaRevision, prettyLabel, hexToRgba, boxGroupsFor, isRequiredEmpty, inspectorFields, type BoxGroupDef } from '@/engine/schema';import { inspectorRegistry, buildContributedSection, isInfoRow } from '@/plugins/inspector';import { localizePlugin } from '@/plugins/localize';import type { AssetInspectorContribution, ComponentInspectorContribution } from '@/plugins/types';@@ -308,9 +308,16 @@ export function SidesControl({);}-// A named-int dropdown (e.g. Camera projection, body type) — a themed popover, not-// a native <select>, so the list matches the editor and searches when long. The-// stored value is the option's int; an unknown value shows a "(n)" placeholder.+// A dropdown over an option set — a themed popover, not a native <select>, so the+// list matches the editor and searches when long. The stored value is the option's+// OWN value, which is an int for a C++ enum and a name for a choice read off an+// asset (an animation, an armature — see EnumOption).+//+// Only ordinal labels are prettified: "SpaceBetween" reads better as "Space+// Between", but a name IS the stored string and must be shown as written, or the+// list would offer "Stand" for a value spelled "stand". A value with no matching+// option still shows as itself (an animation the skeleton no longer declares is a+// thing to SEE, not a blank), and an empty one reads as "None".export function EnumControl({value,options,@@ -322,11 +329,12 @@ export function EnumControl({const pop = usePopover();const trigger = useRef<HTMLButtonElement>(null);const [q, setQ] = useState('');+ const optLabel = (o: EnumOption): string => (typeof o.value === 'number' ? prettyLabel(o.label) : o.label);const cur = options.find((o) => o.value === value);- const label = mixed ? '' : cur ? prettyLabel(cur.label) : `(${value})`;+ const label = mixed ? '' : cur ? optLabel(cur) : String(value) || t('det.noneOption');const searchable = options.length > 8;const ql = q.trim().toLowerCase();- const filtered = ql ? options.filter((o) => prettyLabel(o.label).toLowerCase().includes(ql)) : options;+ const filtered = ql ? options.filter((o) => optLabel(o).toLowerCase().includes(ql)) : options;const { triggerProps, listProps } = useListbox(pop.isOpen, { seedFocus: !searchable });const close = () => {pop.close();@@ -363,7 +371,7 @@ export function EnumControl({close();}}>- <span className="dd-opt-label">{prettyLabel(o.label)}</span>+ <span className="dd-opt-label">{optLabel(o)}</span>{o.value === value && !mixed && <Check size={12} strokeWidth={2.4} />}</button>))}@@ -1390,18 +1398,14 @@ function FieldRow({ entities, comp, field: rawField, write }: { entities: Entitymax: field.max,});- // A string field whose choices depend on the entity's runtime state (e.g. a spine- // animation/skin name) or on project content (an i18n key with its translated- // preview) renders as a dropdown of the live options, falling back to the text- // field when none are available (no skeleton loaded / no locale tables yet).- const dynOpts =- field.type === 'select'- ? (field.selectOptions ?? []).map((o) => ({ value: o }))- : !mixed && !write && field.type === 'string'- ? dynamicEnumOptions(comp, field.key, entities[0])- : null;+ // A fixed set of string choices declared on the field itself (an importer's+ // compression format). Choices that depend on the scene — a spine animation, a+ // dragonBones armature, an i18n key — are an `enum` with name-valued options+ // (see setEnumSource) and render through EnumControl like every other dropdown.+ const selectOpts =+ !mixed && field.type === 'select' ? (field.selectOptions ?? []).map((o) => ({ value: o })) : null;let control;- if (dynOpts) {+ if (selectOpts) {const cur = String(field.value);control = (<span className="field dropdown">@@ -1410,8 +1414,8 @@ function FieldRow({ entities, comp, field: rawField, write }: { entities: Entityvalue={cur}ariaLabel={field.key}options={[- ...(dynOpts.some((o) => o.value === cur) ? [] : [{ value: cur, label: cur || t('det.noneOption') }]),- ...dynOpts,+ ...(selectOpts.some((o) => o.value === cur) ? [] : [{ value: cur, label: cur || t('det.noneOption') }]),+ ...selectOpts,]}onChange={(v) => {begin();@@ -1461,7 +1465,7 @@ function FieldRow({ entities, comp, field: rawField, write }: { entities: Entitycase 'enum':control = (<EnumControl- value={field.value as number}+ value={field.value as string | number}options={field.options ?? []}mixed={mixed}onBegin={begin}diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.tsindex 18e422dc3..6281da279 100644--- a/desktop/src/project/ProjectStore.ts+++ b/desktop/src/project/ProjectStore.ts@@ -18,7 +18,9 @@ import { Boxes } from 'lucide-react';import { spritePrefab, setCanvasDesignSeed, setProjectCameraFit, type EntitySource } from '@/engine/entitySources';import { setPrefabBaseResolver } from '@/engine/SceneQuery';import { setUserSchemas, userSchema, setBitmaskSource, setEnumSource, type UserComponentSchema } from '@/engine/schema';-import { installDragonBonesEnumSources } from '@/engine/dragonBonesNames';+import { installDragonBonesEnumSources, clearDragonBonesNameCache } from '@/engine/dragonBonesNames';+import { installSpineEnumSources } from '@/engine/spineEnums';+import { installLocaleKeyEnumSource } from './localeKeys';import { setProjectActions, type ProjectActionSchema } from '@/ai/actionCatalog';import { setAssetRefProblemResolver } from '@/engine/EditorControlSurface';import { installSkeletalSync, type SkeletalTransport } from '@/engine/skeletalSync';@@ -38,7 +40,7 @@ import { useEditorMode } from '@/store/editorModeStore';import { PlayRealms } from '@/engine/PlayRealm';import { PlayInspect } from '@/engine/PlayInspect';import { useEditorStore } from '@/store/editorStore';-import { resetFsWatch } from './fsWatch';+import { resetFsWatch, fsRefresh } from './fsWatch';import type { DocSnapshot } from '@/document/DirtyRegistry';/** Pad/truncate collision-layer names to the 16 Box2D filter bits (layer 0 = Default). */@@ -244,11 +246,18 @@ class ProjectStoreImpl {});// Collider layer-mask fields resolve their bit labels from this project setting.setBitmaskSource('collisionLayers', () => this.collisionLayerOptions());- // Render `layer` fields become a dropdown once the project names sorting layers.+ // Every dynamic dropdown the editor supplies, in one place. Each names what it+ // answers from: a project fact (sorting layers), the file an entity REFERENCES+ // (dragonBones armatures/animations), the skeleton an entity has LOADED (spine),+ // or the project's locale tables (i18n keys). One registry, one control, one+ // write path — see setEnumSource.setEnumSource('sortingLayers', () => this.sortingLayerOptions());- // Armature / animation dropdowns read the file each entity references, so- // their options are per-entity rather than per-project (see dragonBonesNames).installDragonBonesEnumSources();+ installSpineEnumSources();+ installLocaleKeyEnumSource();+ // A skeleton re-exported outside the editor declares different animations —+ // drop what was parsed from the old file so the next render re-reads it.+ fsRefresh.subscribe(() => clearDragonBonesNameCache());// New Canvas entities seed their design resolution from the project setting.setCanvasDesignSeed(() => this.designResolution());// The device preview reads the project camera fit so its letterbox matches the@@ -369,7 +378,13 @@ class ProjectStoreImpl {*/private async loadUserSchemas(): Promise<void> {try {- const json = await window.estella.fs.read(`${WORKSPACE_DIR}/cache/schemas.json`);+ // Optional: a project with no script components has never written one.+ const json = await window.estella.fs.readOptional(`${WORKSPACE_DIR}/cache/schemas.json`);+ if (json === null) {+ setUserSchemas([]);+ setProjectActions([], []);+ return;+ }const parsed = JSON.parse(json) as| UserComponentSchema[]| { components?: UserComponentSchema[]; actions?: ProjectActionSchema[]; conditions?: string[] };@@ -1387,10 +1402,11 @@ class ProjectStoreImpl {* legacy folder-name convention. */private async loadAssetGroupsConfig(): Promise<void> {try {- this.assetGroupsConfig = JSON.parse(- await window.estella.fs.read(`${WORKSPACE_DIR}/asset-groups.json`),- ) as AssetGroupsConfig;- } catch {+ // Optional: most projects never configure delivery groups at all.+ const json = await window.estella.fs.readOptional(`${WORKSPACE_DIR}/asset-groups.json`);+ this.assetGroupsConfig = json === null ? null : (JSON.parse(json) as AssetGroupsConfig);+ } catch (e) {+ console.warn('[project] asset-groups.json is unreadable — falling back to defaults', e);this.assetGroupsConfig = null;}}diff --git a/desktop/src/project/localeKeys.ts b/desktop/src/project/localeKeys.tsindex 2b680770d..71893abc9 100644--- a/desktop/src/project/localeKeys.ts+++ b/desktop/src/project/localeKeys.ts@@ -3,35 +3,39 @@/*** @file localeKeys.ts — the project's i18n key index behind the Text.i18nKey* picker. Scans every `.eslocale` table and serves the union of keys as- * dynamic-enum options, each labeled with a translated preview (in the+ * enum-source options, each labeled with a translated preview (in the* EDITOR's language when that locale ships, else the first table's).*- * The dynamic-enum provider is synchronous (called during inspector render),- * so the index is a sync cache refreshed asynchronously: a render kicks a scan- * when stale, and a finished scan that CHANGED the list bumps `fsRefresh` so- * open inspectors re-render with the fresh options (no change → no bump, so- * the kick can't loop). File edits mark the cache stale via the same signal.+ * An enum source is synchronous (called during inspector render), so the index is+ * a sync cache refreshed asynchronously: a render kicks a scan when stale, and a+ * finished scan that CHANGED the list POKES the panels so open inspectors re-render+ * with the fresh options (no change → no poke, so the kick can't loop). File edits+ * mark the cache stale via `fsRefresh`.+ *+ * The poke goes to the scene revision, which is what an inspector actually listens+ * to — the same repaint seam the DragonBones name cache uses when its read lands.+ * Bumping `fsRefresh` instead only re-read directories, so the panel kept showing+ * the cold answer (a plain text field) until something else repainted it.*/import { parseLocaleTable } from 'esengine';-import { registerDynamicEnum, type DynamicEnumOption } from '@/engine/schema';+import { setEnumSource } from '@/engine/schema';+import { SceneStore } from '@/engine/SceneStore';+import type { EnumOption } from '@/types';import { ProjectStore } from './ProjectStore';import { fsRefresh } from './fsWatch';import { editorLocale } from '@/i18n';-let options: DynamicEnumOption[] = [];+let options: EnumOption[] = [];let stale = true;let scanning = false;-async function scan(): Promise<DynamicEnumOption[]> {+async function scan(): Promise<EnumOption[]> {// key → per-locale preview text (plural entries preview their `other` form).const previews = new Map<string, Map<string, string>>();for (const { path } of ProjectStore.listAssets('locale')) {- let text: string;- try {- text = await window.estella.fs.read(path);- } catch {- continue; // deleted between scan start and read — the next bump rescans- }+ // Deleted between the listing and the read — the next bump rescans.+ const text = await window.estella.fs.readOptional(path);+ if (text === null) continue;try {const table = parseLocaleTable(text, path);for (const [key, value] of Object.entries(table.entries)) {@@ -62,7 +66,7 @@ function kickScan(): void {const changed = next.length !== options.length|| next.some((o, i) => o.value !== options[i].value || o.label !== options[i].label);options = next;- if (changed) fsRefresh.bump();+ if (changed) SceneStore.poke();}).finally(() => { scanning = false; });}@@ -71,7 +75,10 @@ function kickScan(): void {// render (or directory re-read) kicks the rescan.fsRefresh.subscribe(() => { stale = true; });-registerDynamicEnum('Text', 'i18nKey', () => {- kickScan();- return options;-});+/** Register the `Text.i18nKey` picker's source. Called once, beside the others. */+export function installLocaleKeyEnumSource(): void {+ setEnumSource('localeKeys', () => {+ kickScan();+ return options;+ });+}diff --git a/desktop/tests/dragonbones-enum-source.test.ts b/desktop/tests/dragonbones-enum-source.test.tsindex 2704f2826..4e1d9d4fd 100644--- a/desktop/tests/dragonbones-enum-source.test.ts+++ b/desktop/tests/dragonbones-enum-source.test.ts@@ -19,6 +19,11 @@ vi.mock('@/engine/schema', () => ({setEnumSource: (name: string, provider: never) => sources.set(name, provider),}));+const pokes = { count: 0 };+vi.mock('@/engine/SceneStore', () => ({+ SceneStore: { poke: () => { pokes.count++; } },+}));+const TWO_ARMATURES = JSON.stringify({armature: [{ name: 'Dragon', animation: [{ name: 'walk' }, { name: 'stand' }] },@@ -30,8 +35,11 @@ describe('DragonBones enum sources', () => {beforeEach(async () => {files.clear();sources.clear();+ pokes.count = 0;(globalThis as { window?: unknown }).window = {- estella: { fs: { read: (p: string) => Promise.resolve(files.get(p) ?? '') } },+ // `readOptional`: a ref can outlive the file it names, and absent is an+ // answer (null) rather than a rejection the ipc layer logs as a failure.+ estella: { fs: { readOptional: (p: string) => Promise.resolve(files.get(p) ?? null) } },};const mod = await import('@/engine/dragonBonesNames');mod.clearDragonBonesNameCache();@@ -69,6 +77,24 @@ describe('DragonBones enum sources', () => {expect(anims('')).toEqual(['walk', 'stand']);});+ it('repaints the panels when the read lands, so the dropdown appears by itself', async () => {+ // Nothing else changes when a background read finishes. Without the poke the+ // inspector kept rendering the cold answer (a plain text field) until some+ // unrelated edit repainted it — which is why the dropdown only showed up+ // after a Play/Stop round trip.+ files.set('hero_ske.json', TWO_ARMATURES);+ sources.get('dragonbonesArmatures')!({ skeletonPath: 'hero_ske.json' });+ expect(pokes.count).toBe(0);+ await settle();+ expect(pokes.count).toBe(1);+ });++ it('does not repaint for a read that found nothing (no new options to show)', async () => {+ sources.get('dragonbonesArmatures')!({ skeletonPath: 'missing_ske.json' });+ await settle();+ expect(pokes.count).toBe(0);+ });+it('answers empty for a reference that does not resolve, and stops asking', async () => {const data = { skeletonPath: 'missing_ske.json' };sources.get('dragonbonesArmatures')!(data);diff --git a/desktop/tests/dynamic-enum.test.ts b/desktop/tests/dynamic-enum.test.tsdeleted file mode 100644index ee8298785..000000000--- a/desktop/tests/dynamic-enum.test.ts+++ /dev/null@@ -1,37 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file Per-entity dynamic enum registry — string fields whose choices depend on- * an entity's runtime state (e.g. spine animation/skin names). The inspector- * renders a dropdown when a provider yields options.- */-import { describe, it, expect } from 'vitest';-import { registerDynamicEnum, dynamicEnumOptions } from '@/engine/schema';--describe('dynamic enum registry', () => {- it('returns a provider\'s options for the registered (component, field), normalized', () => {- registerDynamicEnum('Foo', 'anim', () => ['walk', 'run']);- expect(dynamicEnumOptions('Foo', 'anim', 1)).toEqual([{ value: 'walk' }, { value: 'run' }]);- });-- it('keeps a provider\'s display labels (value ≠ label, e.g. i18n key + preview)', () => {- registerDynamicEnum('Foo', 'key', () => [{ value: 'menu.play', label: 'menu.play · 开始' }]);- expect(dynamicEnumOptions('Foo', 'key', 1)).toEqual([{ value: 'menu.play', label: 'menu.play · 开始' }]);- });-- it('is null for an unregistered field, and for empty options (falls back to a text field)', () => {- expect(dynamicEnumOptions('Nope', 'x', 1)).toBeNull();- registerDynamicEnum('Foo', 'empty', () => []);- expect(dynamicEnumOptions('Foo', 'empty', 1)).toBeNull();- });-- it('passes the entity source id to the provider (per-entity options)', () => {- let seen = -1;- registerDynamicEnum('Foo', 'byEntity', (id) => {- seen = id;- return ['x'];- });- dynamicEnumOptions('Foo', 'byEntity', 42);- expect(seen).toBe(42);- });-});diff --git a/desktop/tests/engine-model-sync.test.ts b/desktop/tests/engine-model-sync.test.tsindex 05fd58bc6..305488a57 100644--- a/desktop/tests/engine-model-sync.test.ts+++ b/desktop/tests/engine-model-sync.test.ts@@ -105,6 +105,21 @@ describe.skipIf(!HAS_WASM)('Model-authoritative projection + lossless save', ()expect((wave!.data as { amplitude: number }).amplitude).toBe(5);});+ it('a slice edit to a field the scene OMITS still writes a whole value', () => {+ // Scene data stores only what was authored, so a field sitting at its default+ // simply is not there — a UINode's Transform.position never is, because the+ // layout pass owns it. Merging the edited axis onto the raw stored data wrote+ // `{ x }` with no y/z: the World rejected it ("Missing field: y") and the+ // inspector, unable to recognize the shape, dropped the row out of the panel.+ const id = S.model.addEntity('Widget', [{ type: 'Transform', data: {} }] as never);+ S.commands.setField(id, 'Transform', 'position', 'vec3', [50, NaN, NaN]);++ const data = S.model.entityBySource(id)!.components.find((c) => c.type === 'Transform')!+ .data as Record<string, unknown>;+ expect(data.position).toEqual({ x: 50, y: 0, z: 0 });+ expect(inspectorFields('Transform', data).some((f) => f.key === 'position')).toBe(true);+ });+it('a Transform edit preserves the engine-computed world fields (never clobbers them to the origin)', () => {// worldPosition/worldRotation/worldScale are ES_PROPERTY(readonly) — engine// outputs composed each frame, not authoring inputs. Seed a sentinel worlddiff --git a/desktop/tests/enum-source-context.test.ts b/desktop/tests/enum-source-context.test.tsindex abc2852e2..599694990 100644--- a/desktop/tests/enum-source-context.test.ts+++ b/desktop/tests/enum-source-context.test.ts@@ -2,11 +2,13 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team//// Dynamic dropdown options used to be a project-wide fact (sorting layers) read-// through a source that was handed nothing. Some option sets are not: which-// armatures exist depends on which file THIS entity points at, so two entities of-// one component type legitimately answer differently. These cover the two things-// that had to change for that — the provider seeing the component, and an option-// being allowed to BE a name rather than an index into one.+// through a source that was handed nothing. Most option sets are not: which+// armatures exist depends on which file THIS entity points at, and which+// animations are playable depends on what THIS entity has loaded — so two entities+// of one component type legitimately answer differently. This is the whole+// contract of the one registry every dynamic dropdown goes through: the provider+// sees the component and the entity, an option may BE a name rather than an index+// into one, and it may carry a label that reads differently from what it stores.import { describe, it, expect, afterEach } from 'vitest';import { setEnumSource, inspectorFields } from '@/engine/schema';@@ -16,7 +18,8 @@ afterEach(() => {setEnumSource('sortingLayers', null);});-const fieldsOf = (comp: string, data: Record<string, unknown>) => inspectorFields(comp, data);+const fieldsOf = (comp: string, data: Record<string, unknown>, entity?: number) =>+ inspectorFields(comp, data, undefined, entity);describe('enum sources', () => {it('hands the provider the component`s own values', () => {@@ -69,6 +72,29 @@ describe('enum sources', () => {expect(f?.value).toBe(3);});+ it('hands the provider the entity being inspected', () => {+ // Options that come from what an entity has LOADED (a spine skeleton's+ // animation list) live in the runtime instance bound to that entity, and+ // are reachable from nothing but its id.+ let seen: number | undefined = -1;+ setEnumSource('sortingLayers', (_data, entity) => {+ seen = entity;+ return [{ label: 'Default', value: 0 }];+ });++ fieldsOf('Sprite', { layer: 0 }, 42);+ expect(seen).toBe(42);+ });++ it('keeps a label that reads differently from the value it stores', () => {+ // An i18n key previews its translation; the key is still what gets written.+ setEnumSource('sortingLayers', () => [{ label: 'menu.play · 开始', value: 'menu.play' }]);++ const f = fieldsOf('Sprite', { layer: 'menu.play' }).find((x) => x.key === FIELD);+ expect(f?.options).toEqual([{ label: 'menu.play · 开始', value: 'menu.play' }]);+ expect(f?.value).toBe('menu.play');+ });+it('stays a plain field while its source knows nothing', () => {// A source that yields nothing must not strand the value in an empty// dropdown — free editing has to survive an unwarmed cache.diff --git a/desktop/tests/inspector-write-values.test.ts b/desktop/tests/inspector-write-values.test.tsnew file mode 100644index 000000000..140fbb679--- /dev/null+++ b/desktop/tests/inspector-write-values.test.ts@@ -0,0 +1,60 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+//+// The two coercions every inspector edit passes through, and the two ways they+// used to destroy a value on the way to the model:+//+// - an `enum` is not always an int. A C++ enum's options are ordinals, but an+// option read off an asset (which animation, which armature) IS a name — and+// `Number('walk')` is NaN, which read back as an empty dropdown showing "()".+// - a vec/box edit writes ONE axis and merges the rest. Merging onto data that+// does not carry the field yet (it is at its default, or the runtime owns it)+// produced a PARTIAL value that nothing downstream could read.+import { describe, it, expect } from 'vitest';+import { toModelValue } from '@/engine/SceneCommands';+import { coerceFieldValue } from '@/engine/EditorControlSurface';++describe('toModelValue', () => {+ it('keeps a name-valued enum as the name', () => {+ expect(toModelValue({}, 'enum', 'animation', 'walk')).toBe('walk');+ expect(toModelValue({ animation: 'stand' }, 'enum', 'animation', 'jump')).toBe('jump');+ });++ it('still stores an ordinal enum as a number, including a numeric string', () => {+ expect(toModelValue({}, 'enum', 'projectionType', 1)).toBe(1);+ expect(toModelValue({}, 'enum', 'projectionType', true)).toBe(1);+ });++ it('merges a single vec axis onto the rest of the value', () => {+ const cur = { position: { x: 1, y: 2, z: 3 } };+ expect(toModelValue(cur, 'vec3', 'position', [9, NaN, NaN])).toEqual({ x: 9, y: 2, z: 3 });+ });++ it('is given an EFFECTIVE base by the write door, so an omitted field still merges whole', () => {+ // The door merges the component's defaults under its stored data before+ // calling in (see writeField_); this is that contract from the callee's side.+ const effective = { position: { x: 0, y: 0, z: 0 } }; // default, nothing stored+ expect(toModelValue(effective, 'vec3', 'position', [50, NaN, NaN])).toEqual({ x: 50, y: 0, z: 0 });+ });+});++describe('coerceFieldValue (the automation door)', () => {+ const ANIMS = [+ { label: 'stand', value: 'stand' },+ { label: 'walk', value: 'walk' },+ ];++ it('accepts a name for an enum whose options are names', () => {+ expect(coerceFieldValue('enum', 'animation', 'walk', ANIMS)).toBe('walk');+ });++ it('refuses a name the field cannot hold, naming what it can', () => {+ expect(() => coerceFieldValue('enum', 'animation', 'sprint', ANIMS))+ .toThrow(/stand, walk/);+ });++ it('leaves an ordinal enum coercing to a number', () => {+ expect(coerceFieldValue('enum', 'projectionType', '1', [{ label: 'Ortho', value: 1 }])).toBe(1);+ expect(coerceFieldValue('enum', 'projectionType', 2)).toBe(2);+ });+});diff --git a/sdk/src/component.generated.ts b/sdk/src/component.generated.tsindex c4ff36c5c..100950d29 100644--- a/sdk/src/component.generated.ts+++ b/sdk/src/component.generated.ts@@ -562,6 +562,8 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {colorFields: ['color'],animatableFields: [],fields: {+ skin: { enumSource: "spineSkins" },+ animation: { enumSource: "spineAnimations" },timeScale: { min: 0 },layer: { step: 1, enumSource: "sortingLayers" },skeletonScale: { min: 0 },diff --git a/sdk/src/ui/core/text.ts b/sdk/src/ui/core/text.tsindex 4180fc973..7b32fe284 100644--- a/sdk/src/ui/core/text.ts+++ b/sdk/src/ui/core/text.ts@@ -91,7 +91,7 @@ export const Text = defineComponent<TextData>('Text', {enabled: true,}, {fields: {- i18nKey: { label: 'I18n Key', tooltip: 'Localization key — when set, content is resolved from the Localization catalogs (and re-resolved on locale switch). Leave empty for plain text.' },+ i18nKey: { label: 'I18n Key', enumSource: 'localeKeys', tooltip: 'Localization key — when set, content is resolved from the Localization catalogs (and re-resolved on locale switch). Leave empty for plain text.' },align: { enum: enumOptions(TextAlign), tooltip: 'Horizontal alignment: within the layout box when the entity has a UINode, else it anchors the text to the entity origin (left/center/right edge).' },verticalAlign: { enum: enumOptions(TextVerticalAlign), tooltip: 'Vertical alignment: within the layout box when the entity has a UINode, else it anchors the text to the entity origin (top/middle/bottom).' },overflow: { enum: enumOptions(TextOverflow) },diff --git a/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap b/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snapindex 41b5b6a11..603d3998e 100644--- a/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap+++ b/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap@@ -620,6 +620,9 @@ exports[`builtin FieldMeta (RC9-1 equivalence gate) > matches the golden snapsho},},"SpineAnimation": {+ "animation": {+ "enumSource": "spineAnimations",+ },"layer": {"enumSource": "sortingLayers","step": 1,@@ -627,6 +630,9 @@ exports[`builtin FieldMeta (RC9-1 equivalence gate) > matches the golden snapsho"skeletonScale": {"min": 0,},+ "skin": {+ "enumSource": "spineSkins",+ },"timeScale": {"min": 0,},diff --git a/src/esengine/bindings/EditorAPI.generated.cpp b/src/esengine/bindings/EditorAPI.generated.cppindex 2a8e85500..bcccfae5c 100644--- a/src/esengine/bindings/EditorAPI.generated.cpp+++ b/src/esengine/bindings/EditorAPI.generated.cpp@@ -2,10 +2,10 @@* @file EditorAPI.generated.cpp* @brief Auto-generated editor API with string-dispatched component access* @details Generated by EHT - DO NOT EDIT- * @schema_hash af08590e4bae8cf8+ * @schema_hash 56250acd973c90d3*/-#define ES_EDITOR_API_SCHEMA_HASH "af08590e4bae8cf8"+#define ES_EDITOR_API_SCHEMA_HASH "56250acd973c90d3"#include <emscripten/bind.h>#include <string>diff --git a/src/esengine/ecs/components/SpineAnimation.hpp b/src/esengine/ecs/components/SpineAnimation.hppindex 7797ce2b4..e2ff1dfea 100644--- a/src/esengine/ecs/components/SpineAnimation.hpp+++ b/src/esengine/ecs/components/SpineAnimation.hpp@@ -57,11 +57,11 @@ struct SpineAnimation {std::string atlasPath;/** @brief Current skin name (empty for default) */- ES_PROPERTY()+ ES_PROPERTY(enum_source=spineSkins)std::string skin;/** @brief Current animation name */- ES_PROPERTY()+ ES_PROPERTY(enum_source=spineAnimations)std::string animation;/** @brief Animation playback speed multiplier */