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
fix(input): preserve complete button taps between samples
yhh5626eadb1090
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4b75c2e2d..549f35c41 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,8 @@ published separately; it ships inside the editor.### Fixed+- **Button actions retain complete keyboard and mouse taps between samples.** A press and release within one frame produces both action edges once without leaving the action held, and each input map observes its own pulse. Frame cleanup and host cancellation drop pending pulses; a held alternative absorbs them without replay. Button alternatives use the strongest input so weak analog sources cannot combine into a false press or cancel a keyboard binding.+- **Screen-domain queries reject another world's cached entities.** The UI binding checks registry identity and entity validity before using the resolved screen-domain cache, preventing reused IDs from borrowing a previous world's pointer coordinates and excluding despawned nodes before the next layout pass.- **Authored UI hiding cancels dragging before another layout pass.** Hiding a dragged node or its ancestor stops capture and emits one drag-end event immediately on the next sample, including visibility changes inside drag callbacks. Stale hover cannot start a hidden control, and showing it again does not resume an old capture. Dragging and keyboard focus share the same live visibility rules.diff --git a/sdk/src/input/actionEdges.ts b/sdk/src/input/actionEdges.tsnew file mode 100644index 000000000..7288db5a5--- /dev/null+++ b/sdk/src/input/actionEdges.ts@@ -0,0 +1,37 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+export interface ActionEdge {+ source: 'key' | 'mouse';+ code: string | number;+ down: boolean;+ sequence: number;+}+interface EdgeState {+ readonly owner: object;+ sequence: number;+ readonly events: ActionEdge[];+}+const states = new WeakMap<object, EdgeState>();++/** Ordered physical transitions, shared read-only by all maps until frame cleanup. */+export function recordActionEdge(input: object, source: ActionEdge['source'], code: ActionEdge['code'], down: boolean): void {+ let state = states.get(input);+ if (!state) { state = { owner: {}, sequence: 0, events: [] }; states.set(input, state); }+ state.events.push({ source, code, down, sequence: ++state.sequence });+}++export function actionEdges(input: object): Readonly<EdgeState> | undefined { return states.get(input); }++/** A claimed release cancels that source without manufacturing gameplay edges. */+export function discardActionEdges(input: object, source: ActionEdge['source'], code: ActionEdge['code']): void {+ const events = states.get(input)?.events;+ if (!events) return;+ let keep = 0;+ for (const event of events) if (event.source !== source || event.code !== code) events[keep++] = event;+ events.length = keep;+}++export function clearActionEdges(input: object): void {+ const state = states.get(input);+ if (state) state.events.length = 0;+}diff --git a/sdk/src/input/input.ts b/sdk/src/input/input.tsindex 0495332ac..4e1776db0 100644--- a/sdk/src/input/input.ts+++ b/sdk/src/input/input.ts@@ -9,6 +9,7 @@ import type { GamepadSnapshot, InputEventCallbacks } from '../platform/types';import { inputRouter } from './inputRouter';import { cancelPrimaryPointer, takePrimaryPointerCancellation } from './pointerCancellation';import { recordTouchEnd } from './touchEdges';+import { recordActionEdge, discardActionEdges, clearActionEdges } from './actionEdges';import type { Vec2 } from '../types';/**@@ -150,6 +151,7 @@ export class InputState {noteKeyDown(code: string): void {recordTabModifiers(this, code);if (!this.keysDown.has(code)) {+ recordActionEdge(this, 'key', code, true);this.keysPressed.add(code);this.keysPressedFixed.add(code);}@@ -157,12 +159,14 @@ export class InputState {}noteKeyUp(code: string): void {+ if (this.keysDown.has(code)) recordActionEdge(this, 'key', code, false);this.keysDown.delete(code);this.keysReleased.add(code);this.keysReleasedFixed.add(code);}noteMouseDown(button: number): void {+ if (!this.mouseButtons.has(button)) recordActionEdge(this, 'mouse', button, true);if (button === 0) takePrimaryPointerCancellation(this);this.mouseButtons.add(button);this.mouseButtonsPressed.add(button);@@ -170,6 +174,7 @@ export class InputState {}noteMouseUp(button: number): void {+ if (this.mouseButtons.has(button)) recordActionEdge(this, 'mouse', button, false);this.mouseButtons.delete(button);this.mouseButtonsReleased.add(button);this.mouseButtonsReleasedFixed.add(button);@@ -369,6 +374,7 @@ export class InputState {}clearFrameState(): void {+ clearActionEdges(this);this.keysPressed.clear();clearTabModifiers(this);this.keysReleased.clear();@@ -450,7 +456,10 @@ export function inputEventCallbacks(state: InputState): InputEventCallbacks {},onKeyUp(code) {if (executionOwners.has(state)) return;- if (inputRouter.dispatchKeyUp(code)) state.keysDown.delete(code);+ if (inputRouter.dispatchKeyUp(code)) {+ state.keysDown.delete(code);+ discardActionEdges(state, 'key', code);+ }else if (state.keysDown.has(code)) state.noteKeyUp(code);},onPointerMove(x, y) {@@ -474,6 +483,7 @@ export function inputEventCallbacks(state: InputState): InputEventCallbacks {if (executionOwners.has(state)) return;if (inputRouter.dispatchPointerUp(button)) {state.mouseButtons.delete(button);+ discardActionEdges(state, 'mouse', button);if (button === 0) cancelPrimaryPointer(state);}else if (state.mouseButtons.has(button)) state.noteMouseUp(button);@@ -511,6 +521,7 @@ export function inputEventCallbacks(state: InputState): InputEventCallbacks {state.touchesStarted.delete(id);state.touchesEnded.delete(id);if (primary === true || (primary === undefined && state.touches.size === 0)) {+ discardActionEdges(state, 'mouse', 0);state.mouseButtons.delete(0);state.mouseButtonsPressed.delete(0);state.mouseButtonsReleased.delete(0);diff --git a/sdk/src/input/inputMap.ts b/sdk/src/input/inputMap.tsindex d19a08094..cff25739c 100644--- a/sdk/src/input/inputMap.ts+++ b/sdk/src/input/inputMap.ts@@ -18,6 +18,7 @@ import { SystemLabel } from '../ecs/systemLabels';import { Input, InputState, GamepadAxis, GamepadButton } from './input';import { Storage } from '../util/storage';import type { Vec2 } from '../types';+import { actionEdges, type ActionEdge } from './actionEdges';// =============================================================================// Binding model (plain, serializable — also the rebind / persistence format)@@ -109,8 +110,10 @@ export const Stick = (stick: 'left' | 'right', pad?: number): Binding => ({ kindexport const Virtual = (id: string): Binding => ({ kind: 'virtual', id });// — Action constructors —-/** A digital action, read with `pressed`/`down`/`released`. An analog source- * counts as down past half its range.+/** A digital action, read with `pressed`/`down`/`released`. Alternatives use the+ * strongest value; an analog source counts as down past half its range.+ * A complete keyboard/mouse tap between samples sets both edge flags while+ * leaving `down` false and the sampled value at zero.* @public */export const Button = (...bindings: Binding[]): ActionDef => ({ type: 'button', bindings });/** A signed 1D action in [-1, 1], read with `value`.@@ -130,6 +133,7 @@ const DOWN_THRESHOLD = 0.5;interface ActionState {+ tapSequence: number;value: number; // button: [0,1]; axis: [-1,1]; axis2d: magnitude [0,1]vec: Vec2; // axis2d direction; scalar actions put value in xdown: boolean;@@ -137,6 +141,51 @@ interface ActionState {released: boolean;}+function observedButtonEdges(bindings: Binding[], input: InputState,+ events: readonly ActionEdge[], after: number, previouslyDown: boolean): number {+ let relevant: ActionEdge[] | undefined;+ for (const event of events) {+ if (event.sequence <= after) continue;+ if (bindings.some(binding => event.source === 'mouse'+ ? binding.kind === 'mouse' && binding.button === event.code+ : binding.kind === 'key' && binding.code === event.code+ || binding.kind === 'keys1d' && (binding.neg === event.code || binding.pos === event.code))) {+ (relevant ??= []).push(event);+ }+ }+ if (!relevant) return 0;+ const digital = new Map<string | number, boolean>();+ let other = 0;+ for (const binding of bindings) {+ if (binding.kind === 'key') digital.set(binding.code, input.isKeyDown(binding.code));+ else if (binding.kind === 'mouse') digital.set(binding.button, input.isMouseButtonDown(binding.button));+ else if (binding.kind === 'keys1d') {+ digital.set(binding.neg, input.isKeyDown(binding.neg));+ digital.set(binding.pos, input.isKeyDown(binding.pos));+ } else other = Math.max(other, evalScalar(binding, input));+ }+ for (let i = relevant.length - 1; i >= 0; i--) digital.set(relevant[i].code, !relevant[i].down);+ const down = (): boolean => {+ let value = other;+ for (const binding of bindings) {+ if (binding.kind === 'key') value = Math.max(value, digital.get(binding.code) ? 1 : 0);+ else if (binding.kind === 'mouse') value = Math.max(value, digital.get(binding.button) ? 1 : 0);+ else if (binding.kind === 'keys1d') value = Math.max(value,+ Number(digital.get(binding.pos)) - Number(digital.get(binding.neg)));+ }+ return value >= DOWN_THRESHOLD;+ };+ let held = down(), flags = 0;+ for (const event of relevant) {+ digital.set(event.code, event.down);+ const next = down();+ if (held && !next && (previouslyDown || (flags & 1))) flags |= 2;+ if (!held && next && (!previouslyDown || (flags & 2))) flags |= 1;+ held = next;+ }+ return flags;+}+function evalScalar(b: Binding, input: InputState): number {switch (b.kind) {case 'key': return input.isKeyDown(b.code) ? 1 : 0;@@ -204,17 +253,25 @@ export class InputMap {private readonly defs_ = new Map<string, ActionDef>();private readonly state_ = new Map<string, ActionState>();private pendingListen_: PendingListen | null = null;+ private tapOwner_: object | undefined;constructor(actions: Record<string, ActionDef>) {for (const [name, def] of Object.entries(actions)) {this.defs_.set(name, def);- this.state_.set(name, { value: 0, vec: { x: 0, y: 0 }, down: false, pressed: false, released: false });+ this.state_.set(name, { value: 0, vec: { x: 0, y: 0 }, down: false, pressed: false, released: false, tapSequence: 0 });}}/** @internal Recompute every action from the current raw input. Called once per- * frame by the registered evaluation system; edges diff against last frame. */+ * frame by the registered evaluation system; complete physical taps survive+ * between samples alongside the normal held-state transitions. */evaluate(input: InputState): void {+ const edges = actionEdges(input);+ const tapOwner = edges?.owner;+ if (this.tapOwner_ !== tapOwner) {+ this.tapOwner_ = tapOwner;+ for (const state of this.state_.values()) state.tapSequence = 0;+ }if (this.pendingListen_) this.scanForRebind_(input);for (const [name, def] of this.defs_) {const st = this.state_.get(name)!;@@ -230,7 +287,12 @@ export class InputMap {st.value = Math.min(1, mag);} else {let v = 0;- for (const b of def.bindings) v += evalScalar(b, input);+ for (const b of def.bindings) {+ const value = evalScalar(b, input);+ if (def.type === 'button') {+ v = Math.max(v, value);+ } else v += value;+ }v = def.type === 'button' ? clamp(v, 0, 1) : clamp(v, -1, 1);st.value = v;st.vec.x = v;@@ -240,6 +302,14 @@ export class InputMap {st.down = Math.abs(st.value) >= DOWN_THRESHOLD;st.pressed = st.down && !prevDown;st.released = !st.down && prevDown;+ if (def.type === 'button' && edges?.events.length) {+ const observed = observedButtonEdges(def.bindings, input, edges.events, st.tapSequence, prevDown);+ st.pressed ||= !!(observed & 1);+ st.released ||= !!(observed & 2);+ }+ // A held alternative absorbs taps too, so releasing it cannot replay+ // an earlier pulse. Each map owns its watermark independently.+ st.tapSequence = edges?.sequence ?? 0;}}diff --git a/sdk/tests/input-map-short-tap.test.ts b/sdk/tests/input-map-short-tap.test.tsnew file mode 100644index 000000000..e9409064c--- /dev/null+++ b/sdk/tests/input-map-short-tap.test.ts@@ -0,0 +1,138 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, expect, it } from 'vitest';+import { InputState, inputEventCallbacks } from '../src/input/input';+import { inputRouter } from '../src/input/inputRouter';+import { InputMap, Button, Key, MouseButton, GpAxis, Virtual, Keys1D } from '../src/input/inputMap';++describe('button alternatives and short taps', () => {+ it.each(['key', 'mouse'] as const)('observes a release and repress of a held %s between samples', kind => {+ const input = new InputState(), map = new InputMap({ Fire: Button(kind === 'key' ? Key('Space') : MouseButton(0)) });+ const down = () => kind === 'key' ? input.noteKeyDown('Space') : input.noteMouseDown(0);+ const up = () => kind === 'key' ? input.noteKeyUp('Space') : input.noteMouseUp(0);+ down(); map.evaluate(input); input.clearFrameState();+ up(); down(); map.evaluate(input);+ expect([map.pressed('Fire'), map.released('Fire'), map.down('Fire')]).toEqual([true, true, true]);+ map.evaluate(input);+ expect([map.pressed('Fire'), map.released('Fire')]).toEqual([false, false]);+ input.clearFrameState(); up(); down(); up(); map.evaluate(input);+ expect([map.pressed('Fire'), map.released('Fire'), map.down('Fire')]).toEqual([true, true, false]);+ });+ it.each([true, false])('distinguishes overlapping alias handoff from a gap (overlap=%s)', overlap => {+ const input = new InputState(), map = new InputMap({ Fire: Button(Key('Space'), MouseButton(0)) });+ input.noteKeyDown('Space'); map.evaluate(input); input.clearFrameState();+ if (overlap) { input.noteMouseDown(0); input.noteKeyUp('Space'); }+ else { input.noteKeyUp('Space'); input.noteMouseDown(0); }+ map.evaluate(input);+ expect([map.pressed('Fire'), map.released('Fire'), map.down('Fire')]).toEqual([!overlap, !overlap, true]);+ });+ it('ignores key repeat and preserves signed composite transitions', () => {+ const input = new InputState(), map = new InputMap({ Fire: Button(Keys1D('KeyA', 'KeyD')) });+ input.noteKeyDown('KeyD'); map.evaluate(input); input.clearFrameState();+ input.noteKeyDown('KeyD'); map.evaluate(input);+ expect(map.pressed('Fire')).toBe(false);+ input.noteKeyDown('KeyA'); input.noteKeyUp('KeyA'); map.evaluate(input);+ expect([map.pressed('Fire'), map.released('Fire'), map.down('Fire')]).toEqual([true, true, true]);+ });+ it('does not add two subthreshold alternatives into a press', () => {+ const input = new InputState(), map = new InputMap({ Fire: Button(Virtual('one'), Virtual('two')) });+ input.setVirtual('one', .3); input.setVirtual('two', .3); map.evaluate(input);+ expect(map.value('Fire')).toBe(.3);+ expect(map.down('Fire')).toBe(false);+ expect(map.pressed('Fire')).toBe(false);+ });+ it('does not let a negative axis cancel a keyboard alternative', () => {+ const input = new InputState(), map = new InputMap({ Fire: Button(Key('Space'), GpAxis(0)) });+ input.updateGamepads([{ index: 0, connected: true, buttons: [], axes: [-1], mapping: 'standard' }]);+ input.noteKeyDown('Space'); map.evaluate(input);+ expect(map.value('Fire')).toBe(1);+ expect(map.pressed('Fire')).toBe(true);+ });+ it.each(['key', 'mouse'] as const)('retains a complete %s tap once per map without leaving the button down', kind => {+ const input = new InputState(), binding = kind === 'key' ? Key('Space') : MouseButton(0);+ const maps = [new InputMap({ Fire: Button(binding) }), new InputMap({ Fire: Button(binding) })];+ for (const map of maps) map.evaluate(input);+ const tap = () => {+ if (kind === 'key') { input.noteKeyDown('Space'); input.noteKeyUp('Space'); }+ else { input.noteMouseDown(0); input.noteMouseUp(0); }+ };+ tap();+ for (const map of maps) {+ map.evaluate(input);+ expect(map.pressed('Fire')).toBe(true);+ expect(map.released('Fire')).toBe(true);+ expect(map.down('Fire')).toBe(false);+ expect(map.value('Fire')).toBe(0);+ map.evaluate(input);+ expect(map.pressed('Fire')).toBe(false);+ expect(map.released('Fire')).toBe(false);+ }+ tap();+ maps[0].evaluate(input);+ expect(maps[0].pressed('Fire')).toBe(true);+ input.clearFrameState(); maps[0].evaluate(input);+ expect(maps[0].pressed('Fire')).toBe(false);+ });+ it('does not retrigger a held alias or replay its completed tap after release', () => {+ const input = new InputState(), map = new InputMap({ Fire: Button(Key('Space'), MouseButton(0)) });+ input.noteKeyDown('Space'); map.evaluate(input); input.clearFrameState();+ input.noteMouseDown(0); input.noteMouseUp(0); map.evaluate(input);+ expect(map.down('Fire')).toBe(true);+ expect(map.pressed('Fire')).toBe(false);+ input.noteKeyUp('Space'); map.evaluate(input);+ expect(map.pressed('Fire')).toBe(false);+ expect(map.released('Fire')).toBe(true);+ map.evaluate(input);+ expect(map.pressed('Fire')).toBe(false);+ });+ it('does not replay an old action when an unrelated tap arrives before frame clear', () => {+ const input = new InputState(), map = new InputMap({ Fire: Button(Key('Space')), Jump: Button(Key('KeyJ')) });+ input.noteKeyDown('Space'); input.noteKeyUp('Space'); map.evaluate(input);+ expect(map.pressed('Fire')).toBe(true);+ input.noteKeyDown('KeyJ'); input.noteKeyUp('KeyJ'); map.evaluate(input);+ expect(map.pressed('Fire')).toBe(false);+ expect(map.pressed('Jump')).toBe(true);+ });+ it('drops pending short taps on host cancellation', () => {+ const input = new InputState(), map = new InputMap({ Fire: Button(Key('Space'), MouseButton(0)) });+ input.noteKeyDown('Space'); input.noteKeyUp('Space');+ input.noteMouseDown(0); input.noteMouseUp(0);+ inputEventCallbacks(input).onInputCancel!(); map.evaluate(input);+ expect(map.pressed('Fire')).toBe(false);+ expect(map.released('Fire')).toBe(false);+ });+ it('does not turn a claimed key release into a gameplay tap', () => {+ const input = new InputState(), map = new InputMap({ Fire: Button(Key('Space')) });+ input.noteKeyDown('Space');+ const off = inputRouter.setEditorHandler({ onKeyUp: () => true });+ try { inputEventCallbacks(input).onKeyUp('Space'); } finally { off(); }+ map.evaluate(input);+ expect(map.pressed('Fire')).toBe(false);+ });+ it('does not turn a claimed mouse release into a gameplay tap', () => {+ const input = new InputState(), map = new InputMap({ Fire: Button(MouseButton(0)) });+ input.noteMouseDown(0);+ const off = inputRouter.setEditorHandler({ onPointerUp: () => true });+ try { inputEventCallbacks(input).onPointerUp(0); } finally { off(); }+ map.evaluate(input);+ expect(map.pressed('Fire')).toBe(false);+ });+ it('drops expired pulses for a map that starts after the frame ends', () => {+ const input = new InputState();+ input.noteKeyDown('Space'); input.noteKeyUp('Space'); input.clearFrameState();+ const map = new InputMap({ Fire: Button(Key('Space')) }); map.evaluate(input);+ expect(map.pressed('Fire')).toBe(false);+ });+ it('accepts new taps after cancellation and when switching input streams', () => {+ const map = new InputMap({ Fire: Button(Key('Space')) });+ const first = new InputState(), second = new InputState();+ for (let i = 0; i < 10; i++) { first.noteKeyDown('Space'); first.noteKeyUp('Space'); }+ map.evaluate(first); expect(map.pressed('Fire')).toBe(true);+ inputEventCallbacks(first).onInputCancel!(); map.evaluate(first);+ expect(map.pressed('Fire')).toBe(false);+ first.noteKeyDown('Space'); first.noteKeyUp('Space'); map.evaluate(first);+ expect(map.pressed('Fire')).toBe(true);+ second.noteKeyDown('Space'); second.noteKeyUp('Space'); map.evaluate(second);+ expect(map.pressed('Fire')).toBe(true);+ });+});diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 3663e9202..3a5682f3b 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -28,6 +28,8 @@ export const NOTES_FLOOR = 'v0.65.0';* the reader recognises anyway.*/export const NOTED = {+ 'fix(input): preserve complete button taps between samples':+ { note: 'Button actions retain complete keyboard and mouse taps between samples.' },'fix(ui): scope screen-domain lookup to its registry':{ note: 'Screen-domain queries reject another world\'s cached entities.' },'fix(ui): cancel drag captures from authored visibility changes':