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(assets): cook-time auto-atlas - <name>.atlas folders pack into pages, frames ride the manifest into catalog uv
yhh39e4f963ba3a
diff --git a/desktop/electron/atlasPacker.ts b/desktop/electron/atlasPacker.tsnew file mode 100644index 000000000..fd25793b8--- /dev/null+++ b/desktop/electron/atlasPacker.ts@@ -0,0 +1,169 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Texture-atlas packer for the asset cook. Pure and deterministic: the+ * same inputs produce byte-identical pages, so atlas packing composes+ * with content-addressed staging. Shelf packing over height-sorted+ * input; images that overflow one page spill onto the next.+ *+ * The pack core is dependency-free (raw RGBA in, raw RGBA out); PNG decode/+ * encode live in thin wrappers so the algorithm stays unit-testable without+ * pixel fixtures.+ */+import { PNG } from 'pngjs';++export interface AtlasInputImage {+ /** Stable identity (the project-relative texture path). */+ key: string;+ width: number;+ height: number;+ /** RGBA8, width*height*4 bytes, row 0 = image top. */+ rgba: Uint8Array;+}++export interface AtlasPlacement {+ key: string;+ /** Pixel rect inside the page, y from the page TOP (image space). */+ x: number;+ y: number;+ width: number;+ height: number;+}++export interface AtlasPage {+ width: number;+ height: number;+ placements: AtlasPlacement[];+ /** Composed RGBA8 page pixels (row 0 = top). */+ rgba: Uint8Array;+}++export interface PackOptions {+ /** Page dimension cap (default 2048). */+ maxSize?: number;+ /** Transparent gutter around each image, defends linear-filter bleed (default 2). */+ padding?: number;+}++interface Shelf { y: number; height: number; x: number; }++/** Shelf-pack `sorted` into one width×height page; null when anything overflows. */+function tryPackPage(+ sorted: AtlasInputImage[],+ width: number,+ height: number,+ padding: number,+): AtlasPlacement[] | null {+ const shelves: Shelf[] = [];+ let yCursor = 0;+ const placements: AtlasPlacement[] = [];+ for (const img of sorted) {+ const w = img.width + padding * 2;+ const h = img.height + padding * 2;+ if (w > width || h > height) return null;+ let placed = false;+ for (const shelf of shelves) {+ if (h <= shelf.height && shelf.x + w <= width) {+ placements.push({ key: img.key, x: shelf.x + padding, y: shelf.y + padding, width: img.width, height: img.height });+ shelf.x += w;+ placed = true;+ break;+ }+ }+ if (!placed) {+ if (yCursor + h > height) return null;+ shelves.push({ y: yCursor, height: h, x: w });+ placements.push({ key: img.key, x: padding, y: yCursor + padding, width: img.width, height: img.height });+ yCursor += h;+ }+ }+ return placements;+}++/** Smallest power of two ≥ n (n ≥ 1). */+function nextPow2(n: number): number {+ let p = 1;+ while (p < n) p *= 2;+ return p;+}++function composePage(images: Map<string, AtlasInputImage>, placements: AtlasPlacement[], width: number, height: number): AtlasPage {+ const rgba = new Uint8Array(width * height * 4);+ for (const p of placements) {+ const img = images.get(p.key)!;+ for (let row = 0; row < p.height; row++) {+ const src = row * img.width * 4;+ const dst = ((p.y + row) * width + p.x) * 4;+ rgba.set(img.rgba.subarray(src, src + p.width * 4), dst);+ }+ }+ return { width, height, placements, rgba };+}++/**+ * Pack images into as few pages as possible. Pages are square powers of two:+ * the smallest that fits everything remaining, capped at maxSize; when even a+ * maxSize page cannot hold all remaining images it takes as many as fit (in+ * order) and the rest spill onto the next page. Input order does not matter —+ * images are sorted (height desc, then key) for deterministic, well-packed+ * output.+ */+export function packAtlas(images: AtlasInputImage[], options: PackOptions = {}): AtlasPage[] {+ const maxSize = options.maxSize ?? 2048;+ const padding = options.padding ?? 2;+ const byKey = new Map(images.map((i) => [i.key, i]));+ if (byKey.size !== images.length) throw new Error('packAtlas: duplicate image keys');++ let remaining = [...images].sort((a, b) => (b.height - a.height) || a.key.localeCompare(b.key));+ for (const img of remaining) {+ const needed = Math.max(img.width, img.height) + padding * 2;+ if (needed > maxSize) {+ throw new Error(`packAtlas: '${img.key}' (${img.width}x${img.height}) exceeds the ${maxSize} page cap`);+ }+ }++ const pages: AtlasPage[] = [];+ while (remaining.length > 0) {+ // Grow a square page until everything remaining fits (or we hit the cap).+ let size = nextPow2(Math.max(+ remaining[0].height + padding * 2,+ Math.max(...remaining.map((i) => i.width)) + padding * 2,+ ));+ let placements: AtlasPlacement[] | null = null;+ while (size <= maxSize) {+ placements = tryPackPage(remaining, size, size, padding);+ if (placements) break;+ size *= 2;+ }+ if (placements) {+ pages.push(composePage(byKey, placements, size, size));+ remaining = [];+ break;+ }+ // Even maxSize can't hold everything: fill one maxSize page greedily+ // (prefix of the sorted order that fits), spill the rest.+ const taken: AtlasInputImage[] = [];+ const spill: AtlasInputImage[] = [];+ for (const img of remaining) {+ const attempt = tryPackPage([...taken, img], maxSize, maxSize, padding);+ if (attempt) taken.push(img);+ else spill.push(img);+ }+ pages.push(composePage(byKey, tryPackPage(taken, maxSize, maxSize, padding)!, maxSize, maxSize));+ remaining = spill;+ }+ return pages;+}++/** Decode a PNG into the packer's input shape. */+export function decodePngImage(key: string, png: Uint8Array): AtlasInputImage {+ const decoded = PNG.sync.read(Buffer.from(png));+ return { key, width: decoded.width, height: decoded.height, rgba: new Uint8Array(decoded.data) };+}++/** Encode a composed page back to PNG bytes. */+export function encodePagePng(page: AtlasPage): Uint8Array {+ const png = new PNG({ width: page.width, height: page.height });+ Buffer.from(page.rgba).copy(png.data);+ return new Uint8Array(PNG.sync.write(png));+}diff --git a/desktop/electron/cookAssets.ts b/desktop/electron/cookAssets.tsindex 3aa5dad20..2c105f49f 100644--- a/desktop/electron/cookAssets.ts+++ b/desktop/electron/cookAssets.ts@@ -20,6 +20,7 @@import { writeFile, mkdir, readFile } from 'node:fs/promises';import path from 'node:path';import { scanAssetDatabase, type AssetEntry } from './assetDb';+import { packAtlas, decodePngImage, encodePagePng, type AtlasInputImage } from './atlasPacker';// Single-source content hash (sdk/src/asset/contentHash.ts). Imported as source —// no hand-mirrored copy — so the cook and the runtime agree by construction.import { contentHashHex } from '../../sdk/src/asset/contentHash';@@ -56,6 +57,30 @@ export interface CookManifestEntry extends AssetEntry {* layout read it.*/group: string;+ /**+ * Present when this texture was packed into an atlas page: `path` then points+ * at the PAGE file (URL-level redirect for free) and this records where the+ * original image sits inside it. Frame pixels are in image space (y from the+ * page top); the runtime catalog derives uvOffset/uvScale from frame + page+ * size. Produced by the `<name>.atlas/` folder convention.+ */+ atlas?: {+ page: number;+ frame: { x: number; y: number; width: number; height: number };+ pageWidth: number;+ pageHeight: number;+ };+}++/**+ * Folder-convention atlas detection: a PNG under a `<name>.atlas/` directory is+ * packed into that directory's atlas. Returns the directory path (the atlas's+ * identity — same-named dirs elsewhere are distinct atlases) or null.+ */+const ATLAS_DIR_RE = /^(.*?(?:^|\/)[^/]+\.atlas)\//;+export function atlasDirOf(projectRelPath: string): string | null {+ const m = ATLAS_DIR_RE.exec(projectRelPath.replace(/\\/g, '/'));+ return m ? m[1] : null;}/**@@ -133,10 +158,14 @@ export interface CookResult {*/export async function cookAssets(root: string,- opts: { entryScenes: string[]; outDir: string; contentAddressed?: boolean; compressTextures?: boolean },+ opts: {+ entryScenes: string[]; outDir: string;+ contentAddressed?: boolean; compressTextures?: boolean; atlasTextures?: boolean;+ },): Promise<CookResult> {const contentAddressed = opts.contentAddressed ?? false;const compressTextures = opts.compressTextures ?? false;+ const atlasTextures = opts.atlasTextures ?? false;const { index } = await scanAssetDatabase(root, { write: false });const byUuid = new Map(index.entries.map((e) => [e.uuid, e]));const byPath = new Map(index.entries.map((e) => [e.path, e]));@@ -190,9 +219,101 @@ export async function cookAssets(const manifestEntries: CookManifestEntry[] = [];const staged = new Set<string>(); // staged output paths, for content-addressed dedup++ // ---- Auto-atlas (`<name>.atlas/` folder convention) -----------------------+ // Pack the reachable PNGs of each atlas directory into pages BEFORE the+ // per-asset staging loop; each packed frame's manifest entry then points its+ // `path` at the page file (frame → page redirect happens at the URL level,+ // through the same buildPath machinery as every other rename). Pages are+ // plain textures to the rest of the cook: KTX2 compression and content-+ // addressed naming apply to them exactly as they would to a lone PNG.+ const atlasPlan = new Map<string, NonNullable<CookManifestEntry['atlas']> & {+ pageOutRel: string; pageHash: string; pageSize: number; compressedFormats?: string[];+ }>();+ if (atlasTextures) {+ const groups = new Map<string, AssetEntry[]>();+ for (const uuid of reachable) {+ const entry = byUuid.get(uuid);+ if (!entry || entry.type === 'scene') continue;+ if (path.extname(entry.path).toLowerCase() !== '.png') continue;+ const dir = atlasDirOf(entry.path);+ if (!dir) continue;+ let list = groups.get(dir);+ if (!list) groups.set(dir, (list = []));+ list.push(entry);+ }+ for (const [dir, entries] of [...groups.entries()].sort((a, b) => a[0].localeCompare(b[0]))) {+ const images: AtlasInputImage[] = [];+ for (const entry of [...entries].sort((a, b) => a.path.localeCompare(b.path))) {+ try {+ images.push(decodePngImage(entry.path, await readFile(path.join(root, entry.path))));+ } catch (err) {+ warnings.push(`${entry.path}: atlas decode failed, staging standalone — ${err instanceof Error ? err.message : String(err)}`);+ }+ }+ if (images.length === 0) continue;+ const pages = packAtlas(images);+ for (let n = 0; n < pages.length; n++) {+ let pageBytes: Uint8Array = encodePagePng(pages[n]);+ let pageExt = '.png';+ let compressedFormats: string[] | undefined;+ if (encodePng) {+ pageBytes = await encodePng(pageBytes);+ pageExt = '.ktx2';+ compressedFormats = COMPRESSED_TARGETS;+ }+ const pageHash = contentHashHex(pageBytes);+ const group = subpackageOf(`${dir}/`) ?? 'main';+ const caBase = group === 'main' ? 'assets' : `subpackages/${group}/assets`;+ const pageOutRel = contentAddressed+ ? `${caBase}/${pageHash}${pageExt}`+ : `${dir}.page${n}${pageExt}`;+ const dst = path.join(absOut, pageOutRel);+ if (!staged.has(pageOutRel)) {+ await mkdir(path.dirname(dst), { recursive: true });+ await writeFile(dst, pageBytes);+ staged.add(pageOutRel);+ }+ for (const placement of pages[n].placements) {+ atlasPlan.set(placement.key, {+ page: n,+ frame: { x: placement.x, y: placement.y, width: placement.width, height: placement.height },+ pageWidth: pages[n].width,+ pageHeight: pages[n].height,+ pageOutRel, pageHash, pageSize: pageBytes.byteLength, compressedFormats,+ });+ }+ }+ }+ }+for (const uuid of reachable) {const entry = byUuid.get(uuid);if (!entry) continue;+ // Atlas-packed frame: the page is already staged; this entry just records+ // where the frame lives (page path + rect). Its physical identity IS the+ // page's (hash/size of the bytes actually served for this ref).+ const framePlan = atlasPlan.get(entry.path);+ if (framePlan) {+ manifestEntries.push({+ uuid: entry.uuid,+ path: framePlan.pageOutRel,+ sourcePath: entry.path,+ type: entry.type,+ importer: entry.importer,+ contentHash: framePlan.pageHash,+ size: framePlan.pageSize,+ group: subpackageOf(entry.path) ?? 'main',+ ...(framePlan.compressedFormats ? { compressedFormats: framePlan.compressedFormats } : {}),+ atlas: {+ page: framePlan.page,+ frame: framePlan.frame,+ pageWidth: framePlan.pageWidth,+ pageHeight: framePlan.pageHeight,+ },+ });+ continue;+ }try {let data: Uint8Array = await readFile(path.join(root, entry.path));let ext = path.extname(entry.path);diff --git a/desktop/electron/exportGame.ts b/desktop/electron/exportGame.tsindex a51776db5..9e6645cb8 100644--- a/desktop/electron/exportGame.ts+++ b/desktop/electron/exportGame.ts@@ -210,6 +210,8 @@ export async function exportGame(opts: {/** Encode raster textures to GPU-compressed KTX2 at cook time. Default off* (lossy + encode-time cost — opt in per project). */compressTextures?: boolean;+ /** Pack `<name>.atlas/` folder PNGs into atlas pages at cook time. Default off. */+ atlasTextures?: boolean;title?: string;platform?: ExportPlatform;/** Playable host source (src/playableHost.ts). */@@ -246,6 +248,7 @@ export async function exportGame(opts: {minify: opts.minify,contentAddressed: opts.contentAddressed,compressTextures: opts.compressTextures,+ atlasTextures: opts.atlasTextures,onProgress: opts.onProgress,});}@@ -286,7 +289,7 @@ export async function exportGame(opts: {// 1. Cook reachable assets + manifest (the entry scene file is staged too).progress({ phase: 'Cooking assets' });- const cook = await cookAssets(opts.root, { entryScenes: [opts.entryScene], outDir: payloadDir, contentAddressed: opts.contentAddressed ?? true, compressTextures: opts.compressTextures });+ const cook = await cookAssets(opts.root, { entryScenes: [opts.entryScene], outDir: payloadDir, contentAddressed: opts.contentAddressed ?? true, compressTextures: opts.compressTextures, atlasTextures: opts.atlasTextures });warnings.push(...cook.warnings);progress({ phase: 'Cooking assets', detail: `${cook.included.length} reachable` });diff --git a/desktop/electron/exportPlayable.ts b/desktop/electron/exportPlayable.tsindex 55ee4fb75..be4817641 100644--- a/desktop/electron/exportPlayable.ts+++ b/desktop/electron/exportPlayable.ts@@ -164,6 +164,11 @@ export async function exportPlayable(opts: {try {const manifest = JSON.parse(await readFile(path.join(cookDir, 'assets.manifest.json'), 'utf8')) as CookManifest;manifestEntries = manifest.entries;+ // Playable has no runtime catalog channel yet, so atlas frame/uv metadata+ // cannot reach the sprites — a packed texture would render its whole page.+ if (manifest.entries.some((e) => (e as { atlas?: unknown }).atlas)) {+ warnings.push('cook produced atlas-packed textures, which the playable runtime cannot consume yet — export without atlasTextures for playables.');+ }for (const e of manifest.entries) {const buf = await readFile(path.join(cookDir, e.path));const key = `@uuid:${e.uuid}`;diff --git a/desktop/electron/exportWeChat.ts b/desktop/electron/exportWeChat.tsindex 11b8845ca..de879eac1 100644--- a/desktop/electron/exportWeChat.ts+++ b/desktop/electron/exportWeChat.ts@@ -43,7 +43,11 @@ export interface ExportWeChatResult {}interface CookManifest {- entries: { uuid: string; path: string; sourcePath?: string; type: string; contentHash?: string; size?: number; group?: string }[];+ entries: {+ uuid: string; path: string; sourcePath?: string; type: string;+ contentHash?: string; size?: number; group?: string;+ atlas?: { page: number; frame: { x: number; y: number; width: number; height: number }; pageWidth: number; pageHeight: number };+ }[];}// Editor asset type → AddressableAssetType (sdk/src/assetTypes.ts). The WeChat@@ -155,7 +159,10 @@ async function scanWeChatSideModules(* falls back to stat() for size only if a legacy cook omitted it. */async function buildAddressableManifest(absOut: string): Promise<string> {const cook = JSON.parse(await readFile(path.join(absOut, 'assets.manifest.json'), 'utf8')) as CookManifest;- type Entry = { path: string; address?: string; type: string; size: number; labels: string[]; contentHash?: string };+ type Entry = {+ path: string; address?: string; type: string; size: number; labels: string[]; contentHash?: string;+ metadata?: { atlasPage?: number; atlasFrame?: { x: number; y: number; width: number; height: number }; atlasPageWidth?: number; atlasPageHeight?: number };+ };type Group = { bundleMode: string; labels: string[]; assets: Record<string, Entry> };// One group per cook group: 'main' is local (eager); every other is a lazy// subpackage. bundleMode here is the typed wire value the SDK's normalizeBundleMode@@ -175,6 +182,16 @@ async function buildAddressableManifest(absOut: string): Promise<string> {// its logical→staged catalog from them). Only meaningful when staging// renamed the file (content addressing / texture encoding).if (e.sourcePath && e.sourcePath !== e.path) entry.address = e.sourcePath;+ // Atlas frame → manifest metadata; the runtime derives uv from it and+ // registers the frame under its uuid/address catalog keys.+ if (e.atlas) {+ entry.metadata = {+ atlasPage: e.atlas.page,+ atlasFrame: e.atlas.frame,+ atlasPageWidth: e.atlas.pageWidth,+ atlasPageHeight: e.atlas.pageHeight,+ };+ }group.assets[e.uuid.toLowerCase()] = entry;}// Always emit a main group so the runtime's main package exists even if every@@ -205,6 +222,8 @@ export async function exportWeChat(opts: {contentAddressed?: boolean;/** Encode raster textures to GPU-compressed KTX2 at cook time. */compressTextures?: boolean;+ /** Pack `<name>.atlas/` folder PNGs into atlas pages at cook time. */+ atlasTextures?: boolean;onProgress?: OnExportProgress;}): Promise<ExportWeChatResult> {const title = opts.title ?? 'Game';@@ -216,7 +235,7 @@ export async function exportWeChat(opts: {// 1. Cook reachable assets (paths preserved) + the flat manifest.progress({ phase: 'Cooking assets' });- const cook = await cookAssets(opts.root, { entryScenes: [opts.entryScene], outDir: absOut, contentAddressed: opts.contentAddressed, compressTextures: opts.compressTextures });+ const cook = await cookAssets(opts.root, { entryScenes: [opts.entryScene], outDir: absOut, contentAddressed: opts.contentAddressed, compressTextures: opts.compressTextures, atlasTextures: opts.atlasTextures });warnings.push(...cook.warnings);// 1b. Scan the scene for the optional modules it needs (physics/spine), so thediff --git a/desktop/package.json b/desktop/package.jsonindex 444a6511a..41fdfdc4c 100644--- a/desktop/package.json+++ b/desktop/package.json@@ -64,6 +64,7 @@"esbuild": "^0.27.0","esengine": "workspace:*","lucide-react": "^1.21.0",+ "pngjs": "^7.0.0","react": "^19.2.0","react-dom": "^19.2.0","zustand": "^5.0.14"@@ -72,6 +73,7 @@"@fontsource/inter": "^5.2.8","@fontsource/jetbrains-mono": "^5.2.8","@types/node": "^25.9.3",+ "@types/pngjs": "^6.0.5","@types/react": "^19.2.0","@types/react-dom": "^19.2.0","@vitejs/plugin-react": "^6.0.2",diff --git a/desktop/src/gameHost.ts b/desktop/src/gameHost.tsindex 4588b40fc..d1488fb64 100644--- a/desktop/src/gameHost.ts+++ b/desktop/src/gameHost.ts@@ -11,14 +11,14 @@* Builtin scenes run as-is; project custom-script bundles are a follow-up* (shared with the play realm's import-map work).*/-import { createWebApp, setEditorMode, setPlayMode, initPlayRealmRuntime } from 'esengine';-import type { CatalogData, ESEngineModule, SceneData } from 'esengine';+import { createWebApp, setEditorMode, setPlayMode, initPlayRealmRuntime, atlasCatalogFields } from 'esengine';+import type { CatalogData, CookedAtlasInfo, ESEngineModule, SceneData } from 'esengine';interface GameConfig {entryScene: string;}interface CookedManifest {- entries: { uuid: string; path: string; sourcePath?: string; type: string }[];+ entries: { uuid: string; path: string; sourcePath?: string; type: string; atlas?: CookedAtlasInfo }[];}async function boot(): Promise<void> {@@ -58,12 +58,20 @@ async function boot(): Promise<void> {for (const e of manifest.entries) {assetManifest[e.uuid.toLowerCase()] = `./${e.path}`;const logical = e.sourcePath ?? e.path;+ // Atlas-packed frame: its `path` already points at the PAGE file (URL-level+ // redirect); the catalog additionally carries frame/uv so the scene loader+ // can aim each sprite's uvOffset/uvScale at its rect — keyed by every ref+ // spelling a scene can use, `@uuid:` included.+ const atlasFields = e.atlas ? atlasCatalogFields(e.atlas, `./${e.path}`) : null;+ if (atlasFields) {+ catalog.entries[`@uuid:${e.uuid.toLowerCase()}`] = { type: e.type, buildPath: `./${e.path}`, ...atlasFields };+ }pathMap[logical] = `./${e.path}`;- catalog.entries[logical] = { type: e.type, buildPath: `./${e.path}` };+ catalog.entries[logical] = { type: e.type, buildPath: `./${e.path}`, ...(atlasFields ?? {}) };// The cook writes project-absolute refs as "/<logical>" when the logical// path lacks a passthrough prefix — register that spelling too.pathMap[`/${logical}`] = `./${e.path}`;- catalog.entries[`/${logical}`] = { type: e.type, buildPath: `./${e.path}` };+ catalog.entries[`/${logical}`] = { type: e.type, buildPath: `./${e.path}`, ...(atlasFields ?? {}) };}const wasmBase = new URL('./wasm/', import.meta.url).href; // relative → mount-path agnosticdiff --git a/desktop/tests/atlas-packer.test.ts b/desktop/tests/atlas-packer.test.tsnew file mode 100644index 000000000..6066b51f1--- /dev/null+++ b/desktop/tests/atlas-packer.test.ts@@ -0,0 +1,98 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Atlas packer — deterministic shelf packing + page composition.+ */+import { describe, it, expect } from 'vitest';+import { packAtlas, decodePngImage, encodePagePng, type AtlasInputImage } from '../electron/atlasPacker';++function solid(key: string, width: number, height: number, rgba: [number, number, number, number]): AtlasInputImage {+ const data = new Uint8Array(width * height * 4);+ for (let i = 0; i < width * height; i++) data.set(rgba, i * 4);+ return { key, width, height, rgba: data };+}++describe('packAtlas', () => {+ it('packs everything onto the smallest power-of-two page that fits', () => {+ const pages = packAtlas([+ solid('a', 16, 16, [255, 0, 0, 255]),+ solid('b', 16, 16, [0, 255, 0, 255]),+ solid('c', 16, 16, [0, 0, 255, 255]),+ ]);+ expect(pages).toHaveLength(1);+ expect(pages[0].width).toBe(64); // three 20px padded boxes need one 60px shelf+ expect(pages[0].height).toBe(64);+ expect(pages[0].placements).toHaveLength(3);+ });++ it('is deterministic regardless of input order', () => {+ const images = [+ solid('tall', 8, 32, [1, 2, 3, 255]),+ solid('wide', 32, 8, [4, 5, 6, 255]),+ solid('mid', 16, 16, [7, 8, 9, 255]),+ ];+ const a = packAtlas(images);+ const b = packAtlas([...images].reverse());+ expect(b).toEqual(a);+ });++ it('keeps placements padded and non-overlapping', () => {+ const pages = packAtlas([+ solid('a', 30, 10, [1, 0, 0, 255]),+ solid('b', 10, 30, [0, 1, 0, 255]),+ solid('c', 20, 20, [0, 0, 1, 255]),+ ], { padding: 2 });+ for (const page of pages) {+ for (const p of page.placements) {+ expect(p.x).toBeGreaterThanOrEqual(2);+ expect(p.y).toBeGreaterThanOrEqual(2);+ expect(p.x + p.width).toBeLessThanOrEqual(page.width - 2);+ expect(p.y + p.height).toBeLessThanOrEqual(page.height - 2);+ }+ for (const p of page.placements) {+ for (const q of page.placements) {+ if (p === q) continue;+ const overlap = p.x < q.x + q.width && q.x < p.x + p.width+ && p.y < q.y + q.height && q.y < p.y + p.height;+ expect(overlap).toBe(false);+ }+ }+ }+ });++ it('spills onto extra pages when the cap cannot hold everything', () => {+ const images = Array.from({ length: 5 }, (_, i) => solid(`i${i}`, 40, 40, [i, i, i, 255]));+ const pages = packAtlas(images, { maxSize: 64 });+ expect(pages.length).toBe(5); // one padded 44px box per 64px page+ expect(pages.flatMap((p) => p.placements)).toHaveLength(5);+ });++ it('rejects an image larger than the page cap', () => {+ expect(() => packAtlas([solid('huge', 3000, 8, [0, 0, 0, 255])])).toThrow(/exceeds/);+ });++ it('composes page pixels at the placements', () => {+ const pages = packAtlas([+ solid('red', 2, 2, [255, 0, 0, 255]),+ solid('blue', 2, 2, [0, 0, 255, 255]),+ ], { padding: 1 });+ expect(pages).toHaveLength(1);+ const page = pages[0];+ for (const p of page.placements) {+ const px = (p.y * page.width + p.x) * 4;+ const want = p.key === 'red' ? [255, 0, 0, 255] : [0, 0, 255, 255];+ expect([...page.rgba.subarray(px, px + 4)]).toEqual(want);+ }+ // Padding gutters stay transparent.+ expect(page.rgba[3]).toBe(0);+ });++ it('round-trips through PNG encode/decode', () => {+ const pages = packAtlas([solid('x', 3, 5, [10, 20, 30, 255])]);+ const png = encodePagePng(pages[0]);+ const back = decodePngImage('page', png);+ expect(back.width).toBe(pages[0].width);+ expect(back.height).toBe(pages[0].height);+ expect([...back.rgba]).toEqual([...pages[0].rgba]);+ });+});diff --git a/desktop/tests/cook-assets.test.ts b/desktop/tests/cook-assets.test.tsindex e0dbcf2b0..4964a131f 100644--- a/desktop/tests/cook-assets.test.ts+++ b/desktop/tests/cook-assets.test.ts@@ -303,3 +303,115 @@ describe('cookAssets (A4)', () => {}});});++describe('cookAssets — auto-atlas (<name>.atlas folder convention)', () => {+ const TEX_A = 'cccc1111-1111-4111-8111-111111111111';+ const TEX_B = 'cccc2222-2222-4222-8222-222222222222';+ const LOOSE = 'cccc3333-3333-4333-8333-333333333333';+ const SCENE = 'cccc4444-4444-4444-8444-444444444444';++ function solidPng(width: number, height: number, rgba: [number, number, number, number]): Buffer {+ // eslint-disable-next-line @typescript-eslint/no-require-imports+ const { PNG } = require('pngjs') as typeof import('pngjs');+ const png = new PNG({ width, height });+ for (let i = 0; i < width * height; i++) png.data.set(rgba, i * 4);+ return PNG.sync.write(png);+ }++ function makeAtlasProject(): string {+ const r = mkdtempSync(path.join(tmpdir(), 'estella-cook-atlas-'));+ const wa = (rel: string, type: string, uuid: string, body: string | Buffer): void => {+ const abs = path.join(r, rel);+ mkdirSync(path.dirname(abs), { recursive: true });+ writeFileSync(abs, body);+ writeFileSync(`${abs}.meta`, JSON.stringify({ uuid, version: '2.0', type, importer: {} }));+ };+ wa('assets/sprites/heroes.atlas/a.png', 'texture', TEX_A, solidPng(4, 4, [255, 0, 0, 255]));+ wa('assets/sprites/heroes.atlas/b.png', 'texture', TEX_B, solidPng(4, 4, [0, 255, 0, 255]));+ wa('assets/textures/loose.png', 'texture', LOOSE, solidPng(2, 2, [0, 0, 255, 255]));+ wa('assets/scenes/main.esscene', 'scene', SCENE, JSON.stringify({+ version: '1.0', name: 's', entities: [+ { id: 1, name: 'A', parent: null, children: [], components: [{ type: 'Sprite', data: { texture: `@uuid:${TEX_A}` } }] },+ { id: 2, name: 'B', parent: null, children: [], components: [{ type: 'Sprite', data: { texture: `@uuid:${TEX_B}` } }] },+ { id: 3, name: 'L', parent: null, children: [], components: [{ type: 'Sprite', data: { texture: `@uuid:${LOOSE}` } }] },+ ],+ }));+ return r;+ }++ it('packs atlas-folder PNGs into one staged page with frame metadata', async () => {+ const r = makeAtlasProject();+ try {+ const res = await cookAssets(r, { entryScenes: ['assets/scenes/main.esscene'], outDir: 'out', atlasTextures: true });+ expect(res.ok).toBe(true);+ const manifest = JSON.parse(readFileSync(res.manifestPath!, 'utf8')) as {+ entries: Array<{ uuid: string; path: string; sourcePath: string;+ atlas?: { page: number; frame: { x: number; y: number; width: number; height: number }; pageWidth: number; pageHeight: number } }>;+ };+ const a = manifest.entries.find((e) => e.uuid === TEX_A)!;+ const b = manifest.entries.find((e) => e.uuid === TEX_B)!;+ const loose = manifest.entries.find((e) => e.uuid === LOOSE)!;++ // Both frames point at the SAME page file; the loose texture stages standalone.+ expect(a.path).toBe('assets/sprites/heroes.atlas.page0.png');+ expect(b.path).toBe(a.path);+ expect(a.sourcePath).toBe('assets/sprites/heroes.atlas/a.png');+ expect(loose.path).toBe('assets/textures/loose.png');+ expect(loose.atlas).toBeUndefined();+ expect(existsSync(path.join(res.outDir, a.path))).toBe(true);+ // Frame sources are not staged as standalone files.+ expect(existsSync(path.join(res.outDir, 'assets/sprites/heroes.atlas/a.png'))).toBe(false);++ // Distinct frames inside a shared page whose size both entries agree on.+ expect(a.atlas!.pageWidth).toBe(b.atlas!.pageWidth);+ expect(a.atlas!.frame).not.toEqual(b.atlas!.frame);++ // Decode the staged page: each frame's pixels are its source's color.+ // eslint-disable-next-line @typescript-eslint/no-require-imports+ const { PNG } = require('pngjs') as typeof import('pngjs');+ const page = PNG.sync.read(readFileSync(path.join(res.outDir, a.path)));+ expect(page.width).toBe(a.atlas!.pageWidth);+ const at = (f: { x: number; y: number }) => [...page.data.subarray((f.y * page.width + f.x) * 4, (f.y * page.width + f.x) * 4 + 4)];+ expect(at(a.atlas!.frame)).toEqual([255, 0, 0, 255]);+ expect(at(b.atlas!.frame)).toEqual([0, 255, 0, 255]);+ } finally {+ rmSync(r, { recursive: true, force: true });+ }+ });++ it('stages atlas-folder textures standalone when atlasTextures is off', async () => {+ const r = makeAtlasProject();+ try {+ const res = await cookAssets(r, { entryScenes: ['assets/scenes/main.esscene'], outDir: 'out' });+ const manifest = JSON.parse(readFileSync(res.manifestPath!, 'utf8')) as {+ entries: Array<{ uuid: string; path: string; atlas?: unknown }>;+ };+ const a = manifest.entries.find((e) => e.uuid === TEX_A)!;+ expect(a.path).toBe('assets/sprites/heroes.atlas/a.png');+ expect(a.atlas).toBeUndefined();+ } finally {+ rmSync(r, { recursive: true, force: true });+ }+ });++ it('content-addressed staging names the page by its hash, shared by both frames', async () => {+ const r = makeAtlasProject();+ try {+ const res = await cookAssets(r, {+ entryScenes: ['assets/scenes/main.esscene'], outDir: 'out',+ atlasTextures: true, contentAddressed: true,+ });+ const manifest = JSON.parse(readFileSync(res.manifestPath!, 'utf8')) as {+ entries: Array<{ uuid: string; path: string; contentHash: string; sourcePath: string; atlas?: unknown }>;+ };+ const a = manifest.entries.find((e) => e.uuid === TEX_A)!;+ const b = manifest.entries.find((e) => e.uuid === TEX_B)!;+ expect(a.path).toBe(`assets/${a.contentHash}.png`);+ expect(b.path).toBe(a.path);+ expect(a.sourcePath).toBe('assets/sprites/heroes.atlas/a.png');+ expect(existsSync(path.join(res.outDir, a.path))).toBe(true);+ } finally {+ rmSync(r, { recursive: true, force: true });+ }+ });+});diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex e667c13a7..200695469 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -38,6 +38,9 @@ importers:lucide-react:specifier: ^1.21.0version: 1.21.0([email protected])+ pngjs:+ specifier: ^7.0.0+ version: 7.0.0react:specifier: ^19.2.0version: 19.2.7@@ -57,6 +60,9 @@ importers:'@types/node':specifier: ^25.9.3version: 25.9.3+ '@types/pngjs':+ specifier: ^6.0.5+ version: 6.0.5'@types/react':specifier: ^19.2.0version: 19.2.17@@ -917,6 +923,9 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-603BddQMv3pUcr4U2dhujk83N2tTDVr/34wII2B6bJy6g+8WD6yUb11jszNs0gdi4PesVWl7ABt8nYMVpnLUcg==}+ '@types/[email protected]':+ resolution: {integrity: sha512-0k5eKfrA83JOZPppLtS2C7OUtyNAl2wKNxfyYl9Q5g9lPkgBl/9hNyAu6HuEH2J4XmIv2znEpkDd0SaZVxW6iQ==}+'@types/[email protected]':resolution: {integrity: sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==}peerDependencies:@@ -2231,6 +2240,10 @@ packages:resolution: {integrity: sha512-uysumyrvkUX0rX/dEVqt8gC3sTBzd4zoWfLeS29nb53imdaXVvLINYXTI2GNqzaMuvacNx4uJQ8+b3zXR0pkgQ==}engines: {node: '>=10.4.0'}+ resolution: {integrity: sha512-LKWqWJRhstyYo9pGvgor/ivk2w94eSjE3RGVuzLGlr3NmD8bf7RcYGze1mNdEHRP6TRP6rMuDHk5t44hnTRyow==}+ engines: {node: '>=14.19.0'}+resolution: {integrity: sha512-FfR8sjd4em2T6fb3I2MwAJU7HWVMr9zba+enmQeeWFfCbm+UOC/0X4DS8XtpUTMwWMGbjKYP7xjfNekzyGmB3A==}engines: {node: ^10 || ^12 || >=14}@@ -3592,6 +3605,10 @@ snapshots:dependencies:undici-types: 7.24.6+ '@types/[email protected]':+ dependencies:+ '@types/node': 25.9.3+'@types/[email protected](@types/[email protected])':dependencies:'@types/react': 19.2.17@@ -5031,6 +5048,8 @@ snapshots:base64-js: 1.5.1xmlbuilder: 15.1.1+ [email protected]: {}+dependencies:nanoid: 3.3.13diff --git a/sdk/src/asset/AddressableManifest.ts b/sdk/src/asset/AddressableManifest.tsindex 27a483647..e49db8ad9 100644--- a/sdk/src/asset/AddressableManifest.ts+++ b/sdk/src/asset/AddressableManifest.ts@@ -24,6 +24,9 @@ export interface AddressableManifestAsset {atlas?: string;atlasPage?: number;atlasFrame?: { x: number; y: number; width: number; height: number };+ /** Page pixel size — with atlasFrame, what the runtime derives uv from. */+ atlasPageWidth?: number;+ atlasPageHeight?: number;};}diff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.tsindex bb8dd6fa0..fe5075540 100644--- a/sdk/src/asset/Assets.ts+++ b/sdk/src/asset/Assets.ts@@ -340,8 +340,12 @@ export class Assets {// =========================================================================getAtlasFrame(ref: string): AtlasFrameInfo | null {- const path = this.resolveLoadPath_(ref);- return this.catalog.getAtlasFrame(path);+ // Raw ref first: atlas frames register under every ref SPELLING+ // (`@uuid:…`, logical, "/"-rooted). The resolved path is the fallback —+ // for packed frames it is the shared PAGE path, which cannot key+ // per-frame data.+ return this.catalog.getAtlasFrame(ref)+ ?? this.catalog.getAtlasFrame(this.resolveLoadPath_(ref));}// =========================================================================@@ -773,10 +777,24 @@ export class Assets {const handle = textureHandles.get(path) ?? 0;comp.data[field] = handle;if (counter && handle) counter.addTextureRef(path, entity.id);- const atlasInfo = this.catalog.getAtlasFrame(path);+ // Ref spelling first (per-frame keys); the resolved+ // path for packed frames is the shared page.+ const atlasInfo = this.catalog.getAtlasFrame(ref) ?? this.catalog.getAtlasFrame(path);if (atlasInfo) {- comp.data['uvOffset'] = { x: atlasInfo.uvOffset[0], y: atlasInfo.uvOffset[1] };- comp.data['uvScale'] = { x: atlasInfo.uvScale[0], y: atlasInfo.uvScale[1] };+ // COMPOSE with any authored sub-region rather than+ // stomping it: the authored uv nests inside the frame.+ const aOff = comp.data['uvOffset'] as { x: number; y: number } | undefined;+ const aSc = comp.data['uvScale'] as { x: number; y: number } | undefined;+ const ox = aOff?.x ?? 0, oy = aOff?.y ?? 0;+ const sx = aSc?.x ?? 1, sy = aSc?.y ?? 1;+ comp.data['uvOffset'] = {+ x: atlasInfo.uvOffset[0] + ox * atlasInfo.uvScale[0],+ y: atlasInfo.uvOffset[1] + oy * atlasInfo.uvScale[1],+ };+ comp.data['uvScale'] = {+ x: sx * atlasInfo.uvScale[0],+ y: sy * atlasInfo.uvScale[1],+ };if (atlasInfo.trim) {comp.data['_trimOffsetX'] = atlasInfo.trim.offsetX;comp.data['_trimOffsetY'] = atlasInfo.trim.offsetY;diff --git a/sdk/src/asset/Catalog.ts b/sdk/src/asset/Catalog.tsindex 11729d7ce..359fdfd3c 100644--- a/sdk/src/asset/Catalog.ts+++ b/sdk/src/asset/Catalog.ts@@ -25,6 +25,37 @@ export interface CatalogData {labels?: Record<string, string[]>;}+/** The atlas record a cook/export manifest carries for a packed texture. */+export interface CookedAtlasInfo {+ page?: number;+ frame: { x: number; y: number; width: number; height: number };+ pageWidth: number;+ pageHeight: number;+}++/**+ * Derive a CatalogEntry's atlas fields from a cook-manifest atlas record.+ * Frame pixels are image-space (y from the page TOP); uv is emitted for+ * flipY-uploaded textures (v origin = image bottom), matching the+ * Sprite/UIVisual `uvOffset`/`uvScale` convention. `pagePath` is the page's+ * fetch identity — the same string every frame of the page shares, so texture+ * loading can collapse them onto one GPU texture.+ */+export function atlasCatalogFields(+ atlas: CookedAtlasInfo,+ pagePath: string,+): Pick<CatalogEntry, 'atlas' | 'frame' | 'uv'> {+ const { frame, pageWidth, pageHeight } = atlas;+ return {+ atlas: pagePath,+ frame: { x: frame.x, y: frame.y, w: frame.width, h: frame.height },+ uv: {+ offset: [frame.x / pageWidth, 1 - (frame.y + frame.height) / pageHeight],+ scale: [frame.width / pageWidth, frame.height / pageHeight],+ },+ };+}+export class Catalog {private entries_: Map<string, CatalogEntry>;private addresses_: Map<string, string>;diff --git a/sdk/src/asset/index.ts b/sdk/src/asset/index.tsindex 5077acbcd..51c1d2443 100644--- a/sdk/src/asset/index.ts+++ b/sdk/src/asset/index.ts@@ -18,7 +18,7 @@ export { AssetRefCounter, type AssetRefInfo } from './AssetRefCounter';export { Assets as AssetsImpl, type AssetsOptions, type AssetBundle, type SceneAssetResult, type MissingAsset } from './Assets';export { type Backend, HttpBackend, EmbeddedBackend, type HttpBackendOptions } from './Backend';-export { Catalog, type CatalogData, type CatalogEntry, type AtlasFrameInfo } from './Catalog';+export { Catalog, atlasCatalogFields, type CatalogData, type CatalogEntry, type AtlasFrameInfo, type CookedAtlasInfo } from './Catalog';export {AssetRegistry,UUID_REF_PREFIX,diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex c86b30e5e..6ae62ab9b 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -50,6 +50,8 @@ export {assetPlugin,AssetRefCounter,Catalog,+ atlasCatalogFields,+ type CookedAtlasInfo,type CatalogData,type CatalogEntry,decodeImageBitmap,diff --git a/sdk/src/wechatRuntime.ts b/sdk/src/wechatRuntime.tsindex cd5749efd..e3ca038be 100644--- a/sdk/src/wechatRuntime.ts+++ b/sdk/src/wechatRuntime.ts@@ -16,7 +16,7 @@ import { applyBuildRuntimeConfig, type RuntimeBuildConfig } from './defaults';import { platformReadTextFile, platformInstantiateWasm, platformLoadImagePixels } from './platform';import { toBuildPath } from './assetTypes';import { ManifestModel, type AddressableManifest } from './asset/AddressableManifest';-import { Catalog, type CatalogEntry } from './asset/Catalog';+import { Catalog, atlasCatalogFields, type CatalogEntry } from './asset/Catalog';import { createWeChatSideModuleHost, type WeChatSideModuleFactories } from './sideModules';import type { Vec2 } from './types';import type { SceneData } from './scene';@@ -85,11 +85,25 @@ export async function initWeChatRuntime(config: WeChatRuntimeConfig): Promise<vo// (the logical source path) get a catalog buildPath, so the loaders' inner// text refs (a material's shader) map logical → staged at their fetch// boundary — the same two-map contract the cooked web host wires.+ // Atlas-packed frames additionally register their frame/uv fields, keyed by+ // every ref spelling a scene can use (`@uuid:`, logical, "/"-rooted).const catalogEntries: Record<string, CatalogEntry> = {};- for (const asset of manifestModel.allAssets()) {- if (!asset.address || asset.address === asset.path) continue;- catalogEntries[asset.address] = { type: asset.type, buildPath: asset.path };- catalogEntries[`/${asset.address}`] = { type: asset.type, buildPath: asset.path };+ for (const group of Object.values(manifest.groups)) {+ for (const [uuid, asset] of Object.entries(group.assets)) {+ const md = asset.metadata;+ const atlasFields = md?.atlasFrame && md.atlasPageWidth && md.atlasPageHeight+ ? atlasCatalogFields(+ { page: md.atlasPage, frame: md.atlasFrame, pageWidth: md.atlasPageWidth, pageHeight: md.atlasPageHeight },+ asset.path,+ )+ : null;+ if (atlasFields) {+ catalogEntries[`@uuid:${uuid}`] = { type: asset.type, buildPath: asset.path, ...atlasFields };+ }+ if (!asset.address || asset.address === asset.path) continue;+ catalogEntries[asset.address] = { type: asset.type, buildPath: asset.path, ...(atlasFields ?? {}) };+ catalogEntries[`/${asset.address}`] = { type: asset.type, buildPath: asset.path, ...(atlasFields ?? {}) };+ }}const catalog = Object.keys(catalogEntries).length > 0? Catalog.fromJson({ version: 1, entries: catalogEntries })diff --git a/sdk/tests/atlas-catalog.test.ts b/sdk/tests/atlas-catalog.test.tsnew file mode 100644index 000000000..880cbf358--- /dev/null+++ b/sdk/tests/atlas-catalog.test.ts@@ -0,0 +1,40 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Catalog atlas fields — the cook-manifest → CatalogEntry derivation the+ * cooked hosts (web gameHost / wechatRuntime) share.+ */+import { describe, it, expect } from 'vitest';+import { Catalog, atlasCatalogFields } from '../src/asset/Catalog';++describe('atlasCatalogFields', () => {+ it('derives flipY-space uv from an image-space frame (AnimClipLoader convention)', () => {+ const fields = atlasCatalogFields(+ { frame: { x: 8, y: 4, width: 16, height: 8 }, pageWidth: 64, pageHeight: 32 },+ './assets/page0.png',+ );+ expect(fields.atlas).toBe('./assets/page0.png');+ expect(fields.frame).toEqual({ x: 8, y: 4, w: 16, h: 8 });+ // u = x/pageW; v = 1 - (y+h)/pageH — identical to the sprite-sheet math+ // AnimClipLoader has always used for per-frame uvOffset.+ expect(fields.uv).toEqual({+ offset: [8 / 64, 1 - (4 + 8) / 32],+ scale: [16 / 64, 8 / 32],+ });+ });++ it('produces entries Catalog.getAtlasFrame serves back', () => {+ const fields = atlasCatalogFields(+ { frame: { x: 0, y: 0, width: 4, height: 4 }, pageWidth: 8, pageHeight: 8 },+ 'page.ktx2',+ );+ const catalog = Catalog.fromJson({+ version: 1,+ entries: { '@uuid:abc': { type: 'texture', buildPath: 'page.ktx2', ...fields } },+ });+ const frame = catalog.getAtlasFrame('@uuid:abc')!;+ expect(frame.atlas).toBe('page.ktx2');+ expect(frame.uvOffset).toEqual([0, 0.5]);+ expect(frame.uvScale).toEqual([0.5, 0.5]);+ });+});