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(agent): press the button, do not compute where the button is
esengine30b54531b210
diff --git a/desktop/electron/agent/prompt.ts b/desktop/electron/agent/prompt.tsindex ca7f7d7e7..1cf9b7696 100644--- a/desktop/electron/agent/prompt.ts+++ b/desktop/electron/agent/prompt.ts@@ -35,7 +35,7 @@ Working style:- Look before you edit. get_scene_tree, get_inspector and get_document cost one round trip and are the difference between editing the right entity and editing a plausible one.- You can see the result: capture_viewport renders what the user is looking at, and screenshot takes in the whole window including a running game — as a picture, or, with \`format: 'grid'\`, as a coarse colour grid in TEXT, which is the form to ask for when images cannot reach you. LOOK before you call a visual change done — a material, an effect, a layout, anything whose whole point is what it looks like. Reading back the data you just wrote proves you wrote it, not that it did anything; the difference between "the component says 1.0" and "the sprite is gone" is the entire job.- To read the RUNNING game, ask by name before you write a probe. find_entities says which entities there are and what each carries; inspect_entity gives ONE of them whole — every component with its live data, which is where physics, AI, animation and UI state all are, because they ARE components. list_resources gives the state that belongs to no entity, and get_systems what runs each frame. None of them is confirmed. play_probe is the escape hatch for what they do not answer, and it costs the user a prompt every time.-- A game you have built is not tested until you have PLAYED it: set_play, then step to advance it BY FRAMES — never by waiting. Its loop is throttled to about a frame a second whenever the editor window is not focused, so waiting shows you a frozen picture of a healthy game; \`step\` moves it exactly and deterministically, and three seconds of game time is step 180, not a pause. Set it \`paused\` first when you want to stage a situation and then advance it a frame at a time. play_input presses the keys a player would, find_entities / inspect_entity read what the game now thinks, and screenshot shows what a player would see. Step-look-step is the loop; twenty probes without a screenshot is how a project ships game-over-on-arrival with every component reporting exactly the value it should.+- A game you have built is not tested until you have PLAYED it: set_play, then step to advance it BY FRAMES — never by waiting. Its loop is throttled to about a frame a second whenever the editor window is not focused, so waiting shows you a frozen picture of a healthy game; \`step\` moves it exactly and deterministically, and three seconds of game time is step 180, not a pause. Set it \`paused\` first when you want to stage a situation and then advance it a frame at a time. play_input presses the keys a player would and click_ui presses a BUTTON BY NAME — never compute where a button is and click there, that is the arithmetic that lands beside it and reports success; click_ui puts the point to the engine's own hit test and refuses rather than click the wrong thing. send_gamepad hands the game a controller on a machine with none, and HOLDS it until you release it. find_entities / inspect_entity read what the game now thinks, and screenshot shows what a player would see. Step-look-step is the loop; twenty probes without a screenshot is how a project ships game-over-on-arrival with every component reporting exactly the value it should.- Prefer one apply_scene_ops over many small calls when building something: it is one undo step for the user and one round trip for you, and it is the ONE write the user sees BEFORE it lands — they get a line-by-line preview and can strike parts of it out. A dozen set_field calls give them no such chance, so build with a batch and save the single writes for genuinely single changes.- Units are the editor's: 1 world unit = 1 design pixel. Y is up in the world, and UI is laid out top-down. The world's ORIGIN IS THE CENTRE OF THE VIEW, not a corner: a default camera on a W×H design resolution sees y from −H/2 to +H/2 (its \`orthoSize\` is H/2) and x at least −W/2 to +W/2, wider when the window is. So the bottom of the screen is y = −H/2 and the top is +H/2 — a HUD placed at y = H − 20, or a floor at y = 0, is written in SCREEN coordinates and lands off camera or halfway up. Nothing errors: the entity is there, the fields read back what you wrote, and the picture is empty, which is why the FIRST screenshot of anything you positioned by arithmetic is worth more than the next ten probes.- Game content lives in the WORLD: a board, its pieces, a character are Sprite / ShapeRenderer entities you place with Transform.position. A Canvas and its UINodes are for HUD and menus, and their placement is the layout's OUTPUT — a Transform.position written on a UI node is overwritten at the next relayout, which looks like nothing happened. Move those with layout inputs instead (UINode.position = Absolute, then left/top), or let the flow place them.diff --git a/desktop/electron/surfaceDriver.ts b/desktop/electron/surfaceDriver.tsindex 74b909266..11d4620bb 100644--- a/desktop/electron/surfaceDriver.ts+++ b/desktop/electron/surfaceDriver.ts@@ -334,10 +334,23 @@ export function createSurfaceDriver(key_down: `i.keyDown(${code});`,key_up: `i.keyUp(${code});`,tap: `i.touchStart(${id},${x},${y}); i.touchEnd(${id});`,+ // A pad is HELD until released — a game reads it every frame, so a+ // one-shot press would be gone before the frame that reads it.+ gamepad: `i.gamepad(${Number(input.pad ?? 0)},${JSON.stringify(input.buttons ?? [])},`+ + `${JSON.stringify(input.axes ?? [])});`,+ gamepad_release: `i.releaseGamepad(${input.pad === undefined ? '' : Number(input.pad)});`,}[kind ?? ''];+ // Clicking a NAMED element answers with where it went, so it is not one+ // of the fire-and-forget spellings above.+ if (kind === 'ui') {+ return unwrap(await frame.executeJavaScript(carryError(+ `window.__estellaPlay.clickUi(${JSON.stringify(String(input.target ?? ''))})`,+ )));+ }if (!call) {throw new Error(- `unknown play_input kind "${kind}" — one of click, move, down, up, wheel, key_down, key_up, tap`,+ `unknown play_input kind "${kind}" — one of click, move, down, up, wheel, `+ + 'key_down, key_up, tap, gamepad, gamepad_release, ui',);}return unwrap(await frame.executeJavaScript(carryError(diff --git a/desktop/shared/toolCatalog.mjs b/desktop/shared/toolCatalog.mjsindex 43fc6de6d..63741ee56 100644--- a/desktop/shared/toolCatalog.mjs+++ b/desktop/shared/toolCatalog.mjs@@ -656,6 +656,29 @@ const ATOMS = [schema: obj({ frame: { type: 'number' } }),op: 'play_query',opInput: (i) => ({ kind: 'systems', frame: i.frame }) },+ { name: 'click_ui', effect: 'ephemeral',+ description: 'Click a UI element BY NAME in the running game, or refuse. '+ + 'Computing where a button is and clicking there is the arithmetic that lands beside it and reports success — so the point is put to the ENGINE\'S OWN hit test first, and unless it answers with that element (or a child of it, which is what a label on a button is) nothing is sent and the reply says what is there instead. '+ + 'Answers { entity, name, at, hit }. Two entities of the same name is refused rather than picked between. Use play_input with x/y for anything that is not a UI element.',+ schema: obj({+ target: { type: 'string', description: 'the entity name of the UI element' },+ frame: { type: 'number' },+ }, ['target']),+ op: 'play_input',+ opInput: (i) => ({ kind: 'ui', target: i.target, frame: i.frame }) },+ { name: 'send_gamepad', effect: 'ephemeral',+ description: 'Hand the running game a controller it does not have: `buttons` are analog values 0..1 in W3C standard-gamepad order (0 = A/cross, 1 = B/circle, 12..15 = dpad up/down/left/right), `axes` are signed -1..1 (0,1 = left stick x,y; 2,3 = right). '+ + 'The pad is HELD until you change or release it — a game reads it every frame, so a one-shot press would be gone before the frame that reads it. Send the pressed state, `step`, then send the released state. '+ + '`release: true` gives the index back to real hardware. This is the only way to test a gamepad-only game on a machine with no controller.',+ schema: obj({+ pad: { type: 'number', description: 'controller index (default 0)' },+ buttons: { type: 'array' }, axes: { type: 'array' },+ release: { type: 'boolean' }, frame: { type: 'number' },+ }),+ op: 'play_input',+ opInput: (i) => (i.release+ ? { kind: 'gamepad_release', pad: i.pad, frame: i.frame }+ : { kind: 'gamepad', pad: i.pad ?? 0, buttons: i.buttons ?? [], axes: i.axes ?? [], frame: i.frame }) },{ name: 'play_probe', effect: 'irreversible',description: "Evaluate JS inside the RUNNING play realm and return the result — the gameplay probe. One expression gives its value; several statements need an explicit `return`. "+ 'These are ALREADY IN SCOPE (no prefix, though `window.__estellaPlay` holds them too): 'diff --git a/desktop/src/playHost.ts b/desktop/src/playHost.tsindex 5cb5cb3ad..99dd419a6 100644--- a/desktop/src/playHost.ts+++ b/desktop/src/playHost.ts@@ -14,8 +14,8 @@* Everything is same-origin estella:// (host, sdk, bundle, wasm, assets),* sidestepping the custom-scheme cross-fetch ban.*/-import { createWebApp, setEditorMode, setPlayMode, initPlayRealmRuntime, getComponent, clearUserComponents, getUserComponentFingerprint, probeRegistrations, Net, MessagePortTransport, Assets, Ads, createMockAdProvider, Leaderboard, createLocalLeaderboard, registerPackagedSideModules, Input, inputEventCallbacks, isEntityVisible, setEntityVisible, hasVisibility, takeCensus } from 'esengine';-import type { App, SceneData } from 'esengine';+import { uiPickWorld, uiWorldToScreen, createWebApp, setEditorMode, setPlayMode, initPlayRealmRuntime, getComponent, clearUserComponents, getUserComponentFingerprint, probeRegistrations, Net, MessagePortTransport, Assets, Ads, createMockAdProvider, Leaderboard, createLocalLeaderboard, registerPackagedSideModules, Input, inputEventCallbacks, isEntityVisible, setEntityVisible, hasVisibility, takeCensus } from 'esengine';+import type { App, SceneData, InputState, UICameraData } from 'esengine';import type { ESEngineModule } from 'esengine/wasm';import { PLAY_PROTOCOL_VERSION } from './engine/playProtocol';import type { PlayOutbound, PlayInbound, LiveVisibility } from './engine/playProtocol';@@ -71,6 +71,89 @@ function inspectableTypes(world: App['world'], entity: number): string[] {});}+/** The realm's live InputState, or null before the input plugin is up. */+function inputState(): InputState | null {+ return app ? app.getResource(Input) : null;+}++/**+ * Click the UI element called `name`, CONFIRMING the target first: the engine's+ * own pick is asked what is at the point, and a click is sent only when the+ * answer is that element or a descendant of it (a label on a button is one, and+ * the interaction system bubbles from it anyway).+ */+async function clickUiByName(app_: App, name: string): Promise<unknown> {+ const world = app_.world;+ const nameDef = getComponent('Name');+ const transformDef = getComponent('Transform');+ if (!nameDef || !transformDef) throw new Error('this realm has no Name/Transform components');++ const matches = world.getAllEntities().filter((e) => {+ const n = world.tryGet(e, nameDef) as { value?: string } | null;+ return n?.value === name;+ });+ if (matches.length === 0) {+ throw new Error(`no entity named "${name}" — find_entities lists what there is`);+ }+ if (matches.length > 1) {+ throw new Error(+ `${matches.length} entities are named "${name}" — clicking one of them at random is not a `+ + 'test. Rename them, or click by the id find_entities gave you.',+ );+ }++ const target = matches[0];+ const t = world.tryGet(target, transformDef) as { worldPosition?: { x: number; y: number } } | null;+ const at = t?.worldPosition;+ if (!at) throw new Error(`"${name}" has no Transform, so it has no place to be clicked`);++ const hit = uiPickWorld(world, at.x, at.y);+ if (hit === null) {+ throw new Error(+ `nothing in the UI is at "${name}"'s own position — it is laid out with zero size, hidden, `+ + 'or not a UI element at all. Nothing was clicked.',+ );+ }+ if (!isSelfOrDescendant(world, hit as never as number, target as never as number)) {+ const other = world.tryGet(hit, nameDef) as { value?: string } | null;+ throw new Error(+ `"${name}" is covered: the UI at that point is "${other?.value ?? hit}". Nothing was clicked — `+ + 'move what is on top, or click that instead.',+ );+ }++ const camera = app_.getResourceByName('UICameraInfo') as UICameraData | undefined;+ if (!camera) throw new Error('this realm has no UI camera, so a UI point has no screen position');+ // The exact inverse of what interaction.ts does to a real cursor: it answers+ // in GL pixels, the callbacks take canvas CSS ones. A flip here lands the+ // click a screen-height away, and the WORLD-space pick would still say yes.+ const gl = uiWorldToScreen(camera, at.x, at.y);+ // This realm is a web page, so this is the same source the web platform+ // reads for the ratio the interaction system divides by.+ const dpr = window.devicePixelRatio || 1;+ const screen = { x: gl.x / dpr, y: (camera.screenH - gl.y) / dpr };+ const cb = inputEventCallbacks(app_.getResource(Input));+ cb.onPointerMove?.(screen.x, screen.y);+ cb.onPointerDown?.(0, screen.x, screen.y);+ cb.onPointerUp?.(0);+ return { entity: target as never as number, name, at: screen, hit: hit as never as number };+}++/** Whether `hit` is `target` or under it — a label on a button is a child, and+ * the interaction system bubbles to the parent anyway. */+function isSelfOrDescendant(world: App['world'], hit: number, target: number): boolean {+ const parentDef = getComponent('Parent');+ let at: number | null = hit;+ for (let guard = 0; at !== null && guard < 64; guard++) {+ if (at === target) return true;+ const link: { entity?: number } | null = parentDef+ ? (world.tryGet(at as never, parentDef) as { entity?: number } | null)+ : null;+ at = link?.entity ?? null;+ }+ return false;+}+/** {@link Realm} over the live app — the one place these reach the SDK. */function realm(): Realm {const world = app!.world;@@ -504,7 +587,19 @@ async function buildAppAndRun(msg: InitMessage): Promise<void> {touchStart: (id: number, x: number, y: number) => injected.onTouchStart?.(id, x, y),touchMove: (id: number, x: number, y: number) => injected.onTouchMove?.(id, x, y),touchEnd: (id: number) => injected.onTouchEnd?.(id),+ /** Hand the game a controller it does not have. Held until released and+ * outranking the poll at that index, which runs every frame — a pad+ * merely written in is gone before a system reads it. */+ gamepad: (pad: number, buttons: number[], axes: number[]) => {+ inputState()?.injectGamepad({+ index: pad, connected: true, buttons, axes, mapping: 'standard',+ });+ },+ releaseGamepad: (pad?: number) => inputState()?.releaseGamepad(pad),},+ /** Click a UI element BY NAME, refusing rather than clicking the wrong+ * thing — see {@link clickUiByName}. */+ clickUi: (name: string) => clickUiByName(app!, name),/*** How many of everything is alive right now, as a plain object.*diff --git a/desktop/tests/editor-mcp-tools.test.ts b/desktop/tests/editor-mcp-tools.test.tsindex 6a7845af4..722c20dc1 100644--- a/desktop/tests/editor-mcp-tools.test.ts+++ b/desktop/tests/editor-mcp-tools.test.ts@@ -555,3 +555,46 @@ describe('the named reads over the running game', () => {});});});++/**+ * Naming what to drive instead of computing where it is. Both go through the+ * one input op — clicking a button IS input — so the tools only shape the call.+ */+describe('driving by name', () => {+ const driverWith = (answer: unknown) => {+ const driver = vi.fn() as unknown as { op: ReturnType<typeof vi.fn> } & ((...a: unknown[]) => unknown);+ driver.op = vi.fn(async () => answer);+ return driver;+ };++ it('clicks a UI element by name through the input op', async () => {+ const driver = driverWith({ entity: 7, name: 'Card1', at: { x: 296, y: 171 }, hit: 8 });+ const res = await runTool(toolNamed('click_ui'), driver, { target: 'Card1' });+ expect(driver.op).toHaveBeenCalledWith('play_input', {+ kind: 'ui', target: 'Card1', frame: undefined,+ });+ expect(JSON.parse(res.content[0].text)).toMatchObject({ name: 'Card1', hit: 8 });+ });++ // A pad is HELD, so the pressed state and the released state are two calls —+ // a game reads it every frame, and a one-shot press is gone before the frame+ // that reads it.+ it('holds a gamepad, and releases it as its own call', async () => {+ const driver = driverWith('ok');+ await runTool(toolNamed('send_gamepad'), driver, { buttons: [1, 0], axes: [0.5, 0] });+ expect(driver.op).toHaveBeenCalledWith('play_input', {+ kind: 'gamepad', pad: 0, buttons: [1, 0], axes: [0.5, 0], frame: undefined,+ });++ await runTool(toolNamed('send_gamepad'), driver, { pad: 1, release: true });+ expect(driver.op).toHaveBeenLastCalledWith('play_input', {+ kind: 'gamepad_release', pad: 1, frame: undefined,+ });+ });++ it('tiers both as ephemeral — they drive a realm Stop throws away', () => {+ for (const name of ['click_ui', 'send_gamepad']) {+ expect([name, toolNamed(name).effect]).toEqual([name, 'ephemeral']);+ }+ });+});diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex dce296718..cf84ddfe4 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -3492,6 +3492,7 @@ getTouch: (id: number) => TouchPoint | nullgetTouchCount: () => numbergetTouches: () => TouchPoint[]getVirtual: (id: string) => Vec2+injectGamepad: (snapshot: GamepadSnapshot) => voidisGamepadButtonDown: (button: number, pad?: number) => booleanisGamepadButtonPressed: (button: number, pad?: number) => booleanisGamepadButtonReleased: (button: number, pad?: number) => boolean@@ -3521,6 +3522,7 @@ noteKeyUp: (code: string) => voidnoteMouseDown: (button: number) => voidnoteMouseUp: (button: number) => voidpointerOverUI: boolean+releaseGamepad: (index?: number) => voidscrollDeltaX: numberscrollDeltaY: numbersetVirtual: (id: string, x: number, y?: number) => voiddiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 4fc473972..3e49d1030 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -3500,6 +3500,7 @@ getTouch: (id: number) => TouchPoint | nullgetTouchCount: () => numbergetTouches: () => TouchPoint[]getVirtual: (id: string) => Vec2+injectGamepad: (snapshot: GamepadSnapshot) => voidisGamepadButtonDown: (button: number, pad?: number) => booleanisGamepadButtonPressed: (button: number, pad?: number) => booleanisGamepadButtonReleased: (button: number, pad?: number) => boolean@@ -3529,6 +3530,7 @@ noteKeyUp: (code: string) => voidnoteMouseDown: (button: number) => voidnoteMouseUp: (button: number) => voidpointerOverUI: boolean+releaseGamepad: (index?: number) => voidscrollDeltaX: numberscrollDeltaY: numbersetVirtual: (id: string, x: number, y?: number) => voiddiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 3e2516a82..5b3b45c9c 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -3487,6 +3487,7 @@ getTouch: (id: number) => TouchPoint | nullgetTouchCount: () => numbergetTouches: () => TouchPoint[]getVirtual: (id: string) => Vec2+injectGamepad: (snapshot: GamepadSnapshot) => voidisGamepadButtonDown: (button: number, pad?: number) => booleanisGamepadButtonPressed: (button: number, pad?: number) => booleanisGamepadButtonReleased: (button: number, pad?: number) => boolean@@ -3516,6 +3517,7 @@ noteKeyUp: (code: string) => voidnoteMouseDown: (button: number) => voidnoteMouseUp: (button: number) => voidpointerOverUI: boolean+releaseGamepad: (index?: number) => voidscrollDeltaX: numberscrollDeltaY: numbersetVirtual: (id: string, x: number, y?: number) => voiddiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex b1325d8b2..f8b2e4cce 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -3487,6 +3487,7 @@ getTouch: (id: number) => TouchPoint | nullgetTouchCount: () => numbergetTouches: () => TouchPoint[]getVirtual: (id: string) => Vec2+injectGamepad: (snapshot: GamepadSnapshot) => voidisGamepadButtonDown: (button: number, pad?: number) => booleanisGamepadButtonPressed: (button: number, pad?: number) => booleanisGamepadButtonReleased: (button: number, pad?: number) => boolean@@ -3516,6 +3517,7 @@ noteKeyUp: (code: string) => voidnoteMouseDown: (button: number) => voidnoteMouseUp: (button: number) => voidpointerOverUI: boolean+releaseGamepad: (index?: number) => voidscrollDeltaX: numberscrollDeltaY: numbersetVirtual: (id: string, x: number, y?: number) => voiddiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 1712d080d..96278c8ea 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -3494,6 +3494,7 @@ getTouch: (id: number) => TouchPoint | nullgetTouchCount: () => numbergetTouches: () => TouchPoint[]getVirtual: (id: string) => Vec2+injectGamepad: (snapshot: GamepadSnapshot) => voidisGamepadButtonDown: (button: number, pad?: number) => booleanisGamepadButtonPressed: (button: number, pad?: number) => booleanisGamepadButtonReleased: (button: number, pad?: number) => boolean@@ -3523,6 +3524,7 @@ noteKeyUp: (code: string) => voidnoteMouseDown: (button: number) => voidnoteMouseUp: (button: number) => voidpointerOverUI: boolean+releaseGamepad: (index?: number) => voidscrollDeltaX: numberscrollDeltaY: numbersetVirtual: (id: string, x: number, y?: number) => voiddiff --git a/sdk/src/input/input.ts b/sdk/src/input/input.tsindex eef3d6346..49b07c471 100644--- a/sdk/src/input/input.ts+++ b/sdk/src/input/input.ts@@ -280,9 +280,36 @@ export class InputState {/** Ingest this frame's snapshots: shift current→prev (edge detection) then* store new values. Pads absent from `snapshots` are marked disconnected. */+ /**+ * Pads supplied by the HOST rather than by the hardware — a test harness, a+ * driver, the editor's agent. They outrank the poll at the same index: the+ * poll runs every frame, so anything merely written into {@link gamepads}+ * is gone before a system reads it.+ *+ * @beta+ */+ injectGamepad(snapshot: GamepadSnapshot): void {+ this.injected_.set(snapshot.index, snapshot);+ }++ /** Give an index (or all of them) back to the hardware. @beta */+ releaseGamepad(index?: number): void {+ if (index === undefined) this.injected_.clear();+ else this.injected_.delete(index);+ }++ private injected_ = new Map<number, GamepadSnapshot>();+updateGamepads(snapshots: GamepadSnapshot[]): void {+ // An injected pad REPLACES the polled one at its index; a polled pad at+ // an index nobody injected is untouched, so handing the game a+ // controller does not blind it to one somebody plugged in.+ const merged = this.injected_.size === 0 ? snapshots : [+ ...snapshots.filter((s) => !this.injected_.has(s.index)),+ ...this.injected_.values(),+ ];for (const p of this.gamepads.values()) p.connected = false;- for (const snap of snapshots) {+ for (const snap of merged) {let p = this.gamepads.get(snap.index);if (!p) {p = { connected: true, buttons: [], prevButtons: [], axes: [] };