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
feat(editor): Content Browser asset import (C4)
esengine73fafc570b7d
diff --git a/desktop/electron/importAssets.ts b/desktop/electron/importAssets.tsnew file mode 100644index 000000000..e351b7fb8--- /dev/null+++ b/desktop/electron/importAssets.ts@@ -0,0 +1,86 @@+/**+ * @file Asset import (Content Browser C4). Copies external files into the open+ * project and writes a `.meta` sidecar (fresh uuid + type + importer+ * defaults) so the AssetDatabase scan indexes them immediately — the scan+ * only sees files that HAVE a `.meta`.+ *+ * The ext→type table + importer defaults mirror the canonical CLI+ * `tools/asset-meta.js`; kept in sync by hand (a stable lookup table, and+ * keeping this desktop-contained avoids reaching into the root tools/).+ */+import { copyFile, mkdir, writeFile } from 'node:fs/promises';+import { existsSync } from 'node:fs';+import { randomUUID } from 'node:crypto';+import path from 'node:path';+import { resolveInRoot, META_EXT } from './projectFs';++const META_VERSION = '2.0';++const EXT_TO_TYPE: Record<string, string> = {+ '.png': 'texture', '.jpg': 'texture', '.jpeg': 'texture', '.webp': 'texture', '.bmp': 'texture',+ '.wav': 'audio', '.mp3': 'audio', '.ogg': 'audio', '.aac': 'audio', '.flac': 'audio', '.m4a': 'audio', '.webm': 'audio',+ '.esprefab': 'prefab', '.esscene': 'scene', '.esshader': 'shader', '.esmaterial': 'material', '.esmat': 'material',+ '.estl': 'timeline', '.esanim': 'animation', '.esanimclip': 'animation',+ '.fnt': 'bitmapFont', '.bmfont': 'bitmapFont', '.ttf': 'font', '.otf': 'font', '.woff': 'font', '.woff2': 'font',+ '.tmx': 'tilemap', '.tmj': 'tilemap',+ '.skel': 'spine', '.atlas': 'spine',+};++/** The supported import extensions (no leading dot) — used by the file dialog filter. */+export const IMPORT_EXTENSIONS = Object.keys(EXT_TO_TYPE).map((e) => e.slice(1));++function importerDefaults(type: string): Record<string, unknown> {+ switch (type) {+ case 'texture':+ return { maxSize: 2048, filterMode: 'linear', wrapMode: 'repeat', premultiplyAlpha: false, sliceBorder: { left: 0, right: 0, top: 0, bottom: 0 } };+ case 'prefab':+ case 'scene':+ return { autoMigrate: true };+ case 'spine':+ return { defaultSkin: 'default', premultiplyAlpha: false, scale: 1 };+ default:+ return {};+ }+}++/** A unique destination name in `absDir`: "hero.png" → "hero 2.png" if taken. */+function uniqueName(absDir: string, name: string): string {+ const ext = path.extname(name);+ const stem = name.slice(0, name.length - ext.length);+ let candidate = name;+ for (let i = 2; existsSync(path.join(absDir, candidate)); i++) candidate = `${stem} ${i}${ext}`;+ return candidate;+}++export interface ImportResult {+ /** New project-relative paths of the imported files. */+ imported: string[];+ /** Base names skipped (unknown / unsupported extension). */+ skipped: string[];+}++/**+ * Copy `sources` (absolute, user-picked) into project-relative `destDir`, writing+ * a `.meta` (fresh uuid + extension-derived type) for each. Existing names are+ * deduped, never clobbered; unknown extensions are skipped.+ */+export async function importAssets(root: string, destDir: string, sources: string[]): Promise<ImportResult> {+ const absDir = resolveInRoot(root, destDir);+ await mkdir(absDir, { recursive: true });+ const imported: string[] = [];+ const skipped: string[] = [];+ for (const src of sources) {+ const type = EXT_TO_TYPE[path.extname(src).toLowerCase()];+ if (!type) {+ skipped.push(path.basename(src));+ continue;+ }+ const name = uniqueName(absDir, path.basename(src));+ const absDest = path.join(absDir, name);+ await copyFile(src, absDest);+ const meta = { uuid: randomUUID(), version: META_VERSION, type, importer: importerDefaults(type) };+ await writeFile(absDest + META_EXT, JSON.stringify(meta, null, 2) + '\n', 'utf8');+ imported.push(destDir ? `${destDir}/${name}` : name);+ }+ return { imported, skipped };+}diff --git a/desktop/electron/main.ts b/desktop/electron/main.tsindex 4387a718c..3bd607941 100644--- a/desktop/electron/main.ts+++ b/desktop/electron/main.ts@@ -23,6 +23,7 @@ import { extractProjectSchemas } from './extractSchemas';import { scanAssetDatabase } from './assetDb';import { cookAssets } from './cookAssets';import { startProjectWatch, stopProjectWatch } from './projectWatcher';+import { importAssets, IMPORT_EXTENSIONS } from './importAssets';import { resolveScripts } from '../src/project/format';import type { WorkspaceState } from '../src/project/format';@@ -144,6 +145,21 @@ ipcMain.handle('project:open', async (_e, root: string) => {return opened;});+// Import: OS file picker → copy the chosen files into `destDir` + write `.meta`.+ipcMain.handle('project:importAssets', async (_e, destDir: string) => {+ if (!win) return null;+ const res = await dialog.showOpenDialog(win, {+ title: 'Import Assets',+ properties: ['openFile', 'multiSelections'],+ filters: [+ { name: 'Assets', extensions: IMPORT_EXTENSIONS },+ { name: 'All Files', extensions: ['*'] },+ ],+ });+ if (res.canceled || res.filePaths.length === 0) return null;+ return importAssets(requireRoot(), destDir, res.filePaths);+});+ipcMain.handle('fs:read', (_e, relPath: string) => readInRoot(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 70dcdbe34..54aa6f64c 100644--- a/desktop/electron/preload.ts+++ b/desktop/electron/preload.ts@@ -36,6 +36,10 @@ const api = {scanAssets: (): Promise<ScanAssetsResult> => ipcRenderer.invoke('project:scanAssets'),/** Cook reachable assets for shipping → staged files + runtime manifest in `outDir`. */cookAssets: (outDir?: string): Promise<CookResult> => ipcRenderer.invoke('project:cookAssets', outDir),+ /** Show a file picker and import the chosen files into `destDir` (writes .meta);+ * null if cancelled. */+ importAssets: (destDir: string): Promise<{ imported: string[]; skipped: string[] } | null> =>+ ipcRenderer.invoke('project:importAssets', destDir),},// New-project templates (launcher New tab).templates: {diff --git a/desktop/src/panels/ContentBrowser.tsx b/desktop/src/panels/ContentBrowser.tsxindex 13ef8b8ce..983e9688e 100644--- a/desktop/src/panels/ContentBrowser.tsx+++ b/desktop/src/panels/ContentBrowser.tsx@@ -376,6 +376,23 @@ export function ContentBrowser() {}};+ const importAssets = async () => {+ try {+ const res = await window.estella.project.importAssets(cwd);+ if (!res) return; // cancelled+ refreshFs();+ if (res.imported.length) {+ selectAsset(res.imported[res.imported.length - 1]);+ Toasts.push(`Imported ${res.imported.length} asset${res.imported.length > 1 ? 's' : ''}`, 'success');+ }+ if (res.skipped.length) {+ Toasts.push(`Skipped ${res.skipped.length} unsupported file${res.skipped.length > 1 ? 's' : ''}`, 'warn');+ }+ } catch (e) {+ Toasts.push(`Import failed: ${errMsg(e)}`, 'error');+ }+ };+// Breadcrumb segments: Project › folder › subfolder, each a jump target.const crumbs = useMemo(() => {const out = [{ name: project?.name ?? 'Project', path: '' }];@@ -420,6 +437,7 @@ export function ContentBrowser() {if (!ctx.target) {// Empty-space menu (acts on the current folder).return [+ { label: 'Import…', icon: <Import size={14} />, onClick: () => void importAssets() },{ label: 'New Folder', icon: <FolderPlus size={14} />, onClick: () => void newFolder() },{ sep: true },{ label: 'Show in Explorer', onClick: () => void showInExplorer(cwd) },@@ -515,7 +533,7 @@ export function ContentBrowser() {<button type="button" className="cb-ghost" title="New Folder" onClick={() => void newFolder()}><FolderPlus size={13} strokeWidth={1.9} /></button>- <button type="button" className="cb-add" disabled title="Import (coming soon)">+ <button type="button" className="cb-add" title="Import assets" onClick={() => void importAssets()}><Import size={13} strokeWidth={1.9} /> Import</button></div>diff --git a/desktop/tests/project-fs.test.ts b/desktop/tests/project-fs.test.tsindex 8a49bad70..524536ead 100644--- a/desktop/tests/project-fs.test.ts+++ b/desktop/tests/project-fs.test.ts@@ -16,6 +16,7 @@ import {statInRoot,} from '../electron/projectFs';import { isIgnoredPath } from '../electron/projectWatcher';+import { importAssets } from '../electron/importAssets';let root: string;const read = (rel: string) => readFileSync(path.join(root, rel), 'utf8');@@ -31,6 +32,37 @@ beforeEach(() => {afterEach(() => rmSync(root, { recursive: true, force: true }));+describe('importAssets', () => {+ let ext: string;+ beforeEach(() => {+ // An external source dir (outside the project root) to import from.+ ext = mkdtempSync(path.join(tmpdir(), 'estella-ext-'));+ writeFileSync(path.join(ext, 'logo.png'), 'PNGDATA');+ writeFileSync(path.join(ext, 'notes.xyz'), 'unknown');+ });+ afterEach(() => rmSync(ext, { recursive: true, force: true }));++ it('copies a file + writes a .meta with a uuid and extension-derived type', async () => {+ const res = await importAssets(root, 'assets', [path.join(ext, 'logo.png')]);+ expect(res.imported).toEqual(['assets/logo.png']);+ expect(read('assets/logo.png')).toBe('PNGDATA');+ const meta = JSON.parse(read('assets/logo.png.meta'));+ expect(meta.type).toBe('texture');+ expect(meta.uuid).toMatch(/^[0-9a-f-]{36}$/);+ expect(meta.importer.maxSize).toBe(2048);+ });++ it('skips unknown extensions and dedupes existing names', async () => {+ const res = await importAssets(root, 'assets', [+ path.join(ext, 'notes.xyz'),+ path.join(ext, 'logo.png'),+ path.join(ext, 'logo.png'),+ ]);+ expect(res.skipped).toEqual(['notes.xyz']);+ expect(res.imported).toEqual(['assets/logo.png', 'assets/logo 2.png']);+ });+});+describe('isIgnoredPath (watcher noise filter)', () => {it('ignores the editor cache + heavy dirs (no refresh loop)', () => {// `.esengine` is where we write assets.json — refreshing on it would loop.