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(render): TextureAtlas packs several textures onto one canvas at run time, and RectAnchors, AnchorFlag and AnchorMode are exported from the package root

yhhad31a6115c94
diff --git a/CHANGELOG.md b/CHANGELOG.md
index cb16bb8ae..2ab8b801a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -18,6 +18,7 @@ published separately; it ships inside the editor.
### Added
+- **Pack several textures onto one canvas at run time: `TextureAtlas.pack`.** It draws the textures you give it onto one new canvas (the smallest power-of-two size that holds them, up to `maxSize`, with `padding` between pictures) and returns where each landed: `atlas.sprite(source)` gives the `texture`, `uvOffset` and `uvScale` a `Sprite` takes, `atlas.get(source)` the pixel rectangle. Sprites cut from one canvas batch into one draw. Pictures are copied without blending so their transparency is kept, and the canvas is drawn again from the sources after a graphics device is lost. Its pixels are checked on WebGL2 only, as `RenderTexture`'s are. The Render Texture example builds four cards and packs them.
- **Rich text reads the tags other engines write.** `<size=24>…</size>`, a colour by name (`<color=red>`), and `<br/>` now work beside `<color=#RRGGBB>`, `<font size=…>`, `<b>` and `<i>`. `<u>`, `<s>`, `<outline …>` and `<on click=…>` are accepted so text written for another engine shows no raw tags: the words are kept, the underline, outline and click are not drawn. Unknown tags still show as text.
- **Scroll areas can be pulled past an end and spring back.** A scroll area whose movement is Elastic now does what the setting always said: a drag past an end is stiffer the further out it goes, letting go returns the content, and a flick that reaches an end bounces off it. It is opt-in per area (`ScrollMovement.Elastic`; Clamped, the default, behaves as before), and the gesture model (`ScrollMotion`, with `ScrollContainer.dragTo` and `getOverscroll`) is exported for scrolling anything else the same way.
- **More easing curves.** Sine, quart, quint, expo and circ (each in, out and in-out), bounce in and in-out, and smoothstep and smootherstep join the quad, cubic, back, elastic and out-bounce curves. They are new `EasingType` members after the existing ones, so a saved tween keeps its curve, and they ease the same in a C++ tween and a script value tween.
@@ -89,6 +90,7 @@ published separately; it ships inside the editor.
### Fixed
+- **`RectAnchors`, `AnchorFlag` and `AnchorMode` can be imported from `esengine`.** They were exported from the UI module only, so the import the manual shows did not resolve.
- **Lit materials draw on WebGPU again.** A lit material on the engine's own vertex stage, and a 2D lit shader, built a WebGPU program with a preprocessor line left in it, so the material drew nothing (and a desktop build of a 3D scene came up black). `#if` and `#elif` conditions with `defined`, `!`, `&&`, `||` and parentheses now resolve in a WGSL twin as they do in GLSL.
- **A scanned preview reaches the game's own server.** The page a phone opens from the preview QR code allowed connections only to itself, so a game that logged in to a server on the LAN worked in Play and in a single-file build but not on the phone. The preview now connects as Play does; a shipping web export still connects only to the servers listed in Project Settings → Allowed server origins.
- **The ground has no dark patches on a Mac.** With the depth prepass on (quality high and medium), a material written as a fragment shader alone, the terrain among them, drew its colour from a vertex stage that did not declare its position invariant, while its depth came from one that did. Metal is free to compute the two a bit apart, and wherever they differed the colour failed the equal-depth test: sand, sea floor and grass showed dark triangles. Both stages now declare it, on WebGL2 and WebGPU.
diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.json
index e48557d63..164b24260 100644
--- a/docs/astro/src/data/apiStability.generated.json
+++ b/docs/astro/src/data/apiStability.generated.json
@@ -3,10 +3,10 @@
"counts": {
"public": 115,
"beta": 173,
- "experimental": 2733,
+ "experimental": 2742,
"deprecated": 3
},
- "total": 3021,
+ "total": 3030,
"subsystems": [
{
"id": "mobile-controls",
diff --git a/examples/render-texture/README.md b/examples/render-texture/README.md
index 96a547506..5933960bf 100644
--- a/examples/render-texture/README.md
+++ b/examples/render-texture/README.md
@@ -9,6 +9,10 @@ A quad pinned to the top-right corner shows the whole world live: every frame
a system paints a schematic of the world into a `RenderTexture`, and the
quad's `Sprite` samples the target's `texture`.
+Along the bottom-left, four cards are sprites cut from **one** canvas that
+`TextureAtlas.pack` drew from four separate textures (`src/systems/atlas.ts`); the small
+picture beside them is the canvas itself.
+
| Key | Action |
|---|---|
| **R** | Cycle the target's resolution: 96×60 → 192×120 → 384×240 → 768×480. The quad keeps the same on-screen size, so the fidelity change is obvious (and `resize` semantics are exercised — see below). |
diff --git a/examples/render-texture/src/main.ts b/examples/render-texture/src/main.ts
index 87e05ce9b..7adf80888 100644
--- a/examples/render-texture/src/main.ts
+++ b/examples/render-texture/src/main.ts
@@ -1,24 +1,14 @@
-// Render Texture — offscreen rendering with the RenderTexture API:
-//
-// • A world of colored shapes drifts along orbits far beyond the camera's
-// view — most of the world is offscreen at any moment.
-// • A corner minimap quad shows all of it live: every frame a system paints
-// the world schematically into a RenderTexture with the immediate Draw
-// API, and the quad's Sprite samples the target's textureId.
-// • R cycles the target's resolution through 96×60 → 192×120 → 384×240 →
-// 768×480 at a fixed display size — resize() returns a NEW handle whose
-// textureId the sprite must be re-pointed at.
-//
-// RenderTexture is the low-level surface: Draw commands issued between begin()
-// and end() go into an offscreen target under a view-projection you supply.
-// A whole SCENE goes into one through Camera.renderTarget.
+// Render Texture: a minimap painted into a RenderTexture every frame (R cycles its resolution),
+// and four sprites cut from one TextureAtlas canvas along the bottom (systems/atlas.ts).
import { addStartupSystem, addSystemToSchedule, Schedule } from 'esengine';
import './components';
import { setupSystem } from './systems/setup';
import { orbitSystem } from './systems/orbit';
import { minimapSystem } from './systems/minimap';
+import { atlasSystem } from './systems/atlas';
addStartupSystem(setupSystem);
addSystemToSchedule(Schedule.Update, orbitSystem);
addSystemToSchedule(Schedule.Update, minimapSystem);
+addSystemToSchedule(Schedule.Update, atlasSystem);
diff --git a/examples/render-texture/src/systems/atlas.ts b/examples/render-texture/src/systems/atlas.ts
new file mode 100644
index 000000000..79fe17024
--- /dev/null
+++ b/examples/render-texture/src/systems/atlas.ts
@@ -0,0 +1,82 @@
+import {
+ defineSystem, Commands, Transform, Sprite,
+ RenderTexture, Renderer, Draw, BlendMode, TextureAtlas, onDeviceRestored,
+ type RenderTextureHandle, type TextureAtlasHandle,
+} from 'esengine';
+import { VIEW_HALF_W, VIEW_HALF_H, MINIMAP_LAYER } from '../config';
+
+// The four sources are lopsided on purpose, so a flipped or misplaced cell shows; in a game they
+// would be loaded images. Every sprite shares the one canvas, so they batch.
+
+const SOURCES = [
+ { w: 96, h: 64, color: { r: 0.95, g: 0.45, b: 0.35, a: 1 } },
+ { w: 48, h: 96, color: { r: 0.4, g: 0.75, b: 1, a: 1 } },
+ { w: 64, h: 64, color: { r: 0.55, g: 0.9, b: 0.45, a: 1 } },
+ { w: 80, h: 40, color: { r: 0.95, g: 0.8, b: 0.35, a: 1 } },
+];
+
+function ortho(w: number, h: number): Float32Array {
+ const m = new Float32Array(16);
+ m[0] = 2 / w; m[5] = 2 / h; m[10] = -1; m[12] = -1; m[13] = -1; m[15] = 1;
+ return m;
+}
+
+/** A coloured card with a white square in its top-left corner and a dark bar along its bottom edge. */
+function paint(rt: RenderTextureHandle, color: { r: number; g: number; b: number; a: number }): void {
+ const { width: w, height: h } = rt;
+ const vp = ortho(w, h);
+ RenderTexture.begin(rt, vp);
+ Draw.begin(vp);
+ Renderer.setViewport(0, 0, w, h);
+ Draw.setBlendMode(BlendMode.None);
+ Draw.rect({ x: w / 2, y: h / 2 }, { x: w, y: h }, color);
+ Draw.rect({ x: 12, y: h - 12 }, { x: 16, y: 16 }, { r: 1, g: 1, b: 1, a: 1 });
+ Draw.rect({ x: w / 2, y: 5 }, { x: w - 12, y: 6 }, { r: 0.1, g: 0.1, b: 0.14, a: 1 });
+ Draw.end();
+ RenderTexture.end();
+ RenderTexture.contentDrawn(rt);
+}
+
+let sources: RenderTextureHandle[] | null = null;
+let atlas: TextureAtlasHandle | null = null;
+
+export const atlasSystem = defineSystem(
+ [Commands()],
+ (cmds) => {
+ if (atlas) return;
+ sources = SOURCES.map((s) => RenderTexture.create({ width: s.w, height: s.h, depth: false, filter: 'nearest' }));
+ if (sources.some((rt) => rt.texture === 0)) {
+ sources.forEach((rt) => RenderTexture.release(rt));
+ sources = null;
+ return;
+ }
+ sources.forEach((rt, i) => paint(rt, SOURCES[i].color));
+
+ const packed = TextureAtlas.pack(sources.map((rt) => rt.texture), { filter: 'nearest' });
+ if (!packed) return;
+ atlas = packed;
+ onDeviceRestored(() => {
+ sources!.forEach((rt, i) => paint(rt, SOURCES[i].color));
+ atlas!.repaint();
+ });
+
+ // The four cells, along the bottom-left, each its source's own size.
+ let x = -VIEW_HALF_W + 24;
+ sources.forEach((rt, i) => {
+ const { w, h } = SOURCES[i];
+ cmds.spawn()
+ .insert(Transform, { position: { x: x + w / 2, y: -VIEW_HALF_H + 24 + h / 2, z: 0 } })
+ .insert(Sprite, { ...atlas!.sprite(rt.texture), size: { x: w, y: h }, color: { r: 1, g: 1, b: 1, a: 1 }, layer: MINIMAP_LAYER });
+ x += w + 16;
+ });
+
+ // The whole canvas, next to them.
+ cmds.spawn()
+ .insert(Transform, { position: { x: x + 80, y: -VIEW_HALF_H + 24 + 80, z: 0 } })
+ .insert(Sprite, {
+ texture: atlas.texture, size: { x: 160, y: 160 * atlas.height / atlas.width },
+ color: { r: 1, g: 1, b: 1, a: 1 }, layer: MINIMAP_LAYER,
+ });
+ },
+ { name: 'AtlasSystem' },
+);
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 2f692fdf2..841ee5457 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: 115 public · 161 beta · 1966 experimental · 3 deprecated
+Symbols: 115 public · 161 beta · 1975 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -347,6 +347,16 @@ position: number
width: Dimension | undefined
```
+## AnchorFlag — const @experimental
+```
+Readonly<{ TOP: 1; MID: 2; BOTTOM: 4; LEFT: 8; CENTER: 16; RIGHT: 32; HORIZONTAL: number; VERTICAL: number; }>
+```
+
+## AnchorMode — const @experimental
+```
+Readonly<{ ONCE: 0; ON_RESIZE: 1; ALWAYS: 2; }>
+```
+
## AnchorPreset — interface @experimental
```
h: AnchorAxis
@@ -1109,6 +1119,16 @@ static prototype: AsyncCache<any>
folder: string
```
+## AtlasEntry — interface @experimental
+```
+height: number
+uvOffset: { x: number; y: number; }
+uvScale: { x: number; y: number; }
+width: number
+x: number
+y: number
+```
+
## AttenuationModel — enum @experimental
```
Exponential = 2
@@ -8129,6 +8149,30 @@ tags: readonly string[] | undefined
waterDepth: number | undefined
```
+## RectAnchors — const @experimental
+```
+ComponentDef<RectAnchorsData>
+```
+
+## RectAnchorsData — interface @experimental
+```
+alignFlags: number
+alignMode: number
+bottom: number
+enabled: boolean
+horizontalCenter: number
+isAbsBottom: boolean
+isAbsHorizontalCenter: boolean
+isAbsLeft: boolean
+isAbsRight: boolean
+isAbsTop: boolean
+isAbsVerticalCenter: boolean
+left: number
+right: number
+top: number
+verticalCenter: number
+```
+
## ReflectionAxis — enum @experimental
```
X = 0
@@ -11004,6 +11048,29 @@ type: "text"
(typeof TextVerticalAlign)[keyof typeof TextVerticalAlign]
```
+## TextureAtlas — const @experimental
+```
+{ pack(sources: readonly number[], options?: TextureAtlasOptions): TextureAtlasHandle | null; }
+```
+
+## TextureAtlasHandle — interface @experimental
+```
+get: (source: number) => AtlasEntry | undefined
+height: number
+release: () => void
+repaint: () => void
+sprite: (source: number) => { texture: number; uvOffset: { x: number; y: number; }; uvScale: { x: number; y: number; }; }
+texture: number
+width: number
+```
+
+## TextureAtlasOptions — interface @experimental
+```
+filter: "linear" | "nearest" | undefined
+maxSize: number | undefined
+padding: number | undefined
+```
+
## TextureFilter — type @experimental
```
(typeof TextureFilter)[keyof typeof TextureFilter]
@@ -13219,6 +13286,11 @@ static prototype: Zones
AiRegistry<AiContext>
```
+## alignRectAnchorsNow — function @experimental
+```
+(world: World, entity: Entity, screen: ScreenLayoutData | null): boolean
+```
+
## analyzeCensusSeries — function @experimental
```
(samples: readonly Census[], opts?: CensusSeriesOptions): CensusReport
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index d8f8f83ce..269bc4eed 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: 115 public · 166 beta · 1985 experimental · 3 deprecated
+Symbols: 115 public · 166 beta · 1994 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -347,6 +347,16 @@ position: number
width: Dimension | undefined
```
+## AnchorFlag — const @experimental
+```
+Readonly<{ TOP: 1; MID: 2; BOTTOM: 4; LEFT: 8; CENTER: 16; RIGHT: 32; HORIZONTAL: number; VERTICAL: number; }>
+```
+
+## AnchorMode — const @experimental
+```
+Readonly<{ ONCE: 0; ON_RESIZE: 1; ALWAYS: 2; }>
+```
+
## AnchorPreset — interface @experimental
```
h: AnchorAxis
@@ -1109,6 +1119,16 @@ static prototype: AsyncCache<any>
folder: string
```
+## AtlasEntry — interface @experimental
+```
+height: number
+uvOffset: { x: number; y: number; }
+uvScale: { x: number; y: number; }
+width: number
+x: number
+y: number
+```
+
## AttenuationModel — enum @experimental
```
Exponential = 2
@@ -8342,6 +8362,30 @@ tags: readonly string[] | undefined
waterDepth: number | undefined
```
+## RectAnchors — const @experimental
+```
+ComponentDef<RectAnchorsData>
+```
+
+## RectAnchorsData — interface @experimental
+```
+alignFlags: number
+alignMode: number
+bottom: number
+enabled: boolean
+horizontalCenter: number
+isAbsBottom: boolean
+isAbsHorizontalCenter: boolean
+isAbsLeft: boolean
+isAbsRight: boolean
+isAbsTop: boolean
+isAbsVerticalCenter: boolean
+left: number
+right: number
+top: number
+verticalCenter: number
+```
+
## ReflectionAxis — enum @experimental
```
X = 0
@@ -11217,6 +11261,29 @@ type: "text"
(typeof TextVerticalAlign)[keyof typeof TextVerticalAlign]
```
+## TextureAtlas — const @experimental
+```
+{ pack(sources: readonly number[], options?: TextureAtlasOptions): TextureAtlasHandle | null; }
+```
+
+## TextureAtlasHandle — interface @experimental
+```
+get: (source: number) => AtlasEntry | undefined
+height: number
+release: () => void
+repaint: () => void
+sprite: (source: number) => { texture: number; uvOffset: { x: number; y: number; }; uvScale: { x: number; y: number; }; }
+texture: number
+width: number
+```
+
+## TextureAtlasOptions — interface @experimental
+```
+filter: "linear" | "nearest" | undefined
+maxSize: number | undefined
+padding: number | undefined
+```
+
## TextureFilter — type @experimental
```
(typeof TextureFilter)[keyof typeof TextureFilter]
@@ -13432,6 +13499,11 @@ static prototype: Zones
AiRegistry<AiContext>
```
+## alignRectAnchorsNow — function @experimental
+```
+(world: World, entity: Entity, screen: ScreenLayoutData | null): boolean
+```
+
## analyzeCensusSeries — function @experimental
```
(samples: readonly Census[], opts?: CensusSeriesOptions): CensusReport
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index ce5a1287a..e6e3f2a06 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: 115 public · 163 beta · 1965 experimental · 3 deprecated
+Symbols: 115 public · 163 beta · 1974 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -342,6 +342,16 @@ position: number
width: Dimension | undefined
```
+## AnchorFlag — const @experimental
+```
+Readonly<{ TOP: 1; MID: 2; BOTTOM: 4; LEFT: 8; CENTER: 16; RIGHT: 32; HORIZONTAL: number; VERTICAL: number; }>
+```
+
+## AnchorMode — const @experimental
+```
+Readonly<{ ONCE: 0; ON_RESIZE: 1; ALWAYS: 2; }>
+```
+
## AnchorPreset — interface @experimental
```
h: AnchorAxis
@@ -1104,6 +1114,16 @@ static prototype: AsyncCache<any>
folder: string
```
+## AtlasEntry — interface @experimental
+```
+height: number
+uvOffset: { x: number; y: number; }
+uvScale: { x: number; y: number; }
+width: number
+x: number
+y: number
+```
+
## AttenuationModel — enum @experimental
```
Exponential = 2
@@ -8124,6 +8144,30 @@ tags: readonly string[] | undefined
waterDepth: number | undefined
```
+## RectAnchors — const @experimental
+```
+ComponentDef<RectAnchorsData>
+```
+
+## RectAnchorsData — interface @experimental
+```
+alignFlags: number
+alignMode: number
+bottom: number
+enabled: boolean
+horizontalCenter: number
+isAbsBottom: boolean
+isAbsHorizontalCenter: boolean
+isAbsLeft: boolean
+isAbsRight: boolean
+isAbsTop: boolean
+isAbsVerticalCenter: boolean
+left: number
+right: number
+top: number
+verticalCenter: number
+```
+
## ReflectionAxis — enum @experimental
```
X = 0
@@ -10999,6 +11043,29 @@ type: "text"
(typeof TextVerticalAlign)[keyof typeof TextVerticalAlign]
```
+## TextureAtlas — const @experimental
+```
+{ pack(sources: readonly number[], options?: TextureAtlasOptions): TextureAtlasHandle | null; }
+```
+
+## TextureAtlasHandle — interface @experimental
+```
+get: (source: number) => AtlasEntry | undefined
+height: number
+release: () => void
+repaint: () => void
+sprite: (source: number) => { texture: number; uvOffset: { x: number; y: number; }; uvScale: { x: number; y: number; }; }
+texture: number
+width: number
+```
+
+## TextureAtlasOptions — interface @experimental
+```
+filter: "linear" | "nearest" | undefined
+maxSize: number | undefined
+padding: number | undefined
+```
+
## TextureFilter — type @experimental
```
(typeof TextureFilter)[keyof typeof TextureFilter]
@@ -13214,6 +13281,11 @@ static prototype: Zones
AiRegistry<AiContext>
```
+## alignRectAnchorsNow — function @experimental
+```
+(world: World, entity: Entity, screen: ScreenLayoutData | null): boolean
+```
+
## analyzeCensusSeries — function @experimental
```
(samples: readonly Census[], opts?: CensusSeriesOptions): CensusReport
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 7714aa3a2..dbb7fcea2 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: 115 public · 161 beta · 1987 experimental · 3 deprecated
+Symbols: 115 public · 161 beta · 1996 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -342,6 +342,16 @@ position: number
width: Dimension | undefined
```
+## AnchorFlag — const @experimental
+```
+Readonly<{ TOP: 1; MID: 2; BOTTOM: 4; LEFT: 8; CENTER: 16; RIGHT: 32; HORIZONTAL: number; VERTICAL: number; }>
+```
+
+## AnchorMode — const @experimental
+```
+Readonly<{ ONCE: 0; ON_RESIZE: 1; ALWAYS: 2; }>
+```
+
## AnchorPreset — interface @experimental
```
h: AnchorAxis
@@ -1104,6 +1114,16 @@ static prototype: AsyncCache<any>
folder: string
```
+## AtlasEntry — interface @experimental
+```
+height: number
+uvOffset: { x: number; y: number; }
+uvScale: { x: number; y: number; }
+width: number
+x: number
+y: number
+```
+
## AttenuationModel — enum @experimental
```
Exponential = 2
@@ -8419,6 +8439,30 @@ tags: readonly string[] | undefined
waterDepth: number | undefined
```
+## RectAnchors — const @experimental
+```
+ComponentDef<RectAnchorsData>
+```
+
+## RectAnchorsData — interface @experimental
+```
+alignFlags: number
+alignMode: number
+bottom: number
+enabled: boolean
+horizontalCenter: number
+isAbsBottom: boolean
+isAbsHorizontalCenter: boolean
+isAbsLeft: boolean
+isAbsRight: boolean
+isAbsTop: boolean
+isAbsVerticalCenter: boolean
+left: number
+right: number
+top: number
+verticalCenter: number
+```
+
## ReflectionAxis — enum @experimental
```
X = 0
@@ -11294,6 +11338,29 @@ type: "text"
(typeof TextVerticalAlign)[keyof typeof TextVerticalAlign]
```
+## TextureAtlas — const @experimental
+```
+{ pack(sources: readonly number[], options?: TextureAtlasOptions): TextureAtlasHandle | null; }
+```
+
+## TextureAtlasHandle — interface @experimental
+```
+get: (source: number) => AtlasEntry | undefined
+height: number
+release: () => void
+repaint: () => void
+sprite: (source: number) => { texture: number; uvOffset: { x: number; y: number; }; uvScale: { x: number; y: number; }; }
+texture: number
+width: number
+```
+
+## TextureAtlasOptions — interface @experimental
+```
+filter: "linear" | "nearest" | undefined
+maxSize: number | undefined
+padding: number | undefined
+```
+
## TextureFilter — type @experimental
```
(typeof TextureFilter)[keyof typeof TextureFilter]
@@ -13515,6 +13582,11 @@ static prototype: Zones
AiRegistry<AiContext>
```
+## alignRectAnchorsNow — function @experimental
+```
+(world: World, entity: Entity, screen: ScreenLayoutData | null): boolean
+```
+
## analyzeCensusSeries — function @experimental
```
(samples: readonly Census[], opts?: CensusSeriesOptions): CensusReport
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 0a0ef7e55..1710d5a6a 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: 115 public · 161 beta · 1978 experimental · 3 deprecated
+Symbols: 115 public · 161 beta · 1987 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -342,6 +342,16 @@ position: number
width: Dimension | undefined
```
+## AnchorFlag — const @experimental
+```
+Readonly<{ TOP: 1; MID: 2; BOTTOM: 4; LEFT: 8; CENTER: 16; RIGHT: 32; HORIZONTAL: number; VERTICAL: number; }>
+```
+
+## AnchorMode — const @experimental
+```
+Readonly<{ ONCE: 0; ON_RESIZE: 1; ALWAYS: 2; }>
+```
+
## AnchorPreset — interface @experimental
```
h: AnchorAxis
@@ -1104,6 +1114,16 @@ static prototype: AsyncCache<any>
folder: string
```
+## AtlasEntry — interface @experimental
+```
+height: number
+uvOffset: { x: number; y: number; }
+uvScale: { x: number; y: number; }
+width: number
+x: number
+y: number
+```
+
## AttenuationModel — enum @experimental
```
Exponential = 2
@@ -8131,6 +8151,30 @@ tags: readonly string[] | undefined
waterDepth: number | undefined
```
+## RectAnchors — const @experimental
+```
+ComponentDef<RectAnchorsData>
+```
+
+## RectAnchorsData — interface @experimental
+```
+alignFlags: number
+alignMode: number
+bottom: number
+enabled: boolean
+horizontalCenter: number
+isAbsBottom: boolean
+isAbsHorizontalCenter: boolean
+isAbsLeft: boolean
+isAbsRight: boolean
+isAbsTop: boolean
+isAbsVerticalCenter: boolean
+left: number
+right: number
+top: number
+verticalCenter: number
+```
+
## ReflectionAxis — enum @experimental
```
X = 0
@@ -11006,6 +11050,29 @@ type: "text"
(typeof TextVerticalAlign)[keyof typeof TextVerticalAlign]
```
+## TextureAtlas — const @experimental
+```
+{ pack(sources: readonly number[], options?: TextureAtlasOptions): TextureAtlasHandle | null; }
+```
+
+## TextureAtlasHandle — interface @experimental
+```
+get: (source: number) => AtlasEntry | undefined
+height: number
+release: () => void
+repaint: () => void
+sprite: (source: number) => { texture: number; uvOffset: { x: number; y: number; }; uvScale: { x: number; y: number; }; }
+texture: number
+width: number
+```
+
+## TextureAtlasOptions — interface @experimental
+```
+filter: "linear" | "nearest" | undefined
+maxSize: number | undefined
+padding: number | undefined
+```
+
## TextureFilter — type @experimental
```
(typeof TextureFilter)[keyof typeof TextureFilter]
@@ -13246,6 +13313,11 @@ static prototype: Zones
AiRegistry<AiContext>
```
+## alignRectAnchorsNow — function @experimental
+```
+(world: World, entity: Entity, screen: ScreenLayoutData | null): boolean
+```
+
## analyzeCensusSeries — function @experimental
```
(samples: readonly Census[], opts?: CensusSeriesOptions): CensusReport
diff --git a/sdk/src/core-render.ts b/sdk/src/core-render.ts
index 9cb212778..cfd75a0c4 100644
--- a/sdk/src/core-render.ts
+++ b/sdk/src/core-render.ts
@@ -308,6 +308,13 @@ export {
type RenderTextureOptions,
} from './render/renderTexture';
+export {
+ TextureAtlas,
+ type TextureAtlasHandle,
+ type TextureAtlasOptions,
+ type AtlasEntry,
+} from './render/textureAtlas';
+
// =============================================================================
// Render Pipeline
// =============================================================================
diff --git a/sdk/src/core-ui.ts b/sdk/src/core-ui.ts
index 538fe3cbe..da87cdf4e 100644
--- a/sdk/src/core-ui.ts
+++ b/sdk/src/core-ui.ts
@@ -277,6 +277,8 @@ export {
type PageHandle,
} from './ui';
+export { RectAnchors, AnchorFlag, AnchorMode, alignRectAnchorsNow, type RectAnchorsData } from './ui';
+
export { VirtualJoystick, VirtualButton, VirtualJoystickMode, createVirtualJoystick, createVirtualButton, type VirtualJoystickData, type VirtualButtonData, type VirtualJoystickOptions, type VirtualButtonOptions } from './ui';
export { deferredEntities, deferredRecord } from './scene/deferredInstances';
diff --git a/sdk/src/render/textureAtlas.ts b/sdk/src/render/textureAtlas.ts
new file mode 100644
index 000000000..a6cb40ce4
--- /dev/null
+++ b/sdk/src/render/textureAtlas.ts
@@ -0,0 +1,204 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file textureAtlas.ts
+ * @brief Packs several textures onto one canvas at run time, so sprites that share it batch into one draw.
+ */
+import { Draw } from './draw';
+import { BlendMode } from './blend';
+import { Renderer, onDeviceRestored } from './renderer';
+import { RenderTexture, type RenderTextureHandle } from './renderTexture';
+import { getResourceManager, getTextureDimensions } from '../wasm/resourceManager';
+import { log } from '../util/logger';
+
+/** Where one source texture sits on an atlas. @experimental */
+export interface AtlasEntry {
+ /** Left edge in atlas pixels. */
+ x: number;
+ /** Top edge in atlas pixels, counted from the top of the canvas. */
+ y: number;
+ width: number;
+ height: number;
+ /** What `Sprite.uvOffset` takes to show exactly this entry. */
+ uvOffset: { x: number; y: number };
+ /** What `Sprite.uvScale` takes to show exactly this entry. */
+ uvScale: { x: number; y: number };
+}
+
+/** Options of {@link TextureAtlas.pack}. @experimental */
+export interface TextureAtlasOptions {
+ /** The largest canvas edge to try, in pixels. Default 2048. */
+ maxSize?: number;
+ /** Transparent pixels kept between neighbours so a filtered edge does not pick up the next picture. Default 2. */
+ padding?: number;
+ /** Sampling filter of the canvas. Default `'linear'`. */
+ filter?: 'nearest' | 'linear';
+}
+
+/** A packed canvas and where each source sits on it. @experimental */
+export interface TextureAtlasHandle {
+ /** Resource-table handle of the canvas — what `Sprite.texture` takes. */
+ readonly texture: number;
+ readonly width: number;
+ readonly height: number;
+ /** The entry of a source texture handle, or undefined when it was not packed. */
+ get(source: number): AtlasEntry | undefined;
+ /** `{ texture, uvOffset, uvScale }` for a source, ready to spread into a `Sprite`. */
+ sprite(source: number): { texture: number; uvOffset: { x: number; y: number }; uvScale: { x: number; y: number } };
+ /** Draws the canvas again from the sources; done for you after a device loss. */
+ repaint(): void;
+ /** Frees the canvas. The sources are not touched. */
+ release(): void;
+}
+
+export interface PackSize {
+ width: number;
+ height: number;
+}
+
+export interface PackLayout {
+ width: number;
+ height: number;
+ /** One top-left corner per input, in input order. */
+ places: Array<{ x: number; y: number }>;
+}
+
+const nextPow2 = (n: number): number => {
+ let p = 1;
+ while (p < n) p *= 2;
+ return p;
+};
+
+/** Rows of pictures, tallest first, in a canvas `width` wide; null if they run past `maxHeight`. */
+function shelves(sizes: readonly PackSize[], order: readonly number[], width: number, padding: number, maxHeight: number): { places: Array<{ x: number; y: number }>; used: number } | null {
+ const places = new Array<{ x: number; y: number }>(sizes.length);
+ let x = 0, y = 0, rowHeight = 0;
+ for (const i of order) {
+ const w = sizes[i].width + padding, h = sizes[i].height + padding;
+ if (x + w > width) {
+ y += rowHeight;
+ x = 0;
+ rowHeight = 0;
+ }
+ if (w > width || y + h > maxHeight) return null;
+ places[i] = { x, y };
+ x += w;
+ rowHeight = Math.max(rowHeight, h);
+ }
+ return { places, used: y + rowHeight };
+}
+
+/**
+ * Lays the sizes out on the smallest power-of-two canvas that holds them, widening before it grows
+ * tall. Throws when even `maxSize` on both edges is not enough.
+ * @internal
+ */
+export function packRects(sizes: readonly PackSize[], maxSize: number, padding: number): PackLayout {
+ if (sizes.length === 0) return { width: 1, height: 1, places: [] };
+ const order = sizes.map((_, i) => i).sort((a, b) => sizes[b].height - sizes[a].height || sizes[b].width - sizes[a].width || a - b);
+ let area = 0;
+ for (const s of sizes) area += (s.width + padding) * (s.height + padding);
+ const widest = Math.max(...sizes.map((s) => s.width + padding));
+ for (let width = Math.max(nextPow2(Math.ceil(Math.sqrt(area))), nextPow2(widest)); width <= maxSize; width *= 2) {
+ const laid = shelves(sizes, order, width, padding, maxSize);
+ if (laid) return { width, height: nextPow2(laid.used), places: laid.places };
+ }
+ throw new Error(`${sizes.length} textures do not fit in ${maxSize}×${maxSize} (with ${padding} px of padding)`);
+}
+
+/** Column-major orthographic projection over a rectangle: what RenderTexture.begin wants. */
+function ortho(l: number, r: number, b: number, t: number): Float32Array {
+ const m = new Float32Array(16);
+ m[0] = 2 / (r - l);
+ m[5] = 2 / (t - b);
+ m[10] = -1;
+ m[12] = -(r + l) / (r - l);
+ m[13] = -(t + b) / (t - b);
+ m[15] = 1;
+ return m;
+}
+
+export const TextureAtlas = {
+ /**
+ * Draws `sources` (texture handles) onto one new canvas and returns where each landed. Call it
+ * from a `Schedule.Update` system, not a draw callback. Null while the renderer is not up yet;
+ * throws when a handle has no size or the textures do not fit. Keep the sources alive: a device
+ * loss draws the canvas again from them.
+ * @experimental
+ */
+ pack(sources: readonly number[], options: TextureAtlasOptions = {}): TextureAtlasHandle | null {
+ const maxSize = options.maxSize ?? 2048;
+ const padding = options.padding ?? 2;
+ const unique = [...new Set(sources)];
+ const sizes = unique.map((source) => {
+ const dims = getTextureDimensions(source);
+ if (!dims || dims.width <= 0 || dims.height <= 0) throw new Error(`texture handle ${source} has no size to pack`);
+ return { width: dims.width, height: dims.height };
+ });
+ const layout = packRects(sizes, maxSize, padding);
+
+ const rt: RenderTextureHandle = RenderTexture.create({ width: layout.width, height: layout.height, depth: false, filter: options.filter ?? 'linear' });
+ if (rt.texture === 0) {
+ RenderTexture.release(rt);
+ return null;
+ }
+
+ const entries = new Map<number, AtlasEntry>();
+ unique.forEach((source, i) => {
+ const { x, y } = layout.places[i];
+ const { width, height } = sizes[i];
+ entries.set(source, {
+ x, y, width, height,
+ uvOffset: { x: x / layout.width, y: 1 - (y + height) / layout.height },
+ uvScale: { x: width / layout.width, y: height / layout.height },
+ });
+ });
+
+ const repaint = (): void => {
+ // Pixels count from the top of the canvas, the projection from its bottom.
+ const vp = ortho(0, layout.width, 0, layout.height);
+ RenderTexture.begin(rt, vp);
+ Draw.begin(vp);
+ Renderer.setViewport(0, 0, layout.width, layout.height);
+ // Nothing blends: the first rect clears to transparent and each picture is copied as it is.
+ Draw.setBlendMode(BlendMode.None);
+ Draw.rect({ x: layout.width / 2, y: layout.height / 2 }, { x: layout.width, y: layout.height }, { r: 1, g: 1, b: 1, a: 0 });
+ // Draw takes the device's own texture id, which a device loss renumbers: ask afresh each time.
+ const rm = getResourceManager();
+ for (const [source, e] of entries) {
+ const deviceId = rm?.getTextureGLId(source) ?? 0;
+ if (deviceId === 0) continue;
+ Draw.texture({ x: e.x + e.width / 2, y: layout.height - e.y - e.height / 2 }, { x: e.width, y: e.height }, deviceId);
+ }
+ Draw.end();
+ RenderTexture.end();
+ RenderTexture.contentDrawn(rt);
+ };
+ repaint();
+
+ const unsubscribe = onDeviceRestored(() => {
+ try {
+ repaint();
+ } catch (error) {
+ log.warn('textureAtlas', `the atlas cannot be drawn again after the device came back: ${String(error)}`);
+ }
+ });
+
+ return {
+ texture: rt.texture,
+ width: layout.width,
+ height: layout.height,
+ get: (source) => entries.get(source),
+ sprite: (source) => {
+ const e = entries.get(source);
+ if (!e) throw new Error(`texture handle ${source} is not on this atlas`);
+ return { texture: rt.texture, uvOffset: { ...e.uvOffset }, uvScale: { ...e.uvScale } };
+ },
+ repaint,
+ release: () => {
+ unsubscribe();
+ RenderTexture.release(rt);
+ },
+ };
+ },
+};
diff --git a/sdk/tests/textureAtlas.test.ts b/sdk/tests/textureAtlas.test.ts
new file mode 100644
index 000000000..e98d95482
--- /dev/null
+++ b/sdk/tests/textureAtlas.test.ts
@@ -0,0 +1,130 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Packing textures onto one canvas: where each lands, what uv rectangle shows it, and that a lost device draws it again.
+ */
+import { describe, expect, it, vi, beforeEach } from 'vitest';
+
+const drawn: Array<{ pos: { x: number; y: number }; size: { x: number; y: number }; id: number }> = [];
+let restored: (() => void) | null = null;
+let texture = 500;
+
+vi.mock('../src/render/draw', () => ({
+ Draw: {
+ begin: vi.fn(), end: vi.fn(), setBlendMode: vi.fn(), rect: vi.fn(),
+ texture: (pos: { x: number; y: number }, size: { x: number; y: number }, id: number) => { drawn.push({ pos, size, id }); },
+ },
+}));
+vi.mock('../src/render/renderer', () => ({
+ deviceGeneration: () => 1,
+ Renderer: { setViewport: vi.fn() },
+ onDeviceRestored: (fn: () => void) => { restored = fn; return () => { restored = null; }; },
+}));
+vi.mock('../src/render/renderTexture', () => ({
+ RenderTexture: {
+ create: vi.fn(() => ({ texture, width: 0, height: 0 })),
+ release: vi.fn(), begin: vi.fn(), end: vi.fn(), contentDrawn: vi.fn(),
+ },
+}));
+const dims = new Map<number, { width: number; height: number }>();
+vi.mock('../src/wasm/resourceManager', () => ({
+ getTextureDimensions: (h: number) => dims.get(h) ?? null,
+ getResourceManager: () => ({ getTextureGLId: (h: number) => h + 1000 }),
+}));
+
+import { packRects, TextureAtlas } from '../src/render/textureAtlas';
+
+describe('packRects', () => {
+ const overlap = (a: { x: number; y: number }, as: { width: number; height: number }, b: { x: number; y: number }, bs: { width: number; height: number }) =>
+ a.x < b.x + bs.width && b.x < a.x + as.width && a.y < b.y + bs.height && b.y < a.y + as.height;
+
+ it('keeps every picture inside the canvas and clear of the others', () => {
+ const sizes = [{ width: 64, height: 64 }, { width: 32, height: 48 }, { width: 100, height: 20 }, { width: 17, height: 90 }, { width: 64, height: 64 }];
+ const out = packRects(sizes, 512, 2);
+ sizes.forEach((s, i) => {
+ const p = out.places[i];
+ expect(p.x).toBeGreaterThanOrEqual(0);
+ expect(p.y).toBeGreaterThanOrEqual(0);
+ expect(p.x + s.width).toBeLessThanOrEqual(out.width);
+ expect(p.y + s.height).toBeLessThanOrEqual(out.height);
+ for (let j = i + 1; j < sizes.length; j++) expect(overlap(p, s, out.places[j], sizes[j])).toBe(false);
+ });
+ });
+
+ it('leaves the padding between neighbours', () => {
+ const out = packRects([{ width: 10, height: 10 }, { width: 10, height: 10 }], 64, 4);
+ const [a, b] = out.places;
+ expect(Math.abs(a.x - b.x) >= 14 || Math.abs(a.y - b.y) >= 14).toBe(true);
+ });
+
+ it('picks the smallest power-of-two canvas that holds them', () => {
+ const out = packRects([{ width: 30, height: 30 }], 2048, 0);
+ expect([out.width, out.height]).toEqual([32, 32]);
+ });
+
+ it('grows past a single picture wider than the first guess', () => {
+ const out = packRects([{ width: 200, height: 10 }, { width: 4, height: 4 }], 2048, 0);
+ expect(out.width).toBeGreaterThanOrEqual(200);
+ });
+
+ it('refuses what does not fit, and a picture larger than the canvas', () => {
+ expect(() => packRects([{ width: 600, height: 10 }], 512, 0)).toThrow(/do not fit/);
+ expect(() => packRects(Array.from({ length: 5 }, () => ({ width: 256, height: 256 })), 512, 0)).toThrow(/do not fit/);
+ });
+});
+
+describe('TextureAtlas.pack', () => {
+ beforeEach(() => {
+ drawn.length = 0;
+ dims.clear();
+ dims.set(1, { width: 64, height: 32 });
+ dims.set(2, { width: 16, height: 16 });
+ texture = 500;
+ });
+
+ it('gives each source a uv window measured from the bottom, like a sheet cell', () => {
+ const atlas = TextureAtlas.pack([1, 2], { padding: 0 })!;
+ for (const src of [1, 2]) {
+ const e = atlas.get(src)!;
+ expect(e.uvScale.x).toBeCloseTo(e.width / atlas.width, 9);
+ expect(e.uvScale.y).toBeCloseTo(e.height / atlas.height, 9);
+ expect(e.uvOffset.x).toBeCloseTo(e.x / atlas.width, 9);
+ expect(e.uvOffset.y).toBeCloseTo(1 - (e.y + e.height) / atlas.height, 9);
+ }
+ expect(atlas.sprite(1).texture).toBe(500);
+ });
+
+ it('draws each source into its own rectangle, by the device id, with the vertical axis pointing up', () => {
+ const atlas = TextureAtlas.pack([1, 2], { padding: 0 })!;
+ expect(drawn.map((d) => d.id).sort()).toEqual([1001, 1002]);
+ for (const d of drawn) {
+ const e = atlas.get(d.id - 1000)!;
+ expect(d.pos.x).toBeCloseTo(e.x + e.width / 2, 9);
+ expect(d.pos.y).toBeCloseTo(atlas.height - e.y - e.height / 2, 9);
+ expect(d.size).toEqual({ x: e.width, y: e.height });
+ }
+ });
+
+ it('packs a handle given twice once', () => {
+ const atlas = TextureAtlas.pack([2, 2, 2])!;
+ expect(drawn).toHaveLength(1);
+ expect(atlas.get(2)).toBeDefined();
+ });
+
+ it('draws again when the device comes back, and stops listening once released', () => {
+ const atlas = TextureAtlas.pack([1, 2])!;
+ drawn.length = 0;
+ restored!();
+ expect(drawn).toHaveLength(2);
+ atlas.release();
+ expect(restored).toBeNull();
+ });
+
+ it('says so for a handle with no size, a source it did not pack, and a renderer not up yet', () => {
+ expect(() => TextureAtlas.pack([99])).toThrow(/no size/);
+ const atlas = TextureAtlas.pack([1])!;
+ expect(() => atlas.sprite(2)).toThrow(/not on this atlas/);
+ texture = 0;
+ expect(TextureAtlas.pack([1])).toBeNull();
+ });
+});
diff --git a/tools/goldenProjects.mjs b/tools/goldenProjects.mjs
index e788a3500..b15fcc928 100644
--- a/tools/goldenProjects.mjs
+++ b/tools/goldenProjects.mjs
@@ -1058,6 +1058,8 @@ export const SHIPPED = {
{ notCertifiable: "Cocos Creator project conversion, covered by the converter's unit tests and the editor suite; no golden project is a converted Cocos project, so no packaged frame can decide it." },
"A converted Cocos project is brought up to date when it is opened.":
{ notCertifiable: "Cocos Creator project conversion, covered by the converter's unit tests and the editor suite; no golden project is a converted Cocos project, so no packaged frame can decide it." },
+ "Pack several textures onto one canvas at run time: `TextureAtlas.pack`.":
+ { notCertifiable: "A rendering feature, covered by its unit tests and by the Render Texture example run in the editor; no golden project packs textures, and one packaged frame cannot decide a result that depends on the device." },
};
/** Numeric compare of two `x.y.z` strings. */