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(editor): project prefab assets appear in the Create popover (E4b)

esengine5a1eda886051
diff --git a/desktop/src/components/CreatePopover.tsx b/desktop/src/components/CreatePopover.tsx
index de58daa21..e2a2eb64a 100644
--- a/desktop/src/components/CreatePopover.tsx
+++ b/desktop/src/components/CreatePopover.tsx
@@ -13,6 +13,7 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { ENTITY_SOURCES, userComponentSources, matchSources, type EntitySource } from '@/engine/entitySources';
+import { ProjectStore } from '@/project/ProjectStore';
import { SearchField } from '@/components/SearchField';
import { useDialogFocus } from '@/components/dialogFocus';
@@ -44,8 +45,9 @@ export function CreatePopover({
const shellRef = useRef<HTMLDivElement>(null);
useDialogFocus(shellRef);
- // Static builtins + the user's own components; computed once when the popover opens.
- const all = useMemo(() => [...ENTITY_SOURCES, ...userComponentSources()], []);
+ // Static builtins + the user's own components + the project's prefab assets;
+ // computed once when the popover opens.
+ const all = useMemo(() => [...ENTITY_SOURCES, ...userComponentSources(), ...ProjectStore.prefabSources()], []);
const results = useMemo(() => matchSources(all, query), [all, query]);
const groups = useMemo(() => groupByCategory(results), [results]);
diff --git a/desktop/src/engine/entitySources.ts b/desktop/src/engine/entitySources.ts
index 0bab1f23b..a60059c7d 100644
--- a/desktop/src/engine/entitySources.ts
+++ b/desktop/src/engine/entitySources.ts
@@ -155,7 +155,12 @@ function resolvePlacement(rule: PlacementRule | undefined, ctx: CreateContext):
* new root's source id; the caller handles selection.
*/
export async function createFromSource(source: EntitySource, ctx: CreateContext): Promise<EntityId | null> {
- const prefab = await source.build(ctx);
+ let prefab: PrefabData;
+ try {
+ prefab = await source.build(ctx);
+ } catch {
+ return null; // build aborted (e.g. a prefab asset failed to load; it surfaced its own error)
+ }
const id = SceneCommands.create(prefab, {
parent: resolvePlacement(source.placement, ctx),
position: ctx.position,
diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.ts
index 1f678c515..fd5404199 100644
--- a/desktop/src/project/ProjectStore.ts
+++ b/desktop/src/project/ProjectStore.ts
@@ -11,7 +11,8 @@ import { blankInputMap } from './inputMapDoc';
import { EditorHistory } from '@/engine/EditorHistory';
import { expandScenePrefabs, collapseScenePrefabs } from '@/engine/PrefabInstance';
import { SceneCommands } from '@/engine/SceneCommands';
-import { spritePrefab } from '@/engine/entitySources';
+import { Boxes } from 'lucide-react';
+import { spritePrefab, type EntitySource } from '@/engine/entitySources';
import { setPrefabBaseResolver } from '@/engine/SceneQuery';
import { setUserSchemas, userSchema, setBitmaskSource, setEnumSource, type UserComponentSchema } from '@/engine/schema';
import { installSpineSync, type SpineTransport } from '@/engine/spineSync';
@@ -540,6 +541,39 @@ class ProjectStoreImpl {
return rootId;
}
+ /**
+ * Create-entity sources for the project's `.esprefab` assets — each instantiates
+ * its prefab linked to the asset (so save collapses the instance to a delta). Feeds
+ * the Create popover's 'Prefabs' category (REARCH ENTITY_CREATION E4b). `build`
+ * loads the same PrefabData as the drag-into-scene path; on load failure it toasts +
+ * throws so createFromSource creates nothing.
+ */
+ prefabSources(): EntitySource[] {
+ const out: EntitySource[] = [];
+ for (const [path, uuid] of this.pathToUuid) {
+ if (!path.toLowerCase().endsWith('.esprefab')) continue;
+ const ref = UUID_PREFIX + uuid;
+ const name = (path.split('/').pop() ?? 'Prefab').replace(/\.esprefab$/i, '');
+ out.push({
+ id: `prefab:${path}`,
+ label: name,
+ category: 'Prefabs',
+ icon: Boxes,
+ keywords: [name],
+ build: async () => {
+ const p = await this.loadPrefabAsset(ref);
+ if (!p) {
+ Toasts.push(`Could not load prefab: ${name}`, 'error');
+ throw new Error('prefab load failed');
+ }
+ return p;
+ },
+ linkPrefabRef: () => ref,
+ });
+ }
+ return out;
+ }
+
/**
* Revert a prefab instance to the prefab (Details "Revert"): re-sync the whole
* instance to the asset, discarding all overrides, keeping its placement. Works on
diff --git a/desktop/tests/entity-sources.test.ts b/desktop/tests/entity-sources.test.ts
index f72fe9ace..47abf79cf 100644
--- a/desktop/tests/entity-sources.test.ts
+++ b/desktop/tests/entity-sources.test.ts
@@ -8,7 +8,7 @@
* (not hardcoded), and search matches label/category/keyword. Pure TS.
*/
import { describe, it, expect } from 'vitest';
-import { ENTITY_SOURCES, matchSources, CREATE_CATEGORY_ORDER, tilemapPrefab } from '@/engine/entitySources';
+import { ENTITY_SOURCES, matchSources, CREATE_CATEGORY_ORDER, tilemapPrefab, createFromSource } from '@/engine/entitySources';
const ctx = { parent: null };
@@ -59,4 +59,9 @@ describe('entitySources registry (Create-entity E2)', () => {
const layer = root.components.find((c) => c.type === 'TilemapLayer')!.data as { cellSize: { x: number; y: number } };
expect(layer.cellSize).toMatchObject({ x: 32, y: 16 });
});
+
+ it('createFromSource returns null when build throws (aborted source, e.g. a failed prefab load)', async () => {
+ const bad = { ...ENTITY_SOURCES[0], id: 'bad', build: () => { throw new Error('nope'); } };
+ expect(await createFromSource(bad, { parent: null })).toBeNull();
+ });
});