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
refactor(ui): the engine anchors run in two ordered passes and the Cocos Layout is a system between them, so alignment has one owner instead of a second hand-called copy
yhhe1e2bb08af45
diff --git a/sdk/src/cocos/ui/pass.ts b/sdk/src/cocos/ui/pass.tsindex d16b6e523..26a840e67 100644--- a/sdk/src/cocos/ui/pass.ts+++ b/sdk/src/cocos/ui/pass.ts@@ -2,11 +2,9 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team/*** @file cocos/ui/pass.ts- * @brief The end-of-frame pass that aligns widgets and arranges layouts.+ * @brief Registers the Cocos UI components and the systems that arrange layouts and publish the screen to scripts.*- * Cocos does both after the frame's scripts have run, so a script that moves or resizes something this frame is answered by the- * alignment in the same frame. Widgets go first (a stretched container changes what its layout sees), then layouts innermost-first,- * then widgets once more for the ones that follow a size the layouts just set (those set to align every frame).+ * Alignment is the engine's (RectAnchors); the Layout arithmetic is Cocos's, and runs between the engine's two anchor passes.*/import { Schedule, defineSystem, addSystemToSchedule, GetWorld } from '../../ecs/system';import { Res } from '../../ecs/resource';@@ -15,13 +13,15 @@ import { ScreenLayout, type ScreenLayoutData } from '../../ui/core/screen-layoutimport { ScreenScaling, type ScreenScalingData } from '../../camera/ScreenScaling';import { setCurrentWorld } from '../node';import { declareWidget } from './widget';-import { alignAllRectAnchors } from '../../ui/layout/rect-anchors';+import { rectAnchorsPlugin, setRectAnchorsScreenFallback } from '../../ui/layout/rect-anchors';+import { SystemLabel } from '../../ecs/systemLabels';+import { getDefaultContext } from '../../ecs/context';import { layoutAll, declareLayout } from './layout';import { declareControls } from './controls';import { declareGraphics } from './graphics';import { declareEditBox } from './editBox';import { declareScrollView } from './scrollView';-import { getVisibleSize, setProjectDesign, setSafeInsets, setScreenLayout, setUiCameraData, setVisibleSize, setWindowPixels, visibleSizeGeneration } from './screen';+import { getVisibleSize, setProjectDesign, setSafeInsets, setScreenLayout, setUiCameraData, setVisibleSize, setWindowPixels } from './screen';import { declarePages } from './pages';import { declareMisc } from './misc';@@ -42,15 +42,27 @@ export function declareUiPass(): void {declarePages();declareMisc();declareScrollView();- const system = defineSystem(- [Res(UICameraInfo), Res(ScreenLayout), Res(ScreenScaling), GetWorld()],- (camera, screen, scaling: ScreenScalingData | undefined, world) => {+ // The engine's anchor system places what is pinned; a Cocos Layout then arranges and resizes, and the engine's second anchor pass+ // follows the sizes the layouts set (the nodes set to align every frame). Cocos does both after the frame's scripts have run, so a+ // script that moves or resizes something this frame is answered in the same frame.+ getDefaultContext().pendingPlugins.push(rectAnchorsPlugin);+ setRectAnchorsScreenFallback(() => screenOrVisible(undefined));+ addSystemToSchedule(Schedule.PostUpdate, defineSystem(+ [GetWorld()],+ (world) => {+ const previous = setCurrentWorld(world);+ try { layoutAll(world); } finally { setCurrentWorld(previous); }+ },+ { name: 'Cocos:Layout', touches: { opaque: true }, runAfter: [SystemLabel.RectAnchors], runBefore: [SystemLabel.RectAnchorsLate] },+ ));+ // What scripts read about the screen, before they run: the project design, the visible size and the framebuffer, the safe insets,+ // the camera for the conversions a Cocos `Camera` offers.+ addSystemToSchedule(Schedule.PreUpdate, defineSystem(+ [Res(UICameraInfo), Res(ScreenLayout), Res(ScreenScaling)],+ (camera, screen: ScreenLayoutData | undefined, scaling: ScreenScalingData | undefined) => {if (scaling) setProjectDesign(scaling.designWidth, scaling.designHeight, scaling.scaleMode);- // The camera is kept for the conversions a Cocos `Camera` offers. What the player sees, and the window, are the screen's: the- // layout box UI is placed within, and the framebuffer it projects onto.setUiCameraData(camera ?? null);- const layout = screenOrVisible(screen);- setScreenLayout(layout);+ setScreenLayout(screenOrVisible(screen));if (screen?.valid) {setVisibleSize(screen.right - screen.left, screen.top - screen.bottom);setWindowPixels(screen.viewportW, screen.viewportH);@@ -58,26 +70,7 @@ export function declareUiPass(): void {Math.max(0, screen.safeLeft - screen.left), Math.max(0, screen.right - screen.safeRight),Math.max(0, screen.top - screen.safeTop), Math.max(0, screen.safeBottom - screen.bottom));}- const previous = setCurrentWorld(world);- try {- // The engine's anchors, between the layouts that depend on them: a Layout resizes what a widget then pins to.- alignAllRectAnchors(world, layout, visibleSizeGeneration());- layoutAll(world);- alignAllRectAnchors(world, layout, visibleSizeGeneration());- } finally {- setCurrentWorld(previous);- }- },- { name: 'Cocos:UiPass', touches: { opaque: true } },- );- addSystemToSchedule(Schedule.Last, system);- addSystemToSchedule(Schedule.PreUpdate, defineSystem(- [Res(ScreenScaling), Res(ScreenLayout)],- (scaling: ScreenScalingData | undefined, screen: ScreenLayoutData | undefined) => {- if (scaling) setProjectDesign(scaling.designWidth, scaling.designHeight, scaling.scaleMode);- // what a script reads in start(): the sizes are known before the first frame's pass- if (screen?.valid) { setVisibleSize(screen.right - screen.left, screen.top - screen.bottom); setWindowPixels(screen.viewportW, screen.viewportH); }},- { name: 'Cocos:ProjectDesign', touches: { opaque: true } },+ { name: 'Cocos:Screen', touches: { opaque: true } },));}diff --git a/sdk/src/cocos/ui/screen.ts b/sdk/src/cocos/ui/screen.tsindex 52a3439d2..7ecddd5fe 100644--- a/sdk/src/cocos/ui/screen.ts+++ b/sdk/src/cocos/ui/screen.ts@@ -16,7 +16,6 @@ import type { World } from '../../ecs/world';let uiCamera: UICameraData | null = null;let width = 960;let height = 640;-let generation = 0;let safeLeft = 0;let safeRight = 0;let safeTop = 0;@@ -48,7 +47,6 @@ export function getSafeInsets(): { left: number; right: number; top: number; botexport function setSafeInsets(left: number, right: number, top: number, bottom: number): void {if (left === safeLeft && right === safeRight && top === safeTop && bottom === safeBottom) return;safeLeft = left; safeRight = right; safeTop = top; safeBottom = bottom;- generation++;for (const l of [...listeners]) l('visible');}@@ -57,13 +55,9 @@ export function setVisibleSize(w: number, h: number): void {if (w === width && h === height) return;width = w;height = h;- generation++;for (const l of [...listeners]) l('visible');}-/** Bumps whenever the visible size changes. */-export function visibleSizeGeneration(): number { return generation; }-/** The window (the drawing surface) in physical pixels. */export function getWindowPixels(): { width: number; height: number } { return { width: windowW, height: windowH }; }diff --git a/sdk/src/ecs/systemLabels.ts b/sdk/src/ecs/systemLabels.tsindex 728ae808a..2e27bf83d 100644--- a/sdk/src/ecs/systemLabels.ts+++ b/sdk/src/ecs/systemLabels.ts@@ -21,6 +21,8 @@ export const PluginName = {export const SystemLabel = {UILayout: 'UILayoutSystem',UILayoutLate: 'UILayoutLateSystem',+ RectAnchors: 'RectAnchorsSystem',+ RectAnchorsLate: 'RectAnchorsLateSystem',UIRenderOrder: 'UIRenderOrderSystem',UIInteraction: 'UIInteractionSystem',VirtualControls: 'VirtualControlsSystem',diff --git a/sdk/src/ui/index.ts b/sdk/src/ui/index.tsindex c6c16a208..ca86cc525 100644--- a/sdk/src/ui/index.ts+++ b/sdk/src/ui/index.ts@@ -62,7 +62,7 @@ export { UIMask, MaskMode, type UIMaskData } from './core/ui-mask';export { UIScroll, ScrollMovement, type UIScrollData } from './core/ui-scroll';export { ContentRect, applyContentRect, contentRectContains, localPointInRect, type ContentRectData } from './core/content-rect';export { contentRectPlugin, ContentRectPlugin } from './render/content-rect';-export { RectAnchors, rectAnchorsPlugin, RectAnchorsPlugin, AnchorFlag, AnchorMode, anchoredRect, alignRectAnchorsNow, alignAllRectAnchors, forgetRectAnchors, type RectAnchorsData } from './layout/rect-anchors';+export { RectAnchors, rectAnchorsPlugin, RectAnchorsPlugin, AnchorFlag, AnchorMode, anchoredRect, alignRectAnchorsNow, alignAllRectAnchors, forgetRectAnchors, setRectAnchorsScreenFallback, type RectAnchorsData } from './layout/rect-anchors';export {Text,diff --git a/sdk/src/ui/layout/rect-anchors.ts b/sdk/src/ui/layout/rect-anchors.tsindex 78835bb03..31d57646a 100644--- a/sdk/src/ui/layout/rect-anchors.ts+++ b/sdk/src/ui/layout/rect-anchors.ts@@ -20,6 +20,7 @@ import type { App, Plugin } from '../../app/app';import { defineComponent, registerComponent, Transform } from '../../ecs/component';import { Parent } from '../../ecs/component';import { Res } from '../../ecs/resource';+import { SystemLabel } from '../../ecs/systemLabels';import { defineSystem, Schedule } from '../../ecs/system';import type { World } from '../../ecs/world';import type { Entity } from '../../types';@@ -209,6 +210,25 @@ export function forgetRectAnchors(world: World): void { seenByWorld.delete(worldlet screenGeneration = 0;let lastScreenKey = '';+let screenFallback: (() => ScreenLayoutData | null) | null = null;+/**+ * The screen to align to where the engine has published none yet (a host before its first frame, a test): a layer that knows the+ * size it was told supplies it here, so a root pinned to the screen still has a box.+ */+export function setRectAnchorsScreenFallback(fn: (() => ScreenLayoutData | null) | null): void { screenFallback = fn; }++function alignFrame(world: World, published: ScreenLayoutData | undefined): void {+ const screen = published?.valid ? published : screenFallback?.() ?? published ?? null;+ const key = screen?.valid ? `${screen.left},${screen.right},${screen.bottom},${screen.top}` : '';+ if (key !== lastScreenKey) { lastScreenKey = key; screenGeneration++; }+ alignAllRectAnchors(world, screen, screenGeneration);+}++/**+ * Two passes a frame, the way the engine's own layout has two: anchors place what is pinned, anything that arranges or resizes+ * content (a layout of another layer) runs between them by ordering itself after the first label and before the second, and the+ * second pass moves only the nodes set to follow every frame, since the rest were settled by the first.+ */export class RectAnchorsPlugin implements Plugin {name = 'rectAnchors';@@ -217,13 +237,14 @@ export class RectAnchorsPlugin implements Plugin {const world = app.world;app.addSystemToSchedule(Schedule.PostUpdate, defineSystem([Res(ScreenLayout)],- (screen: ScreenLayoutData) => {- const key = screen?.valid ? `${screen.left},${screen.right},${screen.bottom},${screen.top}` : '';- if (key !== lastScreenKey) { lastScreenKey = key; screenGeneration++; }- alignAllRectAnchors(world, screen ?? null, screenGeneration);- },- { name: 'RectAnchorsSystem' },- ));+ (screen: ScreenLayoutData) => alignFrame(world, screen),+ { name: SystemLabel.RectAnchors },+ ), { runBefore: [SystemLabel.UILayoutLate] });+ app.addSystemToSchedule(Schedule.PostUpdate, defineSystem(+ [Res(ScreenLayout)],+ (screen: ScreenLayoutData) => alignFrame(world, screen),+ { name: SystemLabel.RectAnchorsLate },+ ), { runAfter: [SystemLabel.RectAnchors], runBefore: [SystemLabel.UIRenderOrder] });}}