Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(agent): create_asset without content is the New… menu, one type at a time

yhhbdbb35a19066
diff --git a/desktop/shared/toolCatalog.mjs b/desktop/shared/toolCatalog.mjs
index aed63d361..500aa3717 100644
--- a/desktop/shared/toolCatalog.mjs
+++ b/desktop/shared/toolCatalog.mjs
@@ -383,13 +383,23 @@ const ATOMS = [
{ name: 'create_asset', effect: 'journaled',
description: 'Create a text asset file under a project-relative directory with the given content. `type` is the meta vocabulary: scene, prefab, shader (.esshader), material (.esmaterial), materialgraph (.esmatgraph), animclip (.esanim), animation (.estimeline), tileset, statemachine (.esfsm), behaviortree (.esbt), locale, inputmap, tilemap (.tmj). A bare baseName gets the type\'s canonical extension appended. Returns the project-relative path, immediately referenceable (the registry refresh happens before this resolves). '
+ 'A material graph is the ONE type whose file is not the whole asset: it compiles to a sibling `.esshader`, which is written by save_asset_document — so create it, open_asset it, and save it, rather than leaving a graph with no shader beside it. '
- + "A material's `shader` field names one from list_shader_templates — `builtin:<id>` for a stock template, which needs no shader file of its own; check that list before writing a shader by hand.",
+ + "A material's `shader` field names one from list_shader_templates — `builtin:<id>` for a stock template, which needs no shader file of its own; check that list before writing a shader by hand. "
+ + 'LEAVE `content` OUT to get the document the editor own "New …" menu would have written — a blank scene with its camera, an empty state machine, a material bound to `template` (a shader template id, default sprite-unlit). That is the way to create one of these without reconstructing its file format; supply `content` only for a type that has no blank of its own, or when you already know exactly what the file should say.',
schema: obj({
destDir: { type: 'string' }, baseName: { type: 'string' },
- content: { type: 'string' }, type: { type: 'string' },
- }, ['destDir', 'baseName', 'content', 'type']),
- js: (i) => `window.estella.project.createAsset(${JSON.stringify(i.destDir)}, ${JSON.stringify(i.baseName)}, ${JSON.stringify(i.content)}, ${JSON.stringify(i.type)})
- .then((p) => window.__estellaEditor.refreshAssets().then(() => p))` },
+ content: { type: 'string' }, type: { type: 'string' }, template: { type: 'string' },
+ }, ['destDir', 'baseName', 'type']),
+ // Content omitted means "the one the New… menu would have written". The
+ // editor answers with it rather than the caller reconstructing a format.
+ js: (i) => `(async () => {
+ const content = ${i.content === undefined
+ ? `await window.__estellaEditor.newAssetDocument(${JSON.stringify(i.type)}, ${JSON.stringify({ name: i.baseName, template: i.template })})`
+ : JSON.stringify(i.content)};
+ if (content === null) throw new Error('type "${i.type}" has no blank of its own — supply the content yourself');
+ const path = await window.estella.project.createAsset(${JSON.stringify(i.destDir)}, ${JSON.stringify(i.baseName)}, content, ${JSON.stringify(i.type)});
+ await window.__estellaEditor.refreshAssets();
+ return path;
+ })()` },
{ name: 'delete_asset', effect: 'journaled',
description: 'Delete a project file (or folder) to the OS trash — its `.meta` goes with it and the registry is re-scanned, so nothing is left half-removed. '
+ 'This is how you take back an asset you created by mistake: the editor command behind the Content Browser\'s Delete acts on whatever is SELECTED there, which a driver cannot see. '
diff --git a/desktop/src/main.tsx b/desktop/src/main.tsx
index 044be388a..3fdc2b0cb 100644
--- a/desktop/src/main.tsx
+++ b/desktop/src/main.tsx
@@ -44,6 +44,7 @@ import { App } from './App';
import { ProjectStore } from './project/ProjectStore';
import { AssetRegistry } from './project/AssetRegistry';
import { builtinShaderCatalog, projectShaderEntry } from './material/shaderCatalog';
+import { newAssetDocument } from './project/newAssetDocument';
import { useEditorStore } from './store/editorStore';
import { useSelection } from './store/selectionStore';
import { PlayRealm } from './engine/PlayRealm';
@@ -423,6 +424,10 @@ function buildEditorAutomation(): unknown {
* including the open project's own components and prefabs, so automation sees
* the same list a person does. */
listEntityTemplates: () => allEntitySources().map(({ id, label, category }) => ({ id, label, category })),
+ /** The document a new asset of this type starts as — the one the "New …"
+ * menu writes. Null for a type that has no blank of its own. */
+ newAssetDocument: (type: string, opts?: { name?: string; template?: string }) =>
+ newAssetDocument(type, opts),
/** The material picker's catalog: every shader a material can name, and the
* parameters each takes. The stock ones exist only as runtime values and
* shader source, so nothing about them is in a project's staged types. */
diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.ts
index e1078133f..6ca6e3c6a 100644
--- a/desktop/src/project/ProjectStore.ts
+++ b/desktop/src/project/ProjectStore.ts
@@ -19,6 +19,7 @@ import { SceneModel } from '@/engine/SceneModel';
import { Reconciler } from '@/engine/Reconciler';
import { ViewportController } from '@/engine/ViewportController';
import { blankInputMap } from './inputMapDoc';
+import { blankPrefab, blankScene } from './newAssetDocument';
import { EditorHistory } from '@/engine/EditorHistory';
import { expandScenePrefabs, collapseScenePrefabs } from '@/engine/PrefabInstance';
import { discoverSceneAssets } from 'esengine';
@@ -593,23 +594,7 @@ class ProjectStoreImpl {
/** A fresh, untitled scene document: a single orthographic Camera at the origin. */
private blankScene(): SceneData {
- return {
- version: '1.0',
- name: 'Untitled',
- entities: [
- {
- id: 0,
- name: 'Camera',
- parent: null,
- children: [],
- components: [
- { type: 'Transform', data: { position: { x: 0, y: 0, z: 10 } } },
- { type: 'Camera', data: { projectionType: 1, orthoSize: 300, isActive: true, priority: 0 } },
- ],
- visible: true,
- },
- ],
- } as unknown as SceneData;
+ return blankScene();
}
/**
@@ -691,12 +676,8 @@ class ProjectStoreImpl {
* Goes through `extractPrefab` to mint entity ids — a source's in-memory prefab
* carries `prefabEntityId: '0'`, which the runtime spawn door now refuses.
*/
- private async blankPrefab(name: string): Promise<PrefabData> {
- const built = await sourceById('empty')?.build?.({ parent: null });
- const root = built?.entities[0];
- if (!root) throw new Error('the "Empty" entity source is not registered');
- const entity = { id: 0, name, parent: null, children: [], components: root.components, visible: true };
- return extractPrefab([entity as unknown as ExtractEntity], 0, name);
+ private blankPrefab(name: string): Promise<PrefabData> {
+ return blankPrefab(name);
}
/** Create a blank `.esprefab` under `destDir`; double-click opens it in Prefab Mode. */
diff --git a/desktop/src/project/newAssetDocument.ts b/desktop/src/project/newAssetDocument.ts
new file mode 100644
index 000000000..8e993eb2c
--- /dev/null
+++ b/desktop/src/project/newAssetDocument.ts
@@ -0,0 +1,103 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file newAssetDocument.ts
+ * @brief What a NEW asset of each type is, in one table — the documents the
+ * "New …" menu writes, as data anyone can ask for.
+ *
+ * Each entry references the definition that already existed (the SDK's empty
+ * graph, the shader template's derived defaults) rather than restating a format.
+ * A type with no single blank of its own answers null; a caller then supplies
+ * the content itself, which is honest about there being nothing to hand over.
+ */
+import {
+ builtinShaderTemplate, compileMaterialGraph, emptyAnimatorController, emptyBt, emptyFsm,
+ extractPrefab, newMaterialGraph,
+ type ExtractEntity, type PrefabData, type SceneData,
+} from 'esengine';
+import { blankInputMap } from './inputMapDoc';
+import { newMaterialDocument } from '@/material/shaderCatalog';
+import { sourceById } from '@/engine/entitySources';
+
+/** The scene a new `.esscene` is: one camera, nothing else. */
+export function blankScene(): SceneData {
+ return {
+ version: '1.0',
+ name: 'Untitled',
+ entities: [
+ {
+ id: 0,
+ name: 'Camera',
+ parent: null,
+ children: [],
+ components: [
+ { type: 'Transform', data: { position: { x: 0, y: 0, z: 10 } } },
+ { type: 'Camera', data: { projectionType: 1, orthoSize: 300, isActive: true, priority: 0 } },
+ ],
+ visible: true,
+ },
+ ],
+ } as unknown as SceneData;
+}
+
+/** The prefab a new `.esprefab` is: the Empty entity source, extracted. */
+export async function blankPrefab(name: string): Promise<PrefabData> {
+ const built = await sourceById('empty')?.build?.({ parent: null });
+ const root = built?.entities[0];
+ if (!root) throw new Error('the "Empty" entity source is not registered');
+ const entity = { id: 0, name, parent: null, children: [], components: root.components, visible: true };
+ return extractPrefab([entity as unknown as ExtractEntity], 0, name);
+}
+
+const BLANK_LOCALE = { version: 1, locale: 'en', entries: {} };
+
+/** The clip a new `.estimeline` is: five seconds, looping, no tracks. */
+export const BLANK_CLIP = { version: '1.1', type: 'timeline', duration: 5, wrapMode: 'loop', tracks: [] };
+
+export interface NewDocumentOptions {
+ /** Names the thing inside the document, where the format carries one. */
+ name?: string;
+ /** A shader template id, for the two types that are born bound to one. */
+ template?: string;
+}
+
+const json = (value: unknown): string => `${JSON.stringify(value, null, 2)}\n`;
+
+/**
+ * The text a new asset of `type` starts as, or null when the type has no blank
+ * of its own. `type` is create_asset's vocabulary — the `.meta` type, not the
+ * extension.
+ */
+export async function newAssetDocument(
+ type: string,
+ opts: NewDocumentOptions = {},
+): Promise<string | null> {
+ const template = opts.template ?? 'sprite-unlit';
+ switch (type) {
+ case 'scene': return json(blankScene());
+ case 'prefab': return json(await blankPrefab(opts.name ?? 'Prefab'));
+ case 'material': {
+ const material = newMaterialDocument(template);
+ return material ? json(material) : null;
+ }
+ // Source, not JSON: a shader IS its text, and a stock template is the one
+ // a "Convert to Unique Shader" would have handed over.
+ case 'shader': return builtinShaderTemplate(template)?.source ?? null;
+ case 'materialgraph': {
+ const graph = newMaterialGraph();
+ if (opts.name) graph.name = opts.name;
+ return json(graph);
+ }
+ case 'animation': return json(BLANK_CLIP);
+ case 'statemachine': return json(emptyFsm());
+ case 'behaviortree': return json(emptyBt());
+ case 'animator': return json(emptyAnimatorController());
+ case 'locale': return json(BLANK_LOCALE);
+ case 'inputmap': return json(blankInputMap());
+ default: return null;
+ }
+}
+
+/** The shader a new material graph compiles to, written beside it. */
+export const graphShaderSource = (graphJson: string): string =>
+ compileMaterialGraph(JSON.parse(graphJson));
diff --git a/desktop/src/timeline/openClip.ts b/desktop/src/timeline/openClip.ts
index cfa75eee1..7382871b3 100644
--- a/desktop/src/timeline/openClip.ts
+++ b/desktop/src/timeline/openClip.ts
@@ -11,6 +11,7 @@
*/
import { parseAnimationClip } from 'esengine';
+import { BLANK_CLIP } from '@/project/newAssetDocument';
import { t } from '@/i18n';
import { TimelineDocument } from './TimelineDocument';
import { previewRootFor } from './previewRoot';
@@ -49,10 +50,6 @@ export async function openAnimationClip(path: string): Promise<void> {
}
}
-// A blank multi-track timeline, in the canonical serialized shape parseAnimationClip
-// reads (the Sequencer fills it by recording keys on a selected entity).
-const BLANK_CLIP = { version: '1.1', type: 'timeline', duration: 5, wrapMode: 'loop', tracks: [] };
-
/** Create an empty `.estimeline` timeline in @p dir and open it in the Sequencer. */
export async function createAnimationClip(dir: string): Promise<void> {
const folder = dir ? (dir.endsWith('/') ? dir : `${dir}/`) : '';
diff --git a/desktop/tests/new-asset-document.test.ts b/desktop/tests/new-asset-document.test.ts
new file mode 100644
index 000000000..60a514a82
--- /dev/null
+++ b/desktop/tests/new-asset-document.test.ts
@@ -0,0 +1,61 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file What a new asset of each type starts as.
+ *
+ * One table, and every entry points at the definition that already existed — so
+ * what an agent is handed is what the "New …" menu writes, not a second reading
+ * of the same format. A type with no blank of its own says so, because a made-up
+ * skeleton for one is worse than admitting there is none.
+ */
+import { describe, it, expect } from 'vitest';
+import { newAssetDocument, blankScene, BLANK_CLIP } from '@/project/newAssetDocument';
+
+const parsed = async (type: string, opts?: { name?: string; template?: string }) => {
+ const text = await newAssetDocument(type, opts);
+ expect(text).toBeTruthy();
+ return JSON.parse(text!);
+};
+
+describe('the document a new asset starts as', () => {
+ it('gives a scene its camera', async () => {
+ const scene = await parsed('scene');
+ expect(scene.entities).toHaveLength(1);
+ expect(scene.entities[0].components.map((c: { type: string }) => c.type)).toContain('Camera');
+ expect(blankScene()).toMatchObject({ version: '1.0' });
+ });
+
+ it('binds a material to the template it was asked for', async () => {
+ expect(await parsed('material', { template: 'sprite-outline' }))
+ .toMatchObject({ type: 'material', shader: 'builtin:sprite-outline' });
+ expect(await parsed('material')).toMatchObject({ shader: 'builtin:sprite-unlit' });
+ });
+
+ // A shader IS its text; JSON.parse would be the wrong question to ask of it.
+ it('gives a shader the template source, not a wrapper', async () => {
+ const source = await newAssetDocument('shader', { template: 'sprite-dissolve' });
+ expect(source).toContain('#pragma');
+ });
+
+ it('gives the graph types the empty document the SDK defines', async () => {
+ for (const type of ['statemachine', 'behaviortree', 'animator', 'materialgraph']) {
+ expect(await parsed(type)).toBeTypeOf('object');
+ }
+ });
+
+ it('names what the format carries a name for', async () => {
+ expect(await parsed('materialgraph', { name: 'Water' })).toMatchObject({ name: 'Water' });
+ });
+
+ it('gives the flat types their canonical blank', async () => {
+ expect(await parsed('animation')).toEqual(BLANK_CLIP);
+ expect(await parsed('locale')).toMatchObject({ locale: 'en', entries: {} });
+ expect(await parsed('inputmap')).toMatchObject({ actions: {} });
+ });
+
+ it('says nothing rather than inventing one', async () => {
+ expect(await newAssetDocument('tilemap')).toBeNull();
+ expect(await newAssetDocument('nonsense')).toBeNull();
+ expect(await newAssetDocument('material', { template: 'no-such-template' })).toBeNull();
+ });
+});