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(ui)!: one state mechanism — retire StateMachine/StateVisuals for controller+gears

esengine31695d0a25cd
diff --git a/docs/astro/src/content/docs/guides/ui-components.mdx b/docs/astro/src/content/docs/guides/ui-components.mdx
index 2ae94aa49..72ff4997d 100644
--- a/docs/astro/src/content/docs/guides/ui-components.mdx
+++ b/docs/astro/src/content/docs/guides/ui-components.mdx
@@ -6,7 +6,8 @@ description: The built-in widget factories — Button, Toggle, Slider, Progress,
import { Aside } from '@astrojs/starlight/components';
The widget factories build common controls out of the [UI](/docs/guides/ui/) component
-model (`UINode` + `Interactable` + `StateMachine` + `StateVisuals`), so you don't wire
+model (`UINode` + `Interactable` + a `$interaction`
+[controller with gears](/docs/guides/ui-controllers/)), so you don't wire
each one by hand. Each factory takes an options object and returns either the created
entity (Button) or a **handle** with imperative methods to read and drive it.
diff --git a/docs/astro/src/content/docs/zh-cn/guides/ui-components.mdx b/docs/astro/src/content/docs/zh-cn/guides/ui-components.mdx
index 097962c08..0a36fa354 100644
--- a/docs/astro/src/content/docs/zh-cn/guides/ui-components.mdx
+++ b/docs/astro/src/content/docs/zh-cn/guides/ui-components.mdx
@@ -5,8 +5,8 @@ description: 内置控件工厂——Button、Toggle、Slider、Progress、Dropd
import { Aside } from '@astrojs/starlight/components';
-控件工厂用 [UI](/docs/zh-cn/guides/ui/) 组件模型(`UINode` + `Interactable` + `StateMachine` +
-`StateVisuals`)构建常见控件,免得你逐个手动接线。每个工厂接收一个选项对象,返回创建的实体
+控件工厂用 [UI](/docs/zh-cn/guides/ui/) 组件模型(`UINode` + `Interactable` +
+`$interaction` [控制器与属性绑定](/docs/zh-cn/guides/ui-controllers/))构建常见控件,免得你逐个手动接线。每个工厂接收一个选项对象,返回创建的实体
(Button)或一个带命令式方法、用于读取和驱动它的**句柄(handle)**。
交互式控件需要 world 和 UI 事件队列——`world` 来自 `GetWorld()`,`events` 来自 `Res(UIEvents)`,
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 76bd04694..176b1222b 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -5,7 +5,7 @@ Symbols: 1204 stable · 17 beta · 1 deprecated
## ABI_LAYOUT_HASH — const
```
-"89ad72a9b853289f"
+"f9191aeae848066e"
```
## ANCHOR_AXES — const
@@ -1080,7 +1080,6 @@ onClick: ((entity: Entity) => void) | undefined
parent: number | undefined
states: Record<string, ButtonStateVisual> | undefined
text: string | TextInit | undefined
-transitionFlags: number | undefined
world: World
```
@@ -1557,8 +1556,6 @@ addShadowCaster2D: (entity: Entity, component: ShadowCaster2D) => void
addShapeRenderer: (entity: Entity, component: ShapeRenderer) => void
addSpineAnimation: (entity: Entity, component: SpineAnimation) => void
addSprite: (entity: Entity, component: Sprite) => void
-addStateMachine: (entity: Entity, component: StateMachine) => void
-addStateVisuals: (entity: Entity, component: StateVisuals) => void
addTilemapLayer: (entity: Entity, component: TilemapLayer) => void
addTrailRenderer: (entity: Entity, component: TrailRenderer) => void
addTransform: (entity: Entity, component: Transform) => void
@@ -1590,8 +1587,6 @@ getShadowCaster2D: (entity: Entity) => ShadowCaster2D
getShapeRenderer: (entity: Entity) => ShapeRenderer
getSpineAnimation: (entity: Entity) => SpineAnimation
getSprite: (entity: Entity) => Sprite
-getStateMachine: (entity: Entity) => StateMachine
-getStateVisuals: (entity: Entity) => StateVisuals
getTilemapLayer: (entity: Entity) => TilemapLayer
getTrailRenderer: (entity: Entity) => TrailRenderer
getTransform: (entity: Entity) => Transform
@@ -1619,8 +1614,6 @@ hasShadowCaster2D: (entity: Entity) => boolean
hasShapeRenderer: (entity: Entity) => boolean
hasSpineAnimation: (entity: Entity) => boolean
hasSprite: (entity: Entity) => boolean
-hasStateMachine: (entity: Entity) => boolean
-hasStateVisuals: (entity: Entity) => boolean
hasTilemapLayer: (entity: Entity) => boolean
hasTrailRenderer: (entity: Entity) => boolean
hasTransform: (entity: Entity) => boolean
@@ -1648,8 +1641,6 @@ removeShadowCaster2D: (entity: Entity) => void
removeShapeRenderer: (entity: Entity) => void
removeSpineAnimation: (entity: Entity) => void
removeSprite: (entity: Entity) => void
-removeStateMachine: (entity: Entity) => void
-removeStateVisuals: (entity: Entity) => void
removeTilemapLayer: (entity: Entity) => void
removeTrailRenderer: (entity: Entity) => void
removeTransform: (entity: Entity) => void
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index f850b1f46..5ac6601d1 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -1075,7 +1075,6 @@ onClick: ((entity: Entity) => void) | undefined
parent: number | undefined
states: Record<string, ButtonStateVisual> | undefined
text: string | TextInit | undefined
-transitionFlags: number | undefined
world: World
```
@@ -1552,8 +1551,6 @@ addShadowCaster2D: (entity: Entity, component: ShadowCaster2D) => void
addShapeRenderer: (entity: Entity, component: ShapeRenderer) => void
addSpineAnimation: (entity: Entity, component: SpineAnimation) => void
addSprite: (entity: Entity, component: Sprite) => void
-addStateMachine: (entity: Entity, component: StateMachine) => void
-addStateVisuals: (entity: Entity, component: StateVisuals) => void
addTilemapLayer: (entity: Entity, component: TilemapLayer) => void
addTrailRenderer: (entity: Entity, component: TrailRenderer) => void
addTransform: (entity: Entity, component: Transform) => void
@@ -1585,8 +1582,6 @@ getShadowCaster2D: (entity: Entity) => ShadowCaster2D
getShapeRenderer: (entity: Entity) => ShapeRenderer
getSpineAnimation: (entity: Entity) => SpineAnimation
getSprite: (entity: Entity) => Sprite
-getStateMachine: (entity: Entity) => StateMachine
-getStateVisuals: (entity: Entity) => StateVisuals
getTilemapLayer: (entity: Entity) => TilemapLayer
getTrailRenderer: (entity: Entity) => TrailRenderer
getTransform: (entity: Entity) => Transform
@@ -1614,8 +1609,6 @@ hasShadowCaster2D: (entity: Entity) => boolean
hasShapeRenderer: (entity: Entity) => boolean
hasSpineAnimation: (entity: Entity) => boolean
hasSprite: (entity: Entity) => boolean
-hasStateMachine: (entity: Entity) => boolean
-hasStateVisuals: (entity: Entity) => boolean
hasTilemapLayer: (entity: Entity) => boolean
hasTrailRenderer: (entity: Entity) => boolean
hasTransform: (entity: Entity) => boolean
@@ -1643,8 +1636,6 @@ removeShadowCaster2D: (entity: Entity) => void
removeShapeRenderer: (entity: Entity) => void
removeSpineAnimation: (entity: Entity) => void
removeSprite: (entity: Entity) => void
-removeStateMachine: (entity: Entity) => void
-removeStateVisuals: (entity: Entity) => void
removeTilemapLayer: (entity: Entity) => void
removeTrailRenderer: (entity: Entity) => void
removeTransform: (entity: Entity) => void
diff --git a/sdk/etc/wasm.api.md b/sdk/etc/wasm.api.md
index 3c04b86c7..dfc06a934 100644
--- a/sdk/etc/wasm.api.md
+++ b/sdk/etc/wasm.api.md
@@ -32,8 +32,6 @@ addShadowCaster2D: (entity: Entity, component: ShadowCaster2D) => void
addShapeRenderer: (entity: Entity, component: ShapeRenderer) => void
addSpineAnimation: (entity: Entity, component: SpineAnimation) => void
addSprite: (entity: Entity, component: Sprite) => void
-addStateMachine: (entity: Entity, component: StateMachine) => void
-addStateVisuals: (entity: Entity, component: StateVisuals) => void
addTilemapLayer: (entity: Entity, component: TilemapLayer) => void
addTrailRenderer: (entity: Entity, component: TrailRenderer) => void
addTransform: (entity: Entity, component: Transform) => void
@@ -65,8 +63,6 @@ getShadowCaster2D: (entity: Entity) => ShadowCaster2D
getShapeRenderer: (entity: Entity) => ShapeRenderer
getSpineAnimation: (entity: Entity) => SpineAnimation
getSprite: (entity: Entity) => Sprite
-getStateMachine: (entity: Entity) => StateMachine
-getStateVisuals: (entity: Entity) => StateVisuals
getTilemapLayer: (entity: Entity) => TilemapLayer
getTrailRenderer: (entity: Entity) => TrailRenderer
getTransform: (entity: Entity) => Transform
@@ -94,8 +90,6 @@ hasShadowCaster2D: (entity: Entity) => boolean
hasShapeRenderer: (entity: Entity) => boolean
hasSpineAnimation: (entity: Entity) => boolean
hasSprite: (entity: Entity) => boolean
-hasStateMachine: (entity: Entity) => boolean
-hasStateVisuals: (entity: Entity) => boolean
hasTilemapLayer: (entity: Entity) => boolean
hasTrailRenderer: (entity: Entity) => boolean
hasTransform: (entity: Entity) => boolean
@@ -123,8 +117,6 @@ removeShadowCaster2D: (entity: Entity) => void
removeShapeRenderer: (entity: Entity) => void
removeSpineAnimation: (entity: Entity) => void
removeSprite: (entity: Entity) => void
-removeStateMachine: (entity: Entity) => void
-removeStateVisuals: (entity: Entity) => void
removeTilemapLayer: (entity: Entity) => void
removeTrailRenderer: (entity: Entity) => void
removeTransform: (entity: Entity) => void
diff --git a/sdk/src/component.generated.ts b/sdk/src/component.generated.ts
index 9fe823799..8e30bdfd2 100644
--- a/sdk/src/component.generated.ts
+++ b/sdk/src/component.generated.ts
@@ -7,7 +7,7 @@
import type { AssetFieldType } from './scene';
import type { FieldMeta } from './component';
import type { Color, Entity, Quat, Vec2, Vec3, Vec4 } from './types';
-import type { Dimension, Padding, VisualState } from './wasm.generated';
+import type { Dimension, Padding } from './wasm.generated';
/**
* Single-source-of-truth hash of the C++/TS boundary ABI (component
@@ -15,7 +15,7 @@ import type { Dimension, Padding, VisualState } from './wasm.generated';
* getAbiLayoutHash(); BuiltinBridge.connect() compares them and refuses to
* run on mismatch, because mismatched offsets read the wrong heap bytes.
*/
-export const ABI_LAYOUT_HASH = '89ad72a9b853289f';
+export const ABI_LAYOUT_HASH = 'f9191aeae848066e';
export interface AssetFieldMeta {
field: string;
@@ -516,28 +516,6 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
material: { advanced: true },
},
},
- StateMachine: {
- defaults: {
- current: '',
- previous: '',
- },
- assetFields: [],
- entityFields: [],
- colorFields: [],
- animatableFields: [],
- },
- StateVisuals: {
- defaults: {
- targetGraphic: 0,
- transitionFlags: 0,
- fadeDuration: 0,
- states: [],
- },
- assetFields: [],
- entityFields: ['targetGraphic'],
- colorFields: [],
- animatableFields: [],
- },
TilemapLayer: {
defaults: {
cellSize: { x: 32, y: 32 },
@@ -948,18 +926,6 @@ export interface SpriteData {
enabled: boolean;
}
-export interface StateMachineData {
- current: string;
- previous: string;
-}
-
-export interface StateVisualsData {
- targetGraphic: Entity;
- transitionFlags: number;
- fadeDuration: number;
- states: VisualState[];
-}
-
export interface TilemapLayerData {
cellSize: Vec2;
originOffset: Vec2;
diff --git a/sdk/src/ui/behavior/plugin.ts b/sdk/src/ui/behavior/plugin.ts
index a04933034..ed757ff58 100644
--- a/sdk/src/ui/behavior/plugin.ts
+++ b/sdk/src/ui/behavior/plugin.ts
@@ -11,11 +11,6 @@ import type { Entity, Vec2 } from '../../types';
import { UIEvents, UIEventQueue } from '../core/events';
import { UICameraInfo, type UICameraData } from '../core/ui-camera-info';
import { PluginName, SystemLabel } from '../../systemLabels';
-import {
- createInteractableDriverSystem,
- createStateMachineDiffSystem,
- createStateVisualsApplySystem,
-} from './systems';
import { ListView, ListViewRegistry } from '../collection/list-view';
import { ScrollContainer, ScrollContainerRegistry } from '../collection/scroll-container';
import { KineticScroll } from '../collection/kinetic-scroll';
@@ -26,8 +21,10 @@ import { getEntityDepth } from '../util/helpers';
const SCROLL_DRAG_THRESHOLD_PX = 5;
/**
- * Wires the Layer 2 behavior systems — interactable-driven state machine
- * diffing and state-visual application — and owns the shared event bus.
+ * Wires the Layer 2 behavior systems — list views and scroll containers — and
+ * owns the shared event bus. Interaction *state* (button hover/pressed pages)
+ * lives in the controller layer: the `$interaction` UIController driver + gear
+ * apply (see ui/controller).
*
* Depends on the existing hit-test system to have written UIInteraction
* during PreUpdate; these systems run in Update and react to that data.
@@ -93,20 +90,6 @@ export class UIBehaviorPlugin implements Plugin {
const world = app.world;
- app.addSystemToSchedule(
- Schedule.Update,
- createInteractableDriverSystem(app.world),
- );
- app.addSystemToSchedule(
- Schedule.Update,
- createStateMachineDiffSystem(app.world, events),
- { runAfter: ['InteractableDriverSystem'] },
- );
- app.addSystemToSchedule(
- Schedule.Update,
- createStateVisualsApplySystem(app.world),
- { runAfter: ['StateMachineDiffSystem'] },
- );
app.addSystemToSchedule(
Schedule.Update,
defineSystem([], () => listViews.tick(), { name: 'ListViewSystem' }),
diff --git a/sdk/src/ui/behavior/state-machine.ts b/sdk/src/ui/behavior/state-machine.ts
deleted file mode 100644
index a81e02216..000000000
--- a/sdk/src/ui/behavior/state-machine.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-// SPDX-License-Identifier: Apache-2.0
-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-import { defineBuiltin } from '../../component';
-
-export interface StateMachineData {
- current: string;
- previous: string;
-}
-
-export const StateMachine = defineBuiltin<StateMachineData>('StateMachine', {
- current: '',
- previous: '',
-});
diff --git a/sdk/src/ui/behavior/state-visuals.ts b/sdk/src/ui/behavior/state-visuals.ts
deleted file mode 100644
index 1e4eb762c..000000000
--- a/sdk/src/ui/behavior/state-visuals.ts
+++ /dev/null
@@ -1,64 +0,0 @@
-// SPDX-License-Identifier: Apache-2.0
-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-/**
- * @file ui/behavior/state-visuals.ts
- * @brief StateVisuals — named state → visual overrides.
- *
- * A variable-length `states` list replaced the old 8 hardcoded `slotN*` field
- * quartets + stringly-keyed reflection. The apply system reads the entity's
- * StateMachine.current, finds the matching {@link VisualState} by name, and
- * applies its color/sprite/scale to `targetGraphic`. Mirrors the C++
- * `StateVisuals` builtin; `VisualState` mirrors the C++ POD (flat r/g/b/a so it
- * round-trips through the embind vector path).
- */
-import { defineBuiltin } from '../../component';
-import type { Color, Entity } from '../../types';
-
-export const TransitionFlag = {
- None: 0,
- ColorTint: 1 << 0,
- SpriteSwap: 1 << 1,
- Scale: 1 << 2,
-} as const;
-
-export type TransitionFlag = (typeof TransitionFlag)[keyof typeof TransitionFlag];
-
-/** One named visual state (mirrors the C++ VisualState; color is flat r/g/b/a). */
-export interface VisualState {
- name: string;
- r: number;
- g: number;
- b: number;
- a: number;
- /** Texture-handle id for sprite swap; 0 = none. */
- sprite: number;
- scale: number;
-}
-
-export interface StateVisualsData {
- targetGraphic: Entity;
- transitionFlags: number;
- fadeDuration: number;
- states: VisualState[];
-}
-
-/** Build a {@link VisualState} from a name + Color (+ optional sprite/scale). */
-export function visualState(
- name: string,
- color: Color,
- opts: { sprite?: number; scale?: number } = {},
-): VisualState {
- return {
- name,
- r: color.r, g: color.g, b: color.b, a: color.a,
- sprite: opts.sprite ?? 0,
- scale: opts.scale ?? 1,
- };
-}
-
-export const StateVisuals = defineBuiltin<StateVisualsData>('StateVisuals', {
- targetGraphic: 0 as Entity,
- transitionFlags: 0,
- fadeDuration: 0,
- states: [],
-});
diff --git a/sdk/src/ui/behavior/systems.ts b/sdk/src/ui/behavior/systems.ts
deleted file mode 100644
index eba475575..000000000
--- a/sdk/src/ui/behavior/systems.ts
+++ /dev/null
@@ -1,224 +0,0 @@
-// SPDX-License-Identifier: Apache-2.0
-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-import { defineSystem, type SystemDef } from '../../system';
-import { Transform, type TransformData } from '../../component';
-import { Res, Time, type TimeData } from '../../resource';
-import type { Entity, Color } from '../../types';
-import type { World } from '../../world';
-
-import { Interactable, UIInteraction, type InteractableData, type UIInteractionData } from '../input/interactable';
-import { StateMachine, type StateMachineData } from './state-machine';
-import {
- StateVisuals,
- TransitionFlag,
- type StateVisualsData,
-} from './state-visuals';
-import { UIVisual, type UIVisualData } from '../core/ui-visual';
-import { UIEventType, type UIEventQueue } from '../core/events';
-
-/**
- * State names that the interactable driver owns. If StateMachine.current
- * holds any other value, it was set by user code (e.g. "loading") and
- * the driver must not overwrite it.
- */
-const DRIVER_OWNED_STATES: ReadonlySet<string> = new Set([
- '', 'normal', 'hover', 'pressed', 'disabled',
-]);
-
-/**
- * Pure derivation: choose the state a hit-test pass implies.
- * Extracted so unit tests can cover the branching without a World.
- */
-export function driverStateFor(
- enabled: boolean,
- interaction: UIInteractionData | null,
-): string {
- if (!enabled) return 'disabled';
- if (interaction?.pressed) return 'pressed';
- if (interaction?.hovered) return 'hover';
- return 'normal';
-}
-
-/**
- * Pure lookup: index into `sv.states` of the VisualState whose name matches
- * `state`. Returns -1 if none matches (caller should skip applying visuals).
- */
-export function findStateSlot(sv: StateVisualsData, state: string): number {
- if (state === '') return -1;
- return sv.states.findIndex(s => s.name === state);
-}
-
-/**
- * Writes StateMachine.current based on Interactable + UIInteraction.
- * Leaves user-managed states (anything outside DRIVER_OWNED_STATES) alone.
- */
-export function createInteractableDriverSystem(world: World): SystemDef {
- return defineSystem([], () => {
- const entities = world.getEntitiesWithComponents([Interactable, StateMachine]);
- for (const e of entities) {
- const sm = world.get(e, StateMachine) as StateMachineData;
- if (!DRIVER_OWNED_STATES.has(sm.current)) continue;
-
- const inter = world.has(e, UIInteraction)
- ? (world.get(e, UIInteraction) as UIInteractionData)
- : null;
- const interactable = world.get(e, Interactable) as InteractableData;
- const next = driverStateFor(interactable.enabled, inter);
- if (next !== sm.current) {
- sm.current = next;
- world.insert(e, StateMachine, sm);
- }
- }
- }, { name: 'InteractableDriverSystem' });
-}
-
-/**
- * Emits a `state_changed` event on every StateMachine whose `current`
- * differs from `previous`, then advances `previous` to match.
- */
-export function createStateMachineDiffSystem(
- world: World,
- events: UIEventQueue,
-): SystemDef {
- return defineSystem([], () => {
- const entities = world.getEntitiesWithComponents([StateMachine]);
- for (const e of entities) {
- const sm = world.get(e, StateMachine) as StateMachineData;
- if (sm.current === sm.previous) continue;
- events.emit(e, UIEventType.StateChanged, {
- from: sm.previous,
- to: sm.current,
- });
- sm.previous = sm.current;
- world.insert(e, StateMachine, sm);
- }
- }, { name: 'StateMachineDiffSystem' });
-}
-
-/**
- * Per-entity transition bookkeeping for StateVisualsApplySystem.
- *
- * Kept in a closure Map rather than an ECS component so the state is
- * invisible to serialization and GC'd naturally when an entity's
- * StateVisuals row disappears (stale entries are purged lazily via
- * `world.valid` and slot-change checks). Color and scalar scale fade
- * continuously over `sv.fadeDuration`; sprite swaps snap (can't lerp
- * between two discrete texture handles).
- */
-interface VisualTransitionState {
- readonly toSlot: number;
- elapsed: number;
- /** Snapshot of the target's color at the moment the transition started. */
- readonly startColor: Color;
- /** Snapshot of the target's uniform scale at the moment the transition started. */
- readonly startScale: number;
- /** Settled at `toSlot`: visuals are written, so skip all work until the slot changes. */
- done: boolean;
-}
-
-function lerp(a: number, b: number, t: number): number {
- return a + (b - a) * t;
-}
-
-function lerpColor(from: Color, to: Color, t: number): Color {
- return {
- r: lerp(from.r, to.r, t),
- g: lerp(from.g, to.g, t),
- b: lerp(from.b, to.b, t),
- a: lerp(from.a, to.a, t),
- };
-}
-
-/**
- * Reads StateMachine.current, looks up the matching StateVisuals slot,
- * and applies the selected visual dimensions (color / sprite / scale)
- * to the targetGraphic entity (or the owning entity when unset).
- *
- * When `fadeDuration > 0` and the target slot changed from the last
- * frame's, color and scale continuously interpolate from whatever value
- * the target already had over `fadeDuration` seconds. Sprite swaps are
- * discrete and still snap (no meaningful interpolation between textures).
- */
-export function createStateVisualsApplySystem(world: World): SystemDef {
- const transitions = new Map<Entity, VisualTransitionState>();
-
- return defineSystem([Res(Time)], (time: TimeData) => {
- const dt = time.delta;
- const entities = world.getEntitiesWithComponents([StateMachine, StateVisuals]);
- const seen = new Set<Entity>();
-
- for (const e of entities) {
- seen.add(e);
- const sm = world.get(e, StateMachine) as StateMachineData;
- const sv = world.get(e, StateVisuals) as StateVisualsData;
- const slot = findStateSlot(sv, sm.current);
- if (slot < 0) {
- transitions.delete(e);
- continue;
- }
-
- const target = sv.targetGraphic !== 0 ? sv.targetGraphic : e;
- const flags = sv.transitionFlags;
- const state = sv.states[slot];
- const targetColor: Color = { r: state.r, g: state.g, b: state.b, a: state.a };
- const targetScale = state.scale;
- const fade = Math.max(0, sv.fadeDuration);
-
- // Detect a slot change. If we have no prior entry OR the entry
- // points at a different slot, seed a new transition with the
- // target's *current* values as the "from" endpoint so the fade
- // blends from whatever the user/driver left there.
- let tx = transitions.get(e);
- if (!tx || tx.toSlot !== slot) {
- const startColor = (flags & TransitionFlag.ColorTint) && world.has(target, UIVisual)
- ? { ...(world.get(target, UIVisual) as UIVisualData).color }
- : { ...targetColor };
- const startScale = (flags & TransitionFlag.Scale) && world.has(target, Transform)
- ? (world.get(target, Transform) as TransformData).scale.x
- : targetScale;
- tx = { toSlot: slot, elapsed: 0, startColor, startScale, done: false };
- transitions.set(e, tx);
- } else if (tx.done) {
- // Already settled at this slot: the visuals hold their target
- // values, so skip the per-frame get/insert wasm round-trips until
- // the state (and thus the slot) actually changes.
- continue;
- } else {
- tx.elapsed += dt;
- }
-
- const t = fade > 0 ? Math.min(tx.elapsed / fade, 1) : 1;
-
- if ((flags & TransitionFlag.ColorTint) && world.has(target, UIVisual)) {
- const r = world.get(target, UIVisual) as UIVisualData;
- r.color = t >= 1 ? targetColor : lerpColor(tx.startColor, targetColor, t);
- world.insert(target, UIVisual, r);
- }
-
- if ((flags & TransitionFlag.SpriteSwap) && world.has(target, UIVisual)) {
- // Sprite swap is discrete: apply immediately at the slot change.
- const r = world.get(target, UIVisual) as UIVisualData;
- r.texture = state.sprite;
- world.insert(target, UIVisual, r);
- }
-
- if ((flags & TransitionFlag.Scale) && world.has(target, Transform)) {
- const tr = world.get(target, Transform) as TransformData;
- const s = t >= 1 ? targetScale : lerp(tx.startScale, targetScale, t);
- tr.scale = { x: s, y: s, z: 1 };
- world.insert(target, Transform, tr);
- }
-
- if (t >= 1) {
- tx.done = true;
- }
- }
-
- // Purge entries whose entity vanished or no longer carries the components.
- if (transitions.size > 0) {
- for (const e of transitions.keys()) {
- if (!seen.has(e) || !world.valid(e)) transitions.delete(e);
- }
- }
- }, { name: 'StateVisualsApplySystem' });
-}
diff --git a/sdk/src/ui/behavior/theme-apply.ts b/sdk/src/ui/behavior/theme-apply.ts
index a64405132..b2adc3a08 100644
--- a/sdk/src/ui/behavior/theme-apply.ts
+++ b/sdk/src/ui/behavior/theme-apply.ts
@@ -7,22 +7,25 @@
*
* This is what makes {@link switchTheme} restyle already-constructed widgets, not
* just future ones — the piece a colors-baked-at-construction model otherwise
- * can't express. Lives here (not in `theme/`) because it touches `StateVisuals`
- * (this layer) plus `UIVisual`/`Text` (core); `theme/` is cross-cutting and may
- * not import up into behaviors.
+ * can't express. Lives here (not in `theme/`) because it touches the widgets'
+ * `$interaction` colour gears (behavior state) plus `UIVisual`/`Text` (core);
+ * `theme/` is cross-cutting and may not import up into behaviors.
*/
import type { World } from '../../world';
+import type { Color } from '../../types';
import { ThemeStyle, type ThemeStyleData } from '../theme/theme-style';
import { setTheme, themeColors, type ThemeTokens } from '../theme/tokens';
import { UIVisual, type UIVisualData } from '../core/ui-visual';
import { Text, type TextData } from '../core/text';
-import { StateVisuals, type StateVisualsData } from './state-visuals';
+import { INTERACTION_CONTROLLER } from '../controller/ui-controller';
+import { UIGear, type UIGearData } from '../controller/ui-gear';
/**
* Re-resolve every {@link ThemeStyle} entity's role bindings and write the active
- * theme's colors into its `UIVisual`/`Text`/`StateVisuals`. The existing **alpha
- * is preserved** — only the hue re-themes — so a dimmed `disabled` state keeps its
- * transparency, and a caller's translucency survives a swap.
+ * theme's colors into its `UIVisual`/`Text`/`$interaction` colour gear pages. The
+ * existing **alpha is preserved** — only the hue re-themes — so a dimmed
+ * `disabled` state keeps its transparency, and a caller's translucency survives
+ * a swap.
*/
export function applyThemeToWorld(world: World): void {
const colors = themeColors();
@@ -39,15 +42,21 @@ export function applyThemeToWorld(world: World): void {
const c = colors[s.text];
world.insert(e, Text, { ...t, color: { r: c.r, g: c.g, b: c.b, a: t.color.a } });
}
- if (s.states && world.has(e, StateVisuals)) {
- const sv = world.get(e, StateVisuals) as StateVisualsData;
- const states = sv.states.map((st) => {
- const role = s.states![st.name];
- if (!role) return st;
- const c = colors[role];
- return { ...st, r: c.r, g: c.g, b: c.b }; // keep st.a
+ if (s.states && world.has(e, UIGear)) {
+ const g = world.get(e, UIGear) as UIGearData;
+ const bindings = g.bindings.map((b) => {
+ if (b.controller !== INTERACTION_CONTROLLER
+ || b.component !== 'UIVisual' || b.property !== 'color') return b;
+ const pages = { ...b.pages };
+ for (const [page, role] of Object.entries(s.states!)) {
+ const cur = pages[page];
+ if (cur === undefined || typeof cur !== 'object') continue;
+ const c = colors[role];
+ pages[page] = { r: c.r, g: c.g, b: c.b, a: (cur as Color).a }; // keep alpha
+ }
+ return { ...b, pages };
});
- world.insert(e, StateVisuals, { ...sv, states });
+ world.insert(e, UIGear, { ...g, bindings });
}
}
}
diff --git a/sdk/src/ui/controller/gear-apply.ts b/sdk/src/ui/controller/gear-apply.ts
index a5ced3f36..903571443 100644
--- a/sdk/src/ui/controller/gear-apply.ts
+++ b/sdk/src/ui/controller/gear-apply.ts
@@ -4,12 +4,11 @@
* @file ui/controller/gear-apply.ts
* @brief The systems that turn controller pages into applied field values.
*
- * Two systems, both modelled on the proven StateVisualsApplySystem shape:
+ * Two systems:
*
* • InteractionControllerDriverSystem — writes the `$interaction` controller's
- * `current` page from pointer state (reusing `driverStateFor`), so a button
- * built from UIController + gears reproduces normal/hover/pressed/disabled
- * with no bespoke StateMachine.
+ * `current` page from pointer state (via `driverStateFor`), so a button
+ * built from UIController + gears gets normal/hover/pressed/disabled for free.
* • GearApplySystem — for every UIGear binding, resolves its controller's page,
* looks up the page's value, and writes it to the target field, snapping or
* tweening. It runs in edit mode too (not play-gated): setting a controller's
@@ -24,7 +23,6 @@ import { Res, Time, type TimeData } from '../../resource';
import { applyEasing } from '../../animation/Easing';
import { EntityStateMap } from '../util/helpers';
import { Interactable, UIInteraction, type InteractableData, type UIInteractionData } from '../input/interactable';
-import { driverStateFor } from '../behavior/systems';
import type { Entity } from '../../types';
import type { World } from '../../world';
import {
@@ -110,18 +108,41 @@ export function lerpGearValue(from: unknown, to: unknown, t: number): unknown {
// ─── Systems ────────────────────────────────────────────────────────────────
/**
- * Writes the `$interaction` controller's page from Interactable + UIInteraction,
- * reusing the same pure derivation the legacy StateMachine driver uses. Only
- * touches entities that actually declare a `$interaction` controller, and only
+ * Pages the `$interaction` driver owns. If the controller's `current` holds any
+ * other value, user code set it (e.g. "loading" via {@link setButtonState}) and
+ * the driver must not steal it back.
+ */
+const DRIVER_OWNED_PAGES: ReadonlySet<string> = new Set([
+ '', 'normal', 'hover', 'pressed', 'disabled',
+]);
+
+/**
+ * Pure derivation: choose the interaction page a hit-test pass implies.
+ * Extracted so unit tests can cover the branching without a World.
+ */
+export function driverStateFor(
+ enabled: boolean,
+ interaction: UIInteractionData | null,
+): string {
+ if (!enabled) return 'disabled';
+ if (interaction?.pressed) return 'pressed';
+ if (interaction?.hovered) return 'hover';
+ return 'normal';
+}
+
+/**
+ * Writes the `$interaction` controller's page from Interactable + UIInteraction.
+ * Only touches entities that actually declare a `$interaction` controller, only
* to a page the controller lists — so a controller with a custom page set (say
- * no "disabled") is never forced into a page it doesn't have.
+ * no "disabled") is never forced into a page it doesn't have — and never while
+ * `current` holds a user-managed page outside {@link DRIVER_OWNED_PAGES}.
*/
export function createInteractionControllerDriverSystem(world: World): SystemDef {
return defineSystem([], () => {
for (const e of world.getEntitiesWithComponents([Interactable, UIController])) {
const data = world.get(e, UIController) as UIControllerData;
const ctrl = data.controllers.find(c => c.name === INTERACTION_CONTROLLER);
- if (!ctrl) continue;
+ if (!ctrl || !DRIVER_OWNED_PAGES.has(ctrl.current)) continue;
const inter = world.has(e, UIInteraction)
? (world.get(e, UIInteraction) as UIInteractionData)
@@ -151,8 +172,7 @@ interface BindingTx {
* Applies every UIGear binding from its controller's current page. Snaps when the
* binding has no tween (or the value can't interpolate); otherwise eases from the
* field's value at page-change time over `tween.duration`. Idle bindings settle
- * (stop writing) until their page changes, matching StateVisuals' write-once
- * behaviour so a static UI costs nothing per frame.
+ * (stop writing) until their page changes, so a static UI costs nothing per frame.
*/
export function createGearApplySystem(world: World): SystemDef {
const tracker = new EntityStateMap<Array<BindingTx | null>>();
diff --git a/sdk/src/ui/controller/ui-controller.ts b/sdk/src/ui/controller/ui-controller.ts
index d5e295745..e69e726ef 100644
--- a/sdk/src/ui/controller/ui-controller.ts
+++ b/sdk/src/ui/controller/ui-controller.ts
@@ -4,11 +4,10 @@
* @file ui/controller/ui-controller.ts
* @brief UIController — a shared, named enum-state ("pages") scoped to a UI root.
*
- * The shared, multi-page generalization of the per-entity `StateMachine`: where
- * that holds one entity's interaction state, a controller is a named state that
- * MANY descendant elements subscribe to. Expressed as a plain TS-side
- * `defineComponent` (same class as StateMachineAgent / TimelinePlayer / the
- * physics joints — no C++ struct, serializes through the prefab/scene path). A
+ * A controller is a named state that MANY descendant elements subscribe to —
+ * one enum on the UI root, arbitrarily many geared leaves. Expressed as a plain
+ * TS-side `defineComponent` (same class as StateMachineAgent / TimelinePlayer /
+ * the physics joints — no C++ struct, serializes through the prefab/scene path). A
* controller is deliberately a *dumb enum*, not an FSM: it names a set of `pages`
* and holds the `current` one. Deciding *when* to switch pages is someone else's
* job — game code calling {@link setControllerPage}, the `$interaction` driver,
@@ -43,8 +42,8 @@ export const UIController = defineComponent<UIControllerData>('UIController', {
/**
* The built-in controller name driven by pointer state (normal/hover/pressed/
* disabled). An entity that carries a `$interaction` controller + Interactable
- * gets its button states through gears — the unified replacement for the bespoke
- * StateMachine + StateVisuals pair (color/sprite/scale generalized to any field).
+ * gets its button states through gears — the one mechanism for all widget
+ * interaction visuals (color/sprite/scale, or any other reflected field).
*/
export const INTERACTION_CONTROLLER = '$interaction';
diff --git a/sdk/src/ui/controller/ui-gear.ts b/sdk/src/ui/controller/ui-gear.ts
index d454191a0..09e723a7f 100644
--- a/sdk/src/ui/controller/ui-gear.ts
+++ b/sdk/src/ui/controller/ui-gear.ts
@@ -4,8 +4,8 @@
* @file ui/controller/ui-gear.ts
* @brief UIGear — declarative "per-page value" bindings from a controller.
*
- * The generalization of `StateVisuals` from a fixed colour/sprite/scale trio to
- * ANY reflected field. Each {@link GearBinding} says: "while controller C is on
+ * Per-page overrides for ANY reflected field — not a fixed visual trio. Each
+ * {@link GearBinding} says: "while controller C is on
* page P, this component field should hold value V." One entity can carry many
* bindings, each pointing at a different (controller, field) — so a single
* element's colour follows the interaction controller while its position follows
diff --git a/sdk/src/ui/core/events.ts b/sdk/src/ui/core/events.ts
index 1c5d5b24b..cdf6a9622 100644
--- a/sdk/src/ui/core/events.ts
+++ b/sdk/src/ui/core/events.ts
@@ -25,7 +25,6 @@ export const UIEventType = {
Scroll: 'scroll',
Select: 'select',
Deselect: 'deselect',
- StateChanged: 'state_changed',
} as const;
/**
@@ -36,7 +35,7 @@ export const UIEventType = {
export type UIEventType = typeof UIEventType[keyof typeof UIEventType];
export interface UIEvent<TData = unknown> {
- /** Event type string (e.g. `'click'`, `'state_changed'`). */
+ /** Event type string (e.g. `'click'`, `'change'`). */
readonly type: string;
/** The entity where the event originated. */
readonly target: Entity;
diff --git a/sdk/src/ui/index.ts b/sdk/src/ui/index.ts
index c1859ca57..900888b39 100644
--- a/sdk/src/ui/index.ts
+++ b/sdk/src/ui/index.ts
@@ -112,19 +112,6 @@ export {
type UIInteractionData,
} from './input/interactable';
-export {
- StateMachine,
- type StateMachineData,
-} from './behavior/state-machine';
-
-export {
- StateVisuals,
- TransitionFlag,
- visualState,
- type VisualState,
- type StateVisualsData,
-} from './behavior/state-visuals';
-
export {
Focusable,
FocusManager,
@@ -139,14 +126,6 @@ export {
type DragStateData,
} from './input/draggable';
-export {
- driverStateFor,
- findStateSlot,
- createInteractableDriverSystem,
- createStateMachineDiffSystem,
- createStateVisualsApplySystem,
-} from './behavior/systems';
-
export { UIBehaviorPlugin, uiBehaviorPlugin } from './behavior/plugin';
// ─── Controllers + Gears (shared UI state) ──────────────────────────────────
@@ -176,6 +155,7 @@ export {
export {
createInteractionControllerDriverSystem,
createGearApplySystem,
+ driverStateFor,
readFieldPath,
writeFieldPath,
isLerpable,
@@ -251,6 +231,7 @@ export {
createButton,
setButtonState,
themeButtonStates,
+ interactionGears,
type ButtonOptions,
type ButtonStateVisual,
} from './widgets/button';
diff --git a/sdk/src/ui/theme/theme-style.ts b/sdk/src/ui/theme/theme-style.ts
index 9db694336..87f9d45ec 100644
--- a/sdk/src/ui/theme/theme-style.ts
+++ b/sdk/src/ui/theme/theme-style.ts
@@ -6,7 +6,7 @@
* {@link ThemeColors} role each of an entity's themeable properties uses.
*
* It is the missing link for live re-theming: widgets bake a theme's colors into
- * `UIVisual`/`Text`/`StateVisuals` at construction, so without recording the
+ * `UIVisual`/`Text`/their `$interaction` colour gears at construction, so without recording the
* *role* there is no way to re-resolve them when the theme changes. A widget tags
* the entities it themes (via {@link markThemed}); `applyThemeToWorld` re-resolves
* the tags against the active theme. Not serialized — it lives only on
@@ -25,7 +25,7 @@ export interface ThemeStyleData {
visual?: ColorRole;
/** Role that drives this entity's `Text.color`. */
text?: ColorRole;
- /** State-name → role, for each `StateVisuals` state color. */
+ /** Page-name → role, for each `$interaction` colour-gear page. */
states?: Record<string, ColorRole>;
}
diff --git a/sdk/src/ui/widgets/button.ts b/sdk/src/ui/widgets/button.ts
index 6e0bf4802..14120aa7b 100644
--- a/sdk/src/ui/widgets/button.ts
+++ b/sdk/src/ui/widgets/button.ts
@@ -3,15 +3,16 @@
import type { Color, Entity } from '../../types';
import type { World } from '../../world';
-import { Interactable, UIInteraction } from '../input/interactable';
-import { StateMachine } from '../behavior/state-machine';
+import { Interactable, UIInteraction, type InteractableData } from '../input/interactable';
import {
- StateVisuals,
- TransitionFlag,
- visualState,
- type VisualState,
- type StateVisualsData,
-} from '../behavior/state-visuals';
+ UIController,
+ INTERACTION_CONTROLLER,
+ INTERACTION_PAGES,
+ interactionController,
+ type UIControllerData,
+} from '../controller/ui-controller';
+import { UIGear, gearBinding, type GearBinding, type GearValue } from '../controller/ui-gear';
+import { EasingType } from '../../animation/Easing';
import { UIEventType, type UIEventQueue } from '../core/events';
import { themeColors, themeType } from '../theme/tokens';
import { markThemed } from '../theme/theme-style';
@@ -24,8 +25,8 @@ import {
} from './helpers';
/**
- * Visual overrides for a single button state. Omitted fields stay at
- * their slot default (color white, scale 1, no sprite).
+ * Visual overrides for a single button state. Omitted fields leave the
+ * live value alone on that state (the gear's sparse-page semantics).
*/
export interface ButtonStateVisual {
color?: Color;
@@ -45,26 +46,52 @@ export interface ButtonOptions {
text?: string | TextInit;
/**
* Map of state name (e.g. "normal", "hover", "pressed", "disabled")
- * to its visual override. The Interactable driver writes the four
+ * to its visual override. The `$interaction` driver writes the four
* canonical state names; callers may add more (e.g. "loading") and
- * flip them manually via `setState`. Omit to default to the active
- * theme's control roles ({@link themeButtonStates}).
+ * flip them manually via `setButtonState`. Omit to default to the
+ * active theme's control roles ({@link themeButtonStates}).
*/
states?: Record<string, ButtonStateVisual>;
- /** Combination of TransitionFlag values. Default: ColorTint. */
- transitionFlags?: number;
- /** Lerp time for ColorTint/Scale transitions. Default 0 (snap). */
+ /** Tween time for color/scale state changes. Default 0 (snap). */
fadeDuration?: number;
/** Start in the disabled state (Interactable.enabled = false). */
disabled?: boolean;
onClick?: (entity: Entity) => void;
}
-/** Map the state-name → override record to the VisualState[] list. */
-function buildStates(states: Record<string, ButtonStateVisual>): VisualState[] {
- return Object.entries(states).map(([name, v]) =>
- visualState(name, v.color ?? { r: 1, g: 1, b: 1, a: 1 },
- { sprite: v.sprite, scale: v.scale }));
+/**
+ * Fold the state-name → override record into per-field gear bindings on the
+ * `$interaction` controller. A field a state doesn't override gets no page
+ * entry there (sparse pages: the gear leaves it alone). Sprite swaps are
+ * discrete and always snap; color and scale tween over `fadeDuration`.
+ */
+export function interactionGears(
+ states: Record<string, ButtonStateVisual>,
+ fadeDuration = 0,
+): GearBinding[] {
+ const color: Record<string, GearValue> = {};
+ const sprite: Record<string, GearValue> = {};
+ const scale: Record<string, GearValue> = {};
+ for (const [page, v] of Object.entries(states)) {
+ if (v.color !== undefined) color[page] = { ...v.color };
+ if (v.sprite !== undefined) sprite[page] = v.sprite;
+ if (v.scale !== undefined) scale[page] = { x: v.scale, y: v.scale, z: 1 };
+ }
+ const tween = fadeDuration > 0
+ ? { easing: EasingType.Linear, duration: fadeDuration }
+ : undefined;
+
+ const bindings: GearBinding[] = [];
+ if (Object.keys(color).length > 0) {
+ bindings.push(gearBinding(INTERACTION_CONTROLLER, 'UIVisual', 'color', color, tween));
+ }
+ if (Object.keys(sprite).length > 0) {
+ bindings.push(gearBinding(INTERACTION_CONTROLLER, 'UIVisual', 'texture', sprite));
+ }
+ if (Object.keys(scale).length > 0) {
+ bindings.push(gearBinding(INTERACTION_CONTROLLER, 'Transform', 'scale', scale, tween));
+ }
+ return bindings;
}
/** The canonical button state colors from the active theme's control roles —
@@ -81,11 +108,11 @@ export function themeButtonStates(): Record<string, ButtonStateVisual> {
}
/**
- * Spawn a clickable button entity composed of Interactable +
- * StateMachine + StateVisuals, optionally with a child Text label.
+ * Spawn a clickable button entity composed of Interactable + a `$interaction`
+ * UIController + UIGear state bindings, optionally with a child Text label.
*
- * Click is detected via state_changed (`pressed` → `hover`): the
- * canonical "released while still over the button" gesture.
+ * Click comes straight from the interaction layer's `click` event (released
+ * while still over the button); the handler is gated on Interactable.enabled.
*/
export function createButton(opts: ButtonOptions): Entity {
const { world, events } = opts;
@@ -105,18 +132,19 @@ export function createButton(opts: ButtonOptions): Entity {
world.insert(entity, UIInteraction, {
hovered: false, pressed: false, justPressed: false, justReleased: false,
});
- world.insert(entity, StateMachine, {
- current: opts.disabled ? 'disabled' : 'normal',
- previous: '',
- });
- const visuals: StateVisualsData = {
- targetGraphic: 0 as Entity,
- transitionFlags: opts.transitionFlags ?? TransitionFlag.ColorTint,
- fadeDuration: opts.fadeDuration ?? 0,
- states: buildStates(opts.states ?? themeButtonStates()),
- };
- world.insert(entity, StateVisuals, visuals);
+ const states = opts.states ?? themeButtonStates();
+ // Canonical pages first (the driver's vocabulary), then any custom states
+ // (e.g. "loading") so setButtonState can flip to them.
+ const pages = [
+ ...INTERACTION_PAGES,
+ ...Object.keys(states).filter((s) => !(INTERACTION_PAGES as readonly string[]).includes(s)),
+ ];
+ const ctrl = interactionController(pages);
+ ctrl.current = opts.disabled ? 'disabled' : 'normal';
+ world.insert(entity, UIController, { controllers: [ctrl] });
+ world.insert(entity, UIGear, { bindings: interactionGears(states, opts.fadeDuration ?? 0) });
+
// Only theme-managed default states re-resolve on a theme swap; caller-supplied
// colors are the caller's own.
if (opts.states === undefined) {
@@ -140,11 +168,9 @@ export function createButton(opts: ButtonOptions): Entity {
if (opts.onClick) {
const handler = opts.onClick;
- events.on(entity, UIEventType.StateChanged, (event) => {
- const data = event.data as { from: string; to: string };
- if (data.from === 'pressed' && data.to === 'hover') {
- handler(entity);
- }
+ events.on(entity, UIEventType.Click, () => {
+ const interactable = world.get(entity, Interactable) as InteractableData;
+ if (interactable.enabled) handler(entity);
});
}
@@ -152,13 +178,16 @@ export function createButton(opts: ButtonOptions): Entity {
}
/**
- * Imperatively set a button's state string. Useful for custom states
- * like "loading" that the Interactable driver does not manage.
+ * Imperatively set a button's `$interaction` page. Useful for custom states
+ * like "loading" that the pointer driver does not manage — the driver leaves
+ * any non-canonical page alone until user code switches back.
*/
export function setButtonState(world: World, entity: Entity, state: string): void {
- if (!world.has(entity, StateMachine)) return;
- const sm = world.get(entity, StateMachine) as { current: string; previous: string };
- if (sm.current === state) return;
- sm.current = state;
- world.insert(entity, StateMachine, sm);
+ if (!world.has(entity, UIController)) return;
+ const data = world.get(entity, UIController) as UIControllerData;
+ const ctrl = data.controllers.find((c) => c.name === INTERACTION_CONTROLLER);
+ if (!ctrl || ctrl.current === state) return;
+ if (!ctrl.pages.includes(state)) ctrl.pages.push(state);
+ ctrl.current = state;
+ world.insert(entity, UIController, data);
}
diff --git a/sdk/src/ui/widgets/dropdown.ts b/sdk/src/ui/widgets/dropdown.ts
index e81016dcc..17bd226cf 100644
--- a/sdk/src/ui/widgets/dropdown.ts
+++ b/sdk/src/ui/widgets/dropdown.ts
@@ -4,8 +4,9 @@ import type { Color, Entity } from '../../types';
import type { World } from '../../world';
import { Interactable, UIInteraction } from '../input/interactable';
-import { StateMachine } from '../behavior/state-machine';
-import { StateVisuals, TransitionFlag, visualState, type StateVisualsData } from '../behavior/state-visuals';
+import { UIController, interactionController } from '../controller/ui-controller';
+import { UIGear } from '../controller/ui-gear';
+import { interactionGears } from './button';
import { UIEventType, type UIEventQueue } from '../core/events';
import { Text, type TextData } from '../core/text';
@@ -60,19 +61,22 @@ const INTERACTION_DEFAULT = {
hovered: false, pressed: false, justPressed: false, justReleased: false,
};
-function makeStatesSV(colors: {
- normal: Color; hover: Color; pressed: Color;
-}): StateVisualsData {
- return {
- targetGraphic: 0 as Entity,
- transitionFlags: TransitionFlag.ColorTint,
- fadeDuration: 0,
- states: [
- visualState('normal', colors.normal),
- visualState('hover', colors.hover),
- visualState('pressed', colors.pressed),
- ],
- };
+/** Attach a `$interaction` controller + a color gear over its three pages. */
+function addInteractionStates(
+ world: World,
+ entity: Entity,
+ colors: { normal: Color; hover: Color; pressed: Color },
+): void {
+ world.insert(entity, UIController, {
+ controllers: [interactionController(['normal', 'hover', 'pressed'])],
+ });
+ world.insert(entity, UIGear, {
+ bindings: interactionGears({
+ normal: { color: colors.normal },
+ hover: { color: colors.hover },
+ pressed: { color: colors.pressed },
+ }),
+ });
}
/**
@@ -109,8 +113,7 @@ export function createDropdown<T>(opts: DropdownOptions<T>): DropdownHandle<T> {
});
world.insert(button, Interactable, { enabled: true, blockRaycast: true, raycastTarget: true });
world.insert(button, UIInteraction, INTERACTION_DEFAULT);
- world.insert(button, StateMachine, { current: 'normal', previous: '' });
- world.insert(button, StateVisuals, makeStatesSV(btnColors));
+ addInteractionStates(world, button, btnColors);
if (opts.buttonStates === undefined) {
markThemed(world, button, { states: { normal: 'control', hover: 'controlHover', pressed: 'controlActive' } });
}
@@ -151,12 +154,7 @@ export function createDropdown<T>(opts: DropdownOptions<T>): DropdownHandle<T> {
for (let i = 0; i < opts.options.length; i++) {
const index = i;
const row = spawnOptionRow(index);
- const off = events.on(row, UIEventType.StateChanged, (e) => {
- const d = e.data as { from: string; to: string };
- if (d.from === 'pressed' && d.to === 'hover') {
- selectAndClose(index);
- }
- });
+ const off = events.on(row, UIEventType.Click, () => selectAndClose(index));
optionUnsubs.push(off);
}
}
@@ -177,8 +175,7 @@ export function createDropdown<T>(opts: DropdownOptions<T>): DropdownHandle<T> {
});
world.insert(row, Interactable, { enabled: true, blockRaycast: true, raycastTarget: true });
world.insert(row, UIInteraction, INTERACTION_DEFAULT);
- world.insert(row, StateMachine, { current: 'normal', previous: '' });
- world.insert(row, StateVisuals, makeStatesSV(optColors));
+ addInteractionStates(world, row, optColors);
spawnUIEntity({
world,
@@ -216,11 +213,8 @@ export function createDropdown<T>(opts: DropdownOptions<T>): DropdownHandle<T> {
}
// Click on button toggles popup.
- const offButtonClick = events.on(button, UIEventType.StateChanged, (e) => {
- const d = e.data as { from: string; to: string };
- if (d.from === 'pressed' && d.to === 'hover') {
- isOpen() ? close() : open();
- }
+ const offButtonClick = events.on(button, UIEventType.Click, () => {
+ isOpen() ? close() : open();
});
return {
diff --git a/sdk/src/ui/widgets/prefabs/Button.esprefab b/sdk/src/ui/widgets/prefabs/Button.esprefab
index a29141788..242785c80 100644
--- a/sdk/src/ui/widgets/prefabs/Button.esprefab
+++ b/sdk/src/ui/widgets/prefabs/Button.esprefab
@@ -171,45 +171,50 @@
}
},
{
- "type": "StateMachine",
+ "type": "UIController",
"data": {
- "current": "normal",
- "previous": ""
+ "controllers": [
+ {
+ "name": "$interaction",
+ "pages": [
+ "normal",
+ "hover",
+ "pressed",
+ "disabled"
+ ],
+ "current": "normal"
+ }
+ ]
}
},
{
- "type": "StateVisuals",
+ "type": "UIGear",
"data": {
- "targetGraphic": 0,
- "transitionFlags": 1,
- "fadeDuration": 0,
- "states": [
- {
- "name": "normal",
- "r": 0.22,
- "g": 0.22,
- "b": 0.26,
- "a": 1,
- "sprite": 0,
- "scale": 1
- },
- {
- "name": "hover",
- "r": 0.28,
- "g": 0.28,
- "b": 0.32,
- "a": 1,
- "sprite": 0,
- "scale": 1
- },
+ "bindings": [
{
- "name": "pressed",
- "r": 0.18,
- "g": 0.18,
- "b": 0.22,
- "a": 1,
- "sprite": 0,
- "scale": 1
+ "controller": "$interaction",
+ "component": "UIVisual",
+ "property": "color",
+ "pages": {
+ "normal": {
+ "r": 0.22,
+ "g": 0.22,
+ "b": 0.26,
+ "a": 1
+ },
+ "hover": {
+ "r": 0.28,
+ "g": 0.28,
+ "b": 0.32,
+ "a": 1
+ },
+ "pressed": {
+ "r": 0.18,
+ "g": 0.18,
+ "b": 0.22,
+ "a": 1
+ }
+ }
}
]
}
diff --git a/sdk/src/ui/widgets/prefabs/Dropdown.esprefab b/sdk/src/ui/widgets/prefabs/Dropdown.esprefab
index 5e1e21b68..284a95f94 100644
--- a/sdk/src/ui/widgets/prefabs/Dropdown.esprefab
+++ b/sdk/src/ui/widgets/prefabs/Dropdown.esprefab
@@ -171,45 +171,49 @@
}
},
{
- "type": "StateMachine",
+ "type": "UIController",
"data": {
- "current": "normal",
- "previous": ""
+ "controllers": [
+ {
+ "name": "$interaction",
+ "pages": [
+ "normal",
+ "hover",
+ "pressed"
+ ],
+ "current": "normal"
+ }
+ ]
}
},
{
- "type": "StateVisuals",
+ "type": "UIGear",
"data": {
- "targetGraphic": 0,
- "transitionFlags": 1,
- "fadeDuration": 0,
- "states": [
- {
- "name": "normal",
- "r": 0.22,
- "g": 0.22,
- "b": 0.26,
- "a": 1,
- "sprite": 0,
- "scale": 1
- },
- {
- "name": "hover",
- "r": 0.28,
- "g": 0.28,
- "b": 0.32,
- "a": 1,
- "sprite": 0,
- "scale": 1
- },
+ "bindings": [
{
- "name": "pressed",
- "r": 0.18,
- "g": 0.18,
- "b": 0.22,
- "a": 1,
- "sprite": 0,
- "scale": 1
+ "controller": "$interaction",
+ "component": "UIVisual",
+ "property": "color",
+ "pages": {
+ "normal": {
+ "r": 0.22,
+ "g": 0.22,
+ "b": 0.26,
+ "a": 1
+ },
+ "hover": {
+ "r": 0.28,
+ "g": 0.28,
+ "b": 0.32,
+ "a": 1
+ },
+ "pressed": {
+ "r": 0.18,
+ "g": 0.18,
+ "b": 0.22,
+ "a": 1
+ }
+ }
}
]
}
diff --git a/sdk/src/ui/widgets/prefabs/Toggle.esprefab b/sdk/src/ui/widgets/prefabs/Toggle.esprefab
index 8b87acdd4..aeb0cbc5f 100644
--- a/sdk/src/ui/widgets/prefabs/Toggle.esprefab
+++ b/sdk/src/ui/widgets/prefabs/Toggle.esprefab
@@ -171,45 +171,50 @@
}
},
{
- "type": "StateMachine",
+ "type": "UIController",
"data": {
- "current": "normal",
- "previous": ""
+ "controllers": [
+ {
+ "name": "$interaction",
+ "pages": [
+ "normal",
+ "hover",
+ "pressed",
+ "disabled"
+ ],
+ "current": "normal"
+ }
+ ]
}
},
{
- "type": "StateVisuals",
+ "type": "UIGear",
"data": {
- "targetGraphic": 0,
- "transitionFlags": 1,
- "fadeDuration": 0,
- "states": [
- {
- "name": "normal",
- "r": 0.22,
- "g": 0.22,
- "b": 0.26,
- "a": 1,
- "sprite": 0,
- "scale": 1
- },
- {
- "name": "hover",
- "r": 0.28,
- "g": 0.28,
- "b": 0.32,
- "a": 1,
- "sprite": 0,
- "scale": 1
- },
+ "bindings": [
{
- "name": "pressed",
- "r": 0.18,
- "g": 0.18,
- "b": 0.22,
- "a": 1,
- "sprite": 0,
- "scale": 1
+ "controller": "$interaction",
+ "component": "UIVisual",
+ "property": "color",
+ "pages": {
+ "normal": {
+ "r": 0.22,
+ "g": 0.22,
+ "b": 0.26,
+ "a": 1
+ },
+ "hover": {
+ "r": 0.28,
+ "g": 0.28,
+ "b": 0.32,
+ "a": 1
+ },
+ "pressed": {
+ "r": 0.18,
+ "g": 0.18,
+ "b": 0.22,
+ "a": 1
+ }
+ }
}
]
}
diff --git a/sdk/src/ui/widgets/prefabs/generated.ts b/sdk/src/ui/widgets/prefabs/generated.ts
index 3767801e3..915075791 100644
--- a/sdk/src/ui/widgets/prefabs/generated.ts
+++ b/sdk/src/ui/widgets/prefabs/generated.ts
@@ -175,45 +175,50 @@ export const BUILTIN_UI_PREFABS: Record<string, PrefabData> = {
}
},
{
- "type": "StateMachine",
+ "type": "UIController",
"data": {
- "current": "normal",
- "previous": ""
+ "controllers": [
+ {
+ "name": "$interaction",
+ "pages": [
+ "normal",
+ "hover",
+ "pressed",
+ "disabled"
+ ],
+ "current": "normal"
+ }
+ ]
}
},
{
- "type": "StateVisuals",
+ "type": "UIGear",
"data": {
- "targetGraphic": 0,
- "transitionFlags": 1,
- "fadeDuration": 0,
- "states": [
- {
- "name": "normal",
- "r": 0.22,
- "g": 0.22,
- "b": 0.26,
- "a": 1,
- "sprite": 0,
- "scale": 1
- },
+ "bindings": [
{
- "name": "hover",
- "r": 0.28,
- "g": 0.28,
- "b": 0.32,
- "a": 1,
- "sprite": 0,
- "scale": 1
- },
- {
- "name": "pressed",
- "r": 0.18,
- "g": 0.18,
- "b": 0.22,
- "a": 1,
- "sprite": 0,
- "scale": 1
+ "controller": "$interaction",
+ "component": "UIVisual",
+ "property": "color",
+ "pages": {
+ "normal": {
+ "r": 0.22,
+ "g": 0.22,
+ "b": 0.26,
+ "a": 1
+ },
+ "hover": {
+ "r": 0.28,
+ "g": 0.28,
+ "b": 0.32,
+ "a": 1
+ },
+ "pressed": {
+ "r": 0.18,
+ "g": 0.18,
+ "b": 0.22,
+ "a": 1
+ }
+ }
}
]
}
@@ -552,45 +557,50 @@ export const BUILTIN_UI_PREFABS: Record<string, PrefabData> = {
}
},
{
- "type": "StateMachine",
+ "type": "UIController",
"data": {
- "current": "normal",
- "previous": ""
+ "controllers": [
+ {
+ "name": "$interaction",
+ "pages": [
+ "normal",
+ "hover",
+ "pressed",
+ "disabled"
+ ],
+ "current": "normal"
+ }
+ ]
}
},
{
- "type": "StateVisuals",
+ "type": "UIGear",
"data": {
- "targetGraphic": 0,
- "transitionFlags": 1,
- "fadeDuration": 0,
- "states": [
+ "bindings": [
{
- "name": "normal",
- "r": 0.22,
- "g": 0.22,
- "b": 0.26,
- "a": 1,
- "sprite": 0,
- "scale": 1
- },
- {
- "name": "hover",
- "r": 0.28,
- "g": 0.28,
- "b": 0.32,
- "a": 1,
- "sprite": 0,
- "scale": 1
- },
- {
- "name": "pressed",
- "r": 0.18,
- "g": 0.18,
- "b": 0.22,
- "a": 1,
- "sprite": 0,
- "scale": 1
+ "controller": "$interaction",
+ "component": "UIVisual",
+ "property": "color",
+ "pages": {
+ "normal": {
+ "r": 0.22,
+ "g": 0.22,
+ "b": 0.26,
+ "a": 1
+ },
+ "hover": {
+ "r": 0.28,
+ "g": 0.28,
+ "b": 0.32,
+ "a": 1
+ },
+ "pressed": {
+ "r": 0.18,
+ "g": 0.18,
+ "b": 0.22,
+ "a": 1
+ }
+ }
}
]
}
@@ -1698,45 +1708,49 @@ export const BUILTIN_UI_PREFABS: Record<string, PrefabData> = {
}
},
{
- "type": "StateMachine",
+ "type": "UIController",
"data": {
- "current": "normal",
- "previous": ""
+ "controllers": [
+ {
+ "name": "$interaction",
+ "pages": [
+ "normal",
+ "hover",
+ "pressed"
+ ],
+ "current": "normal"
+ }
+ ]
}
},
{
- "type": "StateVisuals",
+ "type": "UIGear",
"data": {
- "targetGraphic": 0,
- "transitionFlags": 1,
- "fadeDuration": 0,
- "states": [
- {
- "name": "normal",
- "r": 0.22,
- "g": 0.22,
- "b": 0.26,
- "a": 1,
- "sprite": 0,
- "scale": 1
- },
- {
- "name": "hover",
- "r": 0.28,
- "g": 0.28,
- "b": 0.32,
- "a": 1,
- "sprite": 0,
- "scale": 1
- },
+ "bindings": [
{
- "name": "pressed",
- "r": 0.18,
- "g": 0.18,
- "b": 0.22,
- "a": 1,
- "sprite": 0,
- "scale": 1
+ "controller": "$interaction",
+ "component": "UIVisual",
+ "property": "color",
+ "pages": {
+ "normal": {
+ "r": 0.22,
+ "g": 0.22,
+ "b": 0.26,
+ "a": 1
+ },
+ "hover": {
+ "r": 0.28,
+ "g": 0.28,
+ "b": 0.32,
+ "a": 1
+ },
+ "pressed": {
+ "r": 0.18,
+ "g": 0.18,
+ "b": 0.22,
+ "a": 1
+ }
+ }
}
]
}
diff --git a/sdk/src/ui/widgets/toggle.ts b/sdk/src/ui/widgets/toggle.ts
index 66036481e..031479829 100644
--- a/sdk/src/ui/widgets/toggle.ts
+++ b/sdk/src/ui/widgets/toggle.ts
@@ -4,6 +4,7 @@ import type { Color, Entity } from '../../types';
import type { World } from '../../world';
import { UIEventType, type UIEventQueue } from '../core/events';
+import { Interactable, type InteractableData } from '../input/interactable';
import { createButton, type ButtonStateVisual } from './button';
import { spawnUIEntity, setUIVisible, type UINodeInit, type UIVisualInit } from './helpers';
@@ -80,11 +81,9 @@ export function createToggle(opts: ToggleOptions): ToggleHandle {
setUIVisible(world, check, isOn);
- const offClick = events.on(button, UIEventType.StateChanged, (event) => {
- const data = event.data as { from: string; to: string };
- if (data.from === 'pressed' && data.to === 'hover') {
- setIsOn(!isOn);
- }
+ const offClick = events.on(button, UIEventType.Click, () => {
+ const interactable = world.get(button, Interactable) as InteractableData;
+ if (interactable.enabled) setIsOn(!isOn);
});
function setIsOn(value: boolean, silent = false): void {
diff --git a/sdk/src/wasm.generated.ts b/sdk/src/wasm.generated.ts
index d60dc38f8..a3bb9ca24 100644
--- a/sdk/src/wasm.generated.ts
+++ b/sdk/src/wasm.generated.ts
@@ -10,7 +10,6 @@ import type { Entity, Vec2, Vec3, Vec4, Quat } from './types';
export interface UVec2 { x: number; y: number; }
export interface Padding { left: number; top: number; right: number; bottom: number; }
export interface Dimension { value: number; unit: number; }
-export interface VisualState { name: string; r: number; g: number; b: number; a: number; sprite: number; scale: number; }
export type Mat4 = number[];
// Emscripten Vector Types
@@ -403,18 +402,6 @@ export interface Sprite {
enabled: boolean;
}
-export interface StateMachine {
- current: string;
- previous: string;
-}
-
-export interface StateVisuals {
- targetGraphic: number;
- transitionFlags: number;
- fadeDuration: number;
- states: VisualState[];
-}
-
export interface TilemapLayer {
cellSize: Vec2;
originOffset: Vec2;
@@ -589,14 +576,6 @@ export interface Registry {
getSprite(entity: Entity): Sprite;
addSprite(entity: Entity, component: Sprite): void;
removeSprite(entity: Entity): void;
- hasStateMachine(entity: Entity): boolean;
- getStateMachine(entity: Entity): StateMachine;
- addStateMachine(entity: Entity, component: StateMachine): void;
- removeStateMachine(entity: Entity): void;
- hasStateVisuals(entity: Entity): boolean;
- getStateVisuals(entity: Entity): StateVisuals;
- addStateVisuals(entity: Entity, component: StateVisuals): void;
- removeStateVisuals(entity: Entity): void;
hasTilemapLayer(entity: Entity): boolean;
getTilemapLayer(entity: Entity): TilemapLayer;
addTilemapLayer(entity: Entity, component: TilemapLayer): void;
@@ -662,8 +641,6 @@ export interface ESEngineModule {
ShapeRenderer: new () => ShapeRenderer;
SpineAnimation: new () => SpineAnimation;
Sprite: new () => Sprite;
- StateMachine: new () => StateMachine;
- StateVisuals: new () => StateVisuals;
TilemapLayer: new () => TilemapLayer;
TrailRenderer: new () => TrailRenderer;
Transform: new () => Transform;
diff --git a/sdk/tests/emscripten-wrapper.test.ts b/sdk/tests/emscripten-wrapper.test.ts
index 37be59681..76793e8a6 100644
--- a/sdk/tests/emscripten-wrapper.test.ts
+++ b/sdk/tests/emscripten-wrapper.test.ts
@@ -115,45 +115,4 @@ describe.skipIf(!HAS_WASM)('Emscripten wrapper diagnostics', () => {
(registry as unknown as { delete(): void }).delete();
});
- // REARCH_GUI F5: a std::vector<VisualState> component field must round-trip a
- // plain JS array through embind (register_vector + value_object), incl. the
- // std::string member. This is the path the button/dropdown widgets exercise.
- it('round-trips a std::vector<VisualState> through embind', () => {
- const registry = new module.Registry() as unknown as CppRegistry;
- const entity = registry.create();
-
- const reg = registry as unknown as {
- addStateVisuals(e: number, c: unknown): void;
- getStateVisuals(e: number): { states: unknown };
- };
- reg.addStateVisuals(entity, {
- targetGraphic: 0,
- transitionFlags: 1,
- fadeDuration: 0.5,
- states: [
- { name: 'normal', r: 1, g: 0, b: 0, a: 1, sprite: 0, scale: 1 },
- { name: 'hover', r: 0, g: 1, b: 0, a: 1, sprite: 7, scale: 1.25 },
- ],
- });
-
- const states = reg.getStateVisuals(entity).states as
- | Array<Record<string, number | string>>
- | { size(): number; get(i: number): Record<string, number | string> };
- // embind may hand back a plain array or a bound vector — accept both.
- const isArr = Array.isArray(states);
- const len = isArr ? (states as unknown[]).length : (states as { size(): number }).size();
- const at = (i: number) => isArr
- ? (states as Array<Record<string, number | string>>)[i]
- : (states as { get(i: number): Record<string, number | string> }).get(i);
-
- expect(len).toBe(2);
- expect(at(0).name).toBe('normal');
- expect(at(0).r).toBeCloseTo(1, 5);
- expect(at(1).name).toBe('hover');
- expect(at(1).sprite).toBe(7);
- expect(at(1).scale).toBeCloseTo(1.25, 5);
-
- registry.destroy(entity);
- (registry as unknown as { delete(): void }).delete();
- });
});
diff --git a/sdk/tests/ui-behavior.test.ts b/sdk/tests/ui-behavior.test.ts
index 72f5dbd6e..ae13c2ee1 100644
--- a/sdk/tests/ui-behavior.test.ts
+++ b/sdk/tests/ui-behavior.test.ts
@@ -2,9 +2,6 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import { describe, it, expect } from 'vitest';
import {
- StateMachine,
- StateVisuals,
- TransitionFlag,
Interactable,
UIInteraction,
Focusable,
@@ -12,49 +9,6 @@ import {
} from '../src/ui';
describe('ui2 behavior components', () => {
- describe('StateMachine', () => {
- it('registers as a builtin named "StateMachine"', () => {
- expect(StateMachine._builtin).toBe(true);
- expect(StateMachine._name).toBe('StateMachine');
- });
-
- it('defaults to empty current and previous', () => {
- expect(StateMachine._default).toEqual({ current: '', previous: '' });
- });
- });
-
- describe('StateVisuals', () => {
- it('registers as a builtin named "StateVisuals"', () => {
- expect(StateVisuals._builtin).toBe(true);
- expect(StateVisuals._name).toBe('StateVisuals');
- });
-
- it('defaults to an empty states list (variable-length, REARCH_GUI F5)', () => {
- const d = StateVisuals._default as { states: unknown[] };
- expect(Array.isArray(d.states)).toBe(true);
- expect(d.states).toHaveLength(0);
- });
-
- it('declares targetGraphic as an entity reference for serialization', () => {
- // EHT populates entityFields from ES_PROPERTY(entity_ref)
- expect(StateVisuals.entityFields).toContain('targetGraphic');
- });
- });
-
- describe('TransitionFlag', () => {
- it('defines composable bitmask values', () => {
- expect(TransitionFlag.None).toBe(0);
- expect(TransitionFlag.ColorTint).toBe(1);
- expect(TransitionFlag.SpriteSwap).toBe(2);
- expect(TransitionFlag.Scale).toBe(4);
-
- const combined = TransitionFlag.ColorTint | TransitionFlag.Scale;
- expect(combined & TransitionFlag.ColorTint).toBeTruthy();
- expect(combined & TransitionFlag.Scale).toBeTruthy();
- expect(combined & TransitionFlag.SpriteSwap).toBeFalsy();
- });
- });
-
describe('re-exported behaviors', () => {
it('Interactable points at the existing builtin', () => {
expect(Interactable._builtin).toBe(true);
diff --git a/sdk/tests/ui-controller-gear.test.ts b/sdk/tests/ui-controller-gear.test.ts
index c517088ad..db096de92 100644
--- a/sdk/tests/ui-controller-gear.test.ts
+++ b/sdk/tests/ui-controller-gear.test.ts
@@ -3,8 +3,8 @@
/**
* @file ui-controller-gear.test.ts
* @brief UIController + UIGear: page resolution (self/ancestor), gear snap &
- * tween, sparse pages, and the $interaction driver reproducing the
- * StateVisuals normal/hover/pressed states through the unified layer.
+ * tween, sparse pages, and the $interaction driver producing the
+ * normal/hover/pressed/disabled states through the unified layer.
*/
import { describe, expect, it, beforeEach, vi } from 'vitest';
import { Transform, Parent, type TransformData } from '../src/component';
@@ -258,11 +258,21 @@ describe('GearApplySystem — tween', () => {
runSystem(sys, 1.0); // past the end → clamp
expect((world.get(e, UIVisual) as UIVisualData).color).toEqual({ r: 1, g: 1, b: 1, a: 1 });
});
+
+ it('restarts a tween from the live value when the page changes mid-transition', () => {
+ const sys = createGearApplySystem(world as never);
+ runSystem(sys, 0);
+ runSystem(sys, 0.5); // halfway toward 'on': r ≈ 0.5
+ setControllerPage(world as never, e, 'c', 'off');
+ runSystem(sys, 0); // reseed toward 'off' — from the mid-fade value, not from 'on'
+ runSystem(sys, 0.5); // halfway back: 0.5 → 0 at t=0.5 → r ≈ 0.25
+ expect((world.get(e, UIVisual) as UIVisualData).color.r).toBeCloseTo(0.25, 2);
+ });
});
// ─── $interaction driver parity ─────────────────────────────────────────────
-describe('InteractionControllerDriverSystem — StateVisuals parity through gears', () => {
+describe('InteractionControllerDriverSystem — button states through gears', () => {
let world: MockWorld;
let e: Entity;
beforeEach(() => {
@@ -310,4 +320,21 @@ describe('InteractionControllerDriverSystem — StateVisuals parity through gear
expect(getControllerPage(world as never, e, '$interaction')).toBe('disabled');
expect((world.get(e, UIVisual) as UIVisualData).color).toEqual({ r: 0.3, g: 0.3, b: 0.3, a: 1 });
});
+
+ it('leaves a user-managed custom page alone (e.g. "loading")', () => {
+ const driver = createInteractionControllerDriverSystem(world as never);
+ const data = world.get(e, UIController) as UIControllerData;
+ data.controllers[0]!.pages.push('loading');
+ data.controllers[0]!.current = 'loading';
+ world.insert(e, UIController, data);
+
+ world.insert(e, UIInteraction, { hovered: true, pressed: false, justPressed: false, justReleased: false });
+ runSystem(driver, 1 / 60);
+ expect(getControllerPage(world as never, e, '$interaction')).toBe('loading');
+
+ // Back on a driver-owned page, pointer state takes over again.
+ setControllerPage(world as never, e, '$interaction', 'normal');
+ runSystem(driver, 1 / 60);
+ expect(getControllerPage(world as never, e, '$interaction')).toBe('hover');
+ });
});
diff --git a/sdk/tests/ui-slider-dropdown.test.ts b/sdk/tests/ui-slider-dropdown.test.ts
index d39830120..c4bc76ac5 100644
--- a/sdk/tests/ui-slider-dropdown.test.ts
+++ b/sdk/tests/ui-slider-dropdown.test.ts
@@ -182,14 +182,14 @@ describe('createDropdown', () => {
expect(label.content).toBe('Banana');
});
- it('opens popup on button click (pressed → hover)', () => {
+ it('opens popup on button click', () => {
const dd = createDropdown({
world: world as unknown as World, events,
options: ['a', 'b'],
});
expect(dd.isOpen()).toBe(false);
- events.emit(dd.entity, UIEventType.StateChanged, { from: 'pressed', to: 'hover' });
+ events.emit(dd.entity, UIEventType.Click);
expect(dd.isOpen()).toBe(true);
});
@@ -199,10 +199,10 @@ describe('createDropdown', () => {
options: ['a', 'b'],
});
- events.emit(dd.entity, UIEventType.StateChanged, { from: 'pressed', to: 'hover' });
+ events.emit(dd.entity, UIEventType.Click);
expect(dd.isOpen()).toBe(true);
- events.emit(dd.entity, UIEventType.StateChanged, { from: 'pressed', to: 'hover' });
+ events.emit(dd.entity, UIEventType.Click);
expect(dd.isOpen()).toBe(false);
});
diff --git a/sdk/tests/ui-state-visuals-fade.test.ts b/sdk/tests/ui-state-visuals-fade.test.ts
deleted file mode 100644
index 5124bccc4..000000000
--- a/sdk/tests/ui-state-visuals-fade.test.ts
+++ /dev/null
@@ -1,243 +0,0 @@
-// SPDX-License-Identifier: Apache-2.0
-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-/**
- * @file ui-state-visuals-fade.test.ts
- * @brief StateVisualsApplySystem interpolates color/scale when
- * fadeDuration > 0, and snaps otherwise.
- */
-import { describe, expect, it, beforeEach, vi } from 'vitest';
-import { Transform, type TransformData } from '../src/component';
-import { StateMachine, type StateMachineData } from '../src/ui/behavior/state-machine';
-import {
- StateVisuals,
- TransitionFlag,
- visualState,
- type StateVisualsData,
-} from '../src/ui/behavior/state-visuals';
-import { UIVisual, type UIVisualData } from '../src/ui/core/ui-visual';
-import { createStateVisualsApplySystem } from '../src/ui/behavior/systems';
-import type { Entity } from '../src/types';
-import type { SystemDef } from '../src/system';
-import type { AnyComponentDef } from '../src/component';
-
-/**
- * Minimal World surface the apply system uses. Backed by per-component
- * Maps so builtin components (Transform, UIVisual, StateVisuals) don't
- * need a real C++ registry. Enough for behavior-level testing of the
- * fade logic.
- */
-function makeMockWorld() {
- const storage = new Map<AnyComponentDef, Map<Entity, unknown>>();
- const alive = new Set<Entity>();
- let next = 1;
-
- const storeFor = (c: AnyComponentDef) => {
- let s = storage.get(c);
- if (!s) { s = new Map(); storage.set(c, s); }
- return s;
- };
-
- return {
- spawn: () => { const e = next++ as Entity; alive.add(e); return e; },
- valid: (e: Entity) => alive.has(e),
- has: (e: Entity, c: AnyComponentDef) => storeFor(c).has(e),
- get: (e: Entity, c: AnyComponentDef) => storeFor(c).get(e),
- insert: (e: Entity, c: AnyComponentDef, d: unknown) => { storeFor(c).set(e, d); },
- set: (e: Entity, c: AnyComponentDef, d: unknown) => { storeFor(c).set(e, d); },
- remove: (e: Entity, c: AnyComponentDef) => storeFor(c).delete(e),
- getEntitiesWithComponents: (required: AnyComponentDef[]) => {
- const out: Entity[] = [];
- outer: for (const e of alive) {
- for (const c of required) if (!storeFor(c).has(e)) continue outer;
- out.push(e);
- }
- return out;
- },
- };
-}
-
-function makeVisuals(overrides: Partial<StateVisualsData>): StateVisualsData {
- return {
- targetGraphic: 0 as Entity,
- transitionFlags: 0,
- fadeDuration: 0,
- states: [],
- ...overrides,
- } as StateVisualsData;
-}
-
-function runSystem(system: SystemDef, dt: number): void {
- (system._fn as (...a: unknown[]) => void)({ delta: dt, elapsed: 0, frameCount: 0 });
-}
-
-function makeTransform(scale = 1): TransformData {
- return {
- position: { x: 0, y: 0, z: 0 },
- rotation: { x: 0, y: 0, z: 0, w: 1 },
- scale: { x: scale, y: scale, z: 1 },
- worldPosition: { x: 0, y: 0, z: 0 },
- worldRotation: { x: 0, y: 0, z: 0, w: 1 },
- worldScale: { x: scale, y: scale, z: 1 },
- };
-}
-
-function makeRenderer(color = { r: 1, g: 1, b: 1, a: 1 }, texture = 0): UIVisualData {
- return {
- texture, color, size: { x: 10, y: 10 },
- pivot: { x: 0.5, y: 0.5 }, layer: 0, enabled: true,
- } as UIVisualData;
-}
-
-describe('StateVisualsApplySystem — color fade', () => {
- let world: ReturnType<typeof makeMockWorld>;
- let entity: Entity;
-
- beforeEach(() => {
- world = makeMockWorld();
- entity = world.spawn();
- world.insert(entity, Transform, makeTransform());
- world.insert(entity, UIVisual, makeRenderer());
- });
-
- it('snaps immediately when fadeDuration is 0', () => {
- world.insert(entity, StateMachine, { current: 'pressed', previous: '' } as StateMachineData);
- world.insert(entity, StateVisuals, makeVisuals({
- transitionFlags: TransitionFlag.ColorTint,
- fadeDuration: 0,
- states: [visualState('pressed', { r: 0, g: 0, b: 1, a: 1 })],
- }));
-
- const sys = createStateVisualsApplySystem(world as never);
- runSystem(sys, 1 / 60);
-
- const r = world.get(entity, UIVisual) as UIVisualData;
- expect(r.color).toEqual({ r: 0, g: 0, b: 1, a: 1 });
- });
-
- it('stops writing once settled at a slot (no per-frame write amplification)', () => {
- world.insert(entity, StateMachine, { current: 'pressed', previous: '' } as StateMachineData);
- world.insert(entity, StateVisuals, makeVisuals({
- transitionFlags: TransitionFlag.ColorTint,
- fadeDuration: 0,
- states: [visualState('pressed', { r: 0, g: 0, b: 1, a: 1 })],
- }));
-
- const sys = createStateVisualsApplySystem(world as never);
- runSystem(sys, 1 / 60); // slot change → apply + settle
- const insertSpy = vi.spyOn(world, 'insert');
- runSystem(sys, 1 / 60); // idle
- runSystem(sys, 1 / 60); // idle
-
- const visualWrites = insertSpy.mock.calls.filter((c) => c[1] === UIVisual);
- expect(visualWrites).toHaveLength(0);
- });
-
- it('interpolates color halfway at t = duration/2', () => {
- world.insert(entity, StateMachine, { current: 'pressed', previous: '' } as StateMachineData);
- world.insert(entity, StateVisuals, makeVisuals({
- transitionFlags: TransitionFlag.ColorTint,
- fadeDuration: 1.0,
- states: [visualState('pressed', { r: 0, g: 0, b: 0, a: 1 })],
- }));
-
- const sys = createStateVisualsApplySystem(world as never);
- runSystem(sys, 0); // seed transition, t=0
- let r = world.get(entity, UIVisual) as UIVisualData;
- expect(r.color.r).toBeCloseTo(1);
-
- runSystem(sys, 0.5); // advance to t=0.5
- r = world.get(entity, UIVisual) as UIVisualData;
- expect(r.color.r).toBeCloseTo(0.5, 2);
- expect(r.color.g).toBeCloseTo(0.5, 2);
- expect(r.color.b).toBeCloseTo(0.5, 2);
- });
-
- it('clamps to target at t >= duration', () => {
- world.insert(entity, StateMachine, { current: 'pressed', previous: '' } as StateMachineData);
- world.insert(entity, StateVisuals, makeVisuals({
- transitionFlags: TransitionFlag.ColorTint,
- fadeDuration: 0.5,
- states: [visualState('pressed', { r: 0, g: 0, b: 0, a: 1 })],
- }));
-
- const sys = createStateVisualsApplySystem(world as never);
- runSystem(sys, 0);
- runSystem(sys, 1.0);
-
- const r = world.get(entity, UIVisual) as UIVisualData;
- expect(r.color).toEqual({ r: 0, g: 0, b: 0, a: 1 });
- });
-
- it('restarts the fade when the target slot changes mid-transition', () => {
- world.insert(entity, StateMachine, { current: 'a', previous: '' } as StateMachineData);
- world.insert(entity, StateVisuals, makeVisuals({
- transitionFlags: TransitionFlag.ColorTint,
- fadeDuration: 1.0,
- states: [
- visualState('a', { r: 0, g: 0, b: 0, a: 1 }),
- visualState('b', { r: 1, g: 0, b: 0, a: 1 }),
- ],
- }));
-
- const sys = createStateVisualsApplySystem(world as never);
- runSystem(sys, 0);
- runSystem(sys, 0.5);
- let r = world.get(entity, UIVisual) as UIVisualData;
- expect(r.color.r).toBeCloseTo(0.5, 1);
-
- const sm = world.get(entity, StateMachine) as StateMachineData;
- sm.current = 'b';
- world.insert(entity, StateMachine, sm);
-
- runSystem(sys, 0);
- r = world.get(entity, UIVisual) as UIVisualData;
- expect(r.color.r).toBeCloseTo(0.5, 1);
-
- runSystem(sys, 1.0);
- r = world.get(entity, UIVisual) as UIVisualData;
- expect(r.color).toEqual({ r: 1, g: 0, b: 0, a: 1 });
- });
-});
-
-describe('StateVisualsApplySystem — scale fade', () => {
- it('lerps uniform scale across the fade window', () => {
- const world = makeMockWorld();
- const entity = world.spawn();
- world.insert(entity, Transform, makeTransform(1));
- world.insert(entity, UIVisual, makeRenderer());
- world.insert(entity, StateMachine, { current: 'pressed', previous: '' } as StateMachineData);
- world.insert(entity, StateVisuals, makeVisuals({
- transitionFlags: TransitionFlag.Scale,
- fadeDuration: 1.0,
- states: [visualState('pressed', { r: 1, g: 1, b: 1, a: 1 }, { scale: 2 })],
- }));
-
- const sys = createStateVisualsApplySystem(world as never);
- runSystem(sys, 0);
- runSystem(sys, 0.25);
-
- const t = world.get(entity, Transform) as TransformData;
- expect(t.scale.x).toBeCloseTo(1.25, 2);
- expect(t.scale.y).toBeCloseTo(1.25, 2);
- });
-});
-
-describe('StateVisualsApplySystem — sprite swap', () => {
- it('always snaps (never lerps) because textures are discrete', () => {
- const world = makeMockWorld();
- const entity = world.spawn();
- world.insert(entity, UIVisual, makeRenderer({ r: 1, g: 1, b: 1, a: 1 }, 7));
- world.insert(entity, StateMachine, { current: 'pressed', previous: '' } as StateMachineData);
- world.insert(entity, StateVisuals, makeVisuals({
- transitionFlags: TransitionFlag.SpriteSwap,
- fadeDuration: 1.0,
- states: [visualState('pressed', { r: 1, g: 1, b: 1, a: 1 }, { sprite: 42 })],
- }));
-
- const sys = createStateVisualsApplySystem(world as never);
- runSystem(sys, 0);
-
- const r = world.get(entity, UIVisual) as UIVisualData;
- expect(r.texture).toBe(42);
- });
-});
diff --git a/sdk/tests/ui-systems.test.ts b/sdk/tests/ui-systems.test.ts
index afb1e18df..b48b62d01 100644
--- a/sdk/tests/ui-systems.test.ts
+++ b/sdk/tests/ui-systems.test.ts
@@ -1,25 +1,7 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import { describe, it, expect } from 'vitest';
-import {
- driverStateFor,
- findStateSlot,
- TransitionFlag,
- visualState,
- type StateVisualsData,
- type UIInteractionData,
-} from '../src/ui';
-
-const WHITE = { r: 1, g: 1, b: 1, a: 1 };
-const named = (...names: string[]) => names.map(n => visualState(n, WHITE));
-
-const sv = (overrides: Partial<StateVisualsData> = {}): StateVisualsData => ({
- targetGraphic: 0 as never,
- transitionFlags: 0,
- fadeDuration: 0,
- states: [],
- ...overrides,
-});
+import { driverStateFor, type UIInteractionData } from '../src/ui';
const inter = (hovered: boolean, pressed: boolean): UIInteractionData => ({
hovered, pressed, justPressed: false, justReleased: false,
@@ -45,38 +27,3 @@ describe('driverStateFor', () => {
expect(driverStateFor(true, null)).toBe('normal');
});
});
-
-describe('findStateSlot', () => {
- it('returns -1 when state is the empty string', () => {
- expect(findStateSlot(sv({ states: named('normal') }), '')).toBe(-1);
- });
-
- it('returns the index of the matching state', () => {
- const data = sv({ states: named('normal', 'hover', 'pressed') });
- expect(findStateSlot(data, 'normal')).toBe(0);
- expect(findStateSlot(data, 'hover')).toBe(1);
- expect(findStateSlot(data, 'pressed')).toBe(2);
- });
-
- it('returns -1 when no state matches', () => {
- expect(findStateSlot(sv({ states: named('normal') }), 'loading')).toBe(-1);
- });
-
- it('returns -1 when the states list is empty', () => {
- expect(findStateSlot(sv(), 'any')).toBe(-1);
- });
-
- it('returns the first match when names collide', () => {
- const data = sv({ states: named('a', 'x', 'b', 'x') });
- expect(findStateSlot(data, 'x')).toBe(1);
- });
-});
-
-describe('TransitionFlag composability', () => {
- it('composable via bitwise OR', () => {
- const flags = TransitionFlag.ColorTint | TransitionFlag.Scale;
- expect(flags & TransitionFlag.ColorTint).toBeTruthy();
- expect(flags & TransitionFlag.Scale).toBeTruthy();
- expect(flags & TransitionFlag.SpriteSwap).toBe(0);
- });
-});
diff --git a/sdk/tests/ui-theme-swap.test.ts b/sdk/tests/ui-theme-swap.test.ts
index 2ae3fe204..bae7ef001 100644
--- a/sdk/tests/ui-theme-swap.test.ts
+++ b/sdk/tests/ui-theme-swap.test.ts
@@ -2,8 +2,8 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
* @file Live re-theming: switchTheme re-resolves every ThemeStyle-tagged entity's
- * role bindings onto its UIVisual / Text / StateVisuals, so already-built
- * widgets restyle — not just future ones.
+ * role bindings onto its UIVisual / Text / `$interaction` colour gear, so
+ * already-built widgets restyle — not just future ones.
*/
import { describe, it, expect, afterEach } from 'vitest';
import {
@@ -15,11 +15,12 @@ import {
UIVisual,
UIVisualType,
Text,
- StateVisuals,
+ UIGear,
DARK_TOKENS,
LIGHT_TOKENS,
setTheme,
- themeColors,
+ type UIGearData,
+ type GearValue,
} from '../src/ui';
import type { Entity } from '../src/types';
import type { World } from '../src/world';
@@ -75,22 +76,22 @@ describe('live re-theming', () => {
expect(t.color.r).toBeCloseTo(LIGHT_TOKENS.colors.text.r);
});
- it('switchTheme restyles an already-built button (states + label)', () => {
+ const colorPages = (w: World, e: Entity): Record<string, GearValue> =>
+ (w.get(e, UIGear) as UIGearData).bindings.find((b) => b.property === 'color')!.pages;
+
+ it('switchTheme restyles an already-built button (gear pages + label)', () => {
const w = mockWorld();
const btn = createButton({ world: w, events: noEvents, text: 'OK' });
// Built under the default dark theme.
- const svBefore = w.get(btn, StateVisuals) as { states: Array<{ name: string; r: number }> };
- expect(svBefore.states.find((s) => s.name === 'normal')!.r).toBeCloseTo(DARK_TOKENS.colors.control.r);
+ expect((colorPages(w, btn).normal as { r: number }).r).toBeCloseTo(DARK_TOKENS.colors.control.r);
switchTheme(w, LIGHT_TOKENS);
- const sv = w.get(btn, StateVisuals) as { states: Array<{ name: string; r: number; g: number; b: number; a: number }> };
- const normal = sv.states.find((s) => s.name === 'normal')!;
- expect(normal).toMatchObject(LIGHT_TOKENS.colors.control);
- const hover = sv.states.find((s) => s.name === 'hover')!;
- expect(hover).toMatchObject(LIGHT_TOKENS.colors.controlHover);
- // The dimmed 'disabled' state keeps its half alpha; only the hue re-themes.
- const disabled = sv.states.find((s) => s.name === 'disabled')!;
+ const pages = colorPages(w, btn);
+ expect(pages.normal).toMatchObject(LIGHT_TOKENS.colors.control);
+ expect(pages.hover).toMatchObject(LIGHT_TOKENS.colors.controlHover);
+ // The dimmed 'disabled' page keeps its half alpha; only the hue re-themes.
+ const disabled = pages.disabled as { r: number; a: number };
expect(disabled.a).toBeCloseTo(DARK_TOKENS.colors.control.a * 0.5);
expect(disabled.r).toBeCloseTo(LIGHT_TOKENS.colors.control.r);
});
@@ -103,7 +104,6 @@ describe('live re-theming', () => {
});
expect(w.has(btn, ThemeStyle)).toBe(false); // untagged → not theme-managed
switchTheme(w, LIGHT_TOKENS);
- const sv = w.get(btn, StateVisuals) as { states: Array<{ r: number; g: number; b: number }> };
- expect(sv.states[0]).toMatchObject({ r: 0.5, g: 0.1, b: 0.9 }); // caller's color survives
+ expect(colorPages(w, btn).normal).toMatchObject({ r: 0.5, g: 0.1, b: 0.9 }); // caller's color survives
});
});
diff --git a/sdk/tests/ui-widget-prefabs.gen.test.ts b/sdk/tests/ui-widget-prefabs.gen.test.ts
index c08009045..a439a021e 100644
--- a/sdk/tests/ui-widget-prefabs.gen.test.ts
+++ b/sdk/tests/ui-widget-prefabs.gen.test.ts
@@ -68,7 +68,7 @@ describe('UI widget prefab codegen', () => {
const root = typesOf(prefab, prefab.rootEntityId);
expect(root).toEqual(expect.arrayContaining([
- 'Transform', 'UINode', 'UIVisual', 'Interactable', 'UIInteraction', 'StateMachine', 'StateVisuals',
+ 'Transform', 'UINode', 'UIVisual', 'Interactable', 'UIInteraction', 'UIController', 'UIGear',
]));
const rootEnt = entityById(prefab, prefab.rootEntityId);
expect(rootEnt.children.length).toBe(1);
@@ -89,7 +89,7 @@ describe('UI widget prefab codegen', () => {
check: { color: c.primary }, isOn: true,
}).entity as unknown as number,
);
- expect(typesOf(prefab, prefab.rootEntityId)).toEqual(expect.arrayContaining(['UINode', 'Interactable', 'StateVisuals']));
+ expect(typesOf(prefab, prefab.rootEntityId)).toEqual(expect.arrayContaining(['UINode', 'Interactable', 'UIGear']));
expect(entityById(prefab, prefab.rootEntityId).children.length).toBeGreaterThanOrEqual(1);
});
diff --git a/sdk/tests/ui-widgets.test.ts b/sdk/tests/ui-widgets.test.ts
index e881e724f..a09f15f31 100644
--- a/sdk/tests/ui-widgets.test.ts
+++ b/sdk/tests/ui-widgets.test.ts
@@ -7,9 +7,11 @@ import {
createProgress,
createDialog,
setButtonState,
+ interactionGears,
Interactable,
- StateMachine,
- StateVisuals,
+ UIController,
+ UIGear,
+ INTERACTION_CONTROLLER,
UINode,
UIVisual,
UIVisualType,
@@ -17,8 +19,9 @@ import {
FillOrigin,
UIEventQueue,
UIEventType,
- TransitionFlag,
themeColors,
+ type UIControllerData,
+ type UIGearData,
} from '../src/ui';
import type { Entity } from '../src/types';
import type { World } from '../src/world';
@@ -99,6 +102,10 @@ describe('createButton', () => {
events = new UIEventQueue();
});
+ const interactionOf = (btn: Entity) =>
+ (world.get(btn, UIController) as UIControllerData).controllers
+ .find((c) => c.name === INTERACTION_CONTROLLER)!;
+
it('attaches the required components', () => {
const btn = createButton({
world: world as unknown as World,
@@ -114,11 +121,11 @@ describe('createButton', () => {
expect(world.has(btn, UINode)).toBe(true);
expect(world.has(btn, UIVisual)).toBe(true);
expect(world.has(btn, Interactable)).toBe(true);
- expect(world.has(btn, StateMachine)).toBe(true);
- expect(world.has(btn, StateVisuals)).toBe(true);
+ expect(world.has(btn, UIController)).toBe(true);
+ expect(world.has(btn, UIGear)).toBe(true);
});
- it('populates the StateVisuals states list from the `states` map', () => {
+ it('folds the `states` map into a $interaction color gear', () => {
const btn = createButton({
world: world as unknown as World,
events,
@@ -126,31 +133,31 @@ describe('createButton', () => {
normal: { color: { r: 1, g: 0, b: 0, a: 1 } },
hover: { color: { r: 0, g: 1, b: 0, a: 1 } },
},
- transitionFlags: TransitionFlag.ColorTint,
+ fadeDuration: 0.2,
});
- const sv = world.get(btn, StateVisuals) as {
- states: Array<{ name: string; r: number; g: number; b: number; a: number }>;
- transitionFlags: number;
- };
- expect(sv.states.map(s => s.name)).toEqual(['normal', 'hover']);
- expect(sv.states[0]).toMatchObject({ r: 1, g: 0, b: 0, a: 1 });
- expect(sv.transitionFlags).toBe(TransitionFlag.ColorTint);
+ const gear = world.get(btn, UIGear) as UIGearData;
+ expect(gear.bindings).toHaveLength(1);
+ const b = gear.bindings[0]!;
+ expect(b).toMatchObject({ controller: INTERACTION_CONTROLLER, component: 'UIVisual', property: 'color' });
+ expect(b.pages.normal).toEqual({ r: 1, g: 0, b: 0, a: 1 });
+ expect(b.pages.hover).toEqual({ r: 0, g: 1, b: 0, a: 1 });
+ expect(b.pages.pressed).toBeUndefined(); // sparse: unauthored pages leave the field alone
+ expect(b.tween?.duration).toBeCloseTo(0.2);
});
it('defaults its states to the active theme control roles (de-nude)', () => {
const btn = createButton({ world: world as unknown as World, events, text: 'OK' });
- const sv = world.get(btn, StateVisuals) as {
- states: Array<{ name: string; r: number; g: number; b: number; a: number }>;
- };
+ const gear = world.get(btn, UIGear) as UIGearData;
+ const colorGear = gear.bindings.find((b) => b.property === 'color')!;
const c = themeColors();
- expect(sv.states.map(s => s.name)).toEqual(['normal', 'hover', 'pressed', 'disabled']);
- expect(sv.states[0]).toMatchObject(c.control);
- expect(sv.states[1]).toMatchObject(c.controlHover);
- expect(sv.states[2]).toMatchObject(c.controlActive);
+ expect(colorGear.pages.normal).toMatchObject(c.control);
+ expect(colorGear.pages.hover).toMatchObject(c.controlHover);
+ expect(colorGear.pages.pressed).toMatchObject(c.controlActive);
+ expect(colorGear.pages.disabled).toBeDefined();
});
- it('starts in "disabled" state when opts.disabled is true', () => {
+ it('starts on the "disabled" page when opts.disabled is true', () => {
const btn = createButton({
world: world as unknown as World,
events,
@@ -160,25 +167,23 @@ describe('createButton', () => {
},
});
- const sm = world.get(btn, StateMachine) as { current: string };
const i = world.get(btn, Interactable) as { enabled: boolean };
- expect(sm.current).toBe('disabled');
+ expect(interactionOf(btn).current).toBe('disabled');
expect(i.enabled).toBe(false);
});
- it('supports an arbitrary number of states (variable-length, REARCH_GUI F5)', () => {
+ it('lists canonical pages first, then custom states', () => {
const btn = createButton({
world: world as unknown as World,
events,
- states: Object.fromEntries(
- Array.from({ length: 12 }, (_, i) => [`s${i}`, {}]),
- ),
+ states: { normal: {}, loading: {}, celebrating: {} },
});
- const sv = world.get(btn, StateVisuals) as { states: unknown[] };
- expect(sv.states).toHaveLength(12);
+ expect(interactionOf(btn).pages).toEqual(
+ ['normal', 'hover', 'pressed', 'disabled', 'loading', 'celebrating'],
+ );
});
- it('fires onClick when the state transitions pressed → hover', () => {
+ it('fires onClick on the interaction layer click event', () => {
const onClick = vi.fn();
const btn = createButton({
world: world as unknown as World,
@@ -187,32 +192,63 @@ describe('createButton', () => {
onClick,
});
- events.emit(btn, UIEventType.StateChanged, { from: 'pressed', to: 'hover' });
+ events.emit(btn, UIEventType.Click);
expect(onClick).toHaveBeenCalledWith(btn);
});
- it('does not fire onClick on pressed → normal (released outside)', () => {
+ it('swallows clicks while disabled', () => {
const onClick = vi.fn();
const btn = createButton({
world: world as unknown as World,
events,
+ disabled: true,
states: { normal: {}, hover: {}, pressed: {} },
onClick,
});
- events.emit(btn, UIEventType.StateChanged, { from: 'pressed', to: 'normal' });
+ events.emit(btn, UIEventType.Click);
expect(onClick).not.toHaveBeenCalled();
});
- it('setButtonState writes StateMachine.current', () => {
+ it('setButtonState writes the $interaction page, growing the enum for custom states', () => {
const btn = createButton({
world: world as unknown as World,
events,
- states: { normal: {}, loading: {} },
+ states: { normal: {} },
});
setButtonState(world as unknown as World, btn, 'loading');
- expect((world.get(btn, StateMachine) as { current: string }).current).toBe('loading');
+ const ctrl = interactionOf(btn);
+ expect(ctrl.current).toBe('loading');
+ expect(ctrl.pages).toContain('loading');
+ });
+});
+
+describe('interactionGears', () => {
+ it('splits color / sprite / scale overrides into per-field bindings', () => {
+ const bindings = interactionGears({
+ normal: { color: { r: 1, g: 1, b: 1, a: 1 }, sprite: 7, scale: 1 },
+ pressed: { color: { r: 0.5, g: 0.5, b: 0.5, a: 1 }, sprite: 8, scale: 0.95 },
+ }, 0.1);
+
+ const byProp = Object.fromEntries(bindings.map((b) => [b.property, b]));
+ expect(Object.keys(byProp).sort()).toEqual(['color', 'scale', 'texture']);
+ expect(byProp.color!.component).toBe('UIVisual');
+ expect(byProp.texture!.component).toBe('UIVisual');
+ expect(byProp.scale!.component).toBe('Transform');
+ expect(byProp.texture!.pages.pressed).toBe(8);
+ expect(byProp.scale!.pages.pressed).toEqual({ x: 0.95, y: 0.95, z: 1 });
+ // Sprite swaps are discrete: no tween even when fadeDuration is set.
+ expect(byProp.texture!.tween).toBeUndefined();
+ expect(byProp.color!.tween?.duration).toBeCloseTo(0.1);
+ expect(byProp.scale!.tween?.duration).toBeCloseTo(0.1);
+ });
+
+ it('emits no binding for a field no state overrides', () => {
+ const bindings = interactionGears({ normal: { color: { r: 1, g: 1, b: 1, a: 1 } }, hover: {} });
+ expect(bindings).toHaveLength(1);
+ expect(bindings[0]!.property).toBe('color');
+ expect(bindings[0]!.tween).toBeUndefined();
});
});
@@ -245,7 +281,7 @@ describe('createToggle', () => {
onChange,
});
- events.emit(toggle.entity, UIEventType.StateChanged, { from: 'pressed', to: 'hover' });
+ events.emit(toggle.entity, UIEventType.Click);
expect(toggle.isOn()).toBe(true);
expect(onChange).toHaveBeenCalledWith(true, toggle.entity);
diff --git a/src/esengine/bindings/EditorAPI.generated.cpp b/src/esengine/bindings/EditorAPI.generated.cpp
index f9114edbf..944e1c0c6 100644
--- a/src/esengine/bindings/EditorAPI.generated.cpp
+++ b/src/esengine/bindings/EditorAPI.generated.cpp
@@ -2,10 +2,10 @@
* @file EditorAPI.generated.cpp
* @brief Auto-generated editor API with string-dispatched component access
* @details Generated by EHT - DO NOT EDIT
- * @schema_hash e7e95b1cb4e7766a
+ * @schema_hash ab9dd9b394a07d42
*/
-#define ES_EDITOR_API_SCHEMA_HASH "e7e95b1cb4e7766a"
+#define ES_EDITOR_API_SCHEMA_HASH "ab9dd9b394a07d42"
#include <emscripten/bind.h>
#include <string>
@@ -26,8 +26,6 @@
#include "../ecs/components/ShapeRenderer.hpp"
#include "../ecs/components/SpineAnimation.hpp"
#include "../ecs/components/Sprite.hpp"
-#include "../ecs/components/StateMachine.hpp"
-#include "../ecs/components/StateVisuals.hpp"
#include "../ecs/components/TilemapLayer.hpp"
#include "../ecs/components/TrailRenderer.hpp"
#include "../ecs/components/Transform.hpp"
@@ -74,8 +72,6 @@ std::vector<std::string> editor_getComponentNames() {
"ShapeRenderer",
"SpineAnimation",
"Sprite",
- "StateMachine",
- "StateVisuals",
"TilemapLayer",
"TrailRenderer",
"Transform",
@@ -380,17 +376,6 @@ std::string editor_getComponentSchema(const std::string& name) {
{"key":"material","type":"asset","group":"Sprite"},
{"key":"enabled","type":"bool","group":"Sprite"}
])JSON";
- } else if (name == "StateMachine") {
- return R"JSON([
- {"key":"current","type":"string","group":"StateMachine"},
- {"key":"previous","type":"string","group":"StateMachine"}
- ])JSON";
- } else if (name == "StateVisuals") {
- return R"JSON([
- {"key":"targetGraphic","type":"entity","group":"StateVisuals"},
- {"key":"transitionFlags","type":"int","group":"StateVisuals"},
- {"key":"fadeDuration","type":"float","group":"StateVisuals"}
- ])JSON";
} else if (name == "TilemapLayer") {
return R"JSON([
{"key":"cellSize.x","type":"float","group":"TilemapLayer"},
@@ -591,12 +576,6 @@ bool editor_addComponent(Registry& reg, u32 e, const std::string& name) {
} else if (name == "Sprite") {
if (!reg.has<esengine::ecs::Sprite>(entity)) reg.emplace<esengine::ecs::Sprite>(entity);
return true;
- } else if (name == "StateMachine") {
- if (!reg.has<esengine::ecs::StateMachine>(entity)) reg.emplace<esengine::ecs::StateMachine>(entity);
- return true;
- } else if (name == "StateVisuals") {
- if (!reg.has<esengine::ecs::StateVisuals>(entity)) reg.emplace<esengine::ecs::StateVisuals>(entity);
- return true;
} else if (name == "TilemapLayer") {
if (!reg.has<esengine::ecs::TilemapLayer>(entity)) reg.emplace<esengine::ecs::TilemapLayer>(entity);
return true;
@@ -666,10 +645,6 @@ bool editor_removeComponent(Registry& reg, u32 e, const std::string& name) {
if (reg.has<esengine::ecs::SpineAnimation>(entity)) { reg.remove<esengine::ecs::SpineAnimation>(entity); return true; }
} else if (name == "Sprite") {
if (reg.has<esengine::ecs::Sprite>(entity)) { reg.remove<esengine::ecs::Sprite>(entity); return true; }
- } else if (name == "StateMachine") {
- if (reg.has<esengine::ecs::StateMachine>(entity)) { reg.remove<esengine::ecs::StateMachine>(entity); return true; }
- } else if (name == "StateVisuals") {
- if (reg.has<esengine::ecs::StateVisuals>(entity)) { reg.remove<esengine::ecs::StateVisuals>(entity); return true; }
} else if (name == "TilemapLayer") {
if (reg.has<esengine::ecs::TilemapLayer>(entity)) { reg.remove<esengine::ecs::TilemapLayer>(entity); return true; }
} else if (name == "TrailRenderer") {
@@ -712,8 +687,6 @@ bool editor_hasComponent(Registry& reg, u32 e, const std::string& name) {
if (name == "ShapeRenderer") return reg.has<esengine::ecs::ShapeRenderer>(entity);
if (name == "SpineAnimation") return reg.has<esengine::ecs::SpineAnimation>(entity);
if (name == "Sprite") return reg.has<esengine::ecs::Sprite>(entity);
- if (name == "StateMachine") return reg.has<esengine::ecs::StateMachine>(entity);
- if (name == "StateVisuals") return reg.has<esengine::ecs::StateVisuals>(entity);
if (name == "TilemapLayer") return reg.has<esengine::ecs::TilemapLayer>(entity);
if (name == "TrailRenderer") return reg.has<esengine::ecs::TrailRenderer>(entity);
if (name == "Transform") return reg.has<esengine::ecs::Transform>(entity);
@@ -750,8 +723,6 @@ std::vector<std::string> editor_getComponents(Registry& reg, u32 e) {
if (reg.has<esengine::ecs::ShapeRenderer>(entity)) result.push_back("ShapeRenderer");
if (reg.has<esengine::ecs::SpineAnimation>(entity)) result.push_back("SpineAnimation");
if (reg.has<esengine::ecs::Sprite>(entity)) result.push_back("Sprite");
- if (reg.has<esengine::ecs::StateMachine>(entity)) result.push_back("StateMachine");
- if (reg.has<esengine::ecs::StateVisuals>(entity)) result.push_back("StateVisuals");
if (reg.has<esengine::ecs::TilemapLayer>(entity)) result.push_back("TilemapLayer");
if (reg.has<esengine::ecs::TrailRenderer>(entity)) result.push_back("TrailRenderer");
if (reg.has<esengine::ecs::Transform>(entity)) result.push_back("Transform");
@@ -993,12 +964,6 @@ bool editor_setFloat(Registry& reg, u32 e, const std::string& comp, const std::s
else if (field == "parallax.y") { c.parallax.y = value; }
else { return false; }
return true;
- } else if (comp == "StateVisuals") {
- if (!reg.has<esengine::ecs::StateVisuals>(entity)) return false;
- auto& c = reg.get<esengine::ecs::StateVisuals>(entity);
- if (field == "fadeDuration") { c.fadeDuration = value; }
- else { return false; }
- return true;
} else if (comp == "TilemapLayer") {
if (!reg.has<esengine::ecs::TilemapLayer>(entity)) return false;
auto& c = reg.get<esengine::ecs::TilemapLayer>(entity);
@@ -1328,10 +1293,6 @@ f32 editor_getFloat(Registry& reg, u32 e, const std::string& comp, const std::st
else if (field == "tileSpacing.y") { return c.tileSpacing.y; }
else if (field == "parallax.x") { return c.parallax.x; }
else if (field == "parallax.y") { return c.parallax.y; }
- } else if (comp == "StateVisuals") {
- if (!reg.has<esengine::ecs::StateVisuals>(entity)) return 0.0f;
- const auto& c = reg.get<esengine::ecs::StateVisuals>(entity);
- if (field == "fadeDuration") { return c.fadeDuration; }
} else if (comp == "TilemapLayer") {
if (!reg.has<esengine::ecs::TilemapLayer>(entity)) return 0.0f;
const auto& c = reg.get<esengine::ecs::TilemapLayer>(entity);
@@ -1569,13 +1530,6 @@ bool editor_setInt(Registry& reg, u32 e, const std::string& comp, const std::str
else if (field == "material") { c.material = static_cast<u32>(value); }
else { return false; }
return true;
- } else if (comp == "StateVisuals") {
- if (!reg.has<esengine::ecs::StateVisuals>(entity)) return false;
- auto& c = reg.get<esengine::ecs::StateVisuals>(entity);
- if (field == "targetGraphic") { c.targetGraphic = static_cast<Entity>(value); }
- else if (field == "transitionFlags") { c.transitionFlags = static_cast<u32>(value); }
- else { return false; }
- return true;
} else if (comp == "TilemapLayer") {
if (!reg.has<esengine::ecs::TilemapLayer>(entity)) return false;
auto& c = reg.get<esengine::ecs::TilemapLayer>(entity);
@@ -1719,11 +1673,6 @@ i32 editor_getInt(Registry& reg, u32 e, const std::string& comp, const std::stri
if (field == "texture") { return static_cast<i32>(c.texture.id()); }
else if (field == "layer") { return static_cast<i32>(c.layer); }
else if (field == "material") { return static_cast<i32>(c.material); }
- } else if (comp == "StateVisuals") {
- if (!reg.has<esengine::ecs::StateVisuals>(entity)) return 0;
- const auto& c = reg.get<esengine::ecs::StateVisuals>(entity);
- if (field == "targetGraphic") { return static_cast<i32>(static_cast<u32>(c.targetGraphic)); }
- else if (field == "transitionFlags") { return static_cast<i32>(c.transitionFlags); }
} else if (comp == "TilemapLayer") {
if (!reg.has<esengine::ecs::TilemapLayer>(entity)) return 0;
const auto& c = reg.get<esengine::ecs::TilemapLayer>(entity);
@@ -2046,13 +1995,6 @@ bool editor_setString(Registry& reg, u32 e, const std::string& comp, const std::
else { return false; }
c.needsReload = true;
return true;
- } else if (comp == "StateMachine") {
- if (!reg.has<esengine::ecs::StateMachine>(entity)) return false;
- auto& c = reg.get<esengine::ecs::StateMachine>(entity);
- if (field == "current") { c.current = value; }
- else if (field == "previous") { c.previous = value; }
- else { return false; }
- return true;
}
return false;
}
@@ -2073,11 +2015,6 @@ std::string editor_getString(Registry& reg, u32 e, const std::string& comp, cons
else if (field == "atlasPath") { return c.atlasPath; }
else if (field == "skin") { return c.skin; }
else if (field == "animation") { return c.animation; }
- } else if (comp == "StateMachine") {
- if (!reg.has<esengine::ecs::StateMachine>(entity)) return std::string{};
- const auto& c = reg.get<esengine::ecs::StateMachine>(entity);
- if (field == "current") { return c.current; }
- else if (field == "previous") { return c.previous; }
}
return std::string{};
}
diff --git a/src/esengine/bindings/WebBindings.generated.cpp b/src/esengine/bindings/WebBindings.generated.cpp
index 00fd627ea..1ae74c5de 100644
--- a/src/esengine/bindings/WebBindings.generated.cpp
+++ b/src/esengine/bindings/WebBindings.generated.cpp
@@ -26,8 +26,6 @@
#include "../ecs/components/ShapeRenderer.hpp"
#include "../ecs/components/SpineAnimation.hpp"
#include "../ecs/components/Sprite.hpp"
-#include "../ecs/components/StateMachine.hpp"
-#include "../ecs/components/StateVisuals.hpp"
#include "../ecs/components/TilemapLayer.hpp"
#include "../ecs/components/TrailRenderer.hpp"
#include "../ecs/components/Transform.hpp"
@@ -80,15 +78,6 @@ EMSCRIPTEN_BINDINGS(esengine_math) {
value_object<esengine::Dimension>("Dimension")
.field("value", &esengine::Dimension::value)
.field("unit", &esengine::Dimension::unit);
-
- value_object<esengine::VisualState>("VisualState")
- .field("name", &esengine::VisualState::name)
- .field("r", &esengine::VisualState::r)
- .field("g", &esengine::VisualState::g)
- .field("b", &esengine::VisualState::b)
- .field("a", &esengine::VisualState::a)
- .field("sprite", &esengine::VisualState::sprite)
- .field("scale", &esengine::VisualState::scale);
}
// =============================================================================
@@ -668,34 +657,6 @@ SpriteJS spriteToJS(const esengine::ecs::Sprite& c) {
return js;
}
-struct StateVisualsJS {
- u32 targetGraphic;
- u32 transitionFlags;
- f32 fadeDuration;
- emscripten::val states = emscripten::val::array();
-};
-
-esengine::ecs::StateVisuals statevisualsFromJS(const StateVisualsJS& js) {
- esengine::ecs::StateVisuals c;
- c.targetGraphic = Entity(js.targetGraphic);
- c.transitionFlags = js.transitionFlags;
- c.fadeDuration = js.fadeDuration;
- { const size_t n = js.states["length"].as<size_t>();
- c.states.clear(); c.states.reserve(n);
- for (size_t i = 0; i < n; ++i) c.states.push_back(js.states[i].as<esengine::VisualState>()); }
- return c;
-}
-
-StateVisualsJS statevisualsToJS(const esengine::ecs::StateVisuals& c) {
- StateVisualsJS js;
- js.targetGraphic = static_cast<u32>(c.targetGraphic);
- js.transitionFlags = c.transitionFlags;
- js.fadeDuration = c.fadeDuration;
- js.states = emscripten::val::array();
- for (size_t i = 0; i < c.states.size(); ++i) js.states.set(i, emscripten::val(c.states[i]));
- return js;
-}
-
struct TilemapLayerJS {
glm::vec2 cellSize;
glm::vec2 originOffset;
@@ -1144,16 +1105,6 @@ EMSCRIPTEN_BINDINGS(esengine_components) {
.field("material", &SpriteJS::material)
.field("enabled", &SpriteJS::enabled);
- value_object<esengine::ecs::StateMachine>("StateMachine")
- .field("current", &esengine::ecs::StateMachine::current)
- .field("previous", &esengine::ecs::StateMachine::previous);
-
- value_object<StateVisualsJS>("StateVisuals")
- .field("targetGraphic", &StateVisualsJS::targetGraphic)
- .field("transitionFlags", &StateVisualsJS::transitionFlags)
- .field("fadeDuration", &StateVisualsJS::fadeDuration)
- .field("states", &StateVisualsJS::states);
-
value_object<TilemapLayerJS>("TilemapLayer")
.field("cellSize", &TilemapLayerJS::cellSize)
.field("originOffset", &TilemapLayerJS::originOffset)
@@ -1646,47 +1597,6 @@ EMSCRIPTEN_BINDINGS(esengine_registry) {
r.remove<esengine::ecs::Sprite>(entity);
}))
- // StateMachine
- .function("hasStateMachine", optional_override([](Registry& r, u32 e) {
- return r.has<esengine::ecs::StateMachine>(static_cast<Entity>(e));
- }))
- .function("getStateMachine", optional_override([](Registry& r, u32 e) -> esengine::ecs::StateMachine& {
- auto entity = static_cast<Entity>(e);
- static esengine::ecs::StateMachine s_dummy{};
- if (!r.valid(entity) || !r.has<esengine::ecs::StateMachine>(entity)) return s_dummy;
- return r.get<esengine::ecs::StateMachine>(entity);
- }), allow_raw_pointers())
- .function("addStateMachine", optional_override([](Registry& r, u32 e, const esengine::ecs::StateMachine& c) {
- auto entity = static_cast<Entity>(e);
- if (!r.valid(entity)) return;
- r.emplaceOrReplace<esengine::ecs::StateMachine>(entity, c);
- }))
- .function("removeStateMachine", optional_override([](Registry& r, u32 e) {
- auto entity = static_cast<Entity>(e);
- if (!r.valid(entity) || !r.has<esengine::ecs::StateMachine>(entity)) return;
- r.remove<esengine::ecs::StateMachine>(entity);
- }))
-
- // StateVisuals
- .function("hasStateVisuals", optional_override([](Registry& r, u32 e) {
- return r.has<esengine::ecs::StateVisuals>(static_cast<Entity>(e));
- }))
- .function("getStateVisuals", optional_override([](Registry& r, u32 e) {
- auto entity = static_cast<Entity>(e);
- if (!r.valid(entity) || !r.has<esengine::ecs::StateVisuals>(entity)) return StateVisualsJS{};
- return statevisualsToJS(r.get<esengine::ecs::StateVisuals>(entity));
- }))
- .function("addStateVisuals", optional_override([](Registry& r, u32 e, const StateVisualsJS& js) {
- auto entity = static_cast<Entity>(e);
- if (!r.valid(entity)) return;
- r.emplaceOrReplace<esengine::ecs::StateVisuals>(entity, statevisualsFromJS(js));
- }))
- .function("removeStateVisuals", optional_override([](Registry& r, u32 e) {
- auto entity = static_cast<Entity>(e);
- if (!r.valid(entity) || !r.has<esengine::ecs::StateVisuals>(entity)) return;
- r.remove<esengine::ecs::StateVisuals>(entity);
- }))
-
// TilemapLayer
.function("hasTilemapLayer", optional_override([](Registry& r, u32 e) {
return r.has<esengine::ecs::TilemapLayer>(static_cast<Entity>(e));
@@ -1887,8 +1797,6 @@ emscripten::val esengineGetBuiltinComponentNames() {
arr.set(i++, val(std::string("ShapeRenderer")));
arr.set(i++, val(std::string("SpineAnimation")));
arr.set(i++, val(std::string("Sprite")));
- arr.set(i++, val(std::string("StateMachine")));
- arr.set(i++, val(std::string("StateVisuals")));
arr.set(i++, val(std::string("TilemapLayer")));
arr.set(i++, val(std::string("TrailRenderer")));
arr.set(i++, val(std::string("Transform")));
@@ -2138,7 +2046,7 @@ static_assert(offsetof(esengine::ecs::Velocity, angular) == 12, "ABI offset drif
// ABI Hash -- runtime handshake against the SDK bundle
// =============================================================================
-static const char* kEsAbiLayoutHash = "89ad72a9b853289f";
+static const char* kEsAbiLayoutHash = "f9191aeae848066e";
std::string esengineGetAbiLayoutHash() {
return std::string(kEsAbiLayoutHash);
diff --git a/src/esengine/core/UITypes.hpp b/src/esengine/core/UITypes.hpp
index 6b4c68c11..3b15d40b7 100644
--- a/src/esengine/core/UITypes.hpp
+++ b/src/esengine/core/UITypes.hpp
@@ -4,8 +4,6 @@
#include "Types.hpp"
-#include <string>
-
namespace esengine {
struct Padding {
@@ -30,25 +28,4 @@ struct Dimension {
u8 unit{0}; // 0=Px, 1=Percent, 2=Auto
};
-/**
- * @brief One named visual state for StateVisuals.
- *
- * The element type of `StateVisuals.states` — a variable-length list that
- * replaced the old 8 hardcoded `slotN*` field quartets + stringly-keyed
- * reflection. Carried only inside `std::vector<VisualState>` (never a direct
- * pointer-accessed component field), so it may hold a std::string; it marshals
- * to JS 1:1 via embind value_object + register_vector. Colour is flat r/g/b/a
- * (not glm::vec4) so it round-trips cleanly through the vector path. `sprite` is
- * a raw texture-handle id (0 = none).
- */
-struct VisualState {
- std::string name;
- f32 r{1.0f};
- f32 g{1.0f};
- f32 b{1.0f};
- f32 a{1.0f};
- u32 sprite{0};
- f32 scale{1.0f};
-};
-
} // namespace esengine
diff --git a/src/esengine/ecs/components/StateMachine.hpp b/src/esengine/ecs/components/StateMachine.hpp
deleted file mode 100644
index 7030962b5..000000000
--- a/src/esengine/ecs/components/StateMachine.hpp
+++ /dev/null
@@ -1,31 +0,0 @@
-// SPDX-License-Identifier: Apache-2.0
-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-#pragma once
-
-#include "../../core/Types.hpp"
-#include "../../core/Reflection.hpp"
-
-#include <string>
-
-namespace esengine::ecs {
-
-/**
- * @brief Generic named-state field for an entity.
- *
- * @details Holds the current state as a free-form string. State names are
- * user-defined (e.g. "normal", "hover", "pressed", "loading").
- * A StateMachine system compares `current` against `previous`
- * each frame and raises a transition event when they differ.
- */
-ES_COMPONENT()
-struct StateMachine {
- /** @brief Active state name. Written by drivers (Interactable, user code). */
- ES_PROPERTY()
- std::string current;
-
- /** @brief State as of the last processed frame; consumed by transition diffing. */
- ES_PROPERTY()
- std::string previous;
-};
-
-} // namespace esengine::ecs
diff --git a/src/esengine/ecs/components/StateVisuals.hpp b/src/esengine/ecs/components/StateVisuals.hpp
deleted file mode 100644
index 5873f01ec..000000000
--- a/src/esengine/ecs/components/StateVisuals.hpp
+++ /dev/null
@@ -1,56 +0,0 @@
-// SPDX-License-Identifier: Apache-2.0
-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-#pragma once
-
-#include "../../core/Types.hpp"
-#include "../../core/Reflection.hpp"
-#include "../../core/UITypes.hpp" // VisualState
-
-#include <vector>
-
-namespace esengine::ecs {
-
-/**
- * @brief Bitmask flags for `StateVisuals::transitionFlags`.
- *
- * @details Multiple transition modes may be combined. Values are bit
- * positions, not exclusive, so the field is stored as `u32`
- * rather than an ES_ENUM.
- */
-namespace StateVisualsTransition {
- constexpr u32 None = 0;
- constexpr u32 ColorTint = 1u << 0; // write color to targetGraphic UIVisual
- constexpr u32 SpriteSwap = 1u << 1; // write texture to targetGraphic UIVisual
- constexpr u32 Scale = 1u << 2; // multiply targetGraphic Transform scale
-}
-
-/**
- * @brief Maps state names to visual overrides on a target entity.
- *
- * @details A variable-length `states` list (replaced the old 8
- * hardcoded `slotN*` field quartets + stringly-keyed reflection). The
- * visual system reads the owning entity's StateMachine.current, finds
- * the matching VisualState by name, and applies its color / sprite /
- * scale to `targetGraphic` according to `transitionFlags`.
- *
- * `targetGraphic == INVALID_ENTITY` means "apply to self".
- */
-ES_COMPONENT()
-struct StateVisuals {
- ES_PROPERTY(entity_ref)
- Entity targetGraphic = INVALID_ENTITY;
-
- /** @brief Bitmask of StateVisualsTransition constants. */
- ES_PROPERTY()
- u32 transitionFlags{0};
-
- /** @brief Seconds over which to lerp color/scale on state change. 0 = snap. Sprite swap is always instant. */
- ES_PROPERTY()
- f32 fadeDuration{0.0f};
-
- /** @brief Named visual states; looked up by StateMachine.current. */
- ES_PROPERTY()
- std::vector<VisualState> states;
-};
-
-} // namespace esengine::ecs
diff --git a/tools/eht/generators/metadata.py b/tools/eht/generators/metadata.py
index bce38e1c0..887271f4d 100644
--- a/tools/eht/generators/metadata.py
+++ b/tools/eht/generators/metadata.py
@@ -180,8 +180,8 @@ class MetadataGenerator:
return fields
# TS helper types a generated data interface field may reference (imported from
- # './types'); custom-struct names (Padding/Dimension/VisualState) come instead
- # from './wasm.generated'.
+ # './types'); custom-struct names (Padding/Dimension) come instead from
+ # './wasm.generated'.
_BASE_TS_TYPES = {'Entity', 'Vec2', 'Vec3', 'Vec4', 'Quat', 'Color'}
def _data_ts_type(self, prop: Property) -> str:
diff --git a/tools/eht/type_system.py b/tools/eht/type_system.py
index f6f975b1d..94793f9ee 100644
--- a/tools/eht/type_system.py
+++ b/tools/eht/type_system.py
@@ -24,17 +24,12 @@ class TypeSystem:
#
# Structs used as a DIRECT component field (Padding/Dimension) must have only
# primitive members in PtrLayoutGenerator.TYPE_SIZES (they go through the
- # pointer cursor). Structs used ONLY as a `std::vector<Struct>` element
- # (VisualState) are exempt — vectors are never pointer-accessed — so they may
- # carry std::string members.
+ # pointer cursor). Structs used ONLY as a `std::vector<Struct>` element are
+ # exempt — vectors are never pointer-accessed — so they may carry std::string
+ # members.
CUSTOM_STRUCTS = {
'Padding': [('left', 'f32'), ('top', 'f32'), ('right', 'f32'), ('bottom', 'f32')],
'Dimension': [('value', 'f32'), ('unit', 'u8')],
- 'VisualState': [
- ('name', 'std::string'),
- ('r', 'f32'), ('g', 'f32'), ('b', 'f32'), ('a', 'f32'),
- ('sprite', 'u32'), ('scale', 'f32'),
- ],
}
SKIP_TYPES = {'glm::mat4', 'std::function'}
@@ -100,7 +95,7 @@ class TypeSystem:
def struct_vector_js_name(self, cpp_type: str) -> str:
"""embind register_vector binding name for a struct-vector, e.g.
- std::vector<VisualState> -> VectorVisualState."""
+ std::vector<Foo> -> VectorFoo."""
return f'Vector{self.vector_elem(cpp_type)}'
def is_skip(self, cpp_type: str) -> bool:
@@ -154,7 +149,7 @@ class TypeSystem:
if self.is_struct_vector(t):
# embind can't auto-convert a JS array to a registered std::vector, so
# the wrapper field is an emscripten::val (a JS array) and from/toJS
- # convert element-by-element via the VisualState value_object.
+ # convert element-by-element via the element's value_object.
return 'emscripten::val'
return t
@@ -169,7 +164,7 @@ class TypeSystem:
if t in self.VECTOR_TYPES:
return self.VECTOR_TYPES[t][2]
if self.is_struct_vector(t):
- return f'{self.vector_elem(t)}[]' # e.g. VisualState[]
+ return f'{self.vector_elem(t)}[]'
if t in self.CUSTOM_STRUCTS:
return t # the struct name is its own TS interface name
return 'unknown'