A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(ui): shared UIController + declarative UIGear layer
yhh458ab0d35455
diff --git a/examples/ui-controller/.gitignore b/examples/ui-controller/.gitignorenew file mode 100644index 000000000..359472ac2--- /dev/null+++ b/examples/ui-controller/.gitignore@@ -0,0 +1,7 @@+node_modules/+dist/+.vscode/+.idea/+.DS_Store+Thumbs.db+.esengine/cache/diff --git a/examples/ui-controller/assets/scenes/main.esscene b/examples/ui-controller/assets/scenes/main.esscenenew file mode 100644index 000000000..f51af7bd4--- /dev/null+++ b/examples/ui-controller/assets/scenes/main.esscene@@ -0,0 +1,29 @@+{+ "version": "1.0",+ "name": "Main",+ "entities": [+ {+ "id": 0,+ "name": "Camera",+ "parent": null,+ "children": [],+ "components": [+ { "type": "Transform", "data": { "position": { "x": 0, "y": 0, "z": 10 } } },+ { "type": "Camera", "data": { "projectionType": 1, "orthoSize": 300, "isActive": true, "priority": 0 } }+ ],+ "visible": true+ },+ {+ "id": 1,+ "name": "Canvas",+ "parent": null,+ "children": [],+ "components": [+ { "type": "Transform", "data": {} },+ { "type": "Canvas", "data": { "designResolution": { "x": 800, "y": 600 }, "scaleMode": 2 } },+ { "type": "UINode", "data": {} }+ ],+ "visible": true+ }+ ]+}diff --git a/examples/ui-controller/assets/scenes/main.esscene.meta b/examples/ui-controller/assets/scenes/main.esscene.metanew file mode 100644index 000000000..c48ce2f91--- /dev/null+++ b/examples/ui-controller/assets/scenes/main.esscene.meta@@ -0,0 +1,8 @@+{+ "uuid": "71738ee9-2745-45b7-aa22-3d4cb0b82e69",+ "version": "2.0",+ "type": "scene",+ "importer": {+ "autoMigrate": true+ }+}diff --git a/examples/ui-controller/project.esproject b/examples/ui-controller/project.esprojectnew file mode 100644index 000000000..92887b2a3--- /dev/null+++ b/examples/ui-controller/project.esproject@@ -0,0 +1,13 @@+{+ "formatVersion": "1",+ "name": "UI Controllers & Gears",+ "description": "Shared UI controllers + declarative per-page gears: a tab bar, an $interaction button, and a tweened popup.",+ "tag": "UI",+ "version": "0.1.0",+ "defaultScene": "assets/scenes/main.esscene",+ "designResolution": {+ "width": 800,+ "height": 600+ },+ "spineVersion": "none"+}diff --git a/examples/ui-controller/src/main.ts b/examples/ui-controller/src/main.tsnew file mode 100644index 000000000..388760d8b--- /dev/null+++ b/examples/ui-controller/src/main.ts@@ -0,0 +1,8 @@+// UI Controllers & Gears — a shared UIController drives many elements through+// declarative UIGears (no per-widget state code). Built lazily in an Update+// system so it runs once the scene's Canvas exists.+import { addSystemToSchedule, Schedule } from 'esengine';++import { buildSystem } from './systems/build';++addSystemToSchedule(Schedule.Update, buildSystem);diff --git a/examples/ui-controller/src/systems/build.ts b/examples/ui-controller/src/systems/build.tsnew file mode 100644index 000000000..528168c1d--- /dev/null+++ b/examples/ui-controller/src/systems/build.ts@@ -0,0 +1,235 @@+// Everything interesting lives here. Three demos, all built on the same two+// components — UIController (a named enum of "pages") and UIGear (per-page+// values for a field) — plus the free helpers setControllerPage / gearBinding:+//+// 1. Tab bar — one 'tab' controller on the Canvas; the three tab buttons,+// the content card's colour, and the card label's text are each+// a gear keyed to that controller. Click a tab → everything+// reflows. No bespoke state code anywhere.+// 2. $interaction button — a button whose normal/hover/pressed/disabled look+// is a UIController(interactionController) + a colour gear. This+// is the unified replacement for StateMachine + StateVisuals.+// 3. Popup — a 'popup' controller (closed/open) whose panel gears its scale+// and alpha with an eased tween, toggled by the button.+import {+ defineSystem, Res, GetWorld, Schedule,+ UIEvents,+ Transform, UIVisual, Interactable, UIInteraction,+ spawnUIEntity, px, percent, UIPositionType,+ UIController, UIGear, interactionController, controllerState,+ setControllerPage, getControllerPage, gearBinding,+ EasingType,+} from 'esengine';+import type { Entity, World, Color, UIEventQueue } from 'esengine';++const TAB_PAGES = ['overview', 'stats', 'about'] as const;+type TabPage = (typeof TAB_PAGES)[number];++const TAB_LABEL: Record<TabPage, string> = {+ overview: 'Overview', stats: 'Stats', about: 'About',+};+const CARD_COLOR: Record<TabPage, Color> = {+ overview: { r: 0.16, g: 0.18, b: 0.26, a: 1 },+ stats: { r: 0.21, g: 0.16, b: 0.26, a: 1 },+ about: { r: 0.15, g: 0.23, b: 0.21, a: 1 },+};+const CARD_TEXT: Record<TabPage, string> = {+ overview: 'One controller, many gears — this whole card is driven by the "tab" page.',+ stats: 'Switching tabs only changes a page name; every geared field follows.',+ about: 'Controllers + Gears are plain ECS components — they travel with prefabs.',+};++const ACCENT: Color = { r: 0.35, g: 0.55, b: 0.95, a: 1 };+const MUTED: Color = { r: 0.22, g: 0.24, b: 0.30, a: 1 };++const BTN_NORMAL: Color = { r: 0.30, g: 0.33, b: 0.42, a: 1 };+const BTN_HOVER: Color = { r: 0.39, g: 0.43, b: 0.55, a: 1 };+const BTN_PRESSED: Color = { r: 0.22, g: 0.24, b: 0.32, a: 1 };+const BTN_DISABLED: Color = { r: 0.20, g: 0.20, b: 0.24, a: 0.6 };++let built = false;++export const buildSystem = defineSystem(+ [Res(UIEvents), GetWorld()],+ (events: UIEventQueue, world: World) => {+ if (built) return;+ const canvas = world.findEntityByName('Canvas');+ if (canvas === null) return; // scene not loaded yet — try again next frame+ built = true;++ // The Canvas hosts the two shared controllers; gears on descendants+ // resolve up to it. ($interaction lives on the button itself.)+ world.insert(canvas, UIController, {+ controllers: [+ controllerState('tab', [...TAB_PAGES], 'overview'),+ controllerState('popup', ['closed', 'open'], 'closed'),+ ],+ });++ title(world, canvas, 'Controllers & Gears', 26, 24);+ title(world, canvas, 'Click the tabs · hover the button · toggle the popup', 14, 58, MUTED);++ buildTabBar(world, events, canvas);+ buildContentCard(world, canvas);+ buildInteractionButton(world, events, canvas);+ buildPopup(world, canvas);+ },+ { name: 'BuildUIControllerDemo' },+);++// ── 1. Tab bar ───────────────────────────────────────────────────────────────++function buildTabBar(world: World, events: UIEventQueue, canvas: Entity): void {+ TAB_PAGES.forEach((page, i) => {+ const btn = panel(world, canvas, {+ width: 150, height: 40, top: 96, centerOffsetX: (i - 1) * 160,+ color: MUTED,+ });+ makeInteractive(world, btn);+ label(world, btn, TAB_LABEL[page], 15);++ // Radio highlight: this button is ACCENT only on its own page.+ const pages: Record<string, Color> = {};+ for (const p of TAB_PAGES) pages[p] = p === page ? ACCENT : MUTED;+ world.insert(btn, UIGear, {+ bindings: [gearBinding('tab', 'UIVisual', 'color', pages,+ { easing: EasingType.EaseOutCubic, duration: 0.12 })],+ });++ events.on(btn, 'click', () => setControllerPage(world, canvas, 'tab', page));+ });+}++// ── 2. Content card (colour gear + text gear, both keyed to 'tab') ────────────++function buildContentCard(world: World, canvas: Entity): void {+ const card = panel(world, canvas, {+ width: 500, height: 150, top: 150, centerOffsetX: 0,+ color: CARD_COLOR.overview,+ });+ world.insert(card, UIGear, {+ bindings: [gearBinding('tab', 'UIVisual', 'color', CARD_COLOR,+ { easing: EasingType.EaseOutCubic, duration: 0.18 })],+ });++ const text = spawnUIEntity({+ world, parent: card,+ node: { position: UIPositionType.Absolute, insetLeft: px(24), insetRight: px(24),+ insetTop: px(0), insetBottom: px(0) },+ text: { content: CARD_TEXT.overview, fontSize: 16, wordWrap: true,+ color: { r: 0.92, g: 0.94, b: 0.98, a: 1 } },+ });+ // Text is a snap gear (strings can't interpolate).+ world.insert(text, UIGear, {+ bindings: [gearBinding('tab', 'Text', 'content', CARD_TEXT)],+ });+}++// ── 3. $interaction button — StateVisuals parity through the unified layer ─────++function buildInteractionButton(world: World, events: UIEventQueue, canvas: Entity): void {+ const btn = panel(world, canvas, {+ width: 220, height: 46, top: 326, centerOffsetX: 0,+ color: BTN_NORMAL,+ });+ makeInteractive(world, btn);+ label(world, btn, 'Toggle Popup', 15);++ // The button owns its own $interaction controller; the driver writes its+ // page from pointer state and this colour gear paints each page.+ world.insert(btn, UIController, { controllers: [interactionController()] });+ world.insert(btn, UIGear, {+ bindings: [gearBinding('$interaction', 'UIVisual', 'color', {+ normal: BTN_NORMAL, hover: BTN_HOVER, pressed: BTN_PRESSED, disabled: BTN_DISABLED,+ }, { easing: EasingType.EaseOutCubic, duration: 0.1 })],+ });++ events.on(btn, 'click', () => {+ const open = getControllerPage(world, canvas, 'popup') === 'open';+ setControllerPage(world, canvas, 'popup', open ? 'closed' : 'open');+ });+}++// ── 4. Popup — scale + alpha gears with an eased tween on the 'popup' controller ─++function buildPopup(world: World, canvas: Entity): void {+ const popup = spawnUIEntity({+ world, parent: canvas,+ node: { position: UIPositionType.Absolute, width: px(360), height: px(170),+ insetLeft: percent(50), marginLeft: px(-180),+ insetTop: percent(50), marginTop: px(-85) },+ visual: { color: { r: 0.16, g: 0.17, b: 0.24, a: 0 } }, // starts closed → alpha 0+ });+ // Match the 'closed' page at spawn (scale 0.7) so there's no startup pop.+ setScale(world, popup, 0.7);++ world.insert(popup, UIGear, {+ bindings: [+ gearBinding('popup', 'Transform', 'scale',+ { closed: { x: 0.7, y: 0.7, z: 1 }, open: { x: 1, y: 1, z: 1 } },+ { easing: EasingType.EaseOutBack, duration: 0.28 }),+ gearBinding('popup', 'UIVisual', 'color.a',+ { closed: 0, open: 0.97 },+ { easing: EasingType.EaseOutCubic, duration: 0.28 }),+ ],+ });++ const text = spawnUIEntity({+ world, parent: popup,+ node: { position: UIPositionType.Absolute, insetLeft: px(20), insetRight: px(20),+ insetTop: px(0), insetBottom: px(0) },+ text: { content: 'Popped via a "popup" controller.\nScale + alpha are gears with an EaseOutBack tween.',+ fontSize: 15, wordWrap: true, color: { r: 0, g: 0, b: 0, a: 0 } },+ });+ world.insert(text, UIGear, {+ bindings: [gearBinding('popup', 'Text', 'color.a',+ { closed: 0, open: 1 }, { easing: EasingType.EaseOutCubic, duration: 0.28 })],+ });+}++// ── small local UI helpers ────────────────────────────────────────────────────++interface PanelInit { width: number; height: number; top: number; centerOffsetX: number; color: Color; }++/** A horizontally-centered absolute panel at a given top offset. */+function panel(world: World, parent: Entity, p: PanelInit): Entity {+ return spawnUIEntity({+ world, parent,+ node: {+ position: UIPositionType.Absolute,+ width: px(p.width), height: px(p.height),+ insetLeft: percent(50), marginLeft: px(p.centerOffsetX - p.width / 2),+ insetTop: px(p.top),+ },+ visual: { color: p.color },+ });+}++function title(world: World, parent: Entity, content: string, fontSize: number, top: number, color?: Color): Entity {+ return spawnUIEntity({+ world, parent,+ node: { position: UIPositionType.Absolute, width: px(700),+ insetLeft: percent(50), marginLeft: px(-350), insetTop: px(top), height: px(fontSize + 8) },+ text: { content, fontSize, bold: fontSize >= 20, color: color ?? { r: 1, g: 1, b: 1, a: 1 } },+ });+}++function label(world: World, parent: Entity, content: string, fontSize: number): Entity {+ return spawnUIEntity({+ world, parent,+ node: { position: UIPositionType.Absolute, insetLeft: px(0), insetRight: px(0),+ insetTop: px(0), insetBottom: px(0) },+ text: { content, fontSize, color: { r: 1, g: 1, b: 1, a: 1 } },+ });+}++function makeInteractive(world: World, e: Entity): void {+ world.insert(e, Interactable, { enabled: true, blockRaycast: true, raycastTarget: true });+ world.insert(e, UIInteraction, { hovered: false, pressed: false, justPressed: false, justReleased: false });+}++function setScale(world: World, e: Entity, s: number): void {+ const t = world.get(e, Transform) as { scale: { x: number; y: number; z: number } };+ t.scale = { x: s, y: s, z: 1 };+ world.insert(e, Transform, t);+}diff --git a/examples/ui-controller/tsconfig.json b/examples/ui-controller/tsconfig.jsonnew file mode 100644index 000000000..0a8528b29--- /dev/null+++ b/examples/ui-controller/tsconfig.json@@ -0,0 +1,22 @@+{+ "compilerOptions": {+ "target": "ES2020",+ "module": "ESNext",+ "moduleResolution": "bundler",+ "strict": true,+ "esModuleInterop": true,+ "skipLibCheck": true,+ "forceConsistentCasingInFileNames": true,+ "declaration": false,+ "outDir": "./dist",+ "rootDir": ".",+ "baseUrl": ".",+ "paths": {+ "esengine": ["./.esengine/sdk/index.d.ts"],+ "esengine/wasm": ["./.esengine/sdk/wasm.d.ts"],+ "@esengine/editor": ["./.esengine/editor/index.d.ts"]+ }+ },+ "include": ["src/**/*"],+ "exclude": ["node_modules"]+}diff --git a/sdk/src/core-ui.ts b/sdk/src/core-ui.tsindex 9eaf196f6..585f32ce4 100644--- a/sdk/src/core-ui.ts+++ b/sdk/src/core-ui.ts@@ -107,6 +107,29 @@ export {type ReadonlySignal,} from './ui';+// ─── Controllers + Gears (shared UI state) ───────────────────────────────────+// A UIController is a named enum of pages scoped to a UI root; UIGears bind a+// component field to per-page values (snap or tween). The curated authoring+// surface — components, the page-control helpers, and the gear builder.+export {+ UIController,+ UIGear,+ interactionController,+ controllerState,+ INTERACTION_CONTROLLER,+ INTERACTION_PAGES,+ gearBinding,+ setControllerPage,+ getControllerPage,+ findControllerOwner,+ type UIControllerData,+ type ControllerState,+ type UIGearData,+ type GearBinding,+ type GearValue,+ type GearTween,+} from './ui';+// ─── UI code-composition surface ─────────────────────────────────────────────// Promoted so UI can be built in code, not just authored in the editor:// flexbox config, dimension helpers, node/visual/text builders, and the widgetdiff --git a/sdk/src/ui/controller/gear-apply.ts b/sdk/src/ui/controller/gear-apply.tsnew file mode 100644index 000000000..a5ced3f36--- /dev/null+++ b/sdk/src/ui/controller/gear-apply.ts@@ -0,0 +1,219 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @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:+ *+ * • 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.+ * • 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+ * `current` in the editor immediately previews that page, for free.+ *+ * The read/write/lerp helpers are pure and exported so unit tests (and a future+ * editor preview path) can exercise the value logic without a World.+ */+import { defineSystem, type SystemDef } from '../../system';+import { getComponent } from '../../component';+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 {+ UIController,+ INTERACTION_CONTROLLER,+ getControllerPage,+ type UIControllerData,+} from './ui-controller';+import { UIGear, type GearValue, type UIGearData } from './ui-gear';++// ─── Pure field/value helpers ───────────────────────────────────────────────++/** Read the value at a dot-path (returns undefined if the path doesn't resolve). */+export function readFieldPath(data: Record<string, any>, path: string): unknown {+ const parts = path.split('.');+ let cur: any = data;+ for (const p of parts) {+ if (cur == null || typeof cur !== 'object') return undefined;+ cur = cur[p];+ }+ return cur;+}++/**+ * Write `value` at a dot-path. Object values (Color/Vec) are shallow-cloned so a+ * shared authored value never becomes aliased across entities. Returns false+ * (writes nothing) when the path doesn't resolve to an existing leaf.+ */+export function writeFieldPath(data: Record<string, any>, path: string, value: unknown): boolean {+ const parts = path.split('.');+ let cur: any = data;+ for (let i = 0; i < parts.length - 1; i++) {+ cur = cur[parts[i]];+ if (cur == null || typeof cur !== 'object') return false;+ }+ const last = parts[parts.length - 1];+ if (cur == null || typeof cur !== 'object' || !(last in cur)) return false;+ cur[last] = (value !== null && typeof value === 'object') ? { ...(value as object) } : value;+ return true;+}++/** Numbers, colours (`r`…), and vectors (`x`…) interpolate; everything else snaps. */+export function isLerpable(v: unknown): boolean {+ if (typeof v === 'number') return true;+ if (v !== null && typeof v === 'object') {+ const o = v as Record<string, unknown>;+ return typeof o.r === 'number' || typeof o.x === 'number';+ }+ return false;+}++function lerp(a: number, b: number, t: number): number {+ return a + (b - a) * t;+}++/**+ * Interpolate between two gear values at `t`. Handles number, Color (r/g/b/a),+ * and Vec2/Vec3 (x/y/z); any non-numeric or shape-mismatched pair falls through+ * to the target (a snap). Type is chosen from `to` (the authored destination).+ */+export function lerpGearValue(from: unknown, to: unknown, t: number): unknown {+ if (typeof to === 'number') {+ return typeof from === 'number' ? lerp(from, to, t) : to;+ }+ if (to !== null && typeof to === 'object' && from !== null && typeof from === 'object') {+ const f = from as Record<string, number>;+ const g = to as Record<string, number>;+ if (typeof g.r === 'number' && typeof f.r === 'number') {+ return {+ r: lerp(f.r, g.r, t), g: lerp(f.g, g.g, t),+ b: lerp(f.b, g.b, t), a: lerp(f.a ?? 1, g.a ?? 1, t),+ };+ }+ if (typeof g.x === 'number' && typeof f.x === 'number') {+ const out: Record<string, number> = { x: lerp(f.x, g.x, t), y: lerp(f.y, g.y, t) };+ if ('z' in g) out.z = lerp(f.z ?? 0, g.z ?? 0, t);+ return out;+ }+ }+ return to;+}++// ─── 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+ * 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.+ */+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;++ 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 !== ctrl.current && ctrl.pages.includes(next)) {+ ctrl.current = next;+ world.insert(e, UIController, data);+ }+ }+ }, { name: 'InteractionControllerDriverSystem' });+}++/** Per-binding transition bookkeeping (kept out of the ECS, GC'd with the entity). */+interface BindingTx {+ /** Page this transition is heading to / settled at. */+ page: string;+ elapsed: number;+ /** Snapshot of the field value when the page changed (the tween's `from`). */+ from: unknown;+ /** Settled: value written, skip work until the page changes again. */+ done: boolean;+}++/**+ * 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.+ */+export function createGearApplySystem(world: World): SystemDef {+ const tracker = new EntityStateMap<Array<BindingTx | null>>();++ return defineSystem([Res(Time)], (time: TimeData) => {+ const dt = time.delta;+ const seen = new Set<Entity>();++ for (const e of world.getEntitiesWithComponents([UIGear])) {+ seen.add(e);+ const gear = world.get(e, UIGear) as UIGearData;+ const bindings = gear.bindings;++ let txs = tracker.get(e);+ if (!txs || txs.length !== bindings.length) {+ txs = bindings.map(() => null);+ tracker.set(e, txs);+ }++ for (let i = 0; i < bindings.length; i++) {+ const b = bindings[i];+ const page = getControllerPage(world, e, b.controller);+ if (page === null) continue;++ const target = b.pages[page];+ if (target === undefined) continue; // page not authored → leave field alone++ const comp = getComponent(b.component);+ if (!comp || !world.has(e, comp)) continue;++ const fade = Math.max(0, b.tween?.duration ?? 0);+ const lerpable = fade > 0 && isLerpable(target);++ let tx = txs[i];+ if (!tx || tx.page !== page) {+ const cur = readFieldPath(world.get(e, comp) as Record<string, any>, b.property);+ tx = { page, elapsed: 0, from: lerpable ? cur : (target as GearValue), done: false };+ txs[i] = tx;+ } else if (tx.done) {+ continue;+ } else {+ tx.elapsed += dt;+ }++ const t = lerpable ? Math.min(tx.elapsed / fade, 1) : 1;+ const value = (lerpable && t < 1)+ ? lerpGearValue(tx.from, target, applyEasing(b.tween!.easing, t))+ : target;++ const data = world.get(e, comp) as Record<string, any>;+ if (writeFieldPath(data, b.property, value)) {+ world.insert(e, comp, data);+ }+ if (t >= 1) tx.done = true;+ }+ }++ // Purge trackers for entities that no longer carry UIGear (the query only+ // yields live UIGear entities, so anything unseen is gone or stripped).+ for (const [e] of tracker) {+ if (!seen.has(e)) tracker.delete(e);+ }+ }, { name: 'GearApplySystem' });+}diff --git a/sdk/src/ui/controller/index.ts b/sdk/src/ui/controller/index.tsnew file mode 100644index 000000000..8559feadd--- /dev/null+++ b/sdk/src/ui/controller/index.ts@@ -0,0 +1,38 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file ui/controller/index.ts+ * @brief Barrel for the Controller + Gear layer.+ */+export {+ UIController,+ INTERACTION_CONTROLLER,+ INTERACTION_PAGES,+ interactionController,+ controllerState,+ findControllerOwner,+ getControllerPage,+ setControllerPage,+ type ControllerState,+ type UIControllerData,+} from './ui-controller';++export {+ UIGear,+ gearBinding,+ type GearValue,+ type GearTween,+ type GearBinding,+ type UIGearData,+} from './ui-gear';++export {+ createInteractionControllerDriverSystem,+ createGearApplySystem,+ readFieldPath,+ writeFieldPath,+ isLerpable,+ lerpGearValue,+} from './gear-apply';++export { UIControllerPlugin, uiControllerPlugin } from './plugin';diff --git a/sdk/src/ui/controller/plugin.ts b/sdk/src/ui/controller/plugin.tsnew file mode 100644index 000000000..cdf3092f6--- /dev/null+++ b/sdk/src/ui/controller/plugin.ts@@ -0,0 +1,35 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file ui/controller/plugin.ts+ * @brief UIControllerPlugin — wires the controller/gear systems.+ *+ * Runs the `$interaction` driver after the hit-test has written UIInteraction,+ * then the gear-apply pass after the driver so a pointer-driven page change lands+ * the same frame. Neither system is play-gated: in edit mode the driver is inert+ * (no UIInteraction is written outside play), while gear-apply still reflects each+ * controller's authored `current` page — that is the editor's live preview.+ */+import type { App, Plugin } from '../../app';+import { Schedule } from '../../system';+import { SystemLabel } from '../../systemLabels';+import { createGearApplySystem, createInteractionControllerDriverSystem } from './gear-apply';++export class UIControllerPlugin implements Plugin {+ name = 'uiController';++ build(app: App): void {+ app.addSystemToSchedule(+ Schedule.Update,+ createInteractionControllerDriverSystem(app.world),+ { runAfter: [SystemLabel.UIInteraction] },+ );+ app.addSystemToSchedule(+ Schedule.Update,+ createGearApplySystem(app.world),+ { runAfter: ['InteractionControllerDriverSystem'] },+ );+ }+}++export const uiControllerPlugin = new UIControllerPlugin();diff --git a/sdk/src/ui/controller/ui-controller.ts b/sdk/src/ui/controller/ui-controller.tsnew file mode 100644index 000000000..d5e295745--- /dev/null+++ b/sdk/src/ui/controller/ui-controller.ts@@ -0,0 +1,107 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @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+ * 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,+ * or a data-driven `.esfsm` (the same layering as `.esfsm → timeline.play`).+ * Many descendant {@link UIGear}s reference one controller by name and snap/tween+ * their properties as `current` changes; the resolution walks self → ancestors so+ * a controller can live on the UI root while gears live on the leaves.+ */+import { defineComponent } from '../../component';+import { walkParentChain } from '../util/helpers';+import type { Entity } from '../../types';+import type { World } from '../../world';++/** One named enum-state: a page list plus the currently selected page name. */+export interface ControllerState {+ /** Controller name, referenced by gears (e.g. "tab", "$interaction"). */+ name: string;+ /** Ordered page names (the enum's members). */+ pages: string[];+ /** Currently selected page name (should be one of `pages`). */+ current: string;+}++export interface UIControllerData {+ controllers: ControllerState[];+}++export const UIController = defineComponent<UIControllerData>('UIController', {+ controllers: [],+});++/**+ * 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).+ */+export const INTERACTION_CONTROLLER = '$interaction';++/** Canonical interaction pages, in the order the driver prefers them. */+export const INTERACTION_PAGES = ['normal', 'hover', 'pressed', 'disabled'] as const;++/** Build an interaction ControllerState (defaults to the 4 canonical pages). */+export function interactionController(pages: string[] = [...INTERACTION_PAGES]): ControllerState {+ return { name: INTERACTION_CONTROLLER, pages, current: pages[0] ?? 'normal' };+}++/** Build a plain named ControllerState (current defaults to the first page). */+export function controllerState(name: string, pages: string[], current?: string): ControllerState {+ return { name, pages, current: current ?? pages[0] ?? '' };+}++/** The ControllerState named `name` on `entity`, or null if `entity` has none. */+function controllerOn(world: World, entity: Entity, name: string): ControllerState | null {+ if (!world.has(entity, UIController)) return null;+ const data = world.get(entity, UIController) as UIControllerData;+ return data.controllers.find(c => c.name === name) ?? null;+}++/**+ * The entity that OWNS the controller named `name`, searching `entity` then its+ * ancestors (nearest wins). Null if no ancestor declares it. This is how a gear+ * on a leaf finds the controller on the UI root.+ */+export function findControllerOwner(world: World, entity: Entity, name: string): Entity | null {+ if (controllerOn(world, entity, name)) return entity;+ let owner: Entity | null = null;+ walkParentChain(world, entity, (ancestor) => {+ if (controllerOn(world, ancestor, name)) { owner = ancestor; return true; }+ return false;+ });+ return owner;+}++/** The current page of the nearest controller named `name`, or null if none. */+export function getControllerPage(world: World, entity: Entity, name: string): string | null {+ const owner = findControllerOwner(world, entity, name);+ if (owner === null) return null;+ return controllerOn(world, owner, name)!.current;+}++/**+ * Switch the nearest controller named `name` to `page`. No-op (returns false)+ * when the controller is missing, already on that page, or `page` is not one of+ * its declared pages (a guard against typos silently doing nothing visible).+ */+export function setControllerPage(world: World, entity: Entity, name: string, page: string): boolean {+ const owner = findControllerOwner(world, entity, name);+ if (owner === null) return false;+ const data = world.get(owner, UIController) as UIControllerData;+ const ctrl = data.controllers.find(c => c.name === name);+ if (!ctrl || ctrl.current === page || !ctrl.pages.includes(page)) return false;+ ctrl.current = page;+ world.insert(owner, UIController, data);+ return true;+}diff --git a/sdk/src/ui/controller/ui-gear.ts b/sdk/src/ui/controller/ui-gear.tsnew file mode 100644index 000000000..d454191a0--- /dev/null+++ b/sdk/src/ui/controller/ui-gear.ts@@ -0,0 +1,68 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @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+ * 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+ * a tab controller. The addressing mirrors Timeline's PropertyTrack (a `component`+ * name + a dot-path `property`) so both drive fields through the same reflection+ * writer. `pages` is a sparse map keyed by page name: a page with no entry leaves+ * the field untouched (the gear "doesn't care" on that page), and page names —+ * not indices — key it so reordering a controller's pages never misaligns values.+ */+import { defineComponent } from '../../component';+import type { Color, Vec2, Vec3 } from '../../types';+import type { EasingType } from '../../animation/Easing';++/**+ * A per-page value. Numbers, colours, and vectors interpolate when the binding+ * has a `tween`; strings, booleans (and anything else) always snap — e.g. a+ * `Text.content` gear that swaps the label per page. Colours/vectors are the+ * whole-field shape (e.g. `UIVisual.color` → a Color), matching how the inspector+ * and serialization store them.+ */+export type GearValue = number | boolean | string | Color | Vec2 | Vec3;++export interface GearTween {+ /** Easing curve applied across the transition (see {@link EasingType}). */+ easing: EasingType;+ /** Transition length in seconds; 0 (or absent tween) = snap. */+ duration: number;+}++export interface GearBinding {+ /** Name of the controller (resolved on self → nearest ancestor) that drives this. */+ controller: string;+ /** Target component name (e.g. "UIVisual", "Transform", "UINode"). */+ component: string;+ /** Dot-path within the component data (e.g. "color", "color.a", "scale.x"). */+ property: string;+ /** page name → value; a page absent here leaves the field alone on that page. */+ pages: Record<string, GearValue>;+ /** Optional interpolation on page change; omit for an instant snap. */+ tween?: GearTween;+}++export interface UIGearData {+ bindings: GearBinding[];+}++export const UIGear = defineComponent<UIGearData>('UIGear', {+ bindings: [],+});++/** Builder for a single {@link GearBinding} (keeps example/authoring code terse). */+export function gearBinding(+ controller: string,+ component: string,+ property: string,+ pages: Record<string, GearValue>,+ tween?: GearTween,+): GearBinding {+ return { controller, component, property, pages, ...(tween ? { tween } : {}) };+}diff --git a/sdk/src/ui/index.ts b/sdk/src/ui/index.tsindex 581d6e8c5..0176a1a0b 100644--- a/sdk/src/ui/index.ts+++ b/sdk/src/ui/index.ts@@ -149,6 +149,41 @@ export {export { UIBehaviorPlugin, uiBehaviorPlugin } from './behavior/plugin';+// ─── Controllers + Gears (shared UI state) ──────────────────────────────────++export {+ UIController,+ INTERACTION_CONTROLLER,+ INTERACTION_PAGES,+ interactionController,+ controllerState,+ findControllerOwner,+ getControllerPage,+ setControllerPage,+ type ControllerState,+ type UIControllerData,+} from './controller/ui-controller';++export {+ UIGear,+ gearBinding,+ type GearValue,+ type GearTween,+ type GearBinding,+ type UIGearData,+} from './controller/ui-gear';++export {+ createInteractionControllerDriverSystem,+ createGearApplySystem,+ readFieldPath,+ writeFieldPath,+ isLerpable,+ lerpGearValue,+} from './controller/gear-apply';++export { UIControllerPlugin, uiControllerPlugin } from './controller/plugin';+// ─── Collection ─────────────────────────────────────────────────────────────export {diff --git a/sdk/src/ui/ui-plugin.ts b/sdk/src/ui/ui-plugin.tsindex a3aa5a26e..de49790e3 100644--- a/sdk/src/ui/ui-plugin.ts+++ b/sdk/src/ui/ui-plugin.ts@@ -22,6 +22,7 @@ import { safeAreaPlugin } from './layout/safe-area';import { textPlugin } from './text/plugin';import { uiInteractionPlugin } from './input/interaction';import { uiBehaviorPlugin } from './behavior/plugin';+import { uiControllerPlugin } from './controller/plugin';import { dragPlugin } from './input/drag';import { focusPlugin } from './input/focus';import { textInputPlugin } from './text/text-input-plugin';@@ -44,6 +45,7 @@ export class UIPlugin implements Plugin {textPlugin.build(app);uiInteractionPlugin.build(app);uiBehaviorPlugin.build(app);+ uiControllerPlugin.build(app);dragPlugin.build(app);focusPlugin.build(app);textInputPlugin.build(app);diff --git a/sdk/tests/ui-controller-gear.test.ts b/sdk/tests/ui-controller-gear.test.tsnew file mode 100644index 000000000..c517088ad--- /dev/null+++ b/sdk/tests/ui-controller-gear.test.ts@@ -0,0 +1,313 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @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.+ */+import { describe, expect, it, beforeEach, vi } from 'vitest';+import { Transform, Parent, type TransformData } from '../src/component';+import { UIVisual, UIVisualType, type UIVisualData } from '../src/ui/core/ui-visual';+import { UINode } from '../src/ui/core/ui-node';+import { px } from '../src/ui/core/dimension';+import { Interactable, UIInteraction } from '../src/ui/input/interactable';+import { EasingType } from '../src/animation/Easing';+import {+ UIController,+ interactionController,+ controllerState,+ getControllerPage,+ setControllerPage,+ findControllerOwner,+ type UIControllerData,+} from '../src/ui/controller/ui-controller';+import { UIGear, gearBinding, type UIGearData } from '../src/ui/controller/ui-gear';+import {+ createGearApplySystem,+ createInteractionControllerDriverSystem,+ readFieldPath,+ writeFieldPath,+ isLerpable,+ lerpGearValue,+} from '../src/ui/controller/gear-apply';+import type { Entity } from '../src/types';+import type { SystemDef } from '../src/system';+import type { AnyComponentDef } from '../src/component';++/** Minimal World backed by per-component Maps (no C++ registry needed). */+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;+ },+ };+}+type MockWorld = ReturnType<typeof makeMockWorld>;++function runSystem(system: SystemDef, dt: number): void {+ (system._fn as (...a: unknown[]) => void)({ delta: dt, elapsed: 0, frameCount: 0 });+}++function makeVisual(color = { r: 1, g: 1, b: 1, a: 1 }): UIVisualData {+ return {+ visualType: UIVisualType.SolidColor, texture: 0, color,+ uvOffset: { x: 0, y: 0 }, uvScale: { x: 1, y: 1 },+ sliceBorder: { x: 0, y: 0, z: 0, w: 0 }, tileSize: { x: 32, y: 32 },+ fillMethod: 0, fillOrigin: 0, fillAmount: 1, material: 0, enabled: true,+ } as UIVisualData;+}+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 },+ };+}++// ─── Pure helpers ───────────────────────────────────────────────────────────++describe('gear field/value helpers', () => {+ it('reads and writes nested dot-paths', () => {+ const data = { color: { r: 1, g: 1, b: 1, a: 1 }, insetLeft: { value: 10, unit: 0 } };+ expect(readFieldPath(data, 'color')).toEqual({ r: 1, g: 1, b: 1, a: 1 });+ expect(readFieldPath(data, 'insetLeft.value')).toBe(10);+ expect(readFieldPath(data, 'missing.deep')).toBeUndefined();++ expect(writeFieldPath(data, 'insetLeft.value', 42)).toBe(true);+ expect(data.insetLeft.value).toBe(42);+ expect(writeFieldPath(data, 'nope', 1)).toBe(false);+ });++ it('writes primitive values including strings and booleans', () => {+ const data: Record<string, unknown> = { content: 'A', enabled: true, count: 0 };+ expect(writeFieldPath(data, 'content', 'B-page')).toBe(true);+ expect(data.content).toBe('B-page'); // strings snap through unchanged+ expect(writeFieldPath(data, 'enabled', false)).toBe(true);+ expect(data.enabled).toBe(false);+ });++ it('clones object values on write so authored values never alias', () => {+ const authored = { r: 0, g: 0, b: 1, a: 1 };+ const data = { color: { r: 1, g: 1, b: 1, a: 1 } };+ writeFieldPath(data, 'color', authored);+ expect(data.color).toEqual(authored);+ expect(data.color).not.toBe(authored); // distinct object+ });++ it('classifies lerpable values (number/color/vec) vs snap-only', () => {+ expect(isLerpable(5)).toBe(true);+ expect(isLerpable({ r: 1, g: 0, b: 0, a: 1 })).toBe(true);+ expect(isLerpable({ x: 1, y: 2 })).toBe(true);+ expect(isLerpable(true)).toBe(false);+ expect(isLerpable('page')).toBe(false);+ });++ it('interpolates numbers, colors, and vectors; snaps on shape mismatch', () => {+ expect(lerpGearValue(0, 10, 0.5)).toBe(5);+ expect(lerpGearValue({ r: 0, g: 0, b: 0, a: 1 }, { r: 1, g: 1, b: 1, a: 1 }, 0.5))+ .toEqual({ r: 0.5, g: 0.5, b: 0.5, a: 1 });+ expect(lerpGearValue({ x: 0, y: 0 }, { x: 4, y: 8 }, 0.25)).toEqual({ x: 1, y: 2 });+ expect(lerpGearValue(true, false, 0.5)).toBe(false); // non-numeric → snap to target+ });+});++// ─── Controller resolution ──────────────────────────────────────────────────++describe('UIController resolution', () => {+ let world: MockWorld;+ beforeEach(() => { world = makeMockWorld(); });++ it('resolves a controller on the entity itself', () => {+ const e = world.spawn();+ world.insert(e, UIController, { controllers: [controllerState('tab', ['a', 'b'], 'b')] });+ expect(getControllerPage(world as never, e, 'tab')).toBe('b');+ expect(findControllerOwner(world as never, e, 'tab')).toBe(e);+ expect(getControllerPage(world as never, e, 'missing')).toBeNull();+ });++ it('walks ancestors to find a controller on the UI root', () => {+ const root = world.spawn();+ const mid = world.spawn();+ const leaf = world.spawn();+ world.insert(root, UIController, { controllers: [controllerState('tab', ['a', 'b'], 'a')] });+ world.insert(mid, Parent, { entity: root });+ world.insert(leaf, Parent, { entity: mid });+ expect(getControllerPage(world as never, leaf, 'tab')).toBe('a');+ expect(findControllerOwner(world as never, leaf, 'tab')).toBe(root);+ });++ it('setControllerPage switches the page and guards typos / no-ops', () => {+ const e = world.spawn();+ world.insert(e, UIController, { controllers: [controllerState('tab', ['a', 'b'], 'a')] });+ expect(setControllerPage(world as never, e, 'tab', 'b')).toBe(true);+ expect(getControllerPage(world as never, e, 'tab')).toBe('b');+ expect(setControllerPage(world as never, e, 'tab', 'b')).toBe(false); // same page+ expect(setControllerPage(world as never, e, 'tab', 'zzz')).toBe(false); // unknown page+ expect(setControllerPage(world as never, e, 'nope', 'a')).toBe(false); // unknown controller+ });+});++// ─── Gear apply ─────────────────────────────────────────────────────────────++describe('GearApplySystem — snap', () => {+ let world: MockWorld;+ let e: Entity;+ beforeEach(() => {+ world = makeMockWorld();+ e = world.spawn();+ world.insert(e, UIVisual, makeVisual());+ world.insert(e, Transform, makeTransform(1));+ world.insert(e, UINode, { position: 1, insetLeft: px(0) });+ world.insert(e, UIController, { controllers: [controllerState('tab', ['a', 'b'], 'a')] });+ });++ it('applies the current page value to color / scale / inset', () => {+ world.insert(e, UIGear, {+ bindings: [+ gearBinding('tab', 'UIVisual', 'color', {+ a: { r: 1, g: 0, b: 0, a: 1 }, b: { r: 0, g: 0, b: 1, a: 1 },+ }),+ gearBinding('tab', 'Transform', 'scale.x', { a: 1, b: 2 }),+ gearBinding('tab', 'UINode', 'insetLeft.value', { a: 0, b: 100 }),+ ],+ } as UIGearData);++ const sys = createGearApplySystem(world as never);+ runSystem(sys, 1 / 60);+ expect((world.get(e, UIVisual) as UIVisualData).color).toEqual({ r: 1, g: 0, b: 0, a: 1 });+ expect((world.get(e, Transform) as TransformData).scale.x).toBe(1);+ expect((world.get(e, UINode) as any).insetLeft.value).toBe(0);++ setControllerPage(world as never, e, 'tab', 'b');+ runSystem(sys, 1 / 60);+ expect((world.get(e, UIVisual) as UIVisualData).color).toEqual({ r: 0, g: 0, b: 1, a: 1 });+ expect((world.get(e, Transform) as TransformData).scale.x).toBe(2);+ expect((world.get(e, UINode) as any).insetLeft.value).toBe(100);+ });++ it('leaves a field untouched on a page it has no value for (sparse)', () => {+ world.insert(e, UIGear, {+ bindings: [gearBinding('tab', 'UIVisual', 'color', { a: { r: 1, g: 0, b: 0, a: 1 } })],+ } as UIGearData);+ const sys = createGearApplySystem(world as never);+ runSystem(sys, 1 / 60);+ expect((world.get(e, UIVisual) as UIVisualData).color).toEqual({ r: 1, g: 0, b: 0, a: 1 });++ setControllerPage(world as never, e, 'tab', 'b'); // page 'b' unauthored for this gear+ (world.get(e, UIVisual) as UIVisualData).color = { r: 0.3, g: 0.3, b: 0.3, a: 1 };+ runSystem(sys, 1 / 60);+ expect((world.get(e, UIVisual) as UIVisualData).color).toEqual({ r: 0.3, g: 0.3, b: 0.3, a: 1 });+ });++ it('stops writing once settled (no per-frame write amplification)', () => {+ world.insert(e, UIGear, {+ bindings: [gearBinding('tab', 'UIVisual', 'color', { a: { r: 1, g: 0, b: 0, a: 1 } })],+ } as UIGearData);+ const sys = createGearApplySystem(world as never);+ runSystem(sys, 1 / 60);+ const spy = vi.spyOn(world, 'insert');+ runSystem(sys, 1 / 60);+ runSystem(sys, 1 / 60);+ expect(spy.mock.calls.filter(c => c[1] === UIVisual)).toHaveLength(0);+ });+});++describe('GearApplySystem — tween', () => {+ let world: MockWorld;+ let e: Entity;+ beforeEach(() => {+ world = makeMockWorld();+ e = world.spawn();+ world.insert(e, UIVisual, makeVisual({ r: 0, g: 0, b: 0, a: 1 }));+ world.insert(e, UIController, { controllers: [controllerState('c', ['off', 'on'], 'on')] });+ world.insert(e, UIGear, {+ bindings: [gearBinding('c', 'UIVisual', 'color',+ { off: { r: 0, g: 0, b: 0, a: 1 }, on: { r: 1, g: 1, b: 1, a: 1 } },+ { easing: EasingType.Linear, duration: 1.0 })],+ } as UIGearData);+ });++ it('eases color from the current value and clamps at duration', () => {+ const sys = createGearApplySystem(world as never);+ runSystem(sys, 0); // seed transition toward 'on' from black+ expect((world.get(e, UIVisual) as UIVisualData).color.r).toBeCloseTo(0);+ runSystem(sys, 0.5); // halfway+ expect((world.get(e, UIVisual) as UIVisualData).color.r).toBeCloseTo(0.5, 2);+ 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 });+ });+});++// ─── $interaction driver parity ─────────────────────────────────────────────++describe('InteractionControllerDriverSystem — StateVisuals parity through gears', () => {+ let world: MockWorld;+ let e: Entity;+ beforeEach(() => {+ world = makeMockWorld();+ e = world.spawn();+ world.insert(e, UIVisual, makeVisual());+ world.insert(e, Interactable, { enabled: true, blockRaycast: true, raycastTarget: true });+ world.insert(e, UIInteraction, { hovered: false, pressed: false, justPressed: false, justReleased: false });+ world.insert(e, UIController, { controllers: [interactionController()] });+ world.insert(e, UIGear, {+ bindings: [gearBinding('$interaction', 'UIVisual', 'color', {+ normal: { r: 1, g: 1, b: 1, a: 1 },+ hover: { r: 0.8, g: 0.9, b: 1, a: 1 },+ pressed: { r: 0.5, g: 0.5, b: 0.5, a: 1 },+ disabled: { r: 0.3, g: 0.3, b: 0.3, a: 1 },+ })],+ } as UIGearData);+ });++ function tick(driver: SystemDef, apply: SystemDef) {+ runSystem(driver, 1 / 60);+ runSystem(apply, 1 / 60);+ }++ it('drives $interaction page from pointer state and gears the color per page', () => {+ const driver = createInteractionControllerDriverSystem(world as never);+ const apply = createGearApplySystem(world as never);++ tick(driver, apply);+ expect(getControllerPage(world as never, e, '$interaction')).toBe('normal');+ expect((world.get(e, UIVisual) as UIVisualData).color).toEqual({ r: 1, g: 1, b: 1, a: 1 });++ world.insert(e, UIInteraction, { hovered: true, pressed: false, justPressed: false, justReleased: false });+ tick(driver, apply);+ expect(getControllerPage(world as never, e, '$interaction')).toBe('hover');+ expect((world.get(e, UIVisual) as UIVisualData).color).toEqual({ r: 0.8, g: 0.9, b: 1, a: 1 });++ world.insert(e, UIInteraction, { hovered: true, pressed: true, justPressed: false, justReleased: false });+ tick(driver, apply);+ expect(getControllerPage(world as never, e, '$interaction')).toBe('pressed');+ expect((world.get(e, UIVisual) as UIVisualData).color).toEqual({ r: 0.5, g: 0.5, b: 0.5, a: 1 });++ world.insert(e, Interactable, { enabled: false, blockRaycast: true, raycastTarget: true });+ tick(driver, apply);+ 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 });+ });+});