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
refactor(project): the asset database has a name
yhhffdcba9852a8
diff --git a/desktop/src/commands/editorCommands.ts b/desktop/src/commands/editorCommands.tsindex 5d46d58d5..bab027d4b 100644--- a/desktop/src/commands/editorCommands.ts+++ b/desktop/src/commands/editorCommands.ts@@ -10,6 +10,7 @@*/import { commands } from './registry';import { ProjectStore } from '@/project/ProjectStore';+import { AssetRegistry } from '@/project/AssetRegistry';import { confirmDiscard } from '@/project/discardGuard';import { EditorHistory } from '@/engine/EditorHistory';import { SceneCommands } from '@/engine/SceneCommands';@@ -166,7 +167,7 @@ commands.register({// hex) AND the tileset up front, like Tiled's New Map dialog. createTilemapFromTileset// does all the entity wiring; the picker just gathers the grid + palette choice.run: () => {- const list = ProjectStore.listAssets('tileset');+ const list = AssetRegistry.listAssets('tileset');if (list.length === 0) {Toasts.push(t('toast.noTileset'), 'warn');return;diff --git a/desktop/src/components/AgentDrawer.tsx b/desktop/src/components/AgentDrawer.tsxindex 052e2c1e8..2629e1f03 100644--- a/desktop/src/components/AgentDrawer.tsx+++ b/desktop/src/components/AgentDrawer.tsx@@ -54,7 +54,7 @@ import { useSelection } from '@/store/selectionStore';import { EditorControlSurface } from '@/engine/EditorSession';import { previewSceneOps, withoutDeclined, type PreviewScene } from '@/engine/sceneOpsPreview';import type { SceneOp } from '@/engine/sceneOps';-import { ProjectStore } from '@/project/ProjectStore';+import { AssetRegistry } from '@/project/AssetRegistry';import { t } from '@/i18n';/**@@ -1030,7 +1030,7 @@ function mentionMatches(query: string): Mention[] {.slice(0, 24).map((n) => ({ key: `e${n.id}`, insert: n.name, label: n.name, entity: n.id, detail: String(n.id) }));- const assets: Mention[] = ProjectStore.listAssets()+ const assets: Mention[] = AssetRegistry.listAssets().filter((a) => !q || a.name.toLowerCase().includes(q) || a.path.toLowerCase().includes(q)).slice(0, 16).map((a) => ({ key: `a${a.ref}`, insert: a.path, label: a.name, entity: null, detail: a.type }));diff --git a/desktop/src/components/BuildDialog.tsx b/desktop/src/components/BuildDialog.tsxindex 5bffa8e63..3071ef2c9 100644--- a/desktop/src/components/BuildDialog.tsx+++ b/desktop/src/components/BuildDialog.tsx@@ -38,6 +38,7 @@ import { Segmented } from '@/components/Segmented';import { Select } from '@/components/Select';import { Button } from '@/components/Button';import { ProjectStore } from '@/project/ProjectStore';+import { AssetRegistry } from '@/project/AssetRegistry';import { useEditorStore } from '@/store/editorStore';import { t } from '@/i18n';@@ -340,7 +341,7 @@ export function BuildDialog() {// first. Reads the live asset index, so it tracks file changes.const scenesDir = project?.layout?.scenes ?? 'assets/scenes';const excludedScenes = new Set(project?.packaging?.excludeScenes ?? []);- const sceneList = ProjectStore.listAssets()+ const sceneList = AssetRegistry.listAssets().filter((a) => a.type === 'scene' && (a.path.startsWith(`${scenesDir}/`) || a.path === project?.defaultScene)).sort((a, b) =>a.path === project?.defaultScene ? -1 : b.path === project?.defaultScene ? 1 : a.path.localeCompare(b.path));diff --git a/desktop/src/components/TilemapPickerDialog.tsx b/desktop/src/components/TilemapPickerDialog.tsxindex 88c89b359..cad26c4fb 100644--- a/desktop/src/components/TilemapPickerDialog.tsx+++ b/desktop/src/components/TilemapPickerDialog.tsx@@ -14,7 +14,7 @@ import { LayoutGrid } from 'lucide-react';import { Modal } from '@/components/Modal';import { SearchField } from '@/components/SearchField';import { Segmented } from '@/components/Segmented';-import { ProjectStore } from '@/project/ProjectStore';+import { AssetRegistry } from '@/project/AssetRegistry';import { useEditorStore } from '@/store/editorStore';import { createTilemapFromTileset } from '@/tilemap/createTilemap';import {@@ -32,7 +32,7 @@ export function TilemapPickerDialog() {const [staggerIndex, setStaggerIndex] = useState(0);const [hexSide, setHexSide] = useState('');- const tilesets = ProjectStore.listAssets('tileset');+ const tilesets = AssetRegistry.listAssets('tileset');const needle = q.trim().toLowerCase();const shown = needle ? tilesets.filter((ts) => ts.name.toLowerCase().includes(needle)) : tilesets;@@ -40,7 +40,7 @@ export function TilemapPickerDialog() {const hex = isHexOrientation(orientation);const choose = (ref: string) => {- const path = ProjectStore.assetInfo(ref)?.path;+ const path = AssetRegistry.assetInfo(ref)?.path;close();if (!path) return;const grid: TileGridConfig = { orientation };diff --git a/desktop/src/document/openGraphAsset.ts b/desktop/src/document/openGraphAsset.tsindex b87761b7d..f07aa12cc 100644--- a/desktop/src/document/openGraphAsset.ts+++ b/desktop/src/document/openGraphAsset.ts@@ -11,6 +11,7 @@* format factory, extension, and toast strings — a {@link GraphAssetKind}.*/import { ProjectStore } from '@/project/ProjectStore';+import { AssetRegistry } from '@/project/AssetRegistry';import { confirmDiscardDoc } from '@/project/discardGuard';import { dockApi } from '@/layout/dockApi';import { baseName } from '@/project/assetMeta';@@ -66,7 +67,7 @@ export async function openGraphAsset(kind: GraphAssetKind, path: string): Promisexport async function createGraphAsset(kind: GraphAssetKind, dir: string): Promise<void> {const folder = dir ? (dir.endsWith('/') ? dir : `${dir}/`) : '';let rel = `${folder}${kind.defaultName}.${kind.ext}`;- for (let n = 1; ProjectStore.assetRef(rel); n++) rel = `${folder}${kind.defaultName}-${n}.${kind.ext}`;+ for (let n = 1; AssetRegistry.assetRef(rel); n++) rel = `${folder}${kind.defaultName}-${n}.${kind.ext}`;try {await window.estella.fs.write(rel, JSON.stringify(kind.emptyDef(), null, 2) + '\n');diff --git a/desktop/src/engine/FlipbookViewportPreview.ts b/desktop/src/engine/FlipbookViewportPreview.tsindex 85cc939e3..91d6bf44f 100644--- a/desktop/src/engine/FlipbookViewportPreview.ts+++ b/desktop/src/engine/FlipbookViewportPreview.ts@@ -27,7 +27,7 @@ import {import { AnimClipDocument } from '@/flipbook/AnimClipDocument';import { useSelection } from '@/store/selectionStore';import { useEditorStore } from '@/store/editorStore';-import { ProjectStore } from '@/project/ProjectStore';+import { AssetRegistry } from '@/project/AssetRegistry';import { EngineHost } from './EngineHost';import { SceneModel } from './SceneModel';@@ -92,7 +92,7 @@ export class FlipbookViewportPreviewImpl {if (!world.has(rt, SpriteAnimator) || !world.has(rt, Sprite)) return null;const clip = (world.get(rt, SpriteAnimator) as { clip?: string } | undefined)?.clip;if (!clip) return null;- const path = ProjectStore.assetInfo(clip)?.path;+ const path = AssetRegistry.assetInfo(clip)?.path;return path ? { entity: rt as number, clipPath: path } : null;}diff --git a/desktop/src/engine/dragonBonesNames.ts b/desktop/src/engine/dragonBonesNames.tsindex e22309267..dee8688b0 100644--- a/desktop/src/engine/dragonBonesNames.ts+++ b/desktop/src/engine/dragonBonesNames.ts@@ -20,7 +20,7 @@* is a smaller cost than a wasm module loaded to populate a dropdown.*/import { parseDragonBonesNames, type DragonBonesArmatureNames } from '../../../sdk/src/dragonbones/skeletonNames';-import { ProjectStore } from '@/project/ProjectStore';+import { AssetRegistry } from '@/project/AssetRegistry';import { setEnumSource } from './schema';import { SceneStore } from './SceneStore';import type { EnumOption } from '@/types';@@ -46,7 +46,7 @@ function refOf(data: Readonly<Record<string, unknown>>): string {function warm(ref: string): void {if (!ref || cache.has(ref) || inFlight.has(ref)) return;inFlight.add(ref);- const path = ProjectStore.refPath(ref);+ const path = AssetRegistry.refPath(ref);if (!path) {cache.set(ref, []);inFlight.delete(ref);diff --git a/desktop/src/flipbook/createAnimatedSprite.ts b/desktop/src/flipbook/createAnimatedSprite.tsindex 3f780fcd6..82d426e97 100644--- a/desktop/src/flipbook/createAnimatedSprite.ts+++ b/desktop/src/flipbook/createAnimatedSprite.ts@@ -14,7 +14,7 @@ import {import { Images } from 'lucide-react';import { createFromSource, animatedSpritePrefab, type EntitySource } from '@/engine/entitySources';import { useSelection } from '@/store/selectionStore';-import { ProjectStore } from '@/project/ProjectStore';+import { AssetRegistry } from '@/project/AssetRegistry';import { Toasts } from '@/store/Toasts';import { t } from '@/i18n';@@ -47,7 +47,7 @@ export async function createAnimatedSpriteFromClip(clipPath: string,position?: { x: number; y: number },): Promise<void> {- const clipRef = ProjectStore.assetRef(clipPath); // .esanim → @uuid+ const clipRef = AssetRegistry.assetRef(clipPath); // .esanim → @uuidif (!clipRef) {Toasts.push(t('fb.toast.clipUntracked'), 'error');return;@@ -61,7 +61,7 @@ export async function createAnimatedSpriteFromClip(}// Preload the sheet texture so the seeded frame renders immediately in edit mode.const texRef = asset.sheet?.texture ?? asset.frames[0]?.texture;- const texPath = texRef ? ProjectStore.assetInfo(texRef)?.path : undefined;- if (texPath) await ProjectStore.assetRefForPath(texPath, 'texture');+ const texPath = texRef ? AssetRegistry.assetInfo(texRef)?.path : undefined;+ if (texPath) await AssetRegistry.assetRefForPath(texPath, 'texture');await createFromSource(animClipSource(clipPath, clipRef, asset), { parent: null, position });}diff --git a/desktop/src/flipbook/openFlipbook.ts b/desktop/src/flipbook/openFlipbook.tsindex 91281d482..01270731c 100644--- a/desktop/src/flipbook/openFlipbook.ts+++ b/desktop/src/flipbook/openFlipbook.ts@@ -10,6 +10,7 @@ import { createAnimClip, serializeAnimClip } from 'esengine';import { AnimClipDocument } from './AnimClipDocument';import { useSelection } from '@/store/selectionStore';import { ProjectStore } from '@/project/ProjectStore';+import { AssetRegistry } from '@/project/AssetRegistry';import { confirmDiscardDoc } from '@/project/discardGuard';import { dockApi } from '@/layout/dockApi';import { baseName } from '@/project/assetMeta';@@ -52,7 +53,7 @@ function guessCell(w: number, h: number): number {/** Create a .esanim next to a texture (slicing it), then open it. */export async function createFlipbookFromTexture(texturePath: string): Promise<void> {- const ref = ProjectStore.assetRef(texturePath);+ const ref = AssetRegistry.assetRef(texturePath);if (!ref) {Toasts.push(t('fb.toast.texUntracked'), 'error');return;@@ -68,7 +69,7 @@ export async function createFlipbookFromTexture(texturePath: string): Promise<voconst dir = texturePath.includes('/') ? texturePath.slice(0, texturePath.lastIndexOf('/') + 1) : '';const base = baseName(texturePath).replace(/\.[^.]+$/, '') || 'Animation';let rel = `${dir}${base}.esanim`;- for (let n = 1; ProjectStore.assetRef(rel); n++) rel = `${dir}${base}-${n}.esanim`;+ for (let n = 1; AssetRegistry.assetRef(rel); n++) rel = `${dir}${base}-${n}.esanim`;const asset = createAnimClip(ref, cell, cell, size.w, size.h);const uuid = crypto.randomUUID();diff --git a/desktop/src/main.tsx b/desktop/src/main.tsxindex 90cef024e..dffb1d2eb 100644--- a/desktop/src/main.tsx+++ b/desktop/src/main.tsx@@ -41,6 +41,7 @@ import './theme/launcher.css';import './theme/plugins.css';import { App } from './App';import { ProjectStore } from './project/ProjectStore';+import { AssetRegistry } from './project/AssetRegistry';import { useEditorStore } from './store/editorStore';import { useSelection } from './store/selectionStore';import { PlayRealm } from './engine/PlayRealm';@@ -448,7 +449,7 @@ function buildEditorAutomation(): unknown {* `total` reports the full match count even when `assets` is truncated. */listAssets: (opts?: { match?: string; type?: string; limit?: number }) => {const needle = opts?.match?.toLowerCase();- const all = ProjectStore.listAssets().filter(+ const all = AssetRegistry.listAssets().filter((a) => (!opts?.type || a.type === opts.type) && (!needle || a.path.toLowerCase().includes(needle)),);return { total: all.length, assets: all.slice(0, opts?.limit ?? 200) };@@ -473,7 +474,7 @@ function buildEditorAutomation(): unknown {* an image viewer on the user's desktop.*/openAsset: async (path: string, discardChanges = false) => {- const type = ProjectStore.assetTypeAt(path);+ const type = AssetRegistry.assetTypeAt(path);if (!opensInEditor(type)) {throw new Error(`the editor has no editor for a '${type}' asset (${path}) — a double-click would hand it to an `@@ -546,7 +547,7 @@ function buildEditorAutomation(): unknown {* thing an automated caller most needs to know about a delete is what still points at it.*/deleteAsset: async (path: string) => {- const type = ProjectStore.assetTypeAt(path);+ const type = AssetRegistry.assetTypeAt(path);// Best-effort: a scan failure must not stop the delete the caller asked for.const usages = await findAssetUsages(path).catch(() => []);const [result] = await deleteAssets([path]);diff --git a/desktop/src/material/openMaterial.ts b/desktop/src/material/openMaterial.tsindex ece14f8fe..409c198dc 100644--- a/desktop/src/material/openMaterial.ts+++ b/desktop/src/material/openMaterial.ts@@ -9,6 +9,7 @@*/import { builtinShaderTemplate, type MaterialAssetData } from 'esengine';import { ProjectStore } from '@/project/ProjectStore';+import { AssetRegistry } from '@/project/AssetRegistry';import { dockApi } from '@/layout/dockApi';import { useSelection } from '@/store/selectionStore';import { baseName } from '@/project/assetMeta';@@ -29,7 +30,7 @@ export function openMaterial(path: string): void {// Pick a `<base>.esmaterial` name in @p dir that no tracked asset already uses.function uniqueMaterialPath(dir: string, base: string): string {let rel = `${dir}${base}.esmaterial`;- for (let n = 1; ProjectStore.assetRef(rel); n++) rel = `${dir}${base}-${n}.esmaterial`;+ for (let n = 1; AssetRegistry.assetRef(rel); n++) rel = `${dir}${base}-${n}.esmaterial`;return rel;}@@ -108,7 +109,7 @@ export async function createMaterialInstance(parentPath: string): Promise<void>// then adopts the file (mints its `.meta` uuid/type — see EXT_TO_TYPE) so it becomes pickable.function uniqueShaderPath(dir: string, base: string): string {let rel = `${dir}${base}.esshader`;- for (let n = 1; ProjectStore.assetRef(rel); n++) rel = `${dir}${base}-${n}.esshader`;+ for (let n = 1; AssetRegistry.assetRef(rel); n++) rel = `${dir}${base}-${n}.esshader`;return rel;}diff --git a/desktop/src/material/openMaterialGraph.ts b/desktop/src/material/openMaterialGraph.tsindex 2f5e10918..896e83aa1 100644--- a/desktop/src/material/openMaterialGraph.ts+++ b/desktop/src/material/openMaterialGraph.ts@@ -11,6 +11,7 @@import { compileMaterialGraph, newMaterialGraph, type MaterialGraph } from 'esengine';import { MaterialGraphDocument } from './MaterialGraphDocument';import { ProjectStore } from '@/project/ProjectStore';+import { AssetRegistry } from '@/project/AssetRegistry';import { confirmDiscardDoc } from '@/project/discardGuard';import { dockApi } from '@/layout/dockApi';import { baseName } from '@/project/assetMeta';@@ -62,7 +63,7 @@ export async function saveMaterialGraph(path: string, graph: MaterialGraph): Proexport async function createMaterialGraph(dir: string): Promise<void> {const folder = dir ? (dir.endsWith('/') ? dir : `${dir}/`) : '';let rel = `${folder}NewGraph.esmatgraph`;- for (let n = 1; ProjectStore.assetRef(rel); n++) rel = `${folder}NewGraph-${n}.esmatgraph`;+ for (let n = 1; AssetRegistry.assetRef(rel); n++) rel = `${folder}NewGraph-${n}.esmatgraph`;const graph = newMaterialGraph();graph.name = baseName(rel).replace(/\.esmatgraph$/, '');diff --git a/desktop/src/panels/ContentBrowser.tsx b/desktop/src/panels/ContentBrowser.tsxindex 195939f1a..973523d71 100644--- a/desktop/src/panels/ContentBrowser.tsx+++ b/desktop/src/panels/ContentBrowser.tsx@@ -12,6 +12,7 @@ import { ContextMenu, type MenuItem } from '@/components/Menu';import { useTooltip } from '@/components/Tooltip';import { Segmented } from '@/components/Segmented';import { ProjectStore } from '@/project/ProjectStore';+import { AssetRegistry } from '@/project/AssetRegistry';import { Toasts } from '@/store/Toasts';import { useSelection } from '@/store/selectionStore';import { IMAGE_RE, baseName, TYPE_CODE } from '@/project/assetMeta';@@ -54,7 +55,7 @@ const errMsg = (e: unknown) => (e instanceof Error ? e.message : String(e));* chips, sort and double-click open all read, so they cannot disagree. Asked by* PATH, not name: a file's type is not always readable from its name (a Spine JSON* skeleton is a plain `.json`), and the registry knows what its `.meta` recorded. */-const typeAt = (path: string): AssetType => ProjectStore.assetTypeAt(path);+const typeAt = (path: string): AssetType => AssetRegistry.assetTypeAt(path);// Per-delivery-mode presentation (menu label + corner badge; `local` has none).// Keyed by AssetGroupMode so adding a mode to the SDK's ASSET_GROUP_MODES forces@@ -154,7 +155,7 @@ function AssetTipCard({ path, entry }: { path: string; entry: DirEntry }) {const type: AssetType = entry.isDir ? 'folder' : typeAt(path);const isImg = !entry.isDir && IMAGE_RE.test(entry.name);- const assetReference = entry.isDir ? null : ProjectStore.assetRef(path);+ const assetReference = entry.isDir ? null : AssetRegistry.assetRef(path);useEffect(() => {let alive = true;@@ -1004,7 +1005,7 @@ export function ContentBrowser() {const isTileset = targetType === 'tileset';const isAnimClip = targetType === 'animclip';const isMaterial = targetType === 'material';- const ref = entry.isDir ? null : ProjectStore.assetRef(path);+ const ref = entry.isDir ? null : AssetRegistry.assetRef(path);return [// Offered for everything, because opening now always resolves to something —// an editor, the program set for that kind of file, or the OS default. Thediff --git a/desktop/src/panels/Details.tsx b/desktop/src/panels/Details.tsxindex f4d245364..e514797bf 100644--- a/desktop/src/panels/Details.tsx+++ b/desktop/src/panels/Details.tsx@@ -74,6 +74,7 @@ import { buildImporterComponent, applyImporterEdit, readTextureCookSettings } frimport { findAssetUsages } from '@/project/assetUsages';import { FindUsagesDialog } from '@/components/FindUsagesDialog';import { ProjectStore } from '@/project/ProjectStore';+import { AssetRegistry } from '@/project/AssetRegistry';import { confirmDiscard, confirmDiscardDoc } from '@/project/discardGuard';import { t, editorLocale } from '@/i18n';import { componentDocUrl } from '@/engine/componentDocUrl';@@ -1029,7 +1030,7 @@ function MaterialShaderSection({}) {const isBuiltin = asset.shader.startsWith(BUILTIN_SHADER_PREFIX);const shaderPath = isBuiltin ? '' : shaderProjectPathOf(filePath, asset.shader);- const info = shaderPath ? ProjectStore.assetInfo(shaderPath) : null;+ const info = shaderPath ? AssetRegistry.assetInfo(shaderPath) : null;const missing = !isInstance && !isBuiltin && !!asset.shader && !info;// The picker offers built-in templates + every project `.esshader`. An option's value encodes@@ -1037,7 +1038,7 @@ function MaterialShaderSection({// path relative to the material. Pointing several materials at one file here = sharing a shader.const options: { value: string; label: string }[] = [...BUILTIN_SHADER_TEMPLATES.map((tpl) => ({ value: BUILTIN_SHADER_PREFIX + tpl.id, label: t('mat.shaderBuiltin', { name: tpl.label }) })),- ...ProjectStore.listAssets('shader').map((a) => ({ value: `file:${a.path}`, label: a.name })),+ ...AssetRegistry.listAssets('shader').map((a) => ({ value: `file:${a.path}`, label: a.name })),];const current = isBuiltin ? asset.shader : `file:${shaderPath}`;// Keep the current selection visible even when it isn't a listed option (a renamed / missing file).@@ -1443,7 +1444,7 @@ function LocaleTableAssetInspector({ path }: { path: string }) {setSiblings(null);void (async () => {const map = new Map<string, Map<string, string>>();- for (const asset of ProjectStore.listAssets('locale')) {+ for (const asset of AssetRegistry.listAssets('locale')) {if (asset.path === path) continue;try {const sib = parseLocaleTable(await window.estella.fs.read(asset.path), asset.path);@@ -1681,7 +1682,7 @@ function LocaleSection({ title, badge, action, children }: {// rows); other assets show their fs metadata + the image/type glyph preview.function AssetInspector({ path }: { path: string }) {- const type = ProjectStore.assetTypeAt(path);+ const type = AssetRegistry.assetTypeAt(path);if (isMaterialAsset(path)) {return <MaterialAssetInspector path={path} />;}@@ -1836,7 +1837,7 @@ function TexturePlatformOverrides({ importer, write }: { importer: Record<string// (written to the `.meta` sidecar) through the shared ComponentSection engine.function GenericAssetInspector({ path }: { path: string }) {const name = baseName(path);- const type = ProjectStore.assetTypeAt(path);+ const type = AssetRegistry.assetTypeAt(path);const isImage = IMAGE_RE.test(name);const [importer, setImporter] = useState<Record<string, unknown> | null>(null);@@ -1896,7 +1897,7 @@ function GenericAssetInspector({ path }: { path: string }) {};}, [path, isImage]);- const assetRef = ProjectStore.assetRef(path);+ const assetRef = AssetRegistry.assetRef(path);const comp = importer ? buildImporterComponent(type, importer) : null;const write: FieldWrite = (key, _t, value) => {setImporter((cur) => (cur ? applyImporterEdit(cur, key, value as InspectorFieldValue) : cur));@@ -1914,7 +1915,7 @@ function GenericAssetInspector({ path }: { path: string }) {await ProjectStore.refreshAssets();// Push filter/wrap to the live gl handle so the edit viewport updates now// (no scene reload); a no-op for types/assets without a live texture.- if (type === 'texture' || type === 'sprite') ProjectStore.applyLiveTextureSettings(path);+ if (type === 'texture' || type === 'sprite') AssetRegistry.applyLiveTextureSettings(path);Toasts.push(t('det.importSaved'), 'info', 1400);} catch (e) {Toasts.push(t('det.importSaveFailed', { error: String(e) }), 'error');@@ -2245,7 +2246,7 @@ function EditorDetails() {const prefabRef = prefabTag? prefabTag.prefab ?? SceneModel.prefabTag(prefabTag.instanceRoot)?.prefab: undefined;- const prefabName = prefabRef ? ProjectStore.assetInfo(prefabRef)?.name ?? null : null;+ const prefabName = prefabRef ? AssetRegistry.assetInfo(prefabRef)?.name ?? null : null;// Stale overrides the loader dropped from THIS instance on load (keyed by root).const staleOverrides = prefabTag? conflictsByInstance.get(prefabTag.instanceRoot) ?? []@@ -2336,7 +2337,7 @@ function EditorDetails() {type="button"title={t('det.prefabSelectTip')}onClick={() => {- const info = prefabRef ? ProjectStore.assetInfo(prefabRef) : null;+ const info = prefabRef ? AssetRegistry.assetInfo(prefabRef) : null;if (info) useSelection.getState().selectAsset(info.path);}}>diff --git a/desktop/src/panels/FlipbookEditor.tsx b/desktop/src/panels/FlipbookEditor.tsxindex d9a0c6cf3..d8128b7b7 100644--- a/desktop/src/panels/FlipbookEditor.tsx+++ b/desktop/src/panels/FlipbookEditor.tsx@@ -25,7 +25,7 @@ import { Transport } from '@/components/Transport';import { SaveButton } from '@/components/SaveButton';import { AnimClipDocument } from '@/flipbook/AnimClipDocument';import { AnimClipCommands } from '@/flipbook/AnimClipCommands';-import { ProjectStore } from '@/project/ProjectStore';+import { AssetRegistry } from '@/project/AssetRegistry';import { t } from '@/i18n';const THUMB = 34;@@ -54,7 +54,7 @@ export function FlipbookEditor() {const meta = AnimClipDocument.meta;const sheet = asset?.sheet;- const info = sheet ? ProjectStore.assetInfo(sheet.texture) : null;+ const info = sheet ? AssetRegistry.assetInfo(sheet.texture) : null;const texUrl = info ? `estella://project/${info.path}` : null;const [zoom, setZoom] = useState(2);@@ -121,7 +121,7 @@ export function FlipbookEditor() {return cellThumbStyle(texUrl, sheet, cols, Math.min(f.cell, Math.max(0, cellCount - 1)), size);}// Legacy per-texture frame: show the whole referenced image.- const fi = f.texture ? ProjectStore.assetInfo(f.texture) : null;+ const fi = f.texture ? AssetRegistry.assetInfo(f.texture) : null;return fi? { width: size, height: size, backgroundImage: `url(estella://project/${fi.path})`, backgroundSize: 'contain' }: { width: size, height: size };diff --git a/desktop/src/panels/Outliner.tsx b/desktop/src/panels/Outliner.tsxindex e0f68bc81..14e997a5b 100644--- a/desktop/src/panels/Outliner.tsx+++ b/desktop/src/panels/Outliner.tsx@@ -12,6 +12,7 @@ import { SceneCommands } from '@/engine/SceneCommands';import { SceneModel } from '@/engine/SceneModel';import { PlayInspect } from '@/engine/PlayInspect';import { ProjectStore } from '@/project/ProjectStore';+import { AssetRegistry } from '@/project/AssetRegistry';import { ContextMenu, type MenuItem } from '@/components/Menu';import { formatKeybinding } from '@/commands/keybinding';import { contributedContextRows } from '@/plugins/contextMenus';@@ -141,7 +142,7 @@ function prefabInstanceItems(id: number): MenuItem[] {{label: t('out.prefabSelectSource'),onClick: () => {- const info = ProjectStore.assetInfo(ref);+ const info = AssetRegistry.assetInfo(ref);if (info) useSelection.getState().selectAsset(info.path);},},diff --git a/desktop/src/panels/TilemapPainter.tsx b/desktop/src/panels/TilemapPainter.tsxindex 33077486e..ef8f40f44 100644--- a/desktop/src/panels/TilemapPainter.tsx+++ b/desktop/src/panels/TilemapPainter.tsx@@ -21,6 +21,7 @@ import { useSelection } from '@/store/selectionStore';import { SceneModel } from '@/engine/SceneModel';import { SceneCommands } from '@/engine/SceneCommands';import { ProjectStore } from '@/project/ProjectStore';+import { AssetRegistry } from '@/project/AssetRegistry';import { TILE_TOOL_KEY, exitTilePaint } from '@/tools/tileMode';import { MOD_LABEL } from '@/commands/keybinding';import { usePopover, Popover } from '@/components/Popover';@@ -135,7 +136,7 @@ export function TilemapPainter() {// bar can switch between them and painted cells encode to the right global gid.useEffect(() => {const paths = layerTilesetRefs(selectedId)- .map((r) => ProjectStore.assetInfo(r)?.path).filter((p): p is string => !!p);+ .map((r) => AssetRegistry.assetInfo(r)?.path).filter((p): p is string => !!p);if (paths.length === 0) { setTilesets([]); return; }let alive = true;void (async () => {@@ -147,7 +148,7 @@ export function TilemapPainter() {entries.push({ path, asset: a, firstId });let count = a.tileCount ?? 0;if (count <= 0) {- const url = `estella://project/${ProjectStore.assetInfo(a.texture)?.path ?? ''}`;+ const url = `estella://project/${AssetRegistry.assetInfo(a.texture)?.path ?? ''}`;const dims = await loadImageDims(url);count = a.columns * rowsFor(dims.h, a.tileHeight, a.margin, a.spacing);}@@ -176,7 +177,7 @@ export function TilemapPainter() {return () => { alive = false; };}, [tilesetPath, setTilesetAsset, tilesetDocRev]);- const texUrl = asset ? `estella://project/${ProjectStore.assetInfo(asset.texture)?.path ?? ''}` : null;+ const texUrl = asset ? `estella://project/${AssetRegistry.assetInfo(asset.texture)?.path ?? ''}` : null;const [natural, setNatural] = useState<{ w: number; h: number } | null>(null);// On texture change adopt the size straight from the element when it is// already complete — a cache-hit image can finish loading before React@@ -369,7 +370,7 @@ export function TilemapPainter() {};// The project's .estileset assets not already on this layer (populated on open).const addable = addPop.isOpen- ? ProjectStore.listAssets('tileset').filter((a) => !layerTilesetRefs(selectedId).includes(a.ref))+ ? AssetRegistry.listAssets('tileset').filter((a) => !layerTilesetRefs(selectedId).includes(a.ref)): [];const atlas: TileAtlas | null = texUrl && naturaldiff --git a/desktop/src/panels/TilesetEditor.tsx b/desktop/src/panels/TilesetEditor.tsxindex c7dbd7f75..d1a34e663 100644--- a/desktop/src/panels/TilesetEditor.tsx+++ b/desktop/src/panels/TilesetEditor.tsx@@ -32,7 +32,7 @@ import { SaveButton } from '@/components/SaveButton';import { TilesetDocument } from '@/tileset/TilesetDocument';import { TilesetCommands, type TileCollisionMods } from '@/tileset/TilesetCommands';import { useTilesetView } from '@/tileset/tilesetView';-import { ProjectStore } from '@/project/ProjectStore';+import { AssetRegistry } from '@/project/AssetRegistry';import { colsFor, rowsFor, TERRAIN_COLORS } from '@/tools/tileMath';import { AnimPreview, tileThumbStyle, type TileAtlas } from '@/tools/tileThumb';import { SLOPE_PRESETS, presetPointsPx, type SlopePreset } from '@/tileset/slopePresets';@@ -383,7 +383,7 @@ export function TilesetEditor() {const asset = TilesetDocument.asset;const meta = TilesetDocument.meta;- const info = asset ? ProjectStore.assetInfo(asset.texture) : null;+ const info = asset ? AssetRegistry.assetInfo(asset.texture) : null;const texUrl = info ? `estella://project/${info.path}` : null;const [natural, setNatural] = useState<{ w: number; h: number } | null>(null);diff --git a/desktop/src/panels/inspector/controls.tsx b/desktop/src/panels/inspector/controls.tsxindex c503d6973..4815cf811 100644--- a/desktop/src/panels/inspector/controls.tsx+++ b/desktop/src/panels/inspector/controls.tsx@@ -30,7 +30,7 @@ import { useListbox } from '@/components/useListbox';import { SceneModel } from '@/engine/SceneModel';import { SceneStore } from '@/engine/SceneStore';import { prettyLabel, hexToRgba, coerceEnumInput } from '@/engine/schema';-import { ProjectStore } from '@/project/ProjectStore';+import { AssetRegistry } from '@/project/AssetRegistry';import { revealAsset } from '@/project/assetReveal';import { Toasts } from '@/store/Toasts';import { t } from '@/i18n';@@ -989,7 +989,7 @@ export function AssetControl({const box = useRef<HTMLDivElement>(null);const pop = usePopover();const [q, setQ] = useState('');- const info = ProjectStore.assetInfo(value);+ const info = AssetRegistry.assetInfo(value);// Handle-valued slots clear to 0; path-valued slots (spine skeleton/atlas)// are string component fields, so "no asset" is the empty string.const empty = assetType === 'spine-skeleton' || assetType === 'spine-atlas' ? '' : 0;@@ -997,12 +997,12 @@ export function AssetControl({const setRefFromPath = (path: string) => {// Reject a wrong-typed drop (the picker popover already filters; this guards the// drag-drop hole so a font can't land in a texture slot).- if (!ProjectStore.assetTypeAllowed(assetType, path)) {+ if (!AssetRegistry.assetTypeAllowed(assetType, path)) {Toasts.push(t('det.wrongAssetType', { type: assetType ?? '' }), 'error');return;}onBegin?.();- void ProjectStore.assetRefForPath(path, assetType).then((ref) => {+ void AssetRegistry.assetRefForPath(path, assetType).then((ref) => {if (ref) onChange(ref);onEnd?.();});@@ -1030,7 +1030,7 @@ export function AssetControl({};const ql = q.trim().toLowerCase();const assets = pop.isOpen- ? ProjectStore.listAssets(assetType).filter((a) => !ql || a.name.toLowerCase().includes(ql))+ ? AssetRegistry.listAssets(assetType).filter((a) => !ql || a.name.toLowerCase().includes(ql)): [];return (diff --git a/desktop/src/plugins/context.ts b/desktop/src/plugins/context.tsindex a3710d0f2..281956b21 100644--- a/desktop/src/plugins/context.ts+++ b/desktop/src/plugins/context.ts@@ -33,6 +33,7 @@ import { useEditorStore } from '@/store/editorStore';import { EditorControlSurface } from '@/engine/EditorSession';import { EngineHost } from '@/engine/EngineHost';import { ProjectStore } from '@/project/ProjectStore';+import { AssetRegistry } from '@/project/AssetRegistry';import { LogStore } from '@/store/LogStore';import { Toasts } from '@/store/Toasts';import type { InspectorFieldValue } from '@/types';@@ -132,7 +133,7 @@ function projectApi(): EditorProjectApi {root: () => ProjectStore.getSnapshot()?.root ?? null,currentScene: () => ProjectStore.getSnapshot()?.currentScene ?? null,save: () => ProjectStore.save(),- listAssets: () => ProjectStore.listAssets().map((a) => a.path),+ listAssets: () => AssetRegistry.listAssets().map((a) => a.path),refreshAssets: () => ProjectStore.refreshAssets(),};}diff --git a/desktop/src/project/AssetRegistry.ts b/desktop/src/project/AssetRegistry.tsnew file mode 100644index 000000000..b11ad14f8--- /dev/null+++ b/desktop/src/project/AssetRegistry.ts@@ -0,0 +1,345 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file AssetRegistry.ts — what the project's assets are, and where they live.+ *+ * Four lookup tables built from the `.meta` sidecars an asset scan finds: uuid to+ * path, path to uuid, and per-uuid the importer block and the type minted from the+ * file's own content. Everything that resolves a reference reads them — the+ * inspector's asset picker, the Content Browser's drag guard, the prefab loader,+ * the play manifest, the texture import path.+ *+ * They used to be four private Maps inside ProjectStore, whose other jobs are+ * opening a project, the scene document, prefab sessions and the settings+ * manifest. `pathToUuid` alone was read by fifteen of its methods, which is not+ * god-object coupling but the opposite: the asset database is a real shared+ * substrate, and it had no name. Eighteen files reached for ProjectStore when what+ * they wanted was a uuid.+ *+ * This owns the tables and answers questions about them. It does NOT scan — a scan+ * needs the open project, its root and its watcher, which belong to ProjectStore.+ * ProjectStore feeds the result in through {@link rebuild}; the direction is one+ * way, so a query never reaches back for a project.+ *+ * Load bookkeeping lives here too (which refs failed, which hot-loads have+ * started), because both are keyed by the same identities and answer the same+ * question a caller asks about a ref: is this thing actually there.+ */+import { Assets, getEditorType, textureImportSettingsFrom, setTextureParams, setTextureSliceBorder, TextureFilter, TextureWrap } from 'esengine';+import { EngineHost } from '@/engine/EngineHost';+import { assetTypeOf } from '@/project/assetMeta';+import { ASSET_TYPES, assetTypeDef } from '@/project/assetTypes';+import type { AssetType } from '@/types';++export const UUID_PREFIX = '@uuid:';++// UUID v4 shape — serialized refs come in three forms: `@uuid:` (canonical),+// a BARE uuid (`.esanim` flipbook frame textures), or a plain path. A bare+// uuid must resolve through the registry like a prefixed one; treating it as+// a path guarantees a 404 (estella://project/<uuid>) and white sprites.+const UUID_SHAPE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;++/** The uuid carried by a ref (`@uuid:` prefixed, any body — explicit intent —+ * or bare-but-uuid-shaped), else null for plain paths. Lower-cased. */+export function refUuid(ref: string): string | null {+ if (ref.startsWith(UUID_PREFIX)) return ref.slice(UUID_PREFIX.length).toLowerCase();+ return UUID_SHAPE.test(ref) ? ref.toLowerCase() : null;+}++/** One entry of a scanned index — the shape the main process reports. */+export type AssetEntryLite = { uuid: string; path: string; type?: string; importer?: Record<string, unknown> };++/** A pickable asset for the inspector's asset picker. */+export interface AssetEntry {+ ref: string;+ path: string;+ name: string;+ type: AssetType;+}++/** Whether an asset of the editor `type` is a valid pick for a `fieldType` slot. */+function assetMatchesSlot(type: AssetType, path: string, fieldType?: string): boolean {+ if (!fieldType) return true;+ // A 'texture' slot accepts any image (texture or sprite); others match by name.+ if (fieldType === 'texture') return type === 'texture' || type === 'sprite';+ // Spine slots split the shared 'spine' Content-Browser type into its two+ // halves, through the SDK's own classification (.skel vs .atlas) — the same+ // vocabulary the cook's dep scan uses.+ if (fieldType === 'spine-skeleton' || fieldType === 'spine-atlas') {+ const named = getEditorType(path);+ if (named === 'spine-skeleton' || named === 'spine-atlas') return named === fieldType;+ // A JSON skeleton has no extension of its own — Spine 2.1 exports nothing+ // else — so what says it is one is its registered `spine` type, minted from+ // the marker inside the file. Only the skeleton half can arrive unnamed:+ // the atlas is always `.atlas`.+ return fieldType === 'spine-skeleton' && type === 'spine';+ }+ if (type === fieldType) return true;+ // Slots named in the SDK's editorType vocabulary rather than the+ // Content-Browser type name (anim-clip for .esanim, timeline for .estimeline).+ return getEditorType(path) === fieldType;+}++class AssetRegistryImpl {+ /** uuid (lower-case) → project-relative path. */+ private readonly uuidToPath = new Map<string, string>();+ /** project-relative path → uuid (lower-case). */+ private readonly pathToUuid = new Map<string, string>();+ /** uuid → the `.meta` importer block, for import settings and texture params. */+ private readonly uuidToImporter = new Map<string, Record<string, unknown>>();+ /** uuid → the type minted from the file's content (what an extension cannot say). */+ private readonly uuidToType = new Map<string, string>();+ /** path → why its last load failed, so a ref can report more than "missing". */+ private readonly loadFailures = new Map<string, string>();+ /** Refs whose live hot-load is already in flight or done — one attempt each. */+ private readonly hotLoadStarted = new Set<string>();++ // — Lifecycle, driven by ProjectStore's scan ————————————————————————————————++ /**+ * Rebuild the lookup tables from a scanned index, and point the engine's+ * `Assets` at them.+ *+ * Tables only: the prefab cache and live-load bookkeeping are deliberately left+ * alone, because the incremental path invalidates those selectively — a scene+ * save must not drop every loaded `.esprefab`.+ */+ rebuild(entries: readonly AssetEntryLite[]): void {+ this.uuidToPath.clear();+ this.pathToUuid.clear();+ this.uuidToImporter.clear();+ this.uuidToType.clear();+ for (const e of entries) {+ const uuid = e.uuid.toLowerCase();+ this.uuidToPath.set(uuid, e.path);+ this.pathToUuid.set(e.path, uuid);+ if (e.importer) this.uuidToImporter.set(uuid, e.importer);+ if (e.type) this.uuidToType.set(uuid, e.type);+ }++ const assets = EngineHost.getResource(Assets);+ if (assets) {+ assets.baseUrl = 'estella://project';+ assets.setAssetRefResolver((ref) => this.refPath(ref));+ // Edit viewport honors each texture's `.meta` filter/wrap at load — the same+ // settings the runtime applies (was runtime-only, so edit ≠ play before).+ assets.setTextureImportSettingsResolver((ref) => this.textureImportFor(ref));+ }+ }++ /** Drop what a full repopulate invalidates: every load attempt is retried. */+ clearLoadState(): void {+ this.hotLoadStarted.clear();+ this.loadFailures.clear();+ }++ /** True when this ref's one hot-load attempt has already been made. */+ hotLoadStartedFor(ref: string): boolean {+ return this.hotLoadStarted.has(ref);+ }++ markHotLoadStarted(ref: string): void {+ this.hotLoadStarted.add(ref);+ }++ noteLoadFailure(path: string, reason: string): void {+ this.loadFailures.set(path, reason);+ }++ /** A path loaded successfully — forget the last failure recorded against it. */+ clearLoadFailure(path: string): void {+ this.loadFailures.delete(path);+ }++ /** Forget the hot-load attempts made for one project path, so a changed file is+ * loaded again. Hot-load keys are `<slot>:<path>`, one per slot the ref filled. */+ forgetHotLoadsFor(path: string): void {+ for (const key of [...this.hotLoadStarted]) if (key.endsWith(`:${path}`)) this.hotLoadStarted.delete(key);+ }++ // — Raw lookups, for callers that hold one half of the pair ————————————————++ /** The uuid a tracked path was minted with, or undefined. */+ uuidFor(path: string): string | undefined {+ return this.pathToUuid.get(path);+ }++ /** The path a uuid names, or undefined. */+ pathForUuid(uuid: string): string | undefined {+ return this.uuidToPath.get(uuid);+ }++ /** The `.meta` importer block for a uuid, or undefined. */+ importerForUuid(uuid: string): Record<string, unknown> | undefined {+ return this.uuidToImporter.get(uuid);+ }++ /** The content-minted `.meta` type for a uuid, or undefined. */+ typeForUuid(uuid: string): string | undefined {+ return this.uuidToType.get(uuid);+ }++ /** Every (uuid, path) pair. */+ entries(): IterableIterator<[string, string]> {+ return this.uuidToPath.entries();+ }++ /** Every (path, uuid) pair. */+ pathEntries(): IterableIterator<[string, string]> {+ return this.pathToUuid.entries();+ }++ /** Every tracked project path. */+ paths(): IterableIterator<string> {+ return this.uuidToPath.values();+ }++ // — Queries ————————————————————————————————————————————————————————————————++ /** The project path a ref points at, or null when the registry has no such uuid.+ * A plain path resolves to itself. */+ refPath(ref: string): string | null {+ const uuid = refUuid(ref);+ if (uuid === null) return ref;+ return this.uuidToPath.get(uuid) ?? null;+ }++ /** The portable `@uuid:` ref for a tracked path, or null when it is not tracked. */+ assetRef(path: string): string | null {+ const uuid = this.pathToUuid.get(path);+ return uuid ? UUID_PREFIX + uuid : null;+ }++ /** Whether a path is a tracked asset at all. */+ tracks(path: string): boolean {+ return this.pathToUuid.has(path);+ }++ /** The path + leaf name behind a ref, for anything that displays one. */+ assetInfo(ref: unknown): { path: string; name: string } | null {+ if (typeof ref !== 'string' || ref.length === 0) return null;+ const path = ref.startsWith(UUID_PREFIX)+ ? this.uuidToPath.get(ref.slice(UUID_PREFIX.length).toLowerCase())+ : this.assetRef(ref)+ ? ref+ : undefined;+ return path ? { path, name: path.split('/').pop() ?? path } : null;+ }++ /**+ * The Content-Browser type of a project file — the ONE answer the picker, the+ * drag-drop guard and the browser tiles all read, so they cannot disagree about+ * what a file is.+ *+ * The name decides it wherever an extension (or a `_ske.json`-style suffix) can:+ * that claim is cheap, and holds for files the registry has never seen. Where+ * the name says nothing, the registered `.meta` type does — it was minted from+ * the file's own content, which is the only thing that can tell a Spine JSON+ * skeleton from any other `.json`.+ */+ assetTypeAt(path: string): AssetType {+ const byName = assetTypeOf(path.split('/').pop() ?? path);+ if (byName !== 'file') return byName;+ const uuid = this.pathToUuid.get(path);+ const metaType = uuid ? this.uuidToType.get(uuid) : undefined;+ return metaType && assetTypeDef(metaType) !== ASSET_TYPES.file ? (metaType as AssetType) : byName;+ }++ /** Project assets valid for an asset slot (the inspector's asset picker), by name. */+ listAssets(fieldType?: string): AssetEntry[] {+ const out: AssetEntry[] = [];+ for (const [uuid, path] of this.uuidToPath) {+ const name = path.split('/').pop() ?? path;+ const type = this.assetTypeAt(path);+ if (!assetMatchesSlot(type, path, fieldType)) continue;+ out.push({ ref: UUID_PREFIX + uuid, path, name, type });+ }+ return out.sort((a, b) => a.name.localeCompare(b.name));+ }++ /** Whether the asset at `path` is a valid pick for a `fieldType` slot — the same rule+ * the picker popover filters by, exposed so drag-drop can reject a wrong-typed asset. */+ assetTypeAllowed(fieldType: string | undefined, path: string): boolean {+ if (!fieldType) return true;+ return assetMatchesSlot(this.assetTypeAt(path), path, fieldType);+ }++ /** Why a ref does not resolve, or null when it does. Distinguishes "no such uuid"+ * from "registered but its load failed", which a caller cannot tell apart from+ * a null path. */+ assetRefProblem(ref: string): string | null {+ const uuid = refUuid(ref);+ const path = uuid !== null ? (this.uuidToPath.get(uuid) ?? null) : ref;+ if (path === null) return 'unresolved: no asset with this uuid in the registry';+ if (uuid === null && !this.pathToUuid.has(path)) {+ return `unresolved: "${path}" is not a registered asset`;+ }+ const failure = this.loadFailures.get(path);+ return failure ? `load failed: ${failure}` : null;+ }++ /**+ * Turn a Content-Browser drag (a project-relative path) into a portable+ * `@uuid:` ref, preloading the asset so the Reconciler's synchronous projection+ * finds its handle when the model field is set. Textures resolve live; other+ * types are best-effort (resolved at scene load). Returns null if the path+ * isn't a tracked asset.+ */+ async assetRefForPath(path: string, assetType?: string): Promise<string | null> {+ const uuid = this.pathToUuid.get(path);+ if (!uuid) return null;+ const ref = UUID_PREFIX + uuid;+ // Spine slots are path-valued: nothing to preload here — the spine binding+ // (skeleton + atlas + pages) loads as a pair when the component syncs.+ if (assetType === 'spine-skeleton' || assetType === 'spine-atlas') return ref;+ const assets = EngineHost.getResource(Assets);+ if (assets) {+ try {+ if (assetType === 'material') await assets.loadMaterial(ref);+ else if (assetType === 'font') await assets.loadFont(ref);+ else await assets.loadTexture(ref);+ } catch {+ // non-loadable for this slot — the field still stores the ref losslessly+ }+ }+ return ref;+ }++ /** A texture's parsed `.meta` import settings, by ref or by path. */+ textureImportFor(ref: string): ReturnType<typeof textureImportSettingsFrom> {+ const uuid = refUuid(ref) ?? this.pathToUuid.get(ref);+ return textureImportSettingsFrom(uuid ? this.uuidToImporter.get(uuid) : undefined);+ }++ /** The raw `.meta` importer block for a path, or undefined. */+ importerFor(path: string): Record<string, unknown> | undefined {+ const uuid = this.pathToUuid.get(path);+ return uuid ? this.uuidToImporter.get(uuid) : undefined;+ }++ /**+ * Push a texture's just-saved import settings to its LIVE gl handle so the edit+ * viewport reflects a filter/wrap change immediately — no scene reload / sprite+ * repoint (the handle is updated in place; sprites keep referencing it). Call+ * after the asset inspector writes the `.meta` + a refresh.+ */+ applyLiveTextureSettings(path: string): void {+ const uuid = this.pathToUuid.get(path);+ const s = textureImportSettingsFrom(uuid ? this.uuidToImporter.get(uuid) : undefined);+ const handle = uuid ? EngineHost.getResource(Assets)?.getTexture(UUID_PREFIX + uuid)?.handle : undefined;+ if (!s || !handle) return;+ const filter = s.filter === 'nearest' ? TextureFilter.Nearest : TextureFilter.Linear;+ const wrap =+ s.wrap === 'clamp' ? TextureWrap.ClampToEdge : s.wrap === 'mirror' ? TextureWrap.MirroredRepeat : TextureWrap.Repeat;+ setTextureParams(handle, filter, filter, wrap, wrap);+ // The 9-slice border is applied at load; re-stamp it so dragging a border in+ // the asset inspector re-slices the live viewport without a scene reload.+ if (s.sliceBorder) {+ const b = s.sliceBorder;+ setTextureSliceBorder(handle, b.left, b.right, b.top, b.bottom);+ }+ }+}++/** The open project's asset database. Empty until a project is opened. */+export const AssetRegistry = new AssetRegistryImpl();diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.tsindex a058a8578..d0f0295ff 100644--- a/desktop/src/project/ProjectStore.ts+++ b/desktop/src/project/ProjectStore.ts@@ -1,8 +1,9 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamimport { createStore } from 'zustand/vanilla';-import { getComponent, getEditorType, Assets, migratePrefabData, extractPrefab, flattenPrefab, collectExternalEntityRefs, collapseInstance, applyDeltaToSource, buildVariant, validateOverrides, setTextureParams, setTextureSliceBorder, textureImportSettingsFrom, TextureFilter, TextureWrap, Renderer, RETIRED_COMPONENT_TYPES, parseThemeOverrides, resolveAssetGroup, folderGroupMode, withFolderGroup, folderAlwaysInclude, withFolderAlwaysInclude, withActiveRemoteRoot, Audio, applyAudioProjectConfig } from 'esengine';+import { getComponent, Assets, migratePrefabData, extractPrefab, flattenPrefab, collectExternalEntityRefs, collapseInstance, applyDeltaToSource, buildVariant, validateOverrides, textureImportSettingsFrom, Renderer, RETIRED_COMPONENT_TYPES, parseThemeOverrides, resolveAssetGroup, folderGroupMode, withFolderGroup, folderAlwaysInclude, withFolderAlwaysInclude, withActiveRemoteRoot, Audio, applyAudioProjectConfig } from 'esengine';import { importerDefaults, applyImporterEdit } from './assetImporter';+import { AssetRegistry, UUID_PREFIX, refUuid, type AssetEntryLite } from './AssetRegistry';import {runtimeConfigOf, packagedRuntimeFields, normalizeCollisionLayers, normalizeCollisionLayerMasks,type RuntimeProjectConfig,@@ -39,10 +40,7 @@ import { confirmDiscard } from './discardGuard';import { confirm } from '@/components/confirm';import { previewApply } from './applyPreview';import { t } from '@/i18n';-import { assetTypeOf } from '@/project/assetMeta';-import { ASSET_TYPES, assetTypeDef } from '@/project/assetTypes';import { ASSET_SLOTS, metaTypeToSlot } from '@/project/assetSlots';-import type { AssetType } from '@/types';import { resolveLayout, orientationFromDesignResolution, resolveOrientation, cameraScaleModeValue, resolveScripts, DEFAULT_SCRIPTS, WORKSPACE_DIR, PROJECT_MANIFEST_FILE, SORTING_LAYER_COUNT, trimSortingLayers, type OpenedProject, type ProjectFeatures, type ProjectLayout, type ProjectPackaging, type ProjectScripts, type WorkspaceState, type DesignResolution, type ScreenPreset, type ScreenOrientation, type CameraScaleMode, type ExportPlatform } from './format';import { useEditorMode } from '@/store/editorModeStore';import { PlayInspect } from '@/engine/PlayInspect';@@ -51,42 +49,11 @@ import { projectReplacing } from './projectReplacing';import { fsRefresh } from './fsRefresh';import type { DocSnapshot } from '@/document/DirtyRegistry';-/** Whether an asset of the editor `type` is a valid pick for a `fieldType` slot. */-function assetMatchesSlot(type: AssetType, path: string, fieldType?: string): boolean {- if (!fieldType) return true;- // A 'texture' slot accepts any image (texture or sprite); others match by name.- if (fieldType === 'texture') return type === 'texture' || type === 'sprite';- // Spine slots split the shared 'spine' Content-Browser type into its two- // halves, through the SDK's own classification (.skel vs .atlas) — the same- // vocabulary the cook's dep scan uses.- if (fieldType === 'spine-skeleton' || fieldType === 'spine-atlas') {- const named = getEditorType(path);- if (named === 'spine-skeleton' || named === 'spine-atlas') return named === fieldType;- // A JSON skeleton has no extension of its own — Spine 2.1 exports nothing- // else — so what says it is one is its registered `spine` type, minted from- // the marker inside the file. Only the skeleton half can arrive unnamed:- // the atlas is always `.atlas`.- return fieldType === 'spine-skeleton' && type === 'spine';- }- if (type === fieldType) return true;- // Slots named in the SDK's editorType vocabulary rather than the- // Content-Browser type name (anim-clip for .esanim, timeline for .estimeline).- return getEditorType(path) === fieldType;-}-/** A flattened prefab entity as a document entity (the fields a scene document keeps). */function toDocumentEntity(e: ProcessedEntity): DocumentEntity {return { id: e.id, name: e.name, parent: e.parent, children: e.children, components: e.components, visible: e.visible };}-/** A pickable asset for the inspector's asset picker. */-export interface AssetEntry {- ref: string;- path: string;- name: string;- type: AssetType;-}-/*** Editor-side project/workspace model (RC12 §E7-3 / §E6-1).*@@ -101,21 +68,6 @@ export interface AssetEntry {* The lossless model keeps `@uuid:` refs verbatim, so save stays portable.*/-const UUID_PREFIX = '@uuid:';--// UUID v4 shape — serialized refs come in three forms: `@uuid:` (canonical),-// a BARE uuid (`.esanim` flipbook frame textures), or a plain path. A bare-// uuid must resolve through the registry like a prefixed one; treating it as-// a path guarantees a 404 (estella://project/<uuid>) and white sprites.-const UUID_SHAPE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;--/** The uuid carried by a ref (`@uuid:` prefixed, any body — explicit intent —- * or bare-but-uuid-shaped), else null for plain paths. Lower-cased. */-function refUuid(ref: string): string | null {- if (ref.startsWith(UUID_PREFIX)) return ref.slice(UUID_PREFIX.length).toLowerCase();- return UUID_SHAPE.test(ref) ? ref.toLowerCase() : null;-}-/** The subset of the engine's SceneAssetResult the Reconciler resolver reads. */interface PreloadResult {textureHandles: Map<string, number>;@@ -191,24 +143,11 @@ function stripRetiredComponents(data: SceneData): string[] {return [...dropped];}-/** An asset index entry as the registry consumes it (from scanAssets or the- * cached assets.json — same shape). */-type AssetEntryLite = { uuid: string; path: string; type?: string; importer?: Record<string, unknown> };-class ProjectStoreImpl {private readonly store = createStore<{ project: ProjectState | null }>(() => ({ project: null }));- /** uuid → project-relative path, scanned from `.meta` sidecars — the editor's- * asset registry. The engine `Assets` loader resolves refs through it. */- private readonly uuidToPath = new Map<string, string>();- /** path → uuid (reverse), so a Content Browser drag (which carries a path) can- * be turned into a portable `@uuid:` ref for the model. */- private readonly pathToUuid = new Map<string, string>();- /** uuid → the asset's `.meta` importer block, so the edit viewport applies the- * same texture filter/wrap the runtime does (edit == play), and the asset- * inspector's Save can push a live sampler update. */- private readonly uuidToImporter = new Map<string, Record<string, unknown>>();- /** uuid → the asset's `.meta` type — the hot-sync path picks a loader by it. */- private readonly uuidToType = new Map<string, string>();+ // The uuid↔path lookup tables and the load bookkeeping keyed by them live in+ // {@link AssetRegistry}. This still drives the SCAN that fills them — that needs+ // the open project, its root and its watcher — but it no longer owns the answers./** ref → loaded `.esprefab` (PrefabData), for scene load-expand / save-collapse. */private readonly prefabCache = new Map<string, PrefabData>();/** Active Prefab Mode session, or null. Holds the id-preservation map@@ -234,13 +173,6 @@ class ProjectStoreImpl {base: PrefabData | null;baseRef: string | null;} | null = null;- /** Cold refs already handed to a live load this registry generation — the touch- * listener fires on every projection of a still-cold ref, so without this a- * failing asset would re-fetch forever (and a slow one would double-load). */- private readonly hotLoadStarted = new Set<string>();- /** Resolved path → error message for live loads that FAILED — diagnostics- * surfaces these (the model looks fine; only the load knows it's broken). */- private readonly assetLoadFailures = new Map<string, string>();/** Guards the off-critical-path asset revalidation after a cache-first boot. */private revalidating = false;/** Bumped on every project open ({@link adopt}); a revalidation captures it and@@ -275,7 +207,7 @@ class ProjectStoreImpl {setEnumSource('sortingLayers', () => this.sortingLayerOptions(), { exhaustive: false });installDragonBonesEnumSources();installSpineEnumSources();- installLocaleKeyEnumSource(() => this.listAssets('locale'));+ installLocaleKeyEnumSource(() => AssetRegistry.listAssets('locale'));// 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());@@ -296,7 +228,7 @@ class ProjectStoreImpl {});// Diagnostics ask the registry whether a model-healthy asset ref actually// names a real, loadable asset (dead refs draw white boxes in silence).- setAssetRefProblemResolver((ref) => this.assetRefProblem(ref));+ setAssetRefProblemResolver((ref) => AssetRegistry.assetRefProblem(ref));// Instantiating a variant / nested prefab resolves its base through the same// warm-cache reader the scene-load path uses (one resolution truth).SceneCommands.setPrefabResolver(this.prefabResolverSync);@@ -608,7 +540,7 @@ class ProjectStoreImpl {// from the same preload result — for all types, not just textures. Spine// slots resolve to project paths instead (they stay strings in the World).Reconciler.setAssetResolver((ref) => this.handleForRef(ref));- Reconciler.setRefPathResolver((ref) => this.resolveRef(ref));+ Reconciler.setRefPathResolver((ref) => AssetRegistry.refPath(ref));// A projection that resolves COLD (assigned after the scene-open preload)// hands its ref here: async load through the engine loaders, re-project.Reconciler.setAssetTouchListener((ref, slot) => this.hotLoadAsset(ref, slot));@@ -678,7 +610,7 @@ class ProjectStoreImpl {EditorHistory.clearScene();useSelection.getState().select(null);Reconciler.setAssetResolver((ref) => this.handleForRef(ref));- Reconciler.setRefPathResolver((ref) => this.resolveRef(ref));+ Reconciler.setRefPathResolver((ref) => AssetRegistry.refPath(ref));Reconciler.setAssetTouchListener((ref, slot) => this.hotLoadAsset(ref, slot));installSkeletalSync(this.skeletalTransport());Reconciler.adopt(blank, blank); // no @uuid: refs → resolved === raw@@ -706,7 +638,7 @@ class ProjectStoreImpl {// named collision is answered here — emptied on request (the uuid is kept, so refs// to the scene survive), and otherwise refused with the flag that would allow it.const rel = `${destDir.replace(/\/$/, '')}/${base}`;- if (name?.trim() && this.pathToUuid.has(rel)) {+ if (name?.trim() && AssetRegistry.tracks(rel)) {if (!opts?.overwrite) {throw new Error(`"${rel}" already exists — pass overwrite to empty it, or use another name`);}@@ -795,38 +727,13 @@ class ProjectStoreImpl {}/** Rebuild the uuid↔path registry + Assets resolvers from an index's entries,- * dropping ALL caches — a full rescan (project open) can invalidate anything. */+ * dropping ALL caches — a full rescan (project open) can invalidate anything.+ * The prefab cache is ours; the lookup tables and load bookkeeping are the+ * registry's, and it decides what a rebuild keeps. */private populateRegistry(entries: readonly AssetEntryLite[]): void {this.prefabCache.clear();- this.hotLoadStarted.clear();- this.assetLoadFailures.clear();- this.rebuildLookups(entries);- }-- /** Rebuild only the (cheap, in-memory) uuid↔path lookup maps + Assets resolvers- * from an index's entries. Leaves the disk-loaded prefab cache and live-load- * bookkeeping alone — the incremental path invalidates those selectively. */- private rebuildLookups(entries: readonly AssetEntryLite[]): void {- this.uuidToPath.clear();- this.pathToUuid.clear();- this.uuidToImporter.clear();- this.uuidToType.clear();- for (const e of entries) {- const uuid = e.uuid.toLowerCase();- this.uuidToPath.set(uuid, e.path);- this.pathToUuid.set(e.path, uuid);- if (e.importer) this.uuidToImporter.set(uuid, e.importer);- if (e.type) this.uuidToType.set(uuid, e.type);- }-- const assets = EngineHost.getResource(Assets);- if (assets) {- assets.baseUrl = 'estella://project';- assets.setAssetRefResolver((ref) => this.resolveRef(ref));- // Edit viewport honors each texture's `.meta` filter/wrap at load — the same- // settings the runtime applies (was runtime-only, so edit ≠ play before).- assets.setTextureImportSettingsResolver((ref) => this.textureImportFor(ref));- }+ AssetRegistry.clearLoadState();+ AssetRegistry.rebuild(entries);}/**@@ -864,10 +771,10 @@ class ProjectStoreImpl {// must run before rebuildLookups.for (const ref of [...this.prefabCache.keys()]) {const uuid = refUuid(ref);- const p = uuid !== null ? this.uuidToPath.get(uuid) : undefined;+ const p = uuid !== null ? AssetRegistry.pathForUuid(uuid) : undefined;if (!p || changed.has(p) || !kept.has(p)) this.prefabCache.delete(ref);}- this.rebuildLookups(entries);+ AssetRegistry.rebuild(entries);}/** Off-critical-path authoritative scan after a cache-first boot: repopulate +@@ -884,8 +791,8 @@ class ProjectStoreImpl {const fresh = new Map<string, string>();for (const e of entries) fresh.set(e.path, e.uuid.toLowerCase());const changed: string[] = [];- for (const [p, u] of fresh) if (this.pathToUuid.get(p) !== u) changed.push(p);- for (const p of this.pathToUuid.keys()) if (!fresh.has(p)) changed.push(p); // removed+ for (const [p, u] of fresh) if (AssetRegistry.uuidFor(p) !== u) changed.push(p);+ for (const [p] of AssetRegistry.pathEntries()) if (!fresh.has(p)) changed.push(p); // removedif (changed.length === 0) return; // the cache was authoritative — nothing to doconsole.info(`[assets] revalidation: ${changed.length} asset change(s) since the project was last open`);this.populateRegistry(entries);@@ -898,32 +805,10 @@ class ProjectStoreImpl {/** The texture filter/wrap for a ref (`@uuid:` or path), from its `.meta`* importer — the shape `Assets`'s TextureLoader consumes. Undefined ⇒ defaults. */- private textureImportFor(ref: string): ReturnType<typeof textureImportSettingsFrom> {- const uuid = refUuid(ref) ?? this.pathToUuid.get(ref);- return textureImportSettingsFrom(uuid ? this.uuidToImporter.get(uuid) : undefined);- }-/** Push a texture's just-saved import settings to its LIVE gl handle so the edit* viewport reflects a filter/wrap change immediately — no scene reload / sprite* repoint (the handle is updated in place; sprites keep referencing it). Call* after the asset inspector writes the `.meta` + refreshAssets. */- applyLiveTextureSettings(path: string): void {- const uuid = this.pathToUuid.get(path);- const s = textureImportSettingsFrom(uuid ? this.uuidToImporter.get(uuid) : undefined);- const handle = uuid ? EngineHost.getResource(Assets)?.getTexture(UUID_PREFIX + uuid)?.handle : undefined;- if (!s || !handle) return;- const filter = s.filter === 'nearest' ? TextureFilter.Nearest : TextureFilter.Linear;- const wrap =- s.wrap === 'clamp' ? TextureWrap.ClampToEdge : s.wrap === 'mirror' ? TextureWrap.MirroredRepeat : TextureWrap.Repeat;- setTextureParams(handle, filter, filter, wrap, wrap);- // The 9-slice border is applied at load; re-stamp it so dragging a border in- // the asset inspector re-slices the live viewport without a scene reload.- if (s.sliceBorder) {- const b = s.sliceBorder;- setTextureSliceBorder(handle, b.left, b.right, b.top, b.bottom);- }- }-/*** An asset's import settings: its `.meta` importer block layered over the* type's declared defaults, so a caller sees every knob (not just the ones@@ -932,7 +817,7 @@ class ProjectStoreImpl {* writes against.*/async getImportSettings(path: string): Promise<{ type: string; settings: Record<string, unknown> }> {- const type = this.assetTypeAt(path);+ const type = AssetRegistry.assetTypeAt(path);const stored = JSON.parse(await window.estella.fs.read(path + '.meta')).importer as| Record<string, unknown>| undefined;@@ -973,33 +858,22 @@ class ProjectStoreImpl {meta.importer = importer;await window.estella.fs.write(path + '.meta', JSON.stringify(meta, null, 2) + '\n');await this.refreshAssets();- this.applyLiveTextureSettings(path);+ AssetRegistry.applyLiveTextureSettings(path);return importer;}/** Resolve a serialized asset ref to a project-relative path for the engine* loader: a uuid ref (`@uuid:` or bare) → path (null if unknown); a plain* path passes through. */- /** Project-relative path for a `@uuid:` ref (or a plain path unchanged). */- refPath(ref: string): string | null {- return this.resolveRef(ref);- }-- private resolveRef(ref: string): string | null {- const uuid = refUuid(ref);- if (uuid === null) return ref;- return this.uuidToPath.get(uuid) ?? null;- }-/** The project transport skeletal assets load over: ref → `estella://` URL for* fetches, `@uuid:` ref → project path for atlas-dir derivation. */private skeletalTransport(): SkeletalTransport {return {toUrl: (ref) =>ref.startsWith(UUID_PREFIX)- ? `estella://project/${this.resolveRef(ref) ?? ''}`+ ? `estella://project/${AssetRegistry.refPath(ref) ?? ''}`: `estella://project/${ref.replace(/^\//, '')}`,- resolvePath: (ref) => this.resolveRef(ref) ?? ref,+ resolvePath: (ref) => AssetRegistry.refPath(ref) ?? ref,};}@@ -1009,7 +883,7 @@ class ProjectStoreImpl {const tex = EngineHost.getResource(Assets)?.getTexture(ref);if (tex) return tex.handle;const uuid = refUuid(ref);- const path = uuid !== null ? this.uuidToPath.get(uuid) : ref;+ const path = uuid !== null ? AssetRegistry.pathForUuid(uuid) : ref;const r = this.lastAssetResult;if (!path || !r) return 0;return r.materialHandles.get(path) ?? r.fontHandles.get(path) ?? 0;@@ -1025,22 +899,22 @@ class ProjectStoreImpl {* re-fetch forever.*/private hotLoadAsset(ref: string, fieldType: string): void {- const path = this.resolveRef(ref);+ const path = AssetRegistry.refPath(ref);if (path === null) return; // unknown uuid — diagnostics reports it; nothing to loadconst key = `${fieldType}:${path}`;- if (this.hotLoadStarted.has(key)) return;- this.hotLoadStarted.add(key);+ if (AssetRegistry.hotLoadStartedFor(key)) return;+ AssetRegistry.markHotLoadStarted(key);const assets = EngineHost.getResource(Assets);if (!assets) return;void this.loadForSlot(assets, fieldType, ref, path).then(() => {- this.assetLoadFailures.delete(path);- Reconciler.reprojectRefs((r) => this.resolveRef(r) === path);+ AssetRegistry.clearLoadFailure(path);+ Reconciler.reprojectRefs((r) => AssetRegistry.refPath(r) === path);SceneStore.poke();}).catch((err) => {const msg = err instanceof Error ? err.message : String(err);- this.assetLoadFailures.set(path, msg);+ AssetRegistry.noteLoadFailure(path, msg);console.error(`[assets] live load of ${fieldType} "${path}" failed: ${msg}`);});}@@ -1081,15 +955,13 @@ class ProjectStoreImpl {const rel = raw.replace(/\\/g, '/').replace(/\.meta$/, '');if (rel === '' || seen.has(rel)) continue;seen.add(rel);- const uuid = this.pathToUuid.get(rel);+ const uuid = AssetRegistry.uuidFor(rel);if (!uuid) continue; // not a registered asset (or deleted — registry refresh handles it)if (!assets.invalidate(rel)) continue; // nothing was cached → nothing is stale// The asset WAS live: clear the dedup so the reload can start, then reload// through the same slot-typed path a cold projection uses.- for (const key of [...this.hotLoadStarted]) {- if (key.endsWith(`:${rel}`)) this.hotLoadStarted.delete(key);- }- const slot = metaTypeToSlot(this.uuidToType.get(uuid));+ AssetRegistry.forgetHotLoadsFor(rel);+ const slot = metaTypeToSlot(AssetRegistry.typeForUuid(uuid));if (slot) this.hotLoadAsset(UUID_PREFIX + uuid, slot);}}@@ -1100,17 +972,6 @@ class ProjectStoreImpl {* live-load failure. Diagnostics adds these on top of required-empty — the* model value looks perfectly healthy in both cases.*/- assetRefProblem(ref: string): string | null {- const uuid = refUuid(ref);- const path = uuid !== null ? (this.uuidToPath.get(uuid) ?? null) : ref;- if (path === null) return 'unresolved: no asset with this uuid in the registry';- if (uuid === null && !this.pathToUuid.has(path)) {- return `unresolved: "${path}" is not a registered asset`;- }- const failure = this.assetLoadFailures.get(path);- return failure ? `load failed: ${failure}` : null;- }-/** The live material handle a scene's sprites use for @p path (from the last scene* preload), or 0 if the material isn't loaded in the current scene. The Material Editor* uses it to push live edits onto the running material so the viewport reflects them. */@@ -1126,7 +987,7 @@ class ProjectStoreImpl {if (!ref.startsWith(UUID_PREFIX)) return null;const cached = this.prefabCache.get(ref);if (cached) return cached;- const path = this.uuidToPath.get(ref.slice(UUID_PREFIX.length).toLowerCase());+ const path = AssetRegistry.pathForUuid(ref.slice(UUID_PREFIX.length).toLowerCase());if (!path) return null;try {const prefab = migratePrefabData(JSON.parse(await window.estella.fs.read(path))).data as PrefabData;@@ -1203,7 +1064,7 @@ class ProjectStoreImpl {position?: { x: number; y: number },name?: string,): Promise<number | null> {- const uuid = this.pathToUuid.get(path);+ const uuid = AssetRegistry.uuidFor(path);if (!uuid) return null;const ref = UUID_PREFIX + uuid;const prefab = await this.loadPrefabAsset(ref);@@ -1225,7 +1086,7 @@ class ProjectStoreImpl {*/prefabSources(): EntitySource[] {const out: EntitySource[] = [];- for (const [path, uuid] of this.pathToUuid) {+ for (const [path, uuid] of AssetRegistry.pathEntries()) {if (!path.toLowerCase().endsWith('.esprefab')) continue;const ref = UUID_PREFIX + uuid;const name = (path.split('/').pop() ?? 'Prefab').replace(/\.esprefab$/i, '');@@ -1261,7 +1122,7 @@ class ProjectStoreImpl {const tag = SceneModel.prefabTag(id);const ref = tag?.prefab ?? (tag ? SceneModel.prefabTag(tag.instanceRoot)?.prefab : undefined);if (!ref) return;- const info = this.assetInfo(ref);+ const info = AssetRegistry.assetInfo(ref);if (!info) return;await this.openPrefab(info.path, opts);}@@ -1279,7 +1140,7 @@ class ProjectStoreImpl {const instanceRoot = tag?.instanceRoot ?? sourceId;const ref = SceneModel.prefabTag(instanceRoot)?.prefab;if (!ref) return null;- const info = this.assetInfo(ref);+ const info = AssetRegistry.assetInfo(ref);if (!info) return null;const root = SceneModel.entityBySource(instanceRoot);const parent = root?.parent ?? null;@@ -1315,7 +1176,7 @@ class ProjectStoreImpl {const instanceRoot = tag?.instanceRoot ?? sourceId;const ref = SceneModel.prefabTag(instanceRoot)?.prefab;if (!ref) return null;- const info = this.assetInfo(ref);+ const info = AssetRegistry.assetInfo(ref);if (!info) return null;const oldPrefab = await this.loadPrefabAsset(ref);if (!oldPrefab) {@@ -1412,7 +1273,7 @@ class ProjectStoreImpl {const instanceRoot = tag?.instanceRoot ?? sourceId;const ref = SceneModel.prefabTag(instanceRoot)?.prefab;if (!ref) return null;- const info = this.assetInfo(ref);+ const info = AssetRegistry.assetInfo(ref);if (!info) return null;const base = await this.loadPrefabAsset(ref);if (!base) {@@ -1478,7 +1339,7 @@ class ProjectStoreImpl {* the path isn't a tracked texture. One undoable step; the new entity is selected.*/async instantiateSpriteFromPath(path: string, position: { x: number; y: number }): Promise<number | null> {- const ref = await this.assetRefForPath(path, 'texture');+ const ref = await AssetRegistry.assetRefForPath(path, 'texture');if (!ref) return null;const size = await this.imageNaturalSize(path);const name = (path.split('/').pop() ?? 'Sprite').replace(/\.[^.]+$/, '') || 'Sprite';@@ -1536,9 +1397,9 @@ class ProjectStoreImpl {// instead would write `<name>-1.esprefab` and leave every instance in the project// pointing at the stale one — a silent no-op for the caller who asked for an update.// The uuid is KEPT for the same reason: refs are by uuid, and a new one orphans them.- const existingUuid = opts?.replace ? this.pathToUuid.get(rel) : undefined;+ const existingUuid = opts?.replace ? AssetRegistry.uuidFor(rel) : undefined;if (!existingUuid) {- for (let n = 1; this.pathToUuid.has(rel); n++) rel = `assets/prefabs/${base}-${n}.esprefab`;+ for (let n = 1; AssetRegistry.tracks(rel); n++) rel = `assets/prefabs/${base}-${n}.esprefab`;}const uuid = existingUuid ?? crypto.randomUUID();@@ -1576,7 +1437,7 @@ class ProjectStoreImpl {* next load. Reports how many were upgraded.*/async resaveAllPrefabs(): Promise<void> {- const paths = [...this.pathToUuid.keys()].filter((p) => p.endsWith('.esprefab'));+ const paths = [...AssetRegistry.pathEntries()].map(([p]) => p).filter((p) => p.endsWith('.esprefab'));if (paths.length === 0) {Toasts.push(t('proj.resaveNone'), 'info');return;@@ -1601,11 +1462,6 @@ class ProjectStoreImpl {/** A tracked asset's portable `@uuid:` ref for a project-relative path (Copy* Reference), or null if the path isn't an indexed asset. */- assetRef(path: string): string | null {- const uuid = this.pathToUuid.get(path);- return uuid ? UUID_PREFIX + uuid : null;- }-/*** Assemble the isolated play-realm payload: the* current scene as RAW (`@uuid:`) SceneData straight from the expanded model —@@ -1655,7 +1511,7 @@ class ProjectStoreImpl {textureImport?: ParsedTextureImportSettings;};const groups: Record<string, { bundleMode: string; labels: string[]; assets: Record<string, Asset> }> = {};- for (const [uuid, raw] of this.uuidToPath) {+ for (const [uuid, raw] of AssetRegistry.entries()) {const path = raw.replace(/\\/g, '/');const { name, delivery } = resolveAssetGroup(path, this.assetGroupsConfig);const g = (groups[name] ??= { bundleMode: delivery, labels: [], assets: {} });@@ -1663,7 +1519,7 @@ class ProjectStoreImpl {// as it does in a cooked manifest — so Play reads it through the same// channel a shipped build does, rather than a play-only side band that can// drift from it.- const textureImport = textureImportSettingsFrom(this.uuidToImporter.get(uuid));+ const textureImport = textureImportSettingsFrom(AssetRegistry.importerForUuid(uuid));g.assets[uuid.toLowerCase()] = {path, type: typeOfExt(path), size: 0, labels: [],...(textureImport ? { textureImport } : {}),@@ -1694,7 +1550,7 @@ class ProjectStoreImpl {// The realm runs from the project's estella:// origin, so assets are// same-origin estella:// — no cross-scheme dance needed.const assetManifest: Record<string, string> = {};- for (const [uuid, path] of this.uuidToPath) assetManifest[uuid] = `estella://project/${path}`;+ for (const [uuid, path] of AssetRegistry.entries()) assetManifest[uuid] = `estella://project/${path}`;// Play == ship: register every other project scene under its export name// (scenes-dir-relative path sans extension — the same rule exportGame's// discoverProjectScenes uses), so SceneManager.switchTo('levels/boss')@@ -1708,7 +1564,7 @@ class ProjectStoreImpl {};const currentScene = st?.currentScene?.replace(/\\/g, '/') ?? null;const extraScenes: Array<{ name: string; path: string }> = [];- for (const p of this.uuidToPath.values()) {+ for (const p of AssetRegistry.paths()) {const q = p.replace(/\\/g, '/');if (!/\.esscene$/i.test(q) || q === currentScene) continue;extraScenes.push({ name: exportSceneName(q), path: q });@@ -2226,16 +2082,6 @@ class ProjectStoreImpl {/** Display info for an asset ref (`@uuid:` or a project-relative path — the same* forms the loaders accept), or null (none / unresolved). For the inspector's* asset control: the project-relative path + a leaf name. */- assetInfo(ref: unknown): { path: string; name: string } | null {- if (typeof ref !== 'string' || ref.length === 0) return null;- const path = ref.startsWith(UUID_PREFIX)- ? this.uuidToPath.get(ref.slice(UUID_PREFIX.length).toLowerCase())- : this.assetRef(ref)- ? ref- : undefined;- return path ? { path, name: path.split('/').pop() ?? path } : null;- }-/*** The Content-Browser type of a project file — the ONE answer the picker, the* drag-drop guard and the browser tiles all read, so they cannot disagree about@@ -2247,33 +2093,8 @@ class ProjectStoreImpl {* the file's own content, which is the only thing that can tell a Spine JSON* skeleton from any other `.json`.*/- assetTypeAt(path: string): AssetType {- const byName = assetTypeOf(path.split('/').pop() ?? path);- if (byName !== 'file') return byName;- const uuid = this.pathToUuid.get(path);- const metaType = uuid ? this.uuidToType.get(uuid) : undefined;- return metaType && assetTypeDef(metaType) !== ASSET_TYPES.file ? (metaType as AssetType) : byName;- }-- /** Project assets valid for an asset slot (the inspector's asset picker), by name. */- listAssets(fieldType?: string): AssetEntry[] {- const out: AssetEntry[] = [];- for (const [uuid, path] of this.uuidToPath) {- const name = path.split('/').pop() ?? path;- const type = this.assetTypeAt(path);- if (!assetMatchesSlot(type, path, fieldType)) continue;- out.push({ ref: UUID_PREFIX + uuid, path, name, type });- }- return out.sort((a, b) => a.name.localeCompare(b.name));- }-/** Whether the asset at `path` is a valid pick for a `fieldType` slot — the same rule* the picker popover filters by, exposed so drag-drop can reject a wrong-typed asset. */- assetTypeAllowed(fieldType: string | undefined, path: string): boolean {- if (!fieldType) return true;- return assetMatchesSlot(this.assetTypeAt(path), path, fieldType);- }-/*** Turn a Content-Browser drag (a project-relative path) into a portable* `@uuid:` ref, preloading the asset so the Reconciler's synchronous projection@@ -2281,26 +2102,6 @@ class ProjectStoreImpl {* types are best-effort (resolved at scene load). Returns null if the path* isn't a tracked asset.*/- async assetRefForPath(path: string, assetType?: string): Promise<string | null> {- const uuid = this.pathToUuid.get(path);- if (!uuid) return null;- const ref = UUID_PREFIX + uuid;- // Spine slots are path-valued: nothing to preload here — the spine binding- // (skeleton + atlas + pages) loads as a pair when the component syncs.- if (assetType === 'spine-skeleton' || assetType === 'spine-atlas') return ref;- const assets = EngineHost.getResource(Assets);- if (assets) {- try {- if (assetType === 'material') await assets.loadMaterial(ref);- else if (assetType === 'font') await assets.loadFont(ref);- else await assets.loadTexture(ref);- } catch {- // non-loadable for this slot — the field still stores the ref losslessly- }- }- return ref;- }-/*** Serialize the editor's source-of-truth model — lossless (JSON-first) +* prefab-aware: collapse each expanded prefab-instance subtree back to a single@@ -2380,7 +2181,7 @@ class ProjectStoreImpl {if (!st) return;const leaf = path.split('/').pop() ?? path;if (!opts?.discardChanges && !(await confirmDiscard(t('discard.openPrefab', { name: leaf })))) return;- const uuid = this.pathToUuid.get(path);+ const uuid = AssetRegistry.uuidFor(path);const ref = uuid ? UUID_PREFIX + uuid : null;const prefab = ref ? await this.loadPrefabAsset(ref) : null;if (!ref || !prefab) {@@ -2491,7 +2292,7 @@ class ProjectStoreImpl {useSelection.getState().select(null);usePrefabConflicts.getState().clear(); // a prefab document has no scene instancesReconciler.setAssetResolver((ref) => this.handleForRef(ref));- Reconciler.setRefPathResolver((ref) => this.resolveRef(ref));+ Reconciler.setRefPathResolver((ref) => AssetRegistry.refPath(ref));Reconciler.setAssetTouchListener((ref, slot) => this.hotLoadAsset(ref, slot));installSkeletalSync(this.skeletalTransport());Reconciler.adopt(raw, resolved);@@ -2744,3 +2545,5 @@ class ProjectStoreImpl {}export const ProjectStore = new ProjectStoreImpl();++diff --git a/desktop/src/project/assetTypes.ts b/desktop/src/project/assetTypes.tsindex ae02f6390..faaedc968 100644--- a/desktop/src/project/assetTypes.ts+++ b/desktop/src/project/assetTypes.ts@@ -56,7 +56,7 @@ export const ASSET_TYPES: Record<BuiltinAssetType, AssetTypeDef> = {sprite: { extensions: ['jpg', 'jpeg', 'gif'], badge: 'IMG', icon: Image, tint: '#7fa6c4', externalProgram: 'image' },// A skeleton exported as JSON has no extension of its own; it is typed at the// `.meta` mint door by a marker in the file (tools/assetMetaTable.js) and reaches- // this vocabulary through ProjectStore.assetTypeAt — which is why every caller+ // this vocabulary through AssetRegistry.assetTypeAt — which is why every caller// asks that by PATH rather than calling assetTypeOf on a bare name.spine: { extensions: ['atlas', 'skel'], badge: 'SPN', icon: PersonStanding, tint: '#9b8fc0' },// Both halves are one type, as Spine's .skel and .atlas are: which file playsdiff --git a/desktop/src/tilemap/createTilemap.ts b/desktop/src/tilemap/createTilemap.tsindex 2daf2d3d7..d5aeed50d 100644--- a/desktop/src/tilemap/createTilemap.ts+++ b/desktop/src/tilemap/createTilemap.ts@@ -15,7 +15,7 @@ import { createFromSource, tilemapPrefab, type EntitySource, type TileGridConfigimport type { EntityId } from '@/types';import { useSelection } from '@/store/selectionStore';import { useTilemapPaint } from '@/store/tilemapPaintStore';-import { ProjectStore } from '@/project/ProjectStore';+import { AssetRegistry } from '@/project/AssetRegistry';import { dockApi } from '@/layout/dockApi';import { Toasts } from '@/store/Toasts';import { t } from '@/i18n';@@ -61,7 +61,7 @@ function tilesetSource(export async function createTilemapFromTileset(tilesetPath: string, grid?: TileGridConfig,): Promise<EntityId | null> {- const tilesetRef = ProjectStore.assetRef(tilesetPath); // .estileset → @uuid+ const tilesetRef = AssetRegistry.assetRef(tilesetPath); // .estileset → @uuidif (!tilesetRef) {Toasts.push(t('tile.toast.untracked'), 'error');return null;diff --git a/desktop/src/tilemap/layerTilesetModel.ts b/desktop/src/tilemap/layerTilesetModel.tsindex b2a09c757..ba1b5917d 100644--- a/desktop/src/tilemap/layerTilesetModel.ts+++ b/desktop/src/tilemap/layerTilesetModel.ts@@ -13,7 +13,7 @@ import {type TilesetModel, type ResolvedTileset,} from 'esengine';import { SceneModel } from '@/engine/SceneModel';-import { ProjectStore } from '@/project/ProjectStore';+import { AssetRegistry } from '@/project/AssetRegistry';import { loadTilesetAsset } from '@/tileset/loadTileset';/** The `.estileset` ref(s) a TilemapLayer entity references — its `tilesetAssets` list@@ -53,7 +53,7 @@ export async function loadLayerTilesetModel(refs: string[]): Promise<TilesetModeconst list: ResolvedTileset[] = [];for (const ref of refs) {- const path = ProjectStore.assetInfo(ref)?.path;+ const path = AssetRegistry.assetInfo(ref)?.path;if (!path) continue;let asset;try {@@ -63,7 +63,7 @@ export async function loadLayerTilesetModel(refs: string[]): Promise<TilesetMode}let textureHeight: number | undefined;if (!(typeof asset.tileCount === 'number' && asset.tileCount > 0)) {- const texPath = ProjectStore.assetInfo(asset.texture)?.path;+ const texPath = AssetRegistry.assetInfo(asset.texture)?.path;if (texPath) {const h = await imageHeight(`estella://project/${texPath}`);if (h > 0) textureHeight = h;diff --git a/desktop/src/tileset/openTileset.ts b/desktop/src/tileset/openTileset.tsindex 3873a5f0e..d7e857286 100644--- a/desktop/src/tileset/openTileset.ts+++ b/desktop/src/tileset/openTileset.ts@@ -10,6 +10,7 @@import { createTileset as createTilesetAsset, serializeTileset } from 'esengine';import { TilesetDocument } from './TilesetDocument';import { ProjectStore } from '@/project/ProjectStore';+import { AssetRegistry } from '@/project/AssetRegistry';import { confirmDiscardDoc } from '@/project/discardGuard';import { dockApi } from '@/layout/dockApi';import { baseName } from '@/project/assetMeta';@@ -45,7 +46,7 @@ export interface TilesetGridInit {/** Create a .estileset next to a texture (referencing it), then open it. `grid` is the* slice chosen in the New-Tileset dialog; omitted falls back to a plain 16×16 grid. */export async function createTilesetFromTexture(texturePath: string, grid?: TilesetGridInit): Promise<void> {- const ref = ProjectStore.assetRef(texturePath);+ const ref = AssetRegistry.assetRef(texturePath);if (!ref) {Toasts.push(t('tile.toast.texUntracked'), 'error');return;@@ -53,7 +54,7 @@ export async function createTilesetFromTexture(texturePath: string, grid?: Tilesconst dir = texturePath.includes('/') ? texturePath.slice(0, texturePath.lastIndexOf('/') + 1) : '';const base = baseName(texturePath).replace(/\.[^.]+$/, '') || 'Tileset';let rel = `${dir}${base}.estileset`;- for (let n = 1; ProjectStore.assetRef(rel); n++) rel = `${dir}${base}-${n}.estileset`;+ for (let n = 1; AssetRegistry.assetRef(rel); n++) rel = `${dir}${base}-${n}.estileset`;const g = grid ?? { tileWidth: 16, tileHeight: 16, margin: 0, spacing: 0, columns: 1 };const asset = createTilesetAsset(ref, g.tileWidth, g.tileHeight, g.columns);diff --git a/desktop/src/timeline/openClip.ts b/desktop/src/timeline/openClip.tsindex d61010ab7..cfa75eee1 100644--- a/desktop/src/timeline/openClip.ts+++ b/desktop/src/timeline/openClip.ts@@ -18,6 +18,7 @@ import { useSequencerStore } from '@/store/sequencerStore';import { dockApi } from '@/layout/dockApi';import { Toasts } from '@/store/Toasts';import { ProjectStore } from '@/project/ProjectStore';+import { AssetRegistry } from '@/project/AssetRegistry';import { confirmDiscardDoc } from '@/project/discardGuard';import { baseName } from '@/project/assetMeta';@@ -56,7 +57,7 @@ const BLANK_CLIP = { version: '1.1', type: 'timeline', duration: 5, wrapMode: 'lexport async function createAnimationClip(dir: string): Promise<void> {const folder = dir ? (dir.endsWith('/') ? dir : `${dir}/`) : '';let rel = `${folder}NewAnimation.estimeline`;- for (let n = 1; ProjectStore.assetRef(rel); n++) rel = `${folder}NewAnimation-${n}.estimeline`;+ for (let n = 1; AssetRegistry.assetRef(rel); n++) rel = `${folder}NewAnimation-${n}.estimeline`;try {await window.estella.fs.write(rel, JSON.stringify(BLANK_CLIP, null, 2) + '\n');await window.estella.fs.write(diff --git a/desktop/src/timeline/previewRoot.ts b/desktop/src/timeline/previewRoot.tsindex d9927c394..edfc52e3b 100644--- a/desktop/src/timeline/previewRoot.ts+++ b/desktop/src/timeline/previewRoot.ts@@ -12,14 +12,14 @@import { SceneModel } from '@/engine/SceneModel';import { useSelection } from '@/store/selectionStore';-import { ProjectStore } from '@/project/ProjectStore';+import { AssetRegistry } from '@/project/AssetRegistry';import { resolveTimelineRoot, timelinePlayersFor, type TimelineRootEntity } from './timelineRoot';/** Matches the refs that name this project-relative asset path: a `TimelinePlayer`* may hold the `@uuid:` form (what the editor writes) or the path itself. */function refMatcher(filePath: string | null): (ref: string) => boolean {if (!filePath) return () => false;- const uuidRef = ProjectStore.assetRef(filePath);+ const uuidRef = AssetRegistry.assetRef(filePath);return (ref) => ref === filePath || (!!uuidRef && ref === uuidRef);}diff --git a/desktop/tests/field-constraints.test.ts b/desktop/tests/field-constraints.test.tsindex 6aa527aa3..2ba76e9ec 100644--- a/desktop/tests/field-constraints.test.ts+++ b/desktop/tests/field-constraints.test.ts@@ -8,7 +8,7 @@*/import { describe, it, expect } from 'vitest';import { clampFieldValue, isRequiredField, setUserSchemas, componentAuthorability } from '@/engine/schema';-import { ProjectStore } from '@/project/ProjectStore';+import { AssetRegistry } from '@/project/AssetRegistry';describe('field constraints (C1: write-gate clamp + asset-type guard)', () => {it('clampFieldValue bounds a scalar to its declared min/max; passes everything else through', () => {@@ -22,9 +22,9 @@ describe('field constraints (C1: write-gate clamp + asset-type guard)', () => {});it('assetTypeAllowed enforces the slot type by extension (the drag-drop guard)', () => {- expect(ProjectStore.assetTypeAllowed('texture', 'assets/hero.png')).toBe(true);- expect(ProjectStore.assetTypeAllowed('texture', 'assets/thing.esprefab')).toBe(false);- expect(ProjectStore.assetTypeAllowed(undefined, 'assets/anything.xyz')).toBe(true); // unconstrained slot+ expect(AssetRegistry.assetTypeAllowed('texture', 'assets/hero.png')).toBe(true);+ expect(AssetRegistry.assetTypeAllowed('texture', 'assets/thing.esprefab')).toBe(false);+ expect(AssetRegistry.assetTypeAllowed(undefined, 'assets/anything.xyz')).toBe(true); // unconstrained slot});// Whether a component may be authored at all was enforced only while building