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(cocos): Toggle, ToggleContainer, ProgressBar, Slider, BlockInputEvents and ScrollView, Vec4 and Mat4, a capture phase for touches; the drag/inertia/elastic physics is an engine module (ui/collection/scroll-physics) the compatibility layer adapts

yhh5e272c38a7da
diff --git a/pipeline/src/import/cocos/components.ts b/pipeline/src/import/cocos/components.ts
index d9d730bee..fad1d2cd6 100644
--- a/pipeline/src/import/cocos/components.ts
+++ b/pipeline/src/import/cocos/components.ts
@@ -305,25 +305,70 @@ function layout(c: CocosComponent): ComponentData {
return { type: `${LAYER}Layout`, data };
}
+/**
+ * An editor-authored handler list as the data model keeps it: the target nodes in a list of their own (they are entity references the
+ * loader remaps) and the rest of each record beside it. @p prefix names the pair: `click` gives `clickTargets` / `clickHandlers`.
+ */
+function handlerLists(events: unknown, prefix: string, ctx: ComponentContext): Raw {
+ const list = Array.isArray(events) ? events.filter(isObj) : [];
+ return {
+ [`${prefix}Targets`]: list.map((e) => e.target ?? null),
+ [`${prefix}Handlers`]: list.map((e) => {
+ const id = typeof e._componentId === 'string' ? e._componentId : '';
+ const known = id ? ctx.scriptClass?.(id)?.name : undefined;
+ return {
+ component: known ?? (typeof e.component === 'string' ? e.component : ''),
+ handler: typeof e.handler === 'string' ? e.handler : '',
+ customEventData: typeof e.customEventData === 'string' ? e.customEventData : '',
+ };
+ }),
+ };
+}
+
+const BUTTON_FIELDS: Record<string, string> = {
+ _interactable: 'interactable', _transition: 'transition', _zoomScale: 'zoomScale', _duration: 'duration',
+ _normalColor: 'normalColor', _hoverColor: 'hoverColor', _pressedColor: 'pressedColor', _disabledColor: 'disabledColor',
+ _target: 'target',
+};
+
function button(c: CocosComponent, ctx: ComponentContext): ComponentData {
- const data = renamed(c, {
- _interactable: 'interactable', _transition: 'transition', _zoomScale: 'zoomScale', _duration: 'duration',
- _normalColor: 'normalColor', _hoverColor: 'hoverColor', _pressedColor: 'pressedColor', _disabledColor: 'disabledColor',
- _target: 'target',
- });
- // An editor-authored handler holds a node, which the data model keeps in a list of its own beside the rest of the record.
- const events = Array.isArray(c.data.clickEvents) ? c.data.clickEvents.filter(isObj) : [];
- data.clickTargets = events.map((e) => e.target ?? null);
- data.clickHandlers = events.map((e) => {
- const id = typeof e._componentId === 'string' ? e._componentId : '';
- const known = id ? ctx.scriptClass?.(id)?.name : undefined;
- return {
- component: known ?? (typeof e.component === 'string' ? e.component : ''),
- handler: typeof e.handler === 'string' ? e.handler : '',
- customEventData: typeof e.customEventData === 'string' ? e.customEventData : '',
- };
- });
- return { type: `${LAYER}Button`, data };
+ return { type: `${LAYER}Button`, data: { ...renamed(c, BUTTON_FIELDS), ...handlerLists(c.data.clickEvents, 'click', ctx) } };
+}
+
+function toggle(c: CocosComponent, ctx: ComponentContext): ComponentData {
+ return {
+ type: `${LAYER}Toggle`,
+ data: {
+ ...renamed(c, { ...BUTTON_FIELDS, _isChecked: 'isChecked', _checkMark: 'checkMark', _toggleGroup: 'toggleGroup' }),
+ ...handlerLists(c.data.clickEvents, 'click', ctx),
+ ...handlerLists(c.data.checkEvents, 'check', ctx),
+ },
+ };
+}
+
+function toggleContainer(c: CocosComponent, ctx: ComponentContext): ComponentData {
+ return { type: `${LAYER}ToggleContainer`, data: { ...renamed(c, { _allowSwitchOff: 'allowSwitchOff' }), ...handlerLists(c.data.checkEvents, 'check', ctx) } };
+}
+
+function progressBar(c: CocosComponent): ComponentData {
+ return { type: `${LAYER}ProgressBar`, data: renamed(c, { _barSprite: 'barSprite', _mode: 'mode', _totalLength: 'totalLength', _progress: 'progress_', _reverse: 'reverse' }) };
+}
+
+function slider(c: CocosComponent, ctx: ComponentContext): ComponentData {
+ return { type: `${LAYER}Slider`, data: { ...renamed(c, { _handle: 'handle', _direction: 'direction', _progress: 'progress_' }), ...handlerLists(c.data.slideEvents, 'slide', ctx) } };
+}
+
+function scrollView(c: CocosComponent, ctx: ComponentContext): ComponentData {
+ return {
+ type: `${LAYER}ScrollView`,
+ data: {
+ ...renamed(c, {
+ _content: 'content', horizontal: 'horizontal', vertical: 'vertical', inertia: 'inertia', brake: 'brake', elastic: 'elastic',
+ bounceDuration: 'bounceDuration', cancelInnerEvents: 'cancelInnerEvents',
+ }),
+ ...handlerLists(c.data.scrollEvents, 'scroll', ctx),
+ },
+ };
}
/** A script component's fields, with asset references turned into project paths. */
@@ -395,6 +440,24 @@ export function convertNode(node: CocosNode, ctx: ComponentContext, where: strin
case 'cc.Button':
out = button(c, ctx);
break;
+ case 'cc.Toggle':
+ out = toggle(c, ctx);
+ break;
+ case 'cc.ToggleContainer':
+ out = toggleContainer(c, ctx);
+ break;
+ case 'cc.ProgressBar':
+ out = progressBar(c);
+ break;
+ case 'cc.Slider':
+ out = slider(c, ctx);
+ break;
+ case 'cc.ScrollView':
+ out = scrollView(c, ctx);
+ break;
+ case 'cc.BlockInputEvents':
+ out = { type: `${LAYER}BlockInputEvents`, data: { enabled: c.enabled } };
+ break;
default:
out = c.type.startsWith('cc.') ? null : script(c, ctx);
break;
diff --git a/pipeline/tests/cocos-import-layer.test.ts b/pipeline/tests/cocos-import-layer.test.ts
index c8a3fa03f..4ec99ecf9 100644
--- a/pipeline/tests/cocos-import-layer.test.ts
+++ b/pipeline/tests/cocos-import-layer.test.ts
@@ -33,7 +33,7 @@ const ui = (n: number, w: number, h: number): object =>
const scene = [
{ __type__: 'cc.SceneAsset', _name: 'main', scene: { __id__: 1 } }, // 0
{ __type__: 'cc.Scene', _name: 'main', _children: [{ __id__: 2 }] }, // 1
- node('Canvas', 1, [3, 4], [5, 6]), // 2
+ node('Canvas', 1, [3, 4, 12], [5, 6]), // 2
node('Buy', 2, [], [7, 8]), // 3
node('Hud', 2, [], [9, 11]), // 4
ui(2, 960, 640), // 5
@@ -45,6 +45,14 @@ const scene = [
buttonOf: { __id__: 8 }, icon: { __uuid__: PLAIN }, _hidden: { __id__: 99 } }, // 9
{ __type__: 'cc.ClickEvent', target: { __id__: 4 }, component: '', _componentId: compressUuid(HUD), handler: 'onBuy', customEventData: 'gold' }, // 10
{ __type__: 'cc.Layout', node: { __id__: 4 }, _enabled: true, _layoutType: 2, _resizeMode: 1, _spacingY: 8, _paddingTop: 4, _cellSize: { width: 50, height: 60 }, _verticalDirection: 1 }, // 11
+ node('Panel', 2, [], [13, 14, 15, 16, 17]), // 12
+ ui(12, 80, 20), // 13
+ { __type__: 'cc.Toggle', node: { __id__: 12 }, _enabled: true, _isChecked: true, _checkMark: { __id__: 15 }, _interactable: true, _transition: 0,
+ clickEvents: [], checkEvents: [{ __id__: 18 }] }, // 14
+ { __type__: 'cc.Sprite', node: { __id__: 12 }, _enabled: true, _color: { r: 255, g: 255, b: 255, a: 255 } }, // 15
+ { __type__: 'cc.ScrollView', node: { __id__: 12 }, _enabled: true, _content: { __id__: 3 }, vertical: true, horizontal: false, brake: 0.75, bounceDuration: 0.23, scrollEvents: [] }, // 16
+ { __type__: 'cc.ProgressBar', node: { __id__: 12 }, _enabled: true, _barSprite: { __id__: 15 }, _progress: 0.4, _totalLength: 80, _mode: 0 }, // 17
+ { __type__: 'cc.ClickEvent', target: { __id__: 4 }, component: '', _componentId: compressUuid(HUD), handler: 'onPicked', customEventData: 'x' }, // 18
];
describe('importing for the compatibility layer', () => {
@@ -142,6 +150,18 @@ describe('importing for the compatibility layer', () => {
expect(readFileSync(path.join(root, 'out', 'assets', 'cocos', 'resources', 'cfg', 'rules.json'), 'utf8')).toBe('{"a":1}');
});
+ it('carries a toggle, a scroll view and a progress bar, with their node and component references mapped', () => {
+ const panel = entity('Panel').id;
+ const t = comp('Panel', 'Cocos.Toggle').data;
+ expect([t.isChecked, t.checkMark]).toEqual([true, panel]);
+ expect(t.checkTargets).toEqual([entity('Hud').id]);
+ expect(t.checkHandlers).toEqual([{ component: 'Hud', handler: 'onPicked', customEventData: 'x' }]);
+ const sv = comp('Panel', 'Cocos.ScrollView').data;
+ expect([sv.content, sv.vertical, sv.brake, sv.bounceDuration]).toEqual([entity('Buy').id, true, 0.75, 0.23]);
+ const bar = comp('Panel', 'Cocos.ProgressBar').data;
+ expect([bar.barSprite, bar.progress_, bar.totalLength]).toEqual([panel, 0.4, 80]);
+ });
+
it('counts the components it maps', () => {
for (const type of ['cc.Widget', 'cc.Layout', 'cc.Button', 'cc.UITransform']) expect(report.components[type]!.unmapped).toBe(0);
});
diff --git a/sdk/src/cocos/index.ts b/sdk/src/cocos/index.ts
index 2dabd4d2f..727a44c2f 100644
--- a/sdk/src/cocos/index.ts
+++ b/sdk/src/cocos/index.ts
@@ -10,6 +10,7 @@
* Estella component with an instance — and the parts of Cocos that have no counterpart are not simulated (see each file).
*/
export { Vec2, Vec3, Quat, Color, Size, Rect, v2, v3, color, size, rect, math, toRadian, toDegree, clamp, clamp01, lerp } from './math';
+export { Vec4, Mat4 } from './mat4';
export { Component } from './component';
export { Node, setCurrentWorld, getCurrentWorld } from './node';
import { Node as NodeClass } from './node';
@@ -25,7 +26,7 @@ export {
AnimationClip, SceneAsset, EffectAsset, Mesh,
} from './assets';
export { registerBuiltinComponent, type BuiltinAdapter } from './builtins';
-export { UITransform, Label, LabelOutline, LabelShadow, Sprite, UIOpacity, Button, EventHandler, Widget, Layout, getVisibleSize, setVisibleSize } from './ui';
+export { UITransform, Label, LabelOutline, LabelShadow, Sprite, UIOpacity, Button, EventHandler, Widget, Layout, Toggle, ToggleContainer, ProgressBar, Slider, BlockInputEvents, ScrollView, getVisibleSize, setVisibleSize } from './ui';
export { Touch, EventTouch, pumpTouches } from './input';
export { tween, Tween, tweenUtil, easing, updateTweens } from './tween';
export { instantiate, loadPrefab, providePrefab } from './prefabs';
diff --git a/sdk/src/cocos/input.ts b/sdk/src/cocos/input.ts
index b2e46b110..c2346359e 100644
--- a/sdk/src/cocos/input.ts
+++ b/sdk/src/cocos/input.ts
@@ -64,9 +64,17 @@ export class EventTouch {
target: Node | null = null;
currentTarget: Node | null = null;
private stopped_ = false;
+ /** @internal Set by the dispatcher: cancels the touch for the node that claimed it. */
+ _cancelTarget: (() => void) | null = null;
constructor(public readonly type: string, public readonly touch: Touch, private readonly all_: Touch[]) {}
+ /**
+ * Tell the node the touch started on that it is cancelled, and stop sending it the rest of the gesture. A scroll view calls this
+ * once a drag is clearly a drag, so a button under the finger does not also click when it is lifted.
+ */
+ cancelInner(): void { this._cancelTarget?.(); }
+
get propagationStopped(): boolean { return this.stopped_; }
stopPropagation(): void { this.stopped_ = true; }
stopPropagationImmediate(): void { this.stopped_ = true; }
@@ -131,17 +139,27 @@ function hitNode(world: World, point: Vec2): Node | null {
return hits[0]!.node;
}
-/** Hand an event to a node and its ancestors, nearest first, until one stops it. */
-function dispatch(event: EventTouch, from: Node): void {
- event.target = from;
+/**
+ * Hand an event down and up the tree: capture listeners of the ancestors from the top, then the target's own, then the normal
+ * listeners from the target up through its ancestors, until one stops it. @p chainFrom is the node the capture path is read from,
+ * which differs from @p from once a capturing ancestor has cancelled the target.
+ */
+function dispatch(event: EventTouch, from: Node | null, chainFrom: Node | null = from): void {
+ const path: Node[] = [];
+ for (let n: Node | null = chainFrom; n; n = n.parent) path.unshift(n);
+ event.target = from ?? chainFrom;
+ const guard = (fn: () => void, node: Node): void => {
+ try { fn(); } catch (err) { log.error('cocos', `${node.name} ${event.type} listener threw`, err); }
+ };
+ for (const node of path) {
+ if (event.propagationStopped) return;
+ event.currentTarget = node;
+ guard(() => node._emitCapture(event.type, event), node);
+ }
for (let node: Node | null = from; node && !event.propagationStopped; node = node.parent) {
event.currentTarget = node;
- if (!node.hasEventListener(event.type)) continue;
- try {
- node.emit(event.type, event);
- } catch (err) {
- log.error('cocos', `${node.name} ${event.type} listener threw`, err);
- }
+ if (!node.hasEventListener(event.type, false)) continue;
+ guard(() => node!.emit(event.type, event), node);
}
}
@@ -149,7 +167,7 @@ function dispatch(event: EventTouch, from: Node): void {
// The per-frame system.
// ---------------------------------------------------------------------------------------------------------------------
-interface Gesture { touch: Touch; target: Node | null }
+interface Gesture { touch: Touch; target: Node | null; chainFrom: Node | null }
const gestures = new WeakMap<World, Map<number, Gesture>>();
function gesturesOf(world: World): Map<number, Gesture> {
@@ -158,6 +176,20 @@ function gesturesOf(world: World): Map<number, Gesture> {
return g;
}
+/** Give an event the means to cancel the node that claimed its gesture, without bubbling the cancellation back to the canceller. */
+function withCancel(event: EventTouch, gesture: Gesture, live: Touch[]): EventTouch {
+ event._cancelTarget = () => {
+ const target = gesture.target;
+ if (!target) return;
+ gesture.target = null;
+ const cancel = new EventTouch(Node.EventType.TOUCH_CANCEL, gesture.touch, live);
+ cancel.target = target;
+ cancel.currentTarget = target;
+ try { target.emit(Node.EventType.TOUCH_CANCEL, cancel); } catch (err) { log.error('cocos', `${target.name} cancel listener threw`, err); }
+ };
+ return event;
+}
+
/** Turn this frame's pointers into TOUCH_START / MOVE / END events. Exported so a test (or a host with its own loop) can drive it. */
export function pumpTouches(world: World, input: InputState, camera: UICameraData): void {
const book = gesturesOf(world);
@@ -172,24 +204,25 @@ export function pumpTouches(world: World, input: InputState, camera: UICameraDat
if (p.pressed && !gesture) {
const touch = new Touch(p.id, at.x, at.y);
- gesture = { touch, target: hitNode(world, new Vec2(at.x, at.y)) };
+ const hit = hitNode(world, new Vec2(at.x, at.y));
+ gesture = { touch, target: hit, chainFrom: hit };
book.set(p.id, gesture);
live.push(touch);
globalInput.emit(Node.EventType.TOUCH_START, new EventTouch(Node.EventType.TOUCH_START, touch, live));
- if (gesture.target) dispatch(new EventTouch(Node.EventType.TOUCH_START, touch, live), gesture.target);
+ if (gesture.chainFrom) dispatch(withCancel(new EventTouch(Node.EventType.TOUCH_START, touch, live), gesture, live), gesture.target, gesture.chainFrom);
}
if (!gesture) continue;
if (p.down && (at.x !== gesture.touch.getLocationX() || at.y !== gesture.touch.getLocationY())) {
gesture.touch._move(at.x, at.y);
globalInput.emit(Node.EventType.TOUCH_MOVE, new EventTouch(Node.EventType.TOUCH_MOVE, gesture.touch, live));
- if (gesture.target) dispatch(new EventTouch(Node.EventType.TOUCH_MOVE, gesture.touch, live), gesture.target);
+ if (gesture.chainFrom) dispatch(withCancel(new EventTouch(Node.EventType.TOUCH_MOVE, gesture.touch, live), gesture, live), gesture.target, gesture.chainFrom);
}
if (p.released) {
gesture.touch._move(at.x, at.y);
const type = p.cancelled ? Node.EventType.TOUCH_CANCEL : Node.EventType.TOUCH_END;
globalInput.emit(type, new EventTouch(type, gesture.touch, live));
- if (gesture.target) dispatch(new EventTouch(type, gesture.touch, live), gesture.target);
+ if (gesture.chainFrom) dispatch(withCancel(new EventTouch(type, gesture.touch, live), gesture, live), gesture.target, gesture.chainFrom);
book.delete(p.id);
}
}
diff --git a/sdk/src/cocos/mat4.ts b/sdk/src/cocos/mat4.ts
new file mode 100644
index 000000000..309a638a7
--- /dev/null
+++ b/sdk/src/cocos/mat4.ts
@@ -0,0 +1,172 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file cocos/mat4.ts
+ * @brief `Vec4` and `Mat4`, with Cocos's layout.
+ *
+ * `Mat4.m00..m03` is the first COLUMN, so the translation is `m12, m13, m14` and a point is transformed as `M * p`. The static
+ * forms write to `out` and return it, as the other value types do.
+ */
+import { Quat, Vec3 } from './math';
+
+export class Vec4 {
+ static readonly ZERO = Object.freeze(new Vec4(0, 0, 0, 0)) as Vec4;
+ static readonly ONE = Object.freeze(new Vec4(1, 1, 1, 1)) as Vec4;
+
+ constructor(public x = 0, public y = 0, public z = 0, public w = 0) {}
+
+ set(x: number | Vec4, y?: number, z?: number, w?: number): this {
+ if (typeof x === 'object') { this.x = x.x; this.y = x.y; this.z = x.z; this.w = x.w; } else { this.x = x; this.y = y ?? 0; this.z = z ?? 0; this.w = w ?? 0; }
+ return this;
+ }
+ clone(): Vec4 { return new Vec4(this.x, this.y, this.z, this.w); }
+ add(v: Vec4): this { this.x += v.x; this.y += v.y; this.z += v.z; this.w += v.w; return this; }
+ subtract(v: Vec4): this { this.x -= v.x; this.y -= v.y; this.z -= v.z; this.w -= v.w; return this; }
+ multiplyScalar(s: number): this { this.x *= s; this.y *= s; this.z *= s; this.w *= s; return this; }
+ length(): number { return Math.hypot(this.x, this.y, this.z, this.w); }
+ lengthSqr(): number { return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w; }
+ normalize(): this { const l = this.length(); if (l > 0) { this.x /= l; this.y /= l; this.z /= l; this.w /= l; } return this; }
+ dot(v: Vec4): number { return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w; }
+ equals(v: Vec4, epsilon = 1e-6): boolean {
+ return Math.abs(this.x - v.x) <= epsilon && Math.abs(this.y - v.y) <= epsilon && Math.abs(this.z - v.z) <= epsilon && Math.abs(this.w - v.w) <= epsilon;
+ }
+ toString(): string { return `(${this.x.toFixed(2)}, ${this.y.toFixed(2)}, ${this.z.toFixed(2)}, ${this.w.toFixed(2)})`; }
+
+ static add(out: Vec4, a: Vec4, b: Vec4): Vec4 { out.x = a.x + b.x; out.y = a.y + b.y; out.z = a.z + b.z; out.w = a.w + b.w; return out; }
+ static subtract(out: Vec4, a: Vec4, b: Vec4): Vec4 { out.x = a.x - b.x; out.y = a.y - b.y; out.z = a.z - b.z; out.w = a.w - b.w; return out; }
+ static lerp(out: Vec4, a: Vec4, b: Vec4, t: number): Vec4 {
+ out.x = a.x + (b.x - a.x) * t; out.y = a.y + (b.y - a.y) * t; out.z = a.z + (b.z - a.z) * t; out.w = a.w + (b.w - a.w) * t;
+ return out;
+ }
+ static transformMat4(out: Vec4, a: Vec4, m: Mat4): Vec4 {
+ const { x, y, z, w } = a;
+ out.x = m.m00 * x + m.m04 * y + m.m08 * z + m.m12 * w;
+ out.y = m.m01 * x + m.m05 * y + m.m09 * z + m.m13 * w;
+ out.z = m.m02 * x + m.m06 * y + m.m10 * z + m.m14 * w;
+ out.w = m.m03 * x + m.m07 * y + m.m11 * z + m.m15 * w;
+ return out;
+ }
+}
+
+type Sixteen = [number, number, number, number, number, number, number, number, number, number, number, number, number, number, number, number];
+
+export class Mat4 {
+ static readonly IDENTITY = Object.freeze(new Mat4()) as Mat4;
+
+ constructor(
+ public m00 = 1, public m01 = 0, public m02 = 0, public m03 = 0,
+ public m04 = 0, public m05 = 1, public m06 = 0, public m07 = 0,
+ public m08 = 0, public m09 = 0, public m10 = 1, public m11 = 0,
+ public m12 = 0, public m13 = 0, public m14 = 0, public m15 = 1,
+ ) {}
+
+ private a_(): Sixteen {
+ return [this.m00, this.m01, this.m02, this.m03, this.m04, this.m05, this.m06, this.m07, this.m08, this.m09, this.m10, this.m11, this.m12, this.m13, this.m14, this.m15];
+ }
+ private load_(a: ArrayLike<number>): this {
+ this.m00 = a[0]!; this.m01 = a[1]!; this.m02 = a[2]!; this.m03 = a[3]!;
+ this.m04 = a[4]!; this.m05 = a[5]!; this.m06 = a[6]!; this.m07 = a[7]!;
+ this.m08 = a[8]!; this.m09 = a[9]!; this.m10 = a[10]!; this.m11 = a[11]!;
+ this.m12 = a[12]!; this.m13 = a[13]!; this.m14 = a[14]!; this.m15 = a[15]!;
+ return this;
+ }
+
+ set(other: Mat4): this { return this.load_(other.a_()); }
+ clone(): Mat4 { return new Mat4().load_(this.a_()); }
+ identity(): this { return this.load_([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]); }
+ equals(o: Mat4, epsilon = 1e-6): boolean { const a = this.a_(), b = o.a_(); return a.every((v, i) => Math.abs(v - b[i]!) <= epsilon); }
+ toArray(out: number[] = []): number[] { const a = this.a_(); for (let i = 0; i < 16; i++) out[i] = a[i]!; return out; }
+
+ determinant(): number {
+ const [a00, a01, a02, a03, a10, a11, a12, a13, a20, a21, a22, a23, a30, a31, a32, a33] = this.a_();
+ const b00 = a00 * a11 - a01 * a10, b01 = a00 * a12 - a02 * a10, b02 = a00 * a13 - a03 * a10;
+ const b03 = a01 * a12 - a02 * a11, b04 = a01 * a13 - a03 * a11, b05 = a02 * a13 - a03 * a12;
+ const b06 = a20 * a31 - a21 * a30, b07 = a20 * a32 - a22 * a30, b08 = a20 * a33 - a23 * a30;
+ const b09 = a21 * a32 - a22 * a31, b10 = a21 * a33 - a23 * a31, b11 = a22 * a33 - a23 * a32;
+ return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
+ }
+
+ invert(): this { Mat4.invert(this, this); return this; }
+ transpose(): this { Mat4.transpose(this, this); return this; }
+ multiply(other: Mat4): this { Mat4.multiply(this, this, other); return this; }
+
+ getTranslation(out: Vec3 = new Vec3()): Vec3 { out.x = this.m12; out.y = this.m13; out.z = this.m14; return out; }
+ getScale(out: Vec3 = new Vec3()): Vec3 {
+ out.x = Math.hypot(this.m00, this.m01, this.m02);
+ out.y = Math.hypot(this.m04, this.m05, this.m06);
+ out.z = Math.hypot(this.m08, this.m09, this.m10);
+ return out;
+ }
+ getRotation(out: Quat = new Quat()): Quat {
+ const s = this.getScale();
+ const r00 = this.m00 / s.x, r01 = this.m01 / s.x, r02 = this.m02 / s.x;
+ const r10 = this.m04 / s.y, r11 = this.m05 / s.y, r12 = this.m06 / s.y;
+ const r20 = this.m08 / s.z, r21 = this.m09 / s.z, r22 = this.m10 / s.z;
+ const trace = r00 + r11 + r22;
+ if (trace > 0) {
+ const k = Math.sqrt(trace + 1) * 2;
+ out.w = 0.25 * k; out.x = (r12 - r21) / k; out.y = (r20 - r02) / k; out.z = (r01 - r10) / k;
+ } else if (r00 > r11 && r00 > r22) {
+ const k = Math.sqrt(1 + r00 - r11 - r22) * 2;
+ out.w = (r12 - r21) / k; out.x = 0.25 * k; out.y = (r10 + r01) / k; out.z = (r20 + r02) / k;
+ } else if (r11 > r22) {
+ const k = Math.sqrt(1 + r11 - r00 - r22) * 2;
+ out.w = (r20 - r02) / k; out.x = (r10 + r01) / k; out.y = 0.25 * k; out.z = (r21 + r12) / k;
+ } else {
+ const k = Math.sqrt(1 + r22 - r00 - r11) * 2;
+ out.w = (r01 - r10) / k; out.x = (r20 + r02) / k; out.y = (r21 + r12) / k; out.z = 0.25 * k;
+ }
+ return out;
+ }
+
+ static multiply(out: Mat4, a: Mat4, b: Mat4): Mat4 {
+ const A = a.a_(), B = b.a_(), R = new Array<number>(16);
+ for (let col = 0; col < 4; col++) {
+ for (let row = 0; row < 4; row++) {
+ let sum = 0;
+ for (let k = 0; k < 4; k++) sum += A[k * 4 + row]! * B[col * 4 + k]!;
+ R[col * 4 + row] = sum;
+ }
+ }
+ return out.load_(R);
+ }
+
+ static transpose(out: Mat4, a: Mat4): Mat4 {
+ const A = a.a_();
+ return out.load_([A[0], A[4], A[8], A[12], A[1], A[5], A[9], A[13], A[2], A[6], A[10], A[14], A[3], A[7], A[11], A[15]] as Sixteen);
+ }
+
+ /** The inverse; a singular matrix leaves @p out as it was. */
+ static invert(out: Mat4, a: Mat4): Mat4 {
+ const [a00, a01, a02, a03, a10, a11, a12, a13, a20, a21, a22, a23, a30, a31, a32, a33] = a.a_();
+ const b00 = a00 * a11 - a01 * a10, b01 = a00 * a12 - a02 * a10, b02 = a00 * a13 - a03 * a10;
+ const b03 = a01 * a12 - a02 * a11, b04 = a01 * a13 - a03 * a11, b05 = a02 * a13 - a03 * a12;
+ const b06 = a20 * a31 - a21 * a30, b07 = a20 * a32 - a22 * a30, b08 = a20 * a33 - a23 * a30;
+ const b09 = a21 * a32 - a22 * a31, b10 = a21 * a33 - a23 * a31, b11 = a22 * a33 - a23 * a32;
+ let det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
+ if (det === 0) return out;
+ det = 1 / det;
+ return out.load_([
+ (a11 * b11 - a12 * b10 + a13 * b09) * det, (a02 * b10 - a01 * b11 - a03 * b09) * det, (a31 * b05 - a32 * b04 + a33 * b03) * det, (a22 * b04 - a21 * b05 - a23 * b03) * det,
+ (a12 * b08 - a10 * b11 - a13 * b07) * det, (a00 * b11 - a02 * b08 + a03 * b07) * det, (a32 * b02 - a30 * b05 - a33 * b01) * det, (a20 * b05 - a22 * b02 + a23 * b01) * det,
+ (a10 * b10 - a11 * b08 + a13 * b06) * det, (a01 * b08 - a00 * b10 - a03 * b06) * det, (a30 * b04 - a31 * b02 + a33 * b00) * det, (a21 * b02 - a20 * b04 - a23 * b00) * det,
+ (a11 * b07 - a10 * b09 - a12 * b06) * det, (a00 * b09 - a01 * b07 + a02 * b06) * det, (a31 * b01 - a30 * b03 - a32 * b00) * det, (a20 * b03 - a21 * b01 + a22 * b00) * det,
+ ]);
+ }
+
+ /** Translation, rotation and scale composed as `T * R * S`. */
+ static fromTRS(out: Mat4, t: Vec3, q: Quat, s: Vec3): Mat4 {
+ const { x, y, z, w } = q;
+ const x2 = x + x, y2 = y + y, z2 = z + z;
+ const xx = x * x2, xy = x * y2, xz = x * z2, yy = y * y2, yz = y * z2, zz = z * z2, wx = w * x2, wy = w * y2, wz = w * z2;
+ return out.load_([
+ (1 - (yy + zz)) * s.x, (xy + wz) * s.x, (xz - wy) * s.x, 0,
+ (xy - wz) * s.y, (1 - (xx + zz)) * s.y, (yz + wx) * s.y, 0,
+ (xz + wy) * s.z, (yz - wx) * s.z, (1 - (xx + yy)) * s.z, 0,
+ t.x, t.y, t.z, 1,
+ ]);
+ }
+ static fromTranslation(out: Mat4, t: Vec3): Mat4 { return out.load_([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, t.x, t.y, t.z, 1]); }
+ static fromScaling(out: Mat4, s: Vec3): Mat4 { return out.load_([s.x, 0, 0, 0, 0, s.y, 0, 0, 0, 0, s.z, 0, 0, 0, 0, 1]); }
+ static fromQuat(out: Mat4, q: Quat): Mat4 { return Mat4.fromTRS(out, Vec3.ZERO, q, Vec3.ONE); }
+}
diff --git a/sdk/src/cocos/math.ts b/sdk/src/cocos/math.ts
index 763a9d408..0dedcb7a2 100644
--- a/sdk/src/cocos/math.ts
+++ b/sdk/src/cocos/math.ts
@@ -54,6 +54,16 @@ export class Vec3 {
return this;
}
clone(): Vec3 { return new Vec3(this.x, this.y, this.z); }
+ /** A point through a matrix (w = 1), with the perspective divide. */
+ static transformMat4(out: Vec3, a: Vec3, m: { m00: number; m01: number; m02: number; m03: number; m04: number; m05: number; m06: number; m07: number; m08: number; m09: number; m10: number; m11: number; m12: number; m13: number; m14: number; m15: number }): Vec3 {
+ const x = a.x, y = a.y, z = a.z;
+ let w = m.m03 * x + m.m07 * y + m.m11 * z + m.m15;
+ w = w ? 1 / w : 1;
+ out.x = (m.m00 * x + m.m04 * y + m.m08 * z + m.m12) * w;
+ out.y = (m.m01 * x + m.m05 * y + m.m09 * z + m.m13) * w;
+ out.z = (m.m02 * x + m.m06 * y + m.m10 * z + m.m14) * w;
+ return out;
+ }
add(v: Vec3): this { this.x += v.x; this.y += v.y; this.z += v.z; return this; }
subtract(v: Vec3): this { this.x -= v.x; this.y -= v.y; this.z -= v.z; return this; }
multiplyScalar(s: number): this { this.x *= s; this.y *= s; this.z *= s; return this; }
diff --git a/sdk/src/cocos/node.ts b/sdk/src/cocos/node.ts
index a470643be..e4c203040 100644
--- a/sdk/src/cocos/node.ts
+++ b/sdk/src/cocos/node.ts
@@ -81,6 +81,8 @@ export class Node {
/** @internal */ readonly _world: World;
/** @internal */ readonly _entity: Entity;
private listeners_: Map<string, Listener[]> | null = null;
+ /** Listeners registered for the capture phase: they hear a touch on the way DOWN to its target, before the target does. */
+ private captureListeners_: Map<string, Listener[]> | null = null;
/** Cocos's `layer` bitmask: carried, not interpreted. */
layer = 1 << 25;
@@ -331,24 +333,37 @@ export class Node {
// ---- events ----------------------------------------------------------------------------------------------------
- on(type: string, callback: (...args: any[]) => void, target?: unknown, _useCapture?: boolean): typeof callback {
- this.addListener_(type, { callback, target, once: false });
+ on(type: string, callback: (...args: any[]) => void, target?: unknown, useCapture = false): typeof callback {
+ this.addListener_(type, { callback, target, once: false }, useCapture);
return callback;
}
once(type: string, callback: (...args: any[]) => void, target?: unknown): void {
this.addListener_(type, { callback, target, once: true });
}
- off(type: string, callback?: (...args: any[]) => void, target?: unknown): void {
- const list = this.listeners_?.get(type);
+ off(type: string, callback?: (...args: any[]) => void, target?: unknown, useCapture = false): void {
+ const map = useCapture ? this.captureListeners_ : this.listeners_;
+ const list = map?.get(type);
if (!list) return;
- this.listeners_!.set(type, list.filter((l) => (callback && l.callback !== callback) || (target !== undefined && l.target !== target)));
+ map!.set(type, list.filter((l) => (callback && l.callback !== callback) || (target !== undefined && l.target !== target)));
}
/** Remove every listener that was registered with @p target. */
targetOff(target: unknown): void {
- if (!this.listeners_) return;
- for (const [type, list] of this.listeners_) this.listeners_.set(type, list.filter((l) => l.target !== target));
+ for (const map of [this.listeners_, this.captureListeners_]) {
+ if (!map) continue;
+ for (const [type, list] of map) map.set(type, list.filter((l) => l.target !== target));
+ }
+ }
+ hasEventListener(type: string, useCapture?: boolean): boolean {
+ if (useCapture === true) return (this.captureListeners_?.get(type)?.length ?? 0) > 0;
+ if (useCapture === false) return (this.listeners_?.get(type)?.length ?? 0) > 0;
+ return (this.listeners_?.get(type)?.length ?? 0) > 0 || (this.captureListeners_?.get(type)?.length ?? 0) > 0;
+ }
+ /** @internal Call the capture-phase listeners for @p type. */
+ _emitCapture(type: string, ...args: any[]): void {
+ const list = this.captureListeners_?.get(type);
+ if (!list) return;
+ for (const l of [...list]) l.callback.call(l.target, ...args);
}
- hasEventListener(type: string): boolean { return (this.listeners_?.get(type)?.length ?? 0) > 0; }
emit(type: string, ...args: any[]): void {
const list = this.listeners_?.get(type);
if (!list) return;
@@ -359,15 +374,15 @@ export class Node {
}
dispatchEvent(event: { type: string }): void { this.emit(event.type, event); }
- private addListener_(type: string, listener: Listener): void {
+ private addListener_(type: string, listener: Listener, useCapture = false): void {
if (type.startsWith('touch-')) {
let set = touchListeners.get(this._world);
if (!set) touchListeners.set(this._world, (set = new Set()));
set.add(this._entity);
}
- if (!this.listeners_) this.listeners_ = new Map();
- const list = this.listeners_.get(type);
- if (list) list.push(listener); else this.listeners_.set(type, [listener]);
+ const map = useCapture ? (this.captureListeners_ ??= new Map()) : (this.listeners_ ??= new Map());
+ const list = map.get(type);
+ if (list) list.push(listener); else map.set(type, [listener]);
}
}
diff --git a/sdk/src/cocos/ui/button.ts b/sdk/src/cocos/ui/button.ts
index 0619ebb37..edb67ad67 100644
--- a/sdk/src/cocos/ui/button.ts
+++ b/sdk/src/cocos/ui/button.ts
@@ -42,6 +42,21 @@ export class EventHandler {
}
}
+/** Editor-authored handlers are stored as a list of target nodes beside a list of the rest; join them. */
+export function joinHandlers(
+ targets: Array<Node | null>,
+ records: Array<{ component: string; handler: string; customEventData: string }>,
+): EventHandler[] {
+ return records.map((r, i) => {
+ const e = new EventHandler();
+ e.target = targets[i] ?? null;
+ e.component = r.component;
+ e.handler = r.handler;
+ e.customEventData = r.customEventData;
+ return e;
+ });
+}
+
const Transition = Object.freeze({ NONE: 0, COLOR: 1, SPRITE: 2, SCALE: 3 });
const EventType = Object.freeze({ CLICK: 'click' });
@@ -67,16 +82,7 @@ export class Button extends Component {
private restScale_: { x: number; y: number; z: number } | null = null;
onLoad(): void {
- if (this.clickEvents.length === 0) {
- this.clickEvents = this.clickHandlers.map((h, i) => {
- const e = new EventHandler();
- e.target = this.clickTargets[i] ?? null;
- e.component = h.component;
- e.handler = h.handler;
- e.customEventData = h.customEventData;
- return e;
- });
- }
+ if (this.clickEvents.length === 0) this.clickEvents = joinHandlers(this.clickTargets, this.clickHandlers);
}
onEnable(): void {
@@ -109,10 +115,14 @@ export class Button extends Component {
if (this.interactable && this.enabledInHierarchy && inside) {
EventHandler.emitEvents(this.clickEvents, event);
this.node.emit(EventType.CLICK, this);
+ this.onClicked_(event);
}
event.stopPropagation();
}
+ /** A click has been delivered. A button has nothing more to do; a toggle flips here. */
+ protected onClicked_(_event: EventTouch): void { /* nothing */ }
+
private onTouchCancel(): void {
this.pressed_ = false;
this.applyTransition_();
@@ -148,20 +158,22 @@ export class Button extends Component {
}
/** Declare the button's component, so a scene that holds one finds it. */
+export const BUTTON_PROPS: Array<{ name: string; kind: 'number' | 'boolean' | 'color' | 'node' | 'json'; array?: boolean }> = [
+ { name: 'interactable', kind: 'boolean' },
+ { name: 'transition', kind: 'number' },
+ { name: 'zoomScale', kind: 'number' },
+ { name: 'duration', kind: 'number' },
+ { name: 'normalColor', kind: 'color' },
+ { name: 'hoverColor', kind: 'color' },
+ { name: 'pressedColor', kind: 'color' },
+ { name: 'disabledColor', kind: 'color' },
+ { name: 'target', kind: 'node' },
+ { name: 'clickTargets', kind: 'node', array: true },
+ { name: 'clickHandlers', kind: 'json' },
+];
+
export function declareButton(): void {
- declareClass(Button as never, 'Button', [
- { name: 'interactable', kind: 'boolean' },
- { name: 'transition', kind: 'number' },
- { name: 'zoomScale', kind: 'number' },
- { name: 'duration', kind: 'number' },
- { name: 'normalColor', kind: 'color' },
- { name: 'hoverColor', kind: 'color' },
- { name: 'pressedColor', kind: 'color' },
- { name: 'disabledColor', kind: 'color' },
- { name: 'target', kind: 'node' },
- { name: 'clickTargets', kind: 'node', array: true },
- { name: 'clickHandlers', kind: 'json' },
- ]);
+ declareClass(Button as never, 'Button', BUTTON_PROPS);
}
export const isButtonDeclared = (): boolean => classInfoNamed('Button') !== undefined;
diff --git a/sdk/src/cocos/ui/controls.ts b/sdk/src/cocos/ui/controls.ts
new file mode 100644
index 000000000..d14734788
--- /dev/null
+++ b/sdk/src/cocos/ui/controls.ts
@@ -0,0 +1,289 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file cocos/ui/controls.ts
+ * @brief `Toggle`, `ToggleContainer`, `ProgressBar`, `Slider` and `BlockInputEvents`.
+ *
+ * The engine has its own toggles and sliders, but they are built on its flex-laid-out UI nodes; an imported scene is world-space
+ * nodes with a rectangle each, so these are the Cocos components as small script classes over that, with Cocos's rules:
+ * a toggle flips on a click that ends inside it, a group keeps one checked unless it allows none, a bar's fill is its length
+ * times its progress, a slider reads progress from where the finger is along its rectangle.
+ *
+ * Like `Button`, they are declared script classes with stored settings, so a scene that holds one loads it.
+ */
+import { Component } from '../component';
+import { Node } from '../node';
+import { Vec3 } from '../math';
+import { declareClass } from '../host';
+import { Button, BUTTON_PROPS, EventHandler, joinHandlers } from './button';
+import { Sprite } from './sprite';
+import { UITransform } from './uiTransform';
+import type { EventTouch } from '../input';
+
+type Handlers = { component: string; handler: string; customEventData: string }[];
+
+// ---------------------------------------------------------------------------------------------------------------------
+// ToggleContainer / Toggle
+// ---------------------------------------------------------------------------------------------------------------------
+
+export class ToggleContainer extends Component {
+ allowSwitchOff = false;
+ checkTargets: Array<Node | null> = [];
+ checkHandlers: Handlers = [];
+ checkEvents: EventHandler[] = [];
+
+ onLoad(): void {
+ if (this.checkEvents.length === 0) this.checkEvents = joinHandlers(this.checkTargets, this.checkHandlers);
+ }
+
+ onEnable(): void { this.ensureValidState(); }
+
+ /** The toggles under this container that are switched on. */
+ get toggleItems(): Toggle[] {
+ const out: Toggle[] = [];
+ for (const child of this.node.children) {
+ const t = child.getComponent(Toggle);
+ if (t && t.enabled && child.active) out.push(t);
+ }
+ return out;
+ }
+
+ /** At least one on unless switching off is allowed, and never more than one. */
+ ensureValidState(): void {
+ const items = this.toggleItems;
+ const checked = items.filter((t) => t.isChecked);
+ if (!this.allowSwitchOff && checked.length === 0 && items.length > 0) items[0]!.isChecked = true;
+ else if (checked.length > 1) for (const t of checked.slice(1)) t.isChecked = false;
+ }
+
+ anyTogglesChecked(): boolean { return this.toggleItems.some((t) => t.isChecked); }
+ setAllTogglesOff(): void { for (const t of this.toggleItems) t.isChecked = false; }
+
+ /** @internal A toggle in the group switched on: the others go off. */
+ notifyToggleCheck(toggle: Toggle, emit = true): void {
+ for (const t of this.toggleItems) if (t !== toggle && t.isChecked) t.setChecked_(false, emit);
+ if (emit) {
+ EventHandler.emitEvents(this.checkEvents, toggle);
+ this.node.emit('toggle', this);
+ }
+ }
+}
+
+export class Toggle extends Button {
+ static readonly EventType = Object.freeze({ TOGGLE: 'toggle', CLICK: 'click' });
+
+ isChecked = false;
+ /** The graphic shown while checked. */
+ checkMark: Sprite | null = null;
+ toggleGroup: ToggleContainer | null = null;
+ checkTargets: Array<Node | null> = [];
+ checkHandlers: Handlers = [];
+ checkEvents: EventHandler[] = [];
+
+ onLoad(): void {
+ super.onLoad();
+ if (this.checkEvents.length === 0) this.checkEvents = joinHandlers(this.checkTargets, this.checkHandlers);
+ }
+
+ onEnable(): void {
+ super.onEnable();
+ this.updateMark_();
+ }
+
+ /** Check it, as a script's `toggle.check()`: events fire, and its group's others go off. */
+ check(): void { this.setChecked_(true, true); }
+ uncheck(): void { this.setChecked_(false, true); }
+ /** Set without any event. */
+ setIsCheckedWithoutNotify(value: boolean): void { this.isChecked = value; this.updateMark_(); }
+
+ protected onClicked_(_event: EventTouch): void {
+ if (!this.interactable) return;
+ const group = this.toggleGroup;
+ // in a group that needs one on, clicking the one that is on does nothing
+ if (group && group.enabled && this.isChecked && !group.allowSwitchOff) return;
+ this.setChecked_(!this.isChecked, true);
+ }
+
+ /** @internal */
+ setChecked_(value: boolean, emit: boolean): void {
+ if (this.isChecked === value) return;
+ this.isChecked = value;
+ this.updateMark_();
+ if (value && this.toggleGroup && this.toggleGroup.enabled) this.toggleGroup.notifyToggleCheck(this, emit);
+ if (emit) {
+ EventHandler.emitEvents(this.checkEvents, this);
+ this.node.emit(Toggle.EventType.TOGGLE, this);
+ }
+ }
+
+ private updateMark_(): void {
+ if (this.checkMark) this.checkMark.node.active = this.isChecked;
+ }
+}
+
+// ---------------------------------------------------------------------------------------------------------------------
+// ProgressBar
+// ---------------------------------------------------------------------------------------------------------------------
+
+const BarMode = Object.freeze({ HORIZONTAL: 0, VERTICAL: 1, FILLED: 2 });
+
+export class ProgressBar extends Component {
+ static readonly Mode = BarMode;
+
+ mode: number = BarMode.HORIZONTAL;
+ totalLength = 100;
+ progress_ = 0.5;
+ reverse = false;
+ barSprite: Sprite | null = null;
+
+ get progress(): number { return this.progress_; }
+ set progress(v: number) {
+ this.progress_ = Math.min(1, Math.max(0, Number.isFinite(v) ? v : 0));
+ this.update_();
+ }
+
+ onEnable(): void { this.update_(); }
+
+ private update_(): void {
+ const bar = this.barSprite;
+ if (!bar) return;
+ const length = this.totalLength * this.progress_;
+ if (this.mode === BarMode.FILLED) {
+ bar.fillRange = this.reverse ? -this.progress_ : this.progress_;
+ return;
+ }
+ const t = bar.node.getComponent(UITransform);
+ if (!t) return;
+ if (this.mode === BarMode.HORIZONTAL) t.width = length; else t.height = length;
+ }
+}
+
+// ---------------------------------------------------------------------------------------------------------------------
+// Slider
+// ---------------------------------------------------------------------------------------------------------------------
+
+const SliderDirection = Object.freeze({ HORIZONTAL: 0, VERTICAL: 1 });
+
+export class Slider extends Component {
+ static readonly Direction = SliderDirection;
+ static readonly EventType = Object.freeze({ SLIDE: 'slide' });
+
+ direction: number = SliderDirection.HORIZONTAL;
+ progress_ = 0.5;
+ handle: Button | null = null;
+ slideTargets: Array<Node | null> = [];
+ slideHandlers: Handlers = [];
+ slideEvents: EventHandler[] = [];
+
+ get progress(): number { return this.progress_; }
+ set progress(v: number) {
+ const next = Math.min(1, Math.max(0, Number.isFinite(v) ? v : 0));
+ if (next === this.progress_) return;
+ this.progress_ = next;
+ this.placeHandle_();
+ EventHandler.emitEvents(this.slideEvents, this);
+ this.node.emit(Slider.EventType.SLIDE, this);
+ }
+
+ onLoad(): void {
+ if (this.slideEvents.length === 0) this.slideEvents = joinHandlers(this.slideTargets, this.slideHandlers);
+ }
+
+ onEnable(): void {
+ this.node.on(Node.EventType.TOUCH_START, this.onTouch_, this);
+ this.node.on(Node.EventType.TOUCH_MOVE, this.onTouch_, this);
+ const handle = this.handle?.node;
+ if (handle) {
+ handle.on(Node.EventType.TOUCH_START, this.onHandleTouch_, this);
+ handle.on(Node.EventType.TOUCH_MOVE, this.onHandleTouch_, this);
+ }
+ this.placeHandle_();
+ }
+
+ onDisable(): void {
+ this.node.off(Node.EventType.TOUCH_START, this.onTouch_, this);
+ this.node.off(Node.EventType.TOUCH_MOVE, this.onTouch_, this);
+ const handle = this.handle?.node;
+ if (handle) {
+ handle.off(Node.EventType.TOUCH_START, this.onHandleTouch_, this);
+ handle.off(Node.EventType.TOUCH_MOVE, this.onHandleTouch_, this);
+ }
+ }
+
+ private onTouch_(event: EventTouch): void {
+ if (this.handle && !this.handle.interactable) return;
+ this.slideTo_(event);
+ event.stopPropagation();
+ }
+
+ private onHandleTouch_(event: EventTouch): void {
+ this.slideTo_(event);
+ event.stopPropagation();
+ }
+
+ /** Progress from where the finger is along the slider's rectangle. */
+ private slideTo_(event: EventTouch): void {
+ const t = this.node.getComponent(UITransform);
+ if (!t) return;
+ const loc = event.getUILocation();
+ const local = t.convertToNodeSpaceAR(new Vec3(loc.x, loc.y, 0));
+ this.progress = this.direction === SliderDirection.HORIZONTAL
+ ? (local.x + t.anchorX * t.width) / (t.width || 1)
+ : (local.y + t.anchorY * t.height) / (t.height || 1);
+ }
+
+ private placeHandle_(): void {
+ const handle = this.handle?.node;
+ const t = this.node.getComponent(UITransform);
+ if (!handle || !t) return;
+ const p = handle.getPosition();
+ if (this.direction === SliderDirection.HORIZONTAL) handle.setPosition(new Vec3(this.progress_ * t.width - t.anchorX * t.width, p.y, p.z));
+ else handle.setPosition(new Vec3(p.x, this.progress_ * t.height - t.anchorY * t.height, p.z));
+ }
+}
+
+// ---------------------------------------------------------------------------------------------------------------------
+// BlockInputEvents
+// ---------------------------------------------------------------------------------------------------------------------
+
+/** A node that takes every touch that lands on it, so nothing behind it hears it. */
+export class BlockInputEvents extends Component {
+ private readonly stop_ = (event: { stopPropagation(): void }): void => { event.stopPropagation(); };
+ private static readonly TYPES = [Node.EventType.TOUCH_START, Node.EventType.TOUCH_MOVE, Node.EventType.TOUCH_END, Node.EventType.TOUCH_CANCEL];
+
+ onEnable(): void { for (const t of BlockInputEvents.TYPES) this.node.on(t, this.stop_, this); }
+ onDisable(): void { for (const t of BlockInputEvents.TYPES) this.node.off(t, this.stop_, this); }
+}
+
+// ---------------------------------------------------------------------------------------------------------------------
+
+export function declareControls(): void {
+ declareClass(ToggleContainer as never, 'ToggleContainer', [
+ { name: 'allowSwitchOff', kind: 'boolean' },
+ { name: 'checkTargets', kind: 'node', array: true },
+ { name: 'checkHandlers', kind: 'json' },
+ ]);
+ declareClass(Toggle as never, 'Toggle', [
+ ...BUTTON_PROPS,
+ { name: 'isChecked', kind: 'boolean' },
+ { name: 'checkMark', kind: 'component', type: Sprite },
+ { name: 'toggleGroup', kind: 'component', type: ToggleContainer },
+ { name: 'checkTargets', kind: 'node', array: true },
+ { name: 'checkHandlers', kind: 'json' },
+ ]);
+ declareClass(ProgressBar as never, 'ProgressBar', [
+ { name: 'mode', kind: 'number' },
+ { name: 'totalLength', kind: 'number' },
+ { name: 'progress_', kind: 'number' },
+ { name: 'reverse', kind: 'boolean' },
+ { name: 'barSprite', kind: 'component', type: Sprite },
+ ]);
+ declareClass(Slider as never, 'Slider', [
+ { name: 'direction', kind: 'number' },
+ { name: 'progress_', kind: 'number' },
+ { name: 'handle', kind: 'component', type: Button },
+ { name: 'slideTargets', kind: 'node', array: true },
+ { name: 'slideHandlers', kind: 'json' },
+ ]);
+ declareClass(BlockInputEvents as never, 'BlockInputEvents', []);
+}
diff --git a/sdk/src/cocos/ui/index.ts b/sdk/src/cocos/ui/index.ts
index c4b79b07a..ac5dfec85 100644
--- a/sdk/src/cocos/ui/index.ts
+++ b/sdk/src/cocos/ui/index.ts
@@ -8,6 +8,8 @@ export { UITransform, uiTransformDef, ensureUITransform } from './uiTransform';
export { Label, LabelOutline, LabelShadow } from './label';
export { Sprite, UIOpacity } from './sprite';
export { Button, EventHandler, declareButton } from './button';
+export { Toggle, ToggleContainer, ProgressBar, Slider, BlockInputEvents } from './controls';
+export { ScrollView } from './scrollView';
export { Widget, alignWidget } from './widget';
export { Layout } from './layout';
export { getVisibleSize, setVisibleSize } from './screen';
diff --git a/sdk/src/cocos/ui/pass.ts b/sdk/src/cocos/ui/pass.ts
index c27346a4c..6a7c068b9 100644
--- a/sdk/src/cocos/ui/pass.ts
+++ b/sdk/src/cocos/ui/pass.ts
@@ -14,11 +14,15 @@ import { UICameraInfo } from '../../ui/core/ui-camera-info';
import { setCurrentWorld } from '../node';
import { alignAllWidgets, declareWidget } from './widget';
import { layoutAll, declareLayout } from './layout';
+import { declareControls } from './controls';
+import { declareScrollView } from './scrollView';
import { setVisibleSize, setWindowPixels } from './screen';
export function declareUiPass(): void {
declareWidget();
declareLayout();
+ declareControls();
+ declareScrollView();
const system = defineSystem(
[Res(UICameraInfo), GetWorld()],
(camera, world) => {
diff --git a/sdk/src/cocos/ui/scrollView.ts b/sdk/src/cocos/ui/scrollView.ts
new file mode 100644
index 000000000..695594ebd
--- /dev/null
+++ b/sdk/src/cocos/ui/scrollView.ts
@@ -0,0 +1,293 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file cocos/ui/scrollView.ts
+ * @brief `ScrollView`: a content node moved inside a view by dragging, with inertia and an elastic edge.
+ *
+ * The motion is the engine's own scroll physics (ui/collection/scroll-physics.ts); what this adds is Cocos's shape around it. The
+ * view is the content's parent, the content is a child that is bigger, and the offsets scripts read are Cocos's: `getScrollOffset()`
+ * is how far the content has moved toward its end (positive x = scrolled right, positive y = scrolled down).
+ *
+ * Touches are heard in the CAPTURE phase, so a drag that starts on a button inside the content still scrolls; once the finger has
+ * moved far enough to be a drag, the button is cancelled (`cancelInnerEvents`) and does not click on release.
+ *
+ * The glide and the spring have Cocos's character and not its digits: a flick goes on for a time that follows its speed and
+ * eases out, a pull past the end is damped and returns. Scripts that depend on exact distances should not expect them.
+ */
+import { Component } from '../component';
+import { Node } from '../node';
+import { Vec2, Vec3 } from '../math';
+import { declareClass } from '../host';
+import { ScrollAxis } from '../../ui/collection/scroll-physics';
+import { EventHandler, joinHandlers } from './button';
+import { UITransform } from './uiTransform';
+import type { EventTouch } from '../input';
+
+const EventType = Object.freeze({
+ SCROLL_TO_TOP: 'scroll-to-top',
+ SCROLL_TO_BOTTOM: 'scroll-to-bottom',
+ SCROLL_TO_LEFT: 'scroll-to-left',
+ SCROLL_TO_RIGHT: 'scroll-to-right',
+ SCROLLING: 'scrolling',
+ BOUNCE_TOP: 'bounce-top',
+ BOUNCE_BOTTOM: 'bounce-bottom',
+ BOUNCE_LEFT: 'bounce-left',
+ BOUNCE_RIGHT: 'bounce-right',
+ SCROLL_ENDED: 'scroll-ended',
+ TOUCH_UP: 'touch-up',
+ AUTOSCROLL_ENDED_WITH_THRESHOLD: 'autoscroll-ended-with-threshold',
+ SCROLL_BEGAN: 'scroll-began',
+});
+
+/** How far a finger must travel before the touch is a drag and the node under it is cancelled. */
+const DRAG_THRESHOLD = 7;
+
+export class ScrollView extends Component {
+ static readonly EventType = EventType;
+
+ content: Node | null = null;
+ horizontal = false;
+ vertical = true;
+ inertia = true;
+ brake = 0.5;
+ elastic = true;
+ bounceDuration = 1;
+ cancelInnerEvents = true;
+ scrollTargets: Array<Node | null> = [];
+ scrollHandlers: { component: string; handler: string; customEventData: string }[] = [];
+ scrollEvents: EventHandler[] = [];
+
+ private readonly x_ = new ScrollAxis();
+ private readonly y_ = new ScrollAxis();
+ private clock_ = 0;
+ private dragging_ = false;
+ private began_ = false;
+ private travelled_ = 0;
+ private last_: Vec3 | null = null;
+ private resting_ = true;
+ private edge_ = { top: false, bottom: false, left: false, right: false };
+
+ onLoad(): void {
+ if (this.scrollEvents.length === 0) this.scrollEvents = joinHandlers(this.scrollTargets, this.scrollHandlers);
+ }
+
+ onEnable(): void {
+ this.node.on(Node.EventType.TOUCH_START, this.onStart_, this, true);
+ this.node.on(Node.EventType.TOUCH_MOVE, this.onMove_, this, true);
+ this.node.on(Node.EventType.TOUCH_END, this.onEnd_, this, true);
+ this.node.on(Node.EventType.TOUCH_CANCEL, this.onCancel_, this, true);
+ // listening in capture alone leaves the node itself unclaimed when nothing under the finger listens
+ this.node.on(Node.EventType.TOUCH_START, noop, this);
+ this.syncAxes_();
+ this.place_();
+ }
+
+ onDisable(): void {
+ this.node.off(Node.EventType.TOUCH_START, this.onStart_, this, true);
+ this.node.off(Node.EventType.TOUCH_MOVE, this.onMove_, this, true);
+ this.node.off(Node.EventType.TOUCH_END, this.onEnd_, this, true);
+ this.node.off(Node.EventType.TOUCH_CANCEL, this.onCancel_, this, true);
+ this.node.off(Node.EventType.TOUCH_START, noop, this);
+ this.dragging_ = false;
+ }
+
+ update(dt: number): void {
+ this.clock_ += dt;
+ if (!this.dragging_) {
+ this.syncAxes_();
+ const moved = this.x_.update(dt) || this.y_.update(dt);
+ if (moved) { this.place_(); this.notify_(EventType.SCROLLING); }
+ const idle = !this.x_.moving && !this.y_.moving;
+ if (idle && !this.resting_) {
+ this.resting_ = true;
+ this.notify_(EventType.SCROLL_ENDED);
+ } else if (!idle) {
+ this.resting_ = false;
+ }
+ }
+ }
+
+ // ---- the Cocos API ------------------------------------------------------------------------------------------------
+
+ /** How far the content has moved toward its end on each axis (right and down are positive). */
+ getScrollOffset(): Vec2 { return new Vec2(this.x_.offset, this.y_.offset); }
+ getMaxScrollOffset(): Vec2 { this.syncAxes_(); return new Vec2(this.x_.max, this.y_.max); }
+ isScrolling(): boolean { return this.dragging_ || this.x_.moving || this.y_.moving; }
+ isAutoScrolling(): boolean { return !this.dragging_ && (this.x_.moving || this.y_.moving); }
+ stopAutoScroll(): void { this.x_.stop(); this.y_.stop(); }
+
+ scrollToOffset(offset: Vec2, timeInSecond = 0, attenuated = true): void {
+ this.syncAxes_();
+ if (this.horizontal) this.x_.scrollTo(offset.x, timeInSecond, attenuated);
+ if (this.vertical) this.y_.scrollTo(offset.y, timeInSecond, attenuated);
+ if (timeInSecond <= 0) { this.place_(); this.notify_(EventType.SCROLLING); }
+ }
+
+ /** Scroll so the content's position along each axis is @p anchor, 0..1, where (0, 1) is the top-left. */
+ scrollTo(anchor: Vec2, timeInSecond = 0, attenuated = true): void {
+ this.syncAxes_();
+ this.scrollToOffset(new Vec2(anchor.x * this.x_.max, (1 - anchor.y) * this.y_.max), timeInSecond, attenuated);
+ }
+ scrollToTop(t = 0, a = true): void { this.scrollToOffset(new Vec2(this.x_.offset, 0), t, a); }
+ scrollToBottom(t = 0, a = true): void { this.syncAxes_(); this.scrollToOffset(new Vec2(this.x_.offset, this.y_.max), t, a); }
+ scrollToLeft(t = 0, a = true): void { this.scrollToOffset(new Vec2(0, this.y_.offset), t, a); }
+ scrollToRight(t = 0, a = true): void { this.syncAxes_(); this.scrollToOffset(new Vec2(this.x_.max, this.y_.offset), t, a); }
+ scrollToTopLeft(t = 0, a = true): void { this.scrollToOffset(new Vec2(0, 0), t, a); }
+ scrollToTopRight(t = 0, a = true): void { this.syncAxes_(); this.scrollToOffset(new Vec2(this.x_.max, 0), t, a); }
+ scrollToBottomLeft(t = 0, a = true): void { this.syncAxes_(); this.scrollToOffset(new Vec2(0, this.y_.max), t, a); }
+ scrollToBottomRight(t = 0, a = true): void { this.syncAxes_(); this.scrollToOffset(new Vec2(this.x_.max, this.y_.max), t, a); }
+
+ getContentPosition(): Vec3 { return this.content?.getPosition() ?? new Vec3(); }
+ setContentPosition(p: Vec3): void { this.content?.setPosition(p); this.readBack_(); }
+
+ // ---- geometry ------------------------------------------------------------------------------------------------------
+
+ private view_(): UITransform | null { return this.content?.parent?.getComponent(UITransform) ?? null; }
+ private contentSize_(): { w: number; h: number; ax: number; ay: number } | null {
+ const c = this.content;
+ const t = c?.getComponent(UITransform);
+ if (!c || !t) return null;
+ const s = c.getScale();
+ return { w: t.width * Math.abs(s.x), h: t.height * Math.abs(s.y), ax: t.anchorX, ay: t.anchorY };
+ }
+
+ private syncAxes_(): void {
+ const view = this.view_();
+ const c = this.contentSize_();
+ if (!view || !c) return;
+ for (const axis of [this.x_, this.y_]) {
+ axis.settings.inertia = this.inertia;
+ axis.settings.elastic = this.elastic;
+ axis.settings.brake = this.brake;
+ axis.settings.bounceTime = this.bounceDuration;
+ }
+ this.x_.setExtents(view.width, c.w);
+ this.y_.setExtents(view.height, c.h);
+ }
+
+ /** Put the content where the axes say. */
+ private place_(): void {
+ const view = this.view_();
+ const c = this.contentSize_();
+ const content = this.content;
+ if (!view || !c || !content) return;
+ const p = content.getPosition();
+ const viewLeft = -view.anchorX * view.width;
+ const viewTop = (1 - view.anchorY) * view.height;
+ // when the content is narrower than the view it sits at the start edge, as Cocos's does
+ const x = this.horizontal ? viewLeft - this.x_.offset + c.ax * c.w : p.x;
+ const y = this.vertical ? viewTop + this.y_.offset - (1 - c.ay) * c.h : p.y;
+ content.setPosition(new Vec3(x, y, p.z));
+ }
+
+ /** Take the offsets from where the content is now. */
+ private readBack_(): void {
+ const view = this.view_();
+ const c = this.contentSize_();
+ const content = this.content;
+ if (!view || !c || !content) return;
+ const p = content.getPosition();
+ this.x_.offset = -view.anchorX * view.width - (p.x - c.ax * c.w);
+ this.y_.offset = p.y + (1 - c.ay) * c.h - (1 - view.anchorY) * view.height;
+ }
+
+ // ---- touches -------------------------------------------------------------------------------------------------------
+
+ private local_(event: EventTouch): Vec3 | null {
+ const view = this.view_();
+ if (!view) return null;
+ const loc = event.getUILocation();
+ return view.convertToNodeSpaceAR(new Vec3(loc.x, loc.y, 0));
+ }
+
+ private onStart_(event: EventTouch): void {
+ if (!this.content) return;
+ this.syncAxes_();
+ this.readBack_();
+ this.x_.press();
+ this.y_.press();
+ this.dragging_ = true;
+ this.began_ = false;
+ this.travelled_ = 0;
+ this.last_ = this.local_(event);
+ }
+
+ private onMove_(event: EventTouch): void {
+ if (!this.dragging_ || !this.last_) return;
+ const now = this.local_(event);
+ if (!now) return;
+ const dx = now.x - this.last_.x, dy = now.y - this.last_.y;
+ this.last_ = now;
+ this.travelled_ += Math.hypot(dx, dy);
+ if (this.travelled_ < DRAG_THRESHOLD && !this.began_) return;
+ if (!this.began_) {
+ this.began_ = true;
+ this.resting_ = false;
+ if (this.cancelInnerEvents) event.cancelInner();
+ this.notify_(EventType.SCROLL_BEGAN);
+ }
+ const view = this.view_()!;
+ if (this.horizontal) this.x_.drag(-dx, this.clock_, view.width);
+ if (this.vertical) this.y_.drag(dy, this.clock_, view.height);
+ this.place_();
+ this.notify_(EventType.SCROLLING);
+ // a drag the scroll view owns is not the business of anything above it
+ event.stopPropagation();
+ }
+
+ private onEnd_(event: EventTouch): void {
+ if (!this.dragging_) return;
+ this.dragging_ = false;
+ this.notify_(EventType.TOUCH_UP);
+ if (this.began_) {
+ this.x_.release();
+ this.y_.release();
+ event.stopPropagation();
+ }
+ this.began_ = false;
+ }
+
+ private onCancel_(): void {
+ // a cancel the scroll view itself caused must not end its own drag; one from above does
+ if (this.began_) return;
+ this.dragging_ = false;
+ }
+
+ // ---- events --------------------------------------------------------------------------------------------------------
+
+ private notify_(type: string): void {
+ EventHandler.emitEvents(this.scrollEvents, this, type);
+ this.node.emit(type, this);
+ if (type !== EventType.SCROLLING) return;
+ const e = this.edge_;
+ const atTop = this.y_.offset <= 0, atBottom = this.y_.offset >= this.y_.max && this.y_.max > 0;
+ const atLeft = this.x_.offset <= 0, atRight = this.x_.offset >= this.x_.max && this.x_.max > 0;
+ if (atTop && !e.top) { this.notifyEdge_(EventType.SCROLL_TO_TOP); }
+ if (atBottom && !e.bottom) { this.notifyEdge_(EventType.SCROLL_TO_BOTTOM); }
+ if (atLeft && !e.left) { this.notifyEdge_(EventType.SCROLL_TO_LEFT); }
+ if (atRight && !e.right) { this.notifyEdge_(EventType.SCROLL_TO_RIGHT); }
+ e.top = atTop; e.bottom = atBottom; e.left = atLeft; e.right = atRight;
+ }
+
+ private notifyEdge_(type: string): void {
+ EventHandler.emitEvents(this.scrollEvents, this, type);
+ this.node.emit(type, this);
+ }
+}
+
+function noop(): void { /* claims the node for touches; the capture handlers do the work */ }
+
+export function declareScrollView(): void {
+ declareClass(ScrollView as never, 'ScrollView', [
+ { name: 'content', kind: 'node' },
+ { name: 'horizontal', kind: 'boolean' },
+ { name: 'vertical', kind: 'boolean' },
+ { name: 'inertia', kind: 'boolean' },
+ { name: 'brake', kind: 'number' },
+ { name: 'elastic', kind: 'boolean' },
+ { name: 'bounceDuration', kind: 'number' },
+ { name: 'cancelInnerEvents', kind: 'boolean' },
+ { name: 'scrollTargets', kind: 'node', array: true },
+ { name: 'scrollHandlers', kind: 'json' },
+ ]);
+}
diff --git a/sdk/src/ui/collection/scroll-physics.ts b/sdk/src/ui/collection/scroll-physics.ts
new file mode 100644
index 000000000..b10391245
--- /dev/null
+++ b/sdk/src/ui/collection/scroll-physics.ts
@@ -0,0 +1,159 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file ui/collection/scroll-physics.ts
+ * @brief Drag, inertia and elastic bounce for a scrolled content rectangle — independent of how the UI is laid out.
+ *
+ * A scroll area is two rectangles on one axis: the view, and the content that moves inside it. This module knows nothing of nodes
+ * or layout; it is given the two extents, told about drag deltas and releases, and answers where the content should be. A host
+ * (a UINode scroll container, a world-space node in the Cocos compatibility layer) reads the position back each frame and applies it.
+ *
+ * Positions are the content's offset from "top/left edge aligned with the view's": 0 is aligned, and scrolling toward the end is
+ * a growing positive offset up to {@link ScrollAxis.max}. Past either end is overscroll. All values are in the host's own units.
+ *
+ * The feel: a drag past an end is damped the further it goes; a release with velocity glides to rest on a quintic ease-out whose
+ * length and time follow the speed; a rest position past an end springs back over `bounceTime`; `brake` shortens the glide.
+ */
+
+export interface ScrollSettings {
+ /** Glide after release. */
+ inertia: boolean;
+ /** Allow overscroll with a spring back; off clamps hard. */
+ elastic: boolean;
+ /** 0..1: how hard the glide is cut short. 1 stops at once. */
+ brake: number;
+ /** Seconds for the spring back. */
+ bounceTime: number;
+}
+
+export const DEFAULT_SCROLL: Readonly<ScrollSettings> = { inertia: true, elastic: true, brake: 0.5, bounceTime: 1 };
+
+const quintOut = (t: number): number => { const k = t - 1; return k * k * k * k * k + 1; };
+
+/** One axis of a scroll area. */
+export class ScrollAxis {
+ /** The content's offset: 0 = start edges aligned, `max` = end edges aligned. */
+ offset = 0;
+ /** content extent - view extent, never negative. */
+ max = 0;
+ private from_ = 0;
+ private to_ = 0;
+ private t_ = 0;
+ private duration_ = 0;
+ private mode_: 'idle' | 'glide' | 'bounce' = 'idle';
+ private samples_: Array<{ t: number; offset: number }> = [];
+
+ constructor(public settings: ScrollSettings = { ...DEFAULT_SCROLL }) {}
+
+ /** Set the extents; the offset is kept. */
+ setExtents(view: number, content: number): void { this.max = Math.max(0, content - view); }
+
+ get moving(): boolean { return this.mode_ !== 'idle'; }
+
+ /** How far past an end the offset is: negative before the start, positive past the end, 0 inside. */
+ get overscroll(): number {
+ if (this.offset < 0) return this.offset;
+ if (this.offset > this.max) return this.offset - this.max;
+ return 0;
+ }
+
+ /** A finger lands: any glide stops where it is. */
+ press(): void {
+ this.mode_ = 'idle';
+ this.samples_ = [];
+ }
+
+ /** The finger moved by @p delta (positive = content toward its end), at @p time seconds. */
+ drag(delta: number, time: number, viewExtent: number): void {
+ const dir = Math.sign(delta);
+ let remaining = Math.abs(delta);
+ // the part of the move that stays inside the range is free; only what goes past an end is damped
+ const over = this.overscroll;
+ if (over === 0 || Math.sign(over) !== dir) {
+ const room = dir > 0 ? this.max - this.offset : this.offset; // distance to the end this move heads for
+ const free = over !== 0 ? remaining : Math.min(remaining, Math.max(0, room));
+ this.offset += dir * free;
+ remaining -= free;
+ }
+ if (remaining > 0) {
+ if (!this.settings.elastic) {
+ this.offset = Math.min(this.max, Math.max(0, this.offset));
+ } else {
+ const out = Math.abs(this.overscroll);
+ this.offset += dir * remaining * Math.max(0, 1 - out / Math.max(viewExtent, 1)) * 0.5;
+ }
+ }
+ this.samples_.push({ t: time, offset: this.offset });
+ while (this.samples_.length > 2 && time - this.samples_[0]!.t > 0.1) this.samples_.shift();
+ }
+
+ /** The finger lifted: glide if it was moving, then settle. */
+ release(): void {
+ const v = this.velocity_();
+ this.samples_ = [];
+ if (this.overscroll !== 0) { this.bounceBack_(); return; }
+ if (this.settings.inertia && Math.abs(v) > 20) this.glide_(v);
+ else this.mode_ = 'idle';
+ }
+
+ /** Move to @p target (clamped unless elastic) over @p seconds; 0 jumps. */
+ scrollTo(target: number, seconds = 0, attenuated = true): void {
+ const clamped = Math.min(this.max, Math.max(0, target));
+ if (seconds <= 0) { this.offset = clamped; this.mode_ = 'idle'; return; }
+ this.from_ = this.offset;
+ this.to_ = clamped;
+ this.t_ = 0;
+ this.duration_ = seconds;
+ this.mode_ = attenuated ? 'glide' : 'bounce';
+ }
+
+ stop(): void { this.mode_ = 'idle'; }
+
+ /** Advance @p dt seconds. Returns true if the offset changed. */
+ update(dt: number): boolean {
+ if (this.mode_ === 'idle') return false;
+ this.t_ += dt;
+ const k = Math.min(1, this.t_ / this.duration_);
+ const before = this.offset;
+ this.offset = this.from_ + (this.to_ - this.from_) * quintOut(k);
+ if (k >= 1) {
+ this.offset = this.to_;
+ // a glide that ended past an end (elastic) springs back
+ if (this.mode_ === 'glide' && this.overscroll !== 0) this.bounceBack_(); else this.mode_ = 'idle';
+ } else if (this.mode_ === 'glide' && this.settings.elastic === false) {
+ this.offset = Math.min(this.max, Math.max(0, this.offset));
+ }
+ return this.offset !== before;
+ }
+
+ private velocity_(): number {
+ const s = this.samples_;
+ if (s.length < 2) return 0;
+ const a = s[0]!, b = s[s.length - 1]!;
+ const dt = b.t - a.t;
+ return dt > 0 ? (b.offset - a.offset) / dt : 0;
+ }
+
+ private bounceBack_(): void {
+ this.from_ = this.offset;
+ this.to_ = Math.min(this.max, Math.max(0, this.offset));
+ this.t_ = 0;
+ this.duration_ = Math.max(this.settings.bounceTime, 0.01);
+ this.mode_ = 'bounce';
+ }
+
+ private glide_(velocity: number): void {
+ const speed = Math.abs(velocity);
+ // longer for a harder flick; the brake cuts both distance and time
+ const keep = 1 - Math.min(1, Math.max(0, this.settings.brake)) * 0.6;
+ const duration = Math.min(4, Math.sqrt(Math.sqrt(speed / 5))) * keep;
+ const distance = velocity * 0.7 * keep;
+ this.from_ = this.offset;
+ let to = this.offset + distance;
+ if (!this.settings.elastic) to = Math.min(this.max, Math.max(0, to));
+ this.to_ = to;
+ this.t_ = 0;
+ this.duration_ = Math.max(duration, 0.05);
+ this.mode_ = 'glide';
+ }
+}
diff --git a/sdk/tests/cocos/controls-wasm.test.ts b/sdk/tests/cocos/controls-wasm.test.ts
new file mode 100644
index 000000000..0e4dd54bc
--- /dev/null
+++ b/sdk/tests/cocos/controls-wasm.test.ts
@@ -0,0 +1,296 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Toggle, ToggleContainer, ProgressBar, Slider, BlockInputEvents and ScrollView, driven by touches against the real engine.
+ *
+ * The camera is faked as the identity, as in the touch tests, so a screen pixel is a world unit with y flipped.
+ */
+import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
+import type { ESEngineModule } from '../../src/wasm';
+import { App, flushPendingRegistrations } from '../../src/app/app';
+import { Transform, ensureBuiltinComponentsRegistered } from '../../src/ecs/component';
+import { AppContext, setDefaultContext } from '../../src/ecs/context';
+import { InputState } from '../../src/input/input';
+import { resetClassRegistry } from '../../src/cocos/registry';
+import { declareBuiltinScripts } from '../../src/cocos/builtinScripts';
+import {
+ BlockInputEvents, Button, Node, ProgressBar, ScrollView, Slider, Sprite, Toggle, ToggleContainer, UITransform, Vec2,
+ pumpTouches, setCurrentWorld,
+} from '../../src/cocos';
+import { HAS_WASM, loadWasmModule } from '../helpers/loadWasm';
+
+vi.mock('../../src/ui/util/ui-pick', () => ({ screenToUiWorld: (_cam: unknown, glX: number, glY: number) => ({ x: glX, y: glY }) }));
+
+const SURFACE_H = 800;
+const camera = { valid: true, screenH: SURFACE_H } as never;
+
+describe.skipIf(!HAS_WASM)('toggles, bars, sliders and scroll views', () => {
+ let module: ESEngineModule;
+ let registry: InstanceType<ESEngineModule['Registry']> | undefined;
+ let app: App | undefined;
+ let input: InputState;
+
+ beforeAll(async () => { ensureBuiltinComponentsRegistered(); module = await loadWasmModule(); });
+ afterEach(() => {
+ setCurrentWorld(null);
+ app?.world.disconnectCpp();
+ registry?.delete();
+ app = undefined;
+ registry = undefined;
+ });
+
+ function boot(): void {
+ setDefaultContext(new AppContext());
+ ensureBuiltinComponentsRegistered();
+ resetClassRegistry();
+ declareBuiltinScripts();
+ registry = new module.Registry();
+ app = App.new();
+ app.connectCpp(registry as never, module);
+ flushPendingRegistrations(app);
+ setCurrentWorld(app.world);
+ input = new InputState();
+ }
+ const W = () => app!.world;
+ const frame = async (n = 2): Promise<void> => { for (let i = 0; i < n; i++) await app!.tick(1 / 60); };
+
+ function box(name: string, x: number, y: number, w = 100, h = 100, parent?: Node): Node {
+ const n = new Node(name);
+ W().insert(n._entity, Transform);
+ n.addComponent(UITransform)!.setContentSize(w, h);
+ n.setPosition(x, y, 0);
+ parent?.addChild(n);
+ return n;
+ }
+
+ const screenOf = (wx: number, wy: number) => ({ x: wx, y: SURFACE_H - wy });
+ function pump(): void { pumpTouches(W(), input, camera); input.touchesStarted.clear(); input.touchesEnded.clear(); }
+ function press(wx: number, wy: number, id = 1): void { const p = { id, ...screenOf(wx, wy) }; input.touches.set(id, p); input.touchesStarted.set(id, p); pump(); }
+ function move(wx: number, wy: number, id = 1): void { input.touches.set(id, { id, ...screenOf(wx, wy) }); pump(); }
+ function release(wx: number, wy: number, id = 1): void { const p = { id, ...screenOf(wx, wy) }; input.touches.delete(id); input.touchesEnded.set(id, p); pump(); }
+ const tap = (x: number, y: number): void => { press(x, y); release(x, y); };
+
+ // ---- Toggle -----------------------------------------------------------------------------------------------------
+
+ async function toggle(name: string, x: number, y: number, parent?: Node): Promise<{ node: Node; t: Toggle; mark: Node }> {
+ const node = box(name, x, y, 60, 60, parent);
+ const mark = box(`${name}-mark`, 0, 0, 30, 30, node);
+ const markSprite = mark.addComponent(Sprite)!;
+ const t = node.addComponent<Toggle>('Toggle')!;
+ t.checkMark = markSprite;
+ await frame(1);
+ return { node, t, mark };
+ }
+
+ it('flips on a click, shows its check mark only while on, and says so', async () => {
+ boot();
+ const { node, t, mark } = await toggle('t', 200, 200);
+ const seen: boolean[] = [];
+ node.on(Toggle.EventType.TOGGLE, (x: Toggle) => seen.push(x.isChecked));
+ expect(mark.active).toBe(false);
+ tap(200, 200);
+ expect(t.isChecked).toBe(true);
+ expect(mark.active).toBe(true);
+ tap(200, 200);
+ expect(t.isChecked).toBe(false);
+ expect(mark.active).toBe(false);
+ expect(seen).toEqual([true, false]);
+ });
+
+ it('does not flip when it is not interactable, or when set without notify', async () => {
+ boot();
+ const { t, mark } = await toggle('t', 200, 200);
+ t.interactable = false;
+ tap(200, 200);
+ expect(t.isChecked).toBe(false);
+ t.interactable = true;
+ t.setIsCheckedWithoutNotify(true);
+ expect(mark.active).toBe(true);
+ });
+
+ it('keeps one on in a group, and leaves the one that is on alone when switching off is not allowed', async () => {
+ boot();
+ const holder = box('group', 400, 400, 400, 100);
+ const group = holder.addComponent<ToggleContainer>('ToggleContainer')!;
+ const a = await toggle('a', 300, 400, holder);
+ const b = await toggle('b', 500, 400, holder);
+ a.t.toggleGroup = group;
+ b.t.toggleGroup = group;
+ await frame(1);
+ expect(a.t.isChecked || b.t.isChecked).toBe(true); // the container made one on when it enabled
+ const firstOn = a.t.isChecked ? a : b;
+ const other = a.t.isChecked ? b : a;
+ tap(other.node.getWorldPosition().x, other.node.getWorldPosition().y);
+ expect(other.t.isChecked).toBe(true);
+ expect(firstOn.t.isChecked).toBe(false);
+ // clicking the one that is on does nothing
+ tap(other.node.getWorldPosition().x, other.node.getWorldPosition().y);
+ expect(other.t.isChecked).toBe(true);
+ // …unless the group allows none
+ group.allowSwitchOff = true;
+ tap(other.node.getWorldPosition().x, other.node.getWorldPosition().y);
+ expect(other.t.isChecked).toBe(false);
+ expect(group.anyTogglesChecked()).toBe(false);
+ });
+
+ // ---- ProgressBar -----------------------------------------------------------------------------------------------
+
+ it('sizes its bar to total length times progress, clamped', async () => {
+ boot();
+ const holder = box('holder', 0, 0, 200, 20);
+ const barNode = box('bar', 0, 0, 10, 20, holder);
+ const bar = barNode.addComponent(Sprite)!;
+ const p = holder.addComponent<ProgressBar>('ProgressBar')!;
+ p.barSprite = bar;
+ p.totalLength = 200;
+ p.progress = 0.25;
+ expect(barNode.getComponent(UITransform)!.width).toBe(50);
+ p.progress = 2;
+ expect(p.progress).toBe(1);
+ expect(barNode.getComponent(UITransform)!.width).toBe(200);
+ p.progress = -1;
+ expect(barNode.getComponent(UITransform)!.width).toBe(0);
+ p.mode = ProgressBar.Mode.VERTICAL;
+ p.progress = 0.5;
+ expect(barNode.getComponent(UITransform)!.height).toBe(100);
+ });
+
+ // ---- Slider ----------------------------------------------------------------------------------------------------
+
+ it('reads progress from where the finger is along it, moves its handle, and says it slid', async () => {
+ boot();
+ const track = box('track', 300, 300, 200, 20);
+ const knobNode = box('knob', 0, 0, 20, 20, track);
+ const knob = knobNode.addComponent<Button>('Button')!;
+ const s = track.addComponent<Slider>('Slider')!;
+ s.handle = knob;
+ await frame(1);
+ let slid = 0;
+ track.on(Slider.EventType.SLIDE, () => slid++);
+ press(250, 300); // a quarter of the way: the track spans 200..400
+ expect(s.progress).toBeCloseTo(0.25, 5);
+ move(350, 300);
+ expect(s.progress).toBeCloseTo(0.75, 5);
+ release(350, 300);
+ expect(knobNode.position.x).toBeCloseTo(50, 3); // 0.75 * 200 - 100
+ expect(slid).toBe(2);
+ });
+
+ // ---- BlockInputEvents ------------------------------------------------------------------------------------------
+
+ it('takes a touch so the node behind it does not hear it', async () => {
+ boot();
+ const root = box('root', 0, 0, 1000, 1000);
+ const behind = box('behind', 200, 200, 300, 300, root);
+ const front = box('front', 200, 200, 100, 100, root);
+ front.addComponent(BlockInputEvents);
+ await frame(1);
+ let heard = 0;
+ behind.on(Node.EventType.TOUCH_START, () => heard++);
+ tap(200, 200);
+ expect(heard).toBe(0);
+ tap(320, 200); // beside the blocker (it spans 150..250), still on the node behind (50..350)
+ expect(heard).toBe(1);
+ });
+
+ // ---- ScrollView ------------------------------------------------------------------------------------------------
+
+ async function scroller(horizontal = false): Promise<{ view: Node; content: Node; sv: ScrollView; button: Node; clicks: () => number }> {
+ const view = box('view', 300, 300, 200, 200);
+ const content = box('content', 0, 0, horizontal ? 800 : 200, horizontal ? 200 : 800, view);
+ content.getComponent(UITransform)!.setAnchorPoint(horizontal ? 0 : 0.5, horizontal ? 0.5 : 1);
+ const button = box('button', horizontal ? 100 : 0, horizontal ? 0 : -100, 80, 60, content);
+ const b = button.addComponent<Button>('Button')!;
+ void b;
+ let clicked = 0;
+ button.on(Button.EventType.CLICK, () => clicked++);
+ const sv = view.addComponent<ScrollView>('ScrollView')!;
+ sv.content = content;
+ sv.vertical = !horizontal;
+ sv.horizontal = horizontal;
+ await frame(1);
+ return { view, content, sv, button, clicks: () => clicked };
+ }
+
+ it('reports how far the content can go, and starts at the top', async () => {
+ boot();
+ const { sv } = await scroller();
+ expect(sv.getMaxScrollOffset().y).toBe(600);
+ expect(sv.getScrollOffset().y).toBe(0);
+ });
+
+ it('moves the content with the finger, a screen pixel for a world unit, and stops where it is without inertia', async () => {
+ boot();
+ const { content, sv } = await scroller();
+ sv.inertia = false;
+ const top = content.position.y;
+ press(300, 350);
+ move(300, 340); // 10 px: past the drag threshold
+ move(300, 300); // 50 more, upward on screen = toward the content's end
+ release(300, 300);
+ // the finger went DOWN the screen (y decreases) by 50 after the threshold, which pulls the content down: offset shrinks, but
+ // it was at the start, so it is an overscroll that springs back; check the direction through the offset sign mid-drag instead
+ expect(sv.getScrollOffset().y).toBeLessThanOrEqual(0);
+ await frame(90);
+ expect(sv.getScrollOffset().y).toBeCloseTo(0, 1);
+ expect(content.position.y).toBeCloseTo(top, 1);
+ });
+
+ it('scrolls toward the end when the finger moves up the screen, and glides on after a flick', async () => {
+ boot();
+ const { sv } = await scroller();
+ press(300, 250);
+ for (let i = 1; i <= 8; i++) { move(300, 250 + i * 10); await frame(1); } // up the screen: world y grows
+ const held = sv.getScrollOffset().y;
+ expect(held).toBeGreaterThan(40);
+ release(300, 330);
+ await frame(1);
+ await frame(60);
+ expect(sv.getScrollOffset().y).toBeGreaterThan(held);
+ expect(sv.getScrollOffset().y).toBeLessThanOrEqual(600 + 1e-6);
+ });
+
+ it('does not click a button the drag began on, but clicks it on a plain tap', async () => {
+ boot();
+ const { button, sv, clicks } = await scroller();
+ // the button is 100 below the content's top edge; the content's top is at the view's top (y 400)
+ const bx = 300, by = 300; // view centre: content top 400, button centre at 400 - 100 = 300
+ void button;
+ press(bx, by);
+ move(bx, by + 30);
+ move(bx, by + 60);
+ release(bx, by + 60);
+ expect(clicks()).toBe(0);
+ expect(sv.getScrollOffset().y).toBeGreaterThan(0);
+
+ sv.scrollToTop(0);
+ await frame(2);
+ tap(bx, by);
+ expect(clicks()).toBe(1);
+ });
+
+ it('scrolls to the end, to a place over a time, and says it got there', async () => {
+ boot();
+ const { sv, view } = await scroller();
+ const seen: string[] = [];
+ for (const t of [ScrollView.EventType.SCROLL_TO_BOTTOM, ScrollView.EventType.SCROLL_ENDED]) view.on(t, () => seen.push(t));
+ sv.scrollToBottom(0);
+ expect(sv.getScrollOffset().y).toBe(600);
+ sv.scrollToTop(0);
+ sv.scrollToOffset(new Vec2(0, 300), 0.5);
+ await frame(40);
+ expect(sv.getScrollOffset().y).toBe(300);
+ expect(seen).toContain(ScrollView.EventType.SCROLL_TO_BOTTOM);
+ expect(seen).toContain(ScrollView.EventType.SCROLL_ENDED);
+ });
+
+ it('scrolls sideways when horizontal', async () => {
+ boot();
+ const { sv } = await scroller(true);
+ expect(sv.getMaxScrollOffset().x).toBe(600);
+ sv.scrollToRight(0);
+ expect(sv.getScrollOffset().x).toBe(600);
+ sv.scrollToLeft(0);
+ expect(sv.getScrollOffset().x).toBe(0);
+ });
+});
diff --git a/sdk/tests/ui/scroll-physics.test.ts b/sdk/tests/ui/scroll-physics.test.ts
new file mode 100644
index 000000000..fbfcb1371
--- /dev/null
+++ b/sdk/tests/ui/scroll-physics.test.ts
@@ -0,0 +1,111 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Drag, inertia and elastic bounce, with no layout or engine in the way.
+ */
+import { describe, expect, it } from 'vitest';
+import { ScrollAxis } from '../../src/ui/collection/scroll-physics';
+
+const run = (axis: ScrollAxis, seconds: number): void => { for (let i = 0; i < seconds * 60; i++) axis.update(1 / 60); };
+
+function axis(max = 500, over: Partial<ConstructorParameters<typeof ScrollAxis>[0]> = {}): ScrollAxis {
+ const a = new ScrollAxis({ inertia: true, elastic: true, brake: 0.5, bounceTime: 0.5, ...over });
+ a.setExtents(400, 400 + max);
+ return a;
+}
+
+describe('ScrollAxis', () => {
+ it('follows a drag inside its range', () => {
+ const a = axis();
+ a.press();
+ a.drag(30, 0.0, 400);
+ a.drag(20, 0.1, 400);
+ expect(a.offset).toBe(50);
+ expect(a.overscroll).toBe(0);
+ });
+
+ it('damps a drag past an end, more the further out it goes, and lets it back in freely', () => {
+ const a = axis();
+ a.press();
+ a.drag(-100, 0, 400); // 100 past the start
+ const first = a.offset;
+ expect(first).toBeLessThan(0);
+ expect(first).toBeGreaterThan(-100); // damped
+ a.drag(-100, 0.05, 400);
+ expect(a.offset - first).toBeGreaterThan(-100 * 0.5); // the second step moves less than the first would have
+ const out = a.offset;
+ a.drag(20, 0.1, 400);
+ expect(a.offset).toBe(out + 20); // back in: undamped
+ });
+
+ it('springs back inside its range after a release past an end', () => {
+ const a = axis(500, { bounceTime: 0.5 });
+ a.press();
+ a.drag(-80, 0, 400);
+ a.release();
+ run(a, 0.6);
+ expect(a.offset).toBeCloseTo(0, 3);
+ expect(a.moving).toBe(false);
+ });
+
+ it('glides on after a flick, further for a harder one, and rests', () => {
+ const slow = axis(5000), fast = axis(5000);
+ for (const [a, step] of [[slow, 10], [fast, 40]] as const) {
+ a.press();
+ for (let i = 0; i < 6; i++) a.drag(step, i * 0.016, 400);
+ a.release();
+ }
+ const atRelease = { slow: slow.offset, fast: fast.offset };
+ run(slow, 5); run(fast, 5);
+ expect(slow.offset).toBeGreaterThan(atRelease.slow);
+ expect(fast.offset - atRelease.fast).toBeGreaterThan(slow.offset - atRelease.slow);
+ expect(slow.moving).toBe(false);
+ expect(fast.moving).toBe(false);
+ });
+
+ it('does not glide with inertia off, and a finger landing stops a glide where it is', () => {
+ const still = axis(5000, { inertia: false });
+ still.press();
+ for (let i = 0; i < 6; i++) still.drag(30, i * 0.016, 400);
+ still.release();
+ const rest = still.offset;
+ run(still, 1);
+ expect(still.offset).toBe(rest);
+
+ const a = axis(5000);
+ a.press();
+ for (let i = 0; i < 6; i++) a.drag(30, i * 0.016, 400);
+ a.release();
+ run(a, 0.2);
+ const mid = a.offset;
+ a.press();
+ run(a, 1);
+ expect(a.offset).toBe(mid);
+ });
+
+ it('clamps hard when it is not elastic', () => {
+ const a = axis(500, { elastic: false });
+ a.press();
+ a.drag(-100, 0, 400);
+ expect(a.offset).toBe(0);
+ a.drag(2000, 0.1, 400);
+ expect(a.offset).toBe(500);
+ });
+
+ it('scrolls to a place over a time, clamped to its range, or at once', () => {
+ const a = axis(500);
+ a.scrollTo(300, 1);
+ run(a, 1.1);
+ expect(a.offset).toBe(300);
+ a.scrollTo(9999);
+ expect(a.offset).toBe(500);
+ a.scrollTo(-5);
+ expect(a.offset).toBe(0);
+ });
+
+ it('has nothing to scroll when the content fits', () => {
+ const a = new ScrollAxis();
+ a.setExtents(400, 300);
+ expect(a.max).toBe(0);
+ });
+});