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): component add/remove + entity visibility toggle (deferred follow-up)
esengine65104827441e
diff --git a/desktop/src/engine/SceneCommands.ts b/desktop/src/engine/SceneCommands.tsindex 07261db63..d28e71fb5 100644--- a/desktop/src/engine/SceneCommands.ts+++ b/desktop/src/engine/SceneCommands.ts@@ -5,7 +5,7 @@ import { EditorHistory } from './EditorHistory';import { EntityHandles } from './EntityHandles';import { SceneModel } from './SceneModel';import { SceneQuery } from './SceneQuery';-import { componentByName, angleZToQuat, hexToRgb, prettyLabel, type WorldT } from './schema';+import { componentByName, inspectableComponents, angleZToQuat, hexToRgb, prettyLabel, type WorldT } from './schema';// — Entity snapshot capture/restore for undoable create/delete —// Parent/Children carry entity-id references that go stale on re-create, so@@ -377,6 +377,68 @@ export const SceneCommands = {apply(parent);EditorHistory.record('Reparent', () => apply(parent), () => apply(before));},++ /** Add a component (with its registered defaults) to an entity. Undoable. */+ addComponent(id: EntityId, compName: string): void {+ const world = EngineHost.mutableWorld();+ if (!world || !world.valid(id)) return;+ const def = componentByName(compName);+ if (!def || world.has(id, def)) return;+ const data = structuredClone((def as unknown as { _default: unknown })._default);+ const apply = () => {+ if (world.valid(id) && !world.has(id, def)) {+ world.insert(id, def, data as never);+ SceneModel.setComponent(id, compName, data);+ }+ };+ const undo = () => {+ if (world.valid(id) && world.has(id, def)) {+ world.remove(id, def);+ SceneModel.removeComponent(id, compName);+ }+ };+ apply();+ EditorHistory.record(`Add ${prettyLabel(compName)}`, apply, undo);+ },++ /** Remove a component from an entity (Transform / Name are protected). Undoable. */+ removeComponent(id: EntityId, compName: string): void {+ const world = EngineHost.mutableWorld();+ if (!world || !world.valid(id) || compName === 'Transform' || compName === 'Name') return;+ const def = componentByName(compName);+ if (!def || !world.has(id, def)) return;+ const data = structuredClone(world.get(id, def));+ const remove = () => {+ if (world.valid(id) && world.has(id, def)) {+ world.remove(id, def);+ SceneModel.removeComponent(id, compName);+ }+ };+ const restore = () => {+ if (world.valid(id) && !world.has(id, def)) {+ world.insert(id, def, data as never);+ SceneModel.setComponent(id, compName, data);+ }+ };+ remove();+ EditorHistory.record(`Remove ${prettyLabel(compName)}`, remove, restore);+ },++ /**+ * Toggle an entity's editor visibility by flipping the `enabled` field of each+ * of its components that has one (coalesced into one undo step). Lossless ++ * persisted; SceneQuery.readSceneTree reflects it as the row's visibility.+ */+ setEntityVisible(id: EntityId, visible: boolean): void {+ const world = EngineHost.mutableWorld();+ if (!world || !world.valid(id)) return;+ this.beginGesture(visible ? 'Show' : 'Hide');+ for (const { name, def } of inspectableComponents(world, id)) {+ const data = world.get(id, def) as unknown as Record<string, unknown>;+ if ('enabled' in data) this.setField(id, name, 'enabled', 'bool', visible);+ }+ this.endGesture();+ },};// Despawn the entity a handle currently points at (no-op if already deleted).diff --git a/desktop/src/engine/SceneModel.ts b/desktop/src/engine/SceneModel.tsindex bc17bba1e..6f1f8a744 100644--- a/desktop/src/engine/SceneModel.ts+++ b/desktop/src/engine/SceneModel.ts@@ -132,6 +132,21 @@ class SceneModelImpl {}}+ /** Remove a component from a runtime entity's source record. */+ removeComponent(runtime: EntityId, compType: string): void {+ const e = this.sourceEntity(runtime);+ if (e) e.components = e.components.filter((c) => c.type !== compType);+ }++ /** Add or replace a whole component's data on a runtime entity's source record. */+ setComponent(runtime: EntityId, compType: string, data: unknown): void {+ const e = this.sourceEntity(runtime);+ if (!e) return;+ const existing = e.components.find((c) => c.type === compType);+ if (existing) existing.data = data as Record<string, unknown>;+ else e.components.push({ type: compType, data: data as Record<string, unknown> } as SceneComponent);+ }+/** The current scene truth, or null if none loaded. */get current(): SceneData | null {return this.data;diff --git a/desktop/src/engine/SceneQuery.ts b/desktop/src/engine/SceneQuery.tsindex 0e0573493..bca6dc87e 100644--- a/desktop/src/engine/SceneQuery.ts+++ b/desktop/src/engine/SceneQuery.ts@@ -8,8 +8,19 @@ import {kindOf,nameOf,componentByName,+ type ReadonlyWorldT,} from './schema';+// An entity reads as hidden if any of its components is explicitly disabled+// (`enabled: false`) — the editor's visibility toggle flips those.+function isVisible(world: ReadonlyWorldT, id: EntityId): boolean {+ for (const { def } of inspectableComponents(world, id)) {+ const data = world.get(id, def) as unknown as Record<string, unknown>;+ if ('enabled' in data && data.enabled === false) return false;+ }+ return true;+}+// Read-only reflection of the live engine World into editor view-models.export const SceneQuery = {/** Monotonic counter; bump means the entity set / structure changed. */@@ -49,7 +60,7 @@ export const SceneQuery = {id: e,name: nameOf(world, e, kind),kind,- visible: true,+ visible: isVisible(world, e),locked: false,children: kids?.map(build),};diff --git a/desktop/src/engine/schema.ts b/desktop/src/engine/schema.tsindex 805f7ab0e..f5a3bb4f6 100644--- a/desktop/src/engine/schema.ts+++ b/desktop/src/engine/schema.ts@@ -75,6 +75,21 @@ export function inspectableComponents(return out;}+/** Registered components NOT yet on an entity — the "Add Component" candidates. */+export function addableComponents(+ world: ReadonlyWorldT,+ entity: EntityId,+): Array<{ name: string; def: AnyComp; label: string }> {+ const out: Array<{ name: string; def: AnyComp; label: string }> = [];+ for (const [name, rawDef] of getAllRegisteredComponents()) {+ if (HIDDEN_COMPONENTS.has(name) || name === 'Transform') continue;+ const def = rawDef as unknown as AnyComp;+ if (world.has(entity, def)) continue;+ out.push({ name, def, label: prettyLabel(name) });+ }+ return out.sort((a, b) => a.label.localeCompare(b.label));+}+/** The editable fields of one component (its live data introspected by shape). */export function componentFields(def: AnyComp, data: Record<string, unknown>): InspectorField[] {const colorKeys = new Set<string>(def.colorKeys);diff --git a/desktop/src/panels/Details.tsx b/desktop/src/panels/Details.tsxindex 92a5bb203..063c56b51 100644--- a/desktop/src/panels/Details.tsx+++ b/desktop/src/panels/Details.tsx@@ -5,6 +5,8 @@ import { EngineHost } from '@/engine/EngineHost';import { SceneStore } from '@/engine/SceneStore';import { SceneQuery } from '@/engine/SceneQuery';import { SceneCommands } from '@/engine/SceneCommands';+import { addableComponents } from '@/engine/schema';+import { ContextMenu, type MenuItem } from '@/components/Menu';import type { InspectorComponent, InspectorField, EntityId } from '@/types';const AXES = ['x', 'y', 'z'];@@ -248,11 +250,13 @@ function ComponentSection({comp,collapsed,onToggle,+ onMore,}: {entity: EntityId;comp: InspectorComponent;collapsed: boolean;onToggle: () => void;+ onMore: (e: React.MouseEvent, name: string) => void;}) {return (<section className="cblock">@@ -267,7 +271,10 @@ function ComponentSection({type="button"className="cblock__more"title="Component options"- onClick={(e) => e.stopPropagation()}+ onClick={(e) => {+ e.stopPropagation();+ onMore(e, comp.name);+ }}><MoreHorizontal size={15} strokeWidth={2} /></button>@@ -291,6 +298,8 @@ export function Details() {const [query, setQuery] = useState('');const [collapsed, setCollapsed] = useState<Set<string>>(new Set());+ const [compMenu, setCompMenu] = useState<{ x: number; y: number; comp: string } | null>(null);+ const [addMenu, setAddMenu] = useState<{ x: number; y: number } | null>(null);const toggle = (name: string) =>setCollapsed((prev) => {const next = new Set(prev);@@ -335,6 +344,17 @@ export function Details() {);}+ const world = EngineHost.world;+ const addItems: MenuItem[] =+ addMenu && world+ ? (() => {+ const list = addableComponents(world, selectedId);+ return list.length+ ? list.map((c) => ({ label: c.label, onClick: () => SceneCommands.addComponent(selectedId, c.name) }))+ : [{ label: 'All components added', onClick: () => {}, disabled: true }];+ })()+ : [];+return (<div className="panel"><div className="inspector-head">@@ -367,16 +387,36 @@ export function Details() {comp={comp}collapsed={collapsed.has(comp.name)}onToggle={() => toggle(comp.name)}+ onMore={(e, name) => setCompMenu({ x: e.clientX, y: e.clientY, comp: name })}/>))}{query && visible.length === 0 && (<p className="inspector-note">No components match “{query}”.</p>)}- <button type="button" className="add-component">+ <button+ type="button"+ className="add-component"+ onClick={(e) => {+ const r = e.currentTarget.getBoundingClientRect();+ setAddMenu({ x: r.left, y: r.bottom + 2 });+ }}+ ><Plus size={15} strokeWidth={2} /> Add Component</button></div>++ {compMenu && (+ <ContextMenu+ x={compMenu.x}+ y={compMenu.y}+ items={[+ { label: 'Remove Component', onClick: () => SceneCommands.removeComponent(selectedId, compMenu.comp) },+ ]}+ onClose={() => setCompMenu(null)}+ />+ )}+ {addMenu && <ContextMenu x={addMenu.x} y={addMenu.y} items={addItems} onClose={() => setAddMenu(null)} />}</div>);}diff --git a/desktop/src/panels/Outliner.tsx b/desktop/src/panels/Outliner.tsxindex 6ed8c48b3..834312df9 100644--- a/desktop/src/panels/Outliner.tsx+++ b/desktop/src/panels/Outliner.tsx@@ -93,7 +93,15 @@ function Row(props: RowProps) {<span className="tree-row__actions">{node.locked && <Lock size={12} strokeWidth={1.85} className="tree-row__lock" />}- <button type="button" className="tree-row__vis" title="Toggle visibility">+ <button+ type="button"+ className="tree-row__vis"+ title="Toggle visibility"+ onClick={(e) => {+ e.stopPropagation();+ SceneCommands.setEntityVisible(node.id, !node.visible);+ }}+ >{node.visible ? <Eye size={13} strokeWidth={1.85} /> : <EyeOff size={13} strokeWidth={1.85} />}</button></span>diff --git a/desktop/src/theme/app.css b/desktop/src/theme/app.cssindex dab50d1b8..d82a9a625 100644--- a/desktop/src/theme/app.css+++ b/desktop/src/theme/app.css@@ -77,6 +77,8 @@border: 1px solid var(--line-strong);border-radius: var(--r-sm);box-shadow: var(--shadow-pop);+ max-height: 60vh;+ overflow-y: auto;-webkit-app-region: no-drag;}/* Right-click context menu — portaled to body, positioned at the cursor. */diff --git a/desktop/tests/engine-commands.test.ts b/desktop/tests/engine-commands.test.tsindex 83503e843..d0f822d1b 100644--- a/desktop/tests/engine-commands.test.ts+++ b/desktop/tests/engine-commands.test.ts@@ -9,7 +9,7 @@* editor logic (EditorHistory, EntityHandles, schema) runs for real.*/import { describe, it, expect, beforeAll, beforeEach, vi } from 'vitest';-import { App, Transform, Parent } from 'esengine';+import { App, Transform, Parent, Sprite } from 'esengine';import type { ESEngineModule } from 'esengine';import { loadWasmModule, HAS_WASM } from './helpers/loadWasm';@@ -130,4 +130,28 @@ describe.skipIf(!HAS_WASM)('SceneCommands / SceneQuery (headless World)', () =>expect(host.world.has(a, Parent)).toBe(false);expect((host.world.get(b, Parent) as { entity: number }).entity).toBe(a);});++ it('addComponent inserts a component (with defaults); undo/redo round-trips', () => {+ const id = SceneCommands.addEntity()!;+ expect(host.world.has(id, Sprite)).toBe(false);+ SceneCommands.addComponent(id, 'Sprite');+ expect(host.world.has(id, Sprite)).toBe(true);++ EditorHistory.undo();+ expect(host.world.has(id, Sprite)).toBe(false);+ EditorHistory.redo();+ expect(host.world.has(id, Sprite)).toBe(true);+ });++ it('removeComponent removes a component; undo restores it; Transform is protected', () => {+ const id = SceneCommands.addEntity()!;+ SceneCommands.addComponent(id, 'Sprite');+ SceneCommands.removeComponent(id, 'Sprite');+ expect(host.world.has(id, Sprite)).toBe(false);+ EditorHistory.undo();+ expect(host.world.has(id, Sprite)).toBe(true);++ SceneCommands.removeComponent(id, 'Transform');+ expect(host.world.has(id, Transform)).toBe(true);+ });});