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(sdk): a panel can be told it appeared, instead of watching for it
yhh2b268005b522
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4abb9a479..77de16860 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,6 +14,32 @@ published separately; it ships inside the editor.## [Unreleased]+### Added++- **A UI node can say that it arrived on screen, or left it.** Everything a panel does when it+ appears — play the entrance, start the timer, refresh the count — had no event to hang on,+ because a node does not go away by itself: an ANCESTOR's `display` changed, and every node+ under it stopped being drawn without being told. The only way to notice was to walk the parent+ chain of every animated node, every frame, re-deriving what the layout pass had already+ computed. `shown` and `hidden` are those two moments on the same channel as `click`, so the+ answer is an EventBinding row rather than a system, and the whole subtree is told rather than+ just the node whose field changed.++ Visibility is read as the engine's own resolved bit, the same one rendering and hit-testing+ use, so it cannot drift from what you can see. That bit is reachable one entity at a time,+ which makes the scan the entire cost of the feature — so it is gated twice, and on a steady+ frame it is nothing: no listener, no scan (`EntityEventQueue.hasListenersFor` makes that O(1)),+ and no scan on a frame where no UINode was written and nothing moved in the hierarchy — the+ same pair of signals the layout solve and the physics reconcile already gate on. Measured in+ a real UI of 112 nodes: 0 reads per idle frame, one full pass on the frame a panel is toggled.++### Fixed++- **The mock-wasm test harness left every engine-calling plugin inert.** `bootMockApp` connected+ the world but not the App, and `engineApi(app)` answers with the App's module — so plugins that+ reach the engine optional-chained it away and their engine branches never ran under test. They+ passed, silently testing less than they read as testing.+## [0.40.0] - 2026-08-02The agent went from working to being pleasant to work with. It answers from the keyboarddiff --git a/docs/astro/src/content/docs/guides/events.mdx b/docs/astro/src/content/docs/guides/events.mdxindex 374a5e6fb..e77b0ea3b 100644--- a/docs/astro/src/content/docs/guides/events.mdx+++ b/docs/astro/src/content/docs/guides/events.mdx@@ -133,7 +133,20 @@ Widgets emit the standard set (`UIEventType`), and events **bubble**, so a row ohears its buttons:`click` · `press` · `release` · `hover_enter` · `hover_exit` · `focus` · `blur` ·-`change` · `submit` · `drag_start` · `drag_move` · `drag_end` · `scroll` · `select` · `deselect`+`change` · `submit` · `drag_start` · `drag_move` · `drag_end` · `scroll` · `select` · `deselect` ·+`shown` · `hidden`++`shown` and `hidden` are the exception to "a widget emits them": nobody clicked anything, the+node simply arrived on screen or left it — usually because an **ancestor** was shown or hidden,+which is what navigation, tabs and dialogs do. Every node in the subtree is told, so an entrance+animation is a row on the panel that plays it rather than a system that watches for it:++| Event | Action | Target |+|---|---|---|+| `shown` | `tween.play` | *(this entity)* |++The watching costs nothing until something listens for one of the two, and nothing again on a+frame where no UI moved.[Physics](/docs/guides/physics/) contacts reach the same channel (`PhysicsEventType`), so a[trigger area](/docs/guides/markers/) is wired exactly like a button — both participants getdiff --git a/docs/astro/src/content/docs/zh-cn/guides/events.mdx b/docs/astro/src/content/docs/zh-cn/guides/events.mdxindex b2bb88368..11205e02d 100644--- a/docs/astro/src/content/docs/zh-cn/guides/events.mdx+++ b/docs/astro/src/content/docs/zh-cn/guides/events.mdx@@ -127,7 +127,18 @@ registerAction('game.award', {按钮的事件:`click` · `press` · `release` · `hover_enter` · `hover_exit` · `focus` · `blur` ·-`change` · `submit` · `drag_start` · `drag_move` · `drag_end` · `scroll` · `select` · `deselect`+`change` · `submit` · `drag_start` · `drag_move` · `drag_end` · `scroll` · `select` · `deselect` ·+`shown` · `hidden`++`shown` 和 `hidden` 是「控件发出的」里的例外:没人点任何东西,是这个节点出现在了屏幕上、或者离开了+屏幕——通常因为**某个祖先**被显示或隐藏,也就是导航、页签、弹窗在做的事。子树里的每个节点都会被告知,+所以入场动画是挂在那块面板上的一行,而不是一个每帧去盯着的系统:++| 事件 | 动作 | 目标 |+|---|---|---|+| `shown` | `tween.play` | *(本实体)* |++在没有人监听这两个事件之前,这份「盯着」不花任何代价;有人监听、但这一帧 UI 没动过时,同样不花。[物理](/docs/zh-cn/guides/physics/)接触也走同一条通道(`PhysicsEventType`),所以[触发区](/docs/zh-cn/guides/markers/)的接线方式和按钮一模一样——双方都会收到事件,各自拿到对方:diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 3e573605c..acbfbb07c 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -1,7 +1,7 @@# API surface — esengine/index<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 1377 stable · 17 beta · 1 deprecated+Symbols: 1379 stable · 17 beta · 1 deprecated## ABI_LAYOUT_HASH — const```@@ -2625,6 +2625,7 @@ clear: () => voiddrain: () => readonly EntityEvent[]emit: <TData = unknown>(entity: Entity, type: string, data?: TData) => EntityEvent<TData>emitBubbled: (ancestor: Entity, rootEvent: EntityEvent) => EntityEvent+hasListenersFor: (type: string) => booleanon: { (entity: Entity, type: string, handler: EntityEventHandler): Unsubscribe; (type: string, handler: EntityEventHandler): Unsubscribe; }query: (type: string) => readonly EntityEvent[]removeAll: (entity: Entity) => void@@ -7637,6 +7638,7 @@ clear: () => voiddrain: () => readonly EntityEvent[]emit: <TData = unknown>(entity: Entity, type: string, data?: TData) => EntityEvent<TData>emitBubbled: (ancestor: Entity, rootEvent: EntityEvent) => EntityEvent+hasListenersFor: (type: string) => booleanon: { (entity: Entity, type: string, handler: EntityEventHandler): Unsubscribe; (type: string, handler: EntityEventHandler): Unsubscribe; }query: (type: string) => readonly EntityEvent[]removeAll: (entity: Entity) => void@@ -7811,6 +7813,15 @@ check: numberisOn: boolean```+## UIVisibilityPlugin — class+```+build: (app: App) => void+dependencies: "uiInteraction"[]+name: "uiVisibility"+static new (): UIVisibilityPlugin+static prototype: UIVisibilityPlugin+```+## UIVisual — const```BuiltinComponentDef<UIVisualData>@@ -10468,6 +10479,11 @@ Plugin[]UIRenderOrderPlugin```+## uiVisibilityPlugin — const+```+UIVisibilityPlugin+```+## uiWorldToScreen — function```(camera: UICameraData, worldX: number, worldY: number): { x: number; y: number; }diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex ebda86b06..45ea2d49e 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.native<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 1396 stable · 22 beta · 1 deprecated+Symbols: 1398 stable · 22 beta · 1 deprecated## ABI_LAYOUT_HASH — const```@@ -2633,6 +2633,7 @@ clear: () => voiddrain: () => readonly EntityEvent[]emit: <TData = unknown>(entity: Entity, type: string, data?: TData) => EntityEvent<TData>emitBubbled: (ancestor: Entity, rootEvent: EntityEvent) => EntityEvent+hasListenersFor: (type: string) => booleanon: { (entity: Entity, type: string, handler: EntityEventHandler): Unsubscribe; (type: string, handler: EntityEventHandler): Unsubscribe; }query: (type: string) => readonly EntityEvent[]removeAll: (entity: Entity) => void@@ -7801,6 +7802,7 @@ clear: () => voiddrain: () => readonly EntityEvent[]emit: <TData = unknown>(entity: Entity, type: string, data?: TData) => EntityEvent<TData>emitBubbled: (ancestor: Entity, rootEvent: EntityEvent) => EntityEvent+hasListenersFor: (type: string) => booleanon: { (entity: Entity, type: string, handler: EntityEventHandler): Unsubscribe; (type: string, handler: EntityEventHandler): Unsubscribe; }query: (type: string) => readonly EntityEvent[]removeAll: (entity: Entity) => void@@ -7975,6 +7977,15 @@ check: numberisOn: boolean```+## UIVisibilityPlugin — class+```+build: (app: App) => void+dependencies: "uiInteraction"[]+name: "uiVisibility"+static new (): UIVisibilityPlugin+static prototype: UIVisibilityPlugin+```+## UIVisual — const```BuiltinComponentDef<UIVisualData>@@ -10682,6 +10693,11 @@ Plugin[]UIRenderOrderPlugin```+## uiVisibilityPlugin — const+```+UIVisibilityPlugin+```+## uiWorldToScreen — function```(camera: UICameraData, worldX: number, worldY: number): { x: number; y: number; }diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 9261ef0a9..261043973 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.node<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 1376 stable · 19 beta · 1 deprecated+Symbols: 1378 stable · 19 beta · 1 deprecated## ANCHOR_AXES — const```@@ -2620,6 +2620,7 @@ clear: () => voiddrain: () => readonly EntityEvent[]emit: <TData = unknown>(entity: Entity, type: string, data?: TData) => EntityEvent<TData>emitBubbled: (ancestor: Entity, rootEvent: EntityEvent) => EntityEvent+hasListenersFor: (type: string) => booleanon: { (entity: Entity, type: string, handler: EntityEventHandler): Unsubscribe; (type: string, handler: EntityEventHandler): Unsubscribe; }query: (type: string) => readonly EntityEvent[]removeAll: (entity: Entity) => void@@ -7632,6 +7633,7 @@ clear: () => voiddrain: () => readonly EntityEvent[]emit: <TData = unknown>(entity: Entity, type: string, data?: TData) => EntityEvent<TData>emitBubbled: (ancestor: Entity, rootEvent: EntityEvent) => EntityEvent+hasListenersFor: (type: string) => booleanon: { (entity: Entity, type: string, handler: EntityEventHandler): Unsubscribe; (type: string, handler: EntityEventHandler): Unsubscribe; }query: (type: string) => readonly EntityEvent[]removeAll: (entity: Entity) => void@@ -7806,6 +7808,15 @@ check: numberisOn: boolean```+## UIVisibilityPlugin — class+```+build: (app: App) => void+dependencies: "uiInteraction"[]+name: "uiVisibility"+static new (): UIVisibilityPlugin+static prototype: UIVisibilityPlugin+```+## UIVisual — const```BuiltinComponentDef<UIVisualData>@@ -10473,6 +10484,11 @@ Plugin[]UIRenderOrderPlugin```+## uiVisibilityPlugin — const+```+UIVisibilityPlugin+```+## uiWorldToScreen — function```(camera: UICameraData, worldX: number, worldY: number): { x: number; y: number; }diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 2165ce16b..96893c000 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -1,7 +1,7 @@# API surface — esengine/minigame<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 1397 stable · 17 beta · 1 deprecated+Symbols: 1399 stable · 17 beta · 1 deprecated## ANCHOR_AXES — const```@@ -2620,6 +2620,7 @@ clear: () => voiddrain: () => readonly EntityEvent[]emit: <TData = unknown>(entity: Entity, type: string, data?: TData) => EntityEvent<TData>emitBubbled: (ancestor: Entity, rootEvent: EntityEvent) => EntityEvent+hasListenersFor: (type: string) => booleanon: { (entity: Entity, type: string, handler: EntityEventHandler): Unsubscribe; (type: string, handler: EntityEventHandler): Unsubscribe; }query: (type: string) => readonly EntityEvent[]removeAll: (entity: Entity) => void@@ -7847,6 +7848,7 @@ clear: () => voiddrain: () => readonly EntityEvent[]emit: <TData = unknown>(entity: Entity, type: string, data?: TData) => EntityEvent<TData>emitBubbled: (ancestor: Entity, rootEvent: EntityEvent) => EntityEvent+hasListenersFor: (type: string) => booleanon: { (entity: Entity, type: string, handler: EntityEventHandler): Unsubscribe; (type: string, handler: EntityEventHandler): Unsubscribe; }query: (type: string) => readonly EntityEvent[]removeAll: (entity: Entity) => void@@ -8021,6 +8023,15 @@ check: numberisOn: boolean```+## UIVisibilityPlugin — class+```+build: (app: App) => void+dependencies: "uiInteraction"[]+name: "uiVisibility"+static new (): UIVisibilityPlugin+static prototype: UIVisibilityPlugin+```+## UIVisual — const```BuiltinComponentDef<UIVisualData>@@ -10693,6 +10704,11 @@ Plugin[]UIRenderOrderPlugin```+## uiVisibilityPlugin — const+```+UIVisibilityPlugin+```+## uiWorldToScreen — function```(camera: UICameraData, worldX: number, worldY: number): { x: number; y: number; }diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex ea6fb9202..2908afa6c 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -1,7 +1,7 @@# API surface — esengine/wechat<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 1387 stable · 17 beta · 1 deprecated+Symbols: 1389 stable · 17 beta · 1 deprecated## ANCHOR_AXES — const```@@ -2620,6 +2620,7 @@ clear: () => voiddrain: () => readonly EntityEvent[]emit: <TData = unknown>(entity: Entity, type: string, data?: TData) => EntityEvent<TData>emitBubbled: (ancestor: Entity, rootEvent: EntityEvent) => EntityEvent+hasListenersFor: (type: string) => booleanon: { (entity: Entity, type: string, handler: EntityEventHandler): Unsubscribe; (type: string, handler: EntityEventHandler): Unsubscribe; }query: (type: string) => readonly EntityEvent[]removeAll: (entity: Entity) => void@@ -7639,6 +7640,7 @@ clear: () => voiddrain: () => readonly EntityEvent[]emit: <TData = unknown>(entity: Entity, type: string, data?: TData) => EntityEvent<TData>emitBubbled: (ancestor: Entity, rootEvent: EntityEvent) => EntityEvent+hasListenersFor: (type: string) => booleanon: { (entity: Entity, type: string, handler: EntityEventHandler): Unsubscribe; (type: string, handler: EntityEventHandler): Unsubscribe; }query: (type: string) => readonly EntityEvent[]removeAll: (entity: Entity) => void@@ -7813,6 +7815,15 @@ check: numberisOn: boolean```+## UIVisibilityPlugin — class+```+build: (app: App) => void+dependencies: "uiInteraction"[]+name: "uiVisibility"+static new (): UIVisibilityPlugin+static prototype: UIVisibilityPlugin+```+## UIVisual — const```BuiltinComponentDef<UIVisualData>@@ -10492,6 +10503,11 @@ Plugin[]UIRenderOrderPlugin```+## uiVisibilityPlugin — const+```+UIVisibilityPlugin+```+## uiWorldToScreen — function```(camera: UICameraData, worldX: number, worldY: number): { x: number; y: number; }diff --git a/sdk/src/core-plugins.ts b/sdk/src/core-plugins.tsindex f41ca914a..b7bfb1dc3 100644--- a/sdk/src/core-plugins.ts+++ b/sdk/src/core-plugins.ts@@ -26,6 +26,7 @@ export { uiMaskPlugin, UIMaskPlugin } from './ui/render/mask';export { uiInteractionPlugin, UIInteractionPlugin } from './ui/input/interaction';export { uiLayoutPlugin, UILayoutPlugin } from './ui/layout/layout';export { uiRenderOrderPlugin, UIRenderOrderPlugin } from './ui/render/render-order';+export { uiVisibilityPlugin, UIVisibilityPlugin } from './ui/core/visibility';export { textInputPlugin, TextInputPlugin } from './ui/text/text-input-plugin';export { dragPlugin, DragPlugin } from './ui/input/drag';export { focusPlugin, FocusPlugin } from './ui/input/focus';diff --git a/sdk/src/ecs/entityEvents.ts b/sdk/src/ecs/entityEvents.tsindex 4c97b7130..ffc7f5a9b 100644--- a/sdk/src/ecs/entityEvents.ts+++ b/sdk/src/ecs/entityEvents.ts@@ -115,6 +115,11 @@ export class EntityEventQueue {Map<string, Set<EntityEventHandler>>>();private readonly globalHandlers_ = new Map<string, Set<EntityEventHandler>>();+ // How many handlers exist per type, entity-specific and global together. Kept as a+ // count rather than derived on demand so {@link hasListenersFor} is O(1): a producer+ // that has to WATCH for its events (visibility, proximity — anything not already+ // computed) asks every frame, and should cost nothing while nobody is listening.+ private readonly typeCounts_ = new Map<string, number>();private pending_: EntityEvent[] = [];private readonly activeKeys_ = new Set<string>();@@ -148,13 +153,14 @@ export class EntityEventQueue {set = new Set();typeMap.set(type, set);}+ if (!set.has(handler)) this.countType_(type, 1);set.add(handler);return () => {const tm = this.entityHandlers_.get(entity);const s = tm?.get(type);- if (s) {- s.delete(handler);+ if (s?.delete(handler)) {+ this.countType_(type, -1);if (s.size === 0) tm!.delete(type);if (tm && tm.size === 0) this.entityHandlers_.delete(entity);}@@ -170,22 +176,44 @@ export class EntityEventQueue {set = new Set();this.globalHandlers_.set(type, set);}+ if (!set.has(handler)) this.countType_(type, 1);set.add(handler);return () => {const s = this.globalHandlers_.get(type);- if (s) {- s.delete(handler);+ if (s?.delete(handler)) {+ this.countType_(type, -1);if (s.size === 0) this.globalHandlers_.delete(type);}};}+ private countType_(type: string, delta: number): void {+ const next = (this.typeCounts_.get(type) ?? 0) + delta;+ if (next > 0) this.typeCounts_.set(type, next);+ else this.typeCounts_.delete(type);+ }++ /**+ * Is anyone subscribed to this event type, for any entity?+ *+ * For producers that must LOOK for their events rather than being handed them: a+ * visibility watcher walks the UI tree, a proximity watcher measures distances, and+ * neither should do that work into an empty room. Emitting is unaffected — an event+ * with no handlers still queues for `drain()`.+ */+ hasListenersFor(type: string): boolean {+ return this.typeCounts_.has(type);+ }+/*** Remove all entity-specific handlers for `entity`.* Wire this to `world.onDespawn` for automatic cleanup.*/removeAll(entity: Entity): void {+ const typeMap = this.entityHandlers_.get(entity);+ if (!typeMap) return;+ for (const [type, set] of typeMap) this.countType_(type, -set.size);this.entityHandlers_.delete(entity);}diff --git a/sdk/src/ecs/systemLabels.ts b/sdk/src/ecs/systemLabels.tsindex 4798ecfff..a0fae1168 100644--- a/sdk/src/ecs/systemLabels.ts+++ b/sdk/src/ecs/systemLabels.ts@@ -9,6 +9,7 @@ export const PluginName = {UILayout: 'uiLayout',UIInteraction: 'uiInteraction',UIRenderOrder: 'uiRenderOrder',+ UIVisibility: 'uiVisibility',UIMask: 'uiMask',Text: 'text',Focus: 'focus',diff --git a/sdk/src/ui/core/events.ts b/sdk/src/ui/core/events.tsindex 91e7d74d4..91e785f75 100644--- a/sdk/src/ui/core/events.ts+++ b/sdk/src/ui/core/events.ts@@ -38,6 +38,11 @@ export const UIEventType = {DragMove: 'drag_move',DragEnd: 'drag_end',Scroll: 'scroll',+ /** This node arrived on screen — it, or an ancestor, stopped being `display: None`+ * (or it was just created visible). Emitted by the UI visibility watcher. */+ Shown: 'shown',+ /** …and left it, the same way. */+ Hidden: 'hidden',Select: 'select',Deselect: 'deselect',} as const;diff --git a/sdk/src/ui/core/visibility.ts b/sdk/src/ui/core/visibility.tsnew file mode 100644index 000000000..18de6967a--- /dev/null+++ b/sdk/src/ui/core/visibility.ts@@ -0,0 +1,113 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file ui/core/visibility.ts+ * @brief `shown` / `hidden` — a node arriving on or leaving the screen, as events.+ *+ * A UI node goes away because an ANCESTOR's `display` changed: navigation shows a+ * panel, a tab button shows a page, a dialog closes. Every node under it stops being+ * drawn, and until now nothing said so — a game that wanted "play the entrance when+ * this screen appears" had to walk the parent chain of every animated node itself,+ * every frame, and re-derive what the layout pass had already computed.+ *+ * These are the two events for it, on the same channel as `click`: so the answer is+ * data (an EventBinding row from `shown` to a named action) rather than a system.+ *+ * Visibility is read as the engine's own resolved bit (`hidden_in_tree_`, the same+ * one rendering and hit-testing use), so "visible" cannot drift from what you can+ * see. That bit is only reachable one entity at a time, so the scan is gated twice —+ * it is the whole cost of this file, and on a steady frame it must be nothing:+ *+ * · nobody listening ⇒ no scan. A producer that has to LOOK for its events should+ * do nothing into an empty room, and this one has no other reason to run.+ * · nothing moved ⇒ no scan. `hidden_in_tree_` is a function of authored `display`+ * and of the tree, so it cannot change unless a UINode was written or the+ * hierarchy changed — both O(1) to ask about (the same pair PhysicsSystem gates+ * its reconcile on). A UI that is merely being looked at costs two integer+ * comparisons per frame.+ */+import type { App, Plugin } from '../../app/app';+import { defineSystem, Schedule } from '../../ecs/system';+import { Res } from '../../ecs/resource';+import { playModeOnly } from '../../ecs/env';+import { PluginName, SystemLabel } from '../../ecs/systemLabels';+import type { Entity } from '../../types';+import type { CppRegistry } from '../../wasm';+import { engineApi } from '../../ecs/bridge/engineApi';+import { UIEvents, UIEventQueue, UIEventType } from './events';+import { UINode } from './ui-node';++export class UIVisibilityPlugin implements Plugin {+ name = PluginName.UIVisibility;+ dependencies = [PluginName.UIInteraction]; // for the shared UIEvents resource++ build(app: App): void {+ const world = app.world;+ const engine = engineApi(app);+ const registry = engine ? (world.getCppRegistry() as CppRegistry) : undefined;++ // The layout plugin enables this too; asking again is how this plugin stays+ // correct without depending on it having been built first.+ world.enableChangeTracking(UINode);++ /** Last known on-screen state, so a change can be told from a steady value. */+ const seen = new Map<Entity, boolean>();+ /** Watermarks for the two O(1) gates; -1 ⇒ the next frame scans regardless. */+ let scannedTick = -1;+ let scannedVersion = -1;++ world.onDespawn((entity: Entity) => { seen.delete(entity); });++ app.addSystemToSchedule(Schedule.Update, defineSystem(+ [Res(UIEvents)],+ (events: UIEventQueue) => {+ const wanted = events.hasListenersFor(UIEventType.Shown)+ || events.hasListenersFor(UIEventType.Hidden);+ if (!wanted) {+ // Drop the baseline too: whoever subscribes next starts from what+ // is on screen THEN, rather than being told about a change that+ // happened while nobody was asking.+ if (seen.size > 0) seen.clear();+ scannedTick = -1;+ scannedVersion = -1;+ return;+ }+ if (!engine?.getUINodeHiddenInTree || !registry) return;++ // `hidden_in_tree_` is written by the layout pass out of authored+ // `display` and the hierarchy — so a frame that wrote no UINode and+ // moved no entity cannot have changed it. The structural version covers+ // spawn / despawn / reparent (a reparent touches Parent and Children,+ // never UINode); the change tick covers an edited `display`.+ const version = world.getWorldVersion();+ const moved = version !== scannedVersion+ || world.anyChangedSince(UINode, scannedTick);+ if (!moved) return;+ scannedVersion = version;+ // The previous tick, not this one: `anyChangedSince` is exclusive, and a+ // write can still land later in the frame now running — the late layout+ // pass in PostUpdate is exactly that. Costs at most one extra scan while+ // a change settles; UILayoutPlugin takes the same watermark for the same+ // reason.+ scannedTick = world.getWorldTick() - 1;++ for (const entity of world.getEntitiesWithComponents([UINode])) {+ const shown = !engine.getUINodeHiddenInTree(registry, entity);+ const before = seen.get(entity);+ seen.set(entity, shown);+ // These are CHANGES, so the first look at a node only records it. Not+ // just to keep a listener that attaches mid-game from being told that+ // every panel on screen just appeared: a node is created before the+ // layout pass has taken it into the tree, so its first reading is+ // "not on screen" — announced, that is a spurious `hidden` on+ // something that is in the middle of being spawned.+ if (before === undefined || before === shown) continue;+ events.emit(entity, shown ? UIEventType.Shown : UIEventType.Hidden);+ }+ },+ { name: 'UIVisibilityEventSystem' },+ ), { runAfter: [SystemLabel.UILayout], runIf: playModeOnly });+ }+}++export const uiVisibilityPlugin = new UIVisibilityPlugin();diff --git a/sdk/src/ui/index.ts b/sdk/src/ui/index.tsindex 7628d5d11..e49b5fd45 100644--- a/sdk/src/ui/index.ts+++ b/sdk/src/ui/index.ts@@ -382,6 +382,7 @@ export {} from './layout/safe-area';export { UIRenderOrderPlugin, uiRenderOrderPlugin } from './render/render-order';+export { UIVisibilityPlugin, uiVisibilityPlugin } from './core/visibility';// ─── Theme (design tokens) ──────────────────────────────────────────────────diff --git a/sdk/src/ui/ui-plugin.ts b/sdk/src/ui/ui-plugin.tsindex 0bde71eac..f035f6215 100644--- a/sdk/src/ui/ui-plugin.ts+++ b/sdk/src/ui/ui-plugin.ts@@ -28,6 +28,7 @@ import { dragPlugin } from './input/drag';import { focusPlugin } from './input/focus';import { textInputPlugin } from './text/text-input-plugin';import { uiRenderOrderPlugin } from './render/render-order';+import { uiVisibilityPlugin } from './core/visibility';import type { UIEventQueue } from './core/events';import type { ListView } from './collection/list-view';@@ -43,6 +44,7 @@ const SUB_PLUGINS: Plugin[] = [textPlugin,inlineImagePlugin,uiInteractionPlugin,+ uiVisibilityPlugin,uiBehaviorPlugin,uiControllerPlugin,dragPlugin,diff --git a/sdk/tests/helpers/mockApp.ts b/sdk/tests/helpers/mockApp.tsindex 1a67b956f..e03c7f22f 100644--- a/sdk/tests/helpers/mockApp.ts+++ b/sdk/tests/helpers/mockApp.ts@@ -15,12 +15,11 @@import { App } from '../../src/app/app';import { AppContext, setDefaultContext } from '../../src/ecs/context';import { setEditorMode, setPlayMode } from '../../src/ecs/env';-import { createMockModule } from '../mocks/wasm';-import type { ESEngineModule } from '../../src/wasm';+import { createMockModule, type MockModule } from '../mocks/wasm';export interface MockApp {app: App;- module: ESEngineModule;+ module: MockModule;}/**@@ -35,6 +34,11 @@ export function bootMockApp(): MockApp {setPlayMode(false); // standalone runtime ⇒ playModeOnly() === trueconst app = App.new();const module = createMockModule();- app.world.connectCpp(module.getRegistry(), module);+ // Through the App, not `app.world` directly: only this path also hands the App+ // the module, and that is what `engineApi(app)` answers with. Connecting the+ // world alone leaves every engine-calling plugin inert — silently, since they+ // all optional-chain the engine away — which is not what a test means by+ // "connected".+ app.connectCpp(module.getRegistry(), module);return { app, module };}diff --git a/sdk/tests/mocks/wasm.ts b/sdk/tests/mocks/wasm.tsindex 339227767..54fdfe4d3 100644--- a/sdk/tests/mocks/wasm.ts+++ b/sdk/tests/mocks/wasm.ts@@ -3,7 +3,16 @@import type { ESEngineModule, CppRegistry, CppResourceManager } from '../../src/wasm';import type { Entity } from '../../src/types';-export function createMockModule(): ESEngineModule {+/**+ * The mock module, plus the handful of setters that stand in for computation the+ * mock does not do. `setUINodeHiddenInTree` is the layout pass's verdict, which a+ * test states instead of solving.+ */+export interface MockModule extends ESEngineModule {+ setUINodeHiddenInTree(entity: Entity, hidden: boolean): void;+}++export function createMockModule(): MockModule {const entities = new Set<Entity>();const components = new Map<Entity, Map<string, any>>();let nextEntity = 1;@@ -133,9 +142,16 @@ export function createMockModule(): ESEngineModule {}),};+ // `hidden_in_tree_` is layout output, not a stored field, so the mock cannot+ // derive it — a test that needs it says what the layout pass resolved via+ // `setUINodeHiddenInTree`. Default false: a node nobody spoke for is on screen.+ const hiddenInTree = new Map<Entity, boolean>();+return {getRegistry: () => registry,getResourceManager: () => resourceManager,+ getUINodeHiddenInTree: (_registry: unknown, entity: Entity) => hiddenInTree.get(entity) ?? false,+ setUINodeHiddenInTree: (entity: Entity, hidden: boolean) => { hiddenInTree.set(entity, hidden); },GL: {} as any,- } as ESEngineModule;+ } as MockModule;}diff --git a/sdk/tests/ui-visibility-events.test.ts b/sdk/tests/ui-visibility-events.test.tsnew file mode 100644index 000000000..091dec60d--- /dev/null+++ b/sdk/tests/ui-visibility-events.test.ts@@ -0,0 +1,210 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file `shown` / `hidden`, both halves: the listener count the watcher gates on+ * (EntityEventQueue) and the watcher itself, driven through a mock-wasm App+ * whose `getUINodeHiddenInTree` answers what a test says the layout pass+ * resolved. The gating is the design — a UI nobody is listening to, or one+ * that did not move, must not be scanned — so it is asserted by counting the+ * reads the watcher makes, not just the events it emits.+ */+import { describe, it, expect, beforeEach, vi } from 'vitest';+import { flushPendingSystems } from '../src/app/app';+import type { App } from '../src/app/app';+import { EntityEventQueue } from '../src/ecs/entityEvents';+import { UIEvents, UIEventQueue, UIEventType } from '../src/ui/core/events';+import { UINode } from '../src/ui/core/ui-node';+import { uiVisibilityPlugin } from '../src/ui/core/visibility';+import { bootMockApp } from './helpers/mockApp';+import type { MockModule } from './mocks/wasm';+import type { Entity } from '../src/types';++describe('EntityEventQueue.hasListenersFor', () => {+ it('is false until someone subscribes and false again once they all leave', () => {+ const events = new EntityEventQueue();+ expect(events.hasListenersFor('shown')).toBe(false);++ const offGlobal = events.on('shown', () => {});+ expect(events.hasListenersFor('shown')).toBe(true);++ const offEntity = events.on(7 as never, 'shown', () => {});+ offGlobal();+ expect(events.hasListenersFor('shown')).toBe(true); // the entity one is still there++ offEntity();+ expect(events.hasListenersFor('shown')).toBe(false);+ });++ it('counts each handler once, so unsubscribing twice cannot make it negative', () => {+ const events = new EntityEventQueue();+ const handler = () => {};+ const off = events.on(1 as never, 'hidden', handler);+ events.on(1 as never, 'hidden', handler); // same handler: the Set holds one++ off();+ expect(events.hasListenersFor('hidden')).toBe(false);+ off();+ expect(events.hasListenersFor('hidden')).toBe(false);+ });++ it('removeAll(entity) takes that entity\'s handlers out of the count', () => {+ const events = new EntityEventQueue();+ events.on(3 as never, 'shown', () => {});+ events.on(3 as never, 'hidden', () => {});+ expect(events.hasListenersFor('shown')).toBe(true);++ events.removeAll(3 as never);+ expect(events.hasListenersFor('shown')).toBe(false);+ expect(events.hasListenersFor('hidden')).toBe(false);+ });++ it('an event with no listeners still reaches drain() — this gates WATCHING, not emitting', () => {+ const events = new EntityEventQueue();+ events.emit(5 as never, 'shown');+ expect(events.drain().map((e) => e.type)).toEqual(['shown']);+ });++ it('a listener still gets its events after the count has been through zero', () => {+ const events = new EntityEventQueue();+ const seen = vi.fn();+ events.on('shown', () => {})();+ events.on('shown', seen);+ events.emit(2 as never, 'shown');+ expect(seen).toHaveBeenCalledTimes(1);+ });+});++describe('UIVisibilityPlugin', () => {+ let app: App;+ let module: MockModule;+ let events: UIEventQueue;+ /** How many times the watcher asked the engine for a node's resolved bit. */+ let reads: number;++ beforeEach(() => {+ const booted = bootMockApp();+ app = booted.app;+ module = booted.module;++ reads = 0;+ const answer = module.getUINodeHiddenInTree!.bind(module);+ module.getUINodeHiddenInTree = (registry, entity) => {+ reads++;+ return answer(registry, entity);+ };++ events = new UIEventQueue();+ app.insertResource(UIEvents, events);+ uiVisibilityPlugin.build(app);+ flushPendingSystems(app);+ });++ /** A UI node, on screen unless told otherwise. */+ const addNode = (): Entity => {+ const e = app.world.spawn();+ app.world.insert(e, UINode, {});+ return e;+ };++ /** What the layout pass resolved for `e` this frame. */+ const resolve = (e: Entity, hidden: boolean): void => {+ module.setUINodeHiddenInTree(e, hidden);+ // A display edit is a UINode write; that is the signal the watcher gates on.+ app.world.insert(e, UINode, { display: hidden ? 1 : 0 });+ };++ const tick = async (): Promise<string[]> => {+ await app.tick(1 / 60);+ return events.drain().map((ev) => `${ev.type}:${ev.target}`);+ };++ const listen = (): void => { events.on(UIEventType.Shown, () => {}); };++ it('says nothing about the nodes it finds on the first look — those are not changes', async () => {+ listen();+ const a = addNode();+ module.setUINodeHiddenInTree(a, true);+ expect(await tick()).toEqual([]);+ });++ it('emits `hidden` when a node leaves the screen and `shown` when it comes back', async () => {+ listen();+ const panel = addNode();+ await tick(); // baseline: on screen++ resolve(panel, true);+ expect(await tick()).toEqual([`${UIEventType.Hidden}:${panel}`]);++ resolve(panel, false);+ expect(await tick()).toEqual([`${UIEventType.Shown}:${panel}`]);+ });++ it('reports a node hidden by an ANCESTOR, which is the case that has no local edit', async () => {+ listen();+ const panel = addNode();+ const label = addNode();+ app.world.setParent(label, panel);+ await tick();++ // The parent's display changed; the child's own UINode was never written, and+ // the engine resolved the whole subtree as hidden.+ module.setUINodeHiddenInTree(label, true);+ resolve(panel, true);++ expect((await tick()).sort()).toEqual(+ [`${UIEventType.Hidden}:${label}`, `${UIEventType.Hidden}:${panel}`].sort(),+ );+ });++ it('does not scan while nobody is listening, and never reports what changed then', async () => {+ const panel = addNode();+ await tick();+ expect(reads).toBe(0); // no listener ⇒ the engine was not asked anything++ resolve(panel, true);+ expect(await tick()).toEqual([]);++ // Subscribing starts from what is on screen NOW: the node is already hidden,+ // so there is no change to announce — and no stale `hidden` from before.+ listen();+ expect(await tick()).toEqual([]);+ resolve(panel, false);+ expect(await tick()).toEqual([`${UIEventType.Shown}:${panel}`]);+ });++ it('does not scan a frame in which nothing moved', async () => {+ listen();+ addNode();+ await tick();++ const settled = reads;+ await tick();+ await tick();+ expect(reads).toBe(settled); // steady frames cost no engine reads at all+ });++ it('scans again after a reparent, which touches no UINode', async () => {+ listen();+ const panel = addNode();+ const label = addNode();+ await tick();+ await tick(); // let the change watermark settle++ const settled = reads;+ app.world.setParent(label, panel);+ module.setUINodeHiddenInTree(label, true);+ expect(await tick()).toEqual([`${UIEventType.Hidden}:${label}`]);+ expect(reads).toBeGreaterThan(settled);+ });++ it('forgets a despawned entity, so a recycled id does not inherit its state', async () => {+ listen();+ const panel = addNode();+ resolve(panel, true);+ await tick();++ app.world.despawn(panel);+ await tick();+ expect(events.drain()).toEqual([]);+ });+});