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(import): what a PSD becomes, and the layer stack that survives it

yhh61148d060952
diff --git a/desktop b/desktop
index 2c9c04854..171eda26b 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit 2c9c04854c1a6cc65a4b5d044b7b1f4e1c3d092b
+Subproject commit 171eda26ba7067d7eba2e95359612dbe7c103954
diff --git a/pipeline/package.json b/pipeline/package.json
index 7bdcba8ea..5b8af36ab 100644
--- a/pipeline/package.json
+++ b/pipeline/package.json
@@ -14,6 +14,7 @@
"test": "vitest run"
},
"dependencies": {
+ "ag-psd": "^31.0.2",
"draco3dgltf": "^1.5.7",
"esbuild": "^0.27.0",
"esengine": "workspace:*",
diff --git a/pipeline/src/assets/psdImport.ts b/pipeline/src/assets/psdImport.ts
new file mode 100644
index 000000000..b886072cb
--- /dev/null
+++ b/pipeline/src/assets/psdImport.ts
@@ -0,0 +1,211 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file What a `.psd` becomes: one PNG per layer and the prefab that puts them
+ * back where the artist had them.
+ *
+ * PSD is a closed format with thirty years of features behind it, so the
+ * parsing is ag-psd's and what happens here is only the translation — the
+ * same division the FBX import draws. The products are ordinary project
+ * files: nothing downstream learns what a PSD is.
+ */
+import { PNG } from 'pngjs';
+import { readPsd, initializeCanvas, type Layer, type Psd } from 'ag-psd';
+import {
+ PREFAB_FORMAT_VERSION,
+ type PrefabData, type PrefabEntityData, type PrefabComponentData,
+} from 'esengine';
+
+/**
+ * ag-psd reaches for a canvas to hand back layer pixels; `useImageData` makes that
+ * a plain `{data,width,height}`, so an allocator is all it needs — no canvas
+ * library, in a pipeline with no DOM. `createCanvas` stays a thrower rather than a
+ * stub, so a path that truly wants one is loud instead of quietly empty.
+ */
+initializeCanvas(
+ () => { throw new Error('the PSD import decodes to image data and has no canvas'); },
+ (width: number, height: number) => ({
+ data: new Uint8ClampedArray(Math.max(0, width) * Math.max(0, height) * 4),
+ width, height,
+ }) as unknown as ImageData,
+);
+
+/** One layer's pixels, named for the file they will be written to. */
+export interface PsdLayerImage {
+ /** `<stem>_<layer>` plus `.png`, unique within the import. */
+ file: string;
+ bytes: Uint8Array;
+}
+
+export interface PsdImportResult {
+ /** Every layer image to write, bottom of the stack first. */
+ images: PsdLayerImage[];
+ /** The assembly — where each image sits and in what order it draws. */
+ prefab: PrefabData;
+ /** What the document says that the products cannot carry. Never dropped. */
+ warnings: string[];
+}
+
+/** How a layer name becomes a file name: one spelling, so two passes agree. */
+function fileStem(name: string): string {
+ const cleaned = name.trim().replace(/[^\w.-]+/g, '-').replace(/^-+|-+$/g, '');
+ return cleaned === '' ? 'layer' : cleaned;
+}
+
+/** A leaf layer with pixels, or a group, in the order the file stores them. */
+interface Flat {
+ layer: Layer;
+ /** Group depth's parent entity id, or null at the document root. */
+ parent: string | null;
+ id: string;
+ /** Position in the global bottom-to-top stack; only leaves take one. */
+ depth: number;
+}
+
+/**
+ * The stack, flattened bottom-to-top — which is the order the FILE stores layers
+ * in, and therefore the order `children` arrives in. Groups are kept as entities
+ * so the prefab has the artist's own structure, but they take no stack position:
+ * PSD stacking is global, and a group only draws what is inside it.
+ */
+function flatten(psd: Psd): { nodes: Flat[]; leaves: number } {
+ const nodes: Flat[] = [];
+ let depth = 0;
+ let n = 0;
+ const visit = (layers: readonly Layer[] | undefined, parent: string | null): void => {
+ for (const layer of layers ?? []) {
+ const id = `l${n++}`;
+ const group = layer.children !== undefined;
+ nodes.push({ layer, parent, id, depth: group ? -1 : depth++ });
+ if (group) visit(layer.children, id);
+ }
+ };
+ visit(psd.children, null);
+ return { nodes, leaves: depth };
+}
+
+/** Width and height of a layer's own rectangle; zero for one with no pixels. */
+function rect(layer: Layer): { x: number; y: number; w: number; h: number } {
+ const x = layer.left ?? 0;
+ const y = layer.top ?? 0;
+ return { x, y, w: (layer.right ?? x) - x, h: (layer.bottom ?? y) - y };
+}
+
+function entity(id: string, name: string, parent: string | null,
+ components: PrefabComponentData[], visible: boolean): PrefabEntityData {
+ return { prefabEntityId: id, name, parent, children: [], visible, components };
+}
+
+/**
+ * Read `bytes` and produce what a project can hold.
+ *
+ * `stem` names the products and the prefab. `refPrefix` is what a texture ref has
+ * to be prefixed with to resolve from the project root — the images are written
+ * beside the prefab, so it is the destination folder.
+ */
+export function importPsd(bytes: Uint8Array, stem: string, refPrefix = ''): PsdImportResult {
+ const psd = readPsd(bytes, {
+ useImageData: true,
+ // The flattened composite and the thumbnail are pictures of the result;
+ // what this import wants is the parts. Skipping them is most of the read.
+ skipCompositeImageData: true,
+ skipThumbnail: true,
+ });
+
+ const warnings: string[] = [];
+ const images: PsdLayerImage[] = [];
+ const entities: PrefabEntityData[] = [];
+ const used = new Set<string>();
+
+ const root = entity('root', stem, null,
+ [{ type: 'Transform', data: { position: { x: 0, y: 0, z: 0 } } }], true);
+ entities.push(root);
+
+ const { nodes, leaves } = flatten(psd);
+ // Sprite.order is a signed byte, so a stack taller than that cannot be
+ // expressed and the top layers would all pin to the same value — said out
+ // loud, because the picture would be subtly wrong rather than obviously so.
+ if (leaves > 128) {
+ warnings.push(`${leaves} layers: only the lowest 128 keep a distinct draw order `
+ + '(Sprite.order is -128..127) — merge layers in Photoshop, or split the document');
+ }
+
+ const byId = new Map<string, PrefabEntityData>([['root', root]]);
+ const parentOf = (node: Flat): PrefabEntityData =>
+ (node.parent === null ? root : byId.get(node.parent) ?? root);
+
+ for (const node of nodes) {
+ const { layer, id } = node;
+ const name = layer.name ?? id;
+ const holder = parentOf(node);
+ // A group's own rectangle is its contents' union and moves when they do,
+ // so it carries no offset of its own — its children are already placed in
+ // document space. An identity Transform keeps that true.
+ if (layer.children !== undefined) {
+ holder.children.push(id);
+ const group = entity(id, name, node.parent,
+ [{ type: 'Transform', data: { position: { x: 0, y: 0, z: 0 } } }],
+ layer.hidden !== true);
+ entities.push(group);
+ byId.set(id, group);
+ continue;
+ }
+
+ const { x, y, w, h } = rect(layer);
+ const data = layer.imageData;
+ if (w <= 0 || h <= 0 || !data) {
+ // An adjustment or effect layer has no pixels of its own. It is not a
+ // failure and not a sprite; naming it is how the artist learns which
+ // part of the document did not come across.
+ warnings.push(`"${name}" has no pixels of its own (an adjustment, effect or empty layer) — not imported`);
+ continue;
+ }
+ if (layer.blendMode !== undefined && layer.blendMode !== 'normal') {
+ warnings.push(`"${name}" uses the "${layer.blendMode}" blend mode, which a Sprite cannot carry `
+ + '— assign it a material with that blend mode');
+ }
+
+ let file = `${stem}_${fileStem(name)}`;
+ for (let n = 2; used.has(file.toLowerCase()); n++) file = `${stem}_${fileStem(name)}-${n}`;
+ used.add(file.toLowerCase());
+
+ const png = new PNG({ width: data.width, height: data.height });
+ Buffer.from(data.data.buffer, data.data.byteOffset, data.data.byteLength).copy(png.data);
+ images.push({ file: `${file}.png`, bytes: new Uint8Array(PNG.sync.write(png)) });
+
+ // PSD measures from the top-left with Y down; the engine's Y is up and a
+ // sprite is placed by its centre. So the document's centre becomes the
+ // prefab's origin and the layer's own centre is offset from it.
+ holder.children.push(id);
+ entities.push(entity(id, name, node.parent, [
+ { type: 'Transform', data: { position: {
+ x: x + w / 2 - psd.width / 2,
+ y: psd.height / 2 - (y + h / 2),
+ z: 0,
+ } } },
+ { type: 'Sprite', data: {
+ texture: `${refPrefix}${file}.png`,
+ size: { x: w, y: h },
+ // Opacity is the layer's, and a Sprite spends it in the tint's alpha.
+ color: { r: 1, g: 1, b: 1, a: layer.opacity ?? 1 },
+ // The one field that makes a stack a stack. Bottom-to-top is the
+ // order the file stores layers in, so the index IS the answer.
+ order: Math.min(127, node.depth),
+ } },
+ ], layer.hidden !== true));
+ }
+
+ return {
+ images,
+ prefab: { version: PREFAB_FORMAT_VERSION, name: stem, rootEntityId: 'root', entities },
+ warnings,
+ };
+}
+
+/** The extensions this import claims. */
+export const PSD_EXTENSIONS = ['.psd', '.psb'];
+
+export function isPsdSource(file: string): boolean {
+ const dot = file.lastIndexOf('.');
+ return dot >= 0 && PSD_EXTENSIONS.includes(file.slice(dot).toLowerCase());
+}
diff --git a/pipeline/tests/psd-import.test.ts b/pipeline/tests/psd-import.test.ts
new file mode 100644
index 000000000..91cdaa4a7
--- /dev/null
+++ b/pipeline/tests/psd-import.test.ts
@@ -0,0 +1,187 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file What a `.psd` becomes — the claims a screenshot cannot make.
+ *
+ * The fixture is WRITTEN with ag-psd rather than checked in as a binary, so what
+ * each layer contains is stated here in the same file that asserts it: a blob
+ * would make every expectation below a number nobody could check.
+ *
+ * Two things carry the whole import and neither is visible in a picture of the
+ * result: that the stack order survives as `Sprite.order`, and that PSD's
+ * top-left, Y-down document becomes the engine's centred, Y-up placement.
+ */
+import { describe, it, expect } from 'vitest';
+import { writePsd, type Psd } from 'ag-psd';
+import { PNG } from 'pngjs';
+import { importPsd, isPsdSource } from '../src/assets/psdImport';
+import type { PrefabEntityData } from 'esengine';
+
+const rgba = (w: number, h: number, [r, g, b, a]: number[]): ImageData => {
+ const data = new Uint8ClampedArray(w * h * 4);
+ for (let i = 0; i < w * h; i++) {
+ data[i * 4] = r!; data[i * 4 + 1] = g!; data[i * 4 + 2] = b!; data[i * 4 + 3] = a!;
+ }
+ return { data, width: w, height: h } as ImageData;
+};
+
+/** A 64x48 document: a full-bleed background, a half-opaque square, a group with
+ * one layer in it, and one layer the artist turned off. */
+function fixture(): Uint8Array {
+ const psd: Psd = {
+ width: 64, height: 48,
+ children: [
+ { name: 'bg', left: 0, top: 0, right: 64, bottom: 48, imageData: rgba(64, 48, [255, 0, 0, 255]) },
+ { name: 'head', left: 10, top: 4, right: 26, bottom: 20, imageData: rgba(16, 16, [0, 0, 255, 255]), opacity: 0.5 },
+ { name: 'props', opened: true, children: [
+ { name: 'inner', left: 40, top: 30, right: 48, bottom: 38, imageData: rgba(8, 8, [0, 255, 0, 255]) },
+ ] },
+ { name: 'scratch', left: 0, top: 0, right: 8, bottom: 8, imageData: rgba(8, 8, [1, 2, 3, 255]), hidden: true },
+ ],
+ };
+ return new Uint8Array(writePsd(psd, { generateThumbnail: false }));
+}
+
+const byName = (entities: PrefabEntityData[], name: string): PrefabEntityData => {
+ const found = entities.find((e) => e.name === name);
+ if (!found) throw new Error(`no entity named ${name} in ${entities.map((e) => e.name).join(', ')}`);
+ return found;
+};
+
+const sprite = (e: PrefabEntityData): Record<string, unknown> =>
+ e.components.find((c) => c.type === 'Sprite')!.data as Record<string, unknown>;
+const position = (e: PrefabEntityData): { x: number; y: number } =>
+ (e.components.find((c) => c.type === 'Transform')!.data as { position: { x: number; y: number } }).position;
+
+describe('isPsdSource', () => {
+ it('claims .psd and .psb, whatever the case, and nothing else', () => {
+ expect(isPsdSource('a/b/Art.PSD')).toBe(true);
+ expect(isPsdSource('big.psb')).toBe(true);
+ expect(isPsdSource('art.png')).toBe(false);
+ expect(isPsdSource('psd')).toBe(false);
+ });
+});
+
+describe('importPsd', () => {
+ it('writes one image per layer with pixels, and none for a group', () => {
+ const { images } = importPsd(fixture(), 'hero');
+ expect(images.map((i) => i.file))
+ .toEqual(['hero_bg.png', 'hero_head.png', 'hero_inner.png', 'hero_scratch.png']);
+ });
+
+ it('writes real PNGs at the layer’s own size, not the document’s', () => {
+ const { images } = importPsd(fixture(), 'hero');
+ const head = PNG.sync.read(Buffer.from(images.find((i) => i.file === 'hero_head.png')!.bytes));
+ expect([head.width, head.height]).toEqual([16, 16]);
+ // The layer's own colour, so the pixels came from the layer and not the composite.
+ expect([...head.data.subarray(0, 4)]).toEqual([0, 0, 255, 255]);
+ });
+
+ // The claim the whole import rests on. PSD stacking is the file's order, and
+ // Sprite.order is the only field that expresses it inside one sorting layer —
+ // without this the layers arrive coincident and the stack is submission order.
+ it('turns the layer stack into Sprite.order, bottom-up from zero', () => {
+ const { prefab } = importPsd(fixture(), 'hero');
+ expect(sprite(byName(prefab.entities, 'bg')).order).toBe(0);
+ expect(sprite(byName(prefab.entities, 'head')).order).toBe(1);
+ expect(sprite(byName(prefab.entities, 'inner')).order).toBe(2);
+ expect(sprite(byName(prefab.entities, 'scratch')).order).toBe(3);
+ });
+
+ // PSD measures from the top-left with Y down and the engine's Y is up, so a
+ // sign error here reads as "the art is upside down" and nothing else says why.
+ it('recentres the document and flips Y', () => {
+ const { prefab } = importPsd(fixture(), 'hero');
+ // Full-bleed background: its centre IS the document centre.
+ expect(position(byName(prefab.entities, 'bg'))).toEqual({ x: 0, y: 0, z: 0 });
+ // head spans x 10..26, y 4..20 in a 64x48 document: centre (18, 12) →
+ // (18 - 32, 24 - 12).
+ expect(position(byName(prefab.entities, 'head'))).toMatchObject({ x: -14, y: 12 });
+ // inner is low and to the right, so its y must come out NEGATIVE.
+ expect(position(byName(prefab.entities, 'inner'))).toMatchObject({ x: 12, y: -10 });
+ });
+
+ it('sizes each sprite to its own layer rectangle', () => {
+ const { prefab } = importPsd(fixture(), 'hero');
+ expect(sprite(byName(prefab.entities, 'head')).size).toEqual({ x: 16, y: 16 });
+ expect(sprite(byName(prefab.entities, 'bg')).size).toEqual({ x: 64, y: 48 });
+ });
+
+ it('spends layer opacity in the tint’s alpha', () => {
+ const { prefab } = importPsd(fixture(), 'hero');
+ const { a } = sprite(byName(prefab.entities, 'head')).color as { a: number };
+ expect(a).toBeCloseTo(0.5, 2);
+ expect((sprite(byName(prefab.entities, 'bg')).color as { a: number }).a).toBe(1);
+ });
+
+ // Turned off, not thrown away: the artist's document arrives whole, and the
+ // entity is one click from being back.
+ it('keeps a hidden layer as an invisible entity rather than dropping it', () => {
+ const { prefab } = importPsd(fixture(), 'hero');
+ expect(byName(prefab.entities, 'scratch').visible).toBe(false);
+ expect(byName(prefab.entities, 'bg').visible).toBe(true);
+ });
+
+ it('keeps a group as a parent entity, with its layer inside it', () => {
+ const { prefab } = importPsd(fixture(), 'hero');
+ const group = byName(prefab.entities, 'props');
+ expect(group.components.map((c) => c.type)).toEqual(['Transform']);
+ expect(byName(prefab.entities, 'inner').parent).toBe(group.prefabEntityId);
+ expect(group.children).toEqual([byName(prefab.entities, 'inner').prefabEntityId]);
+ });
+
+ it('names textures so they resolve from the folder the products landed in', () => {
+ const { prefab } = importPsd(fixture(), 'hero', 'assets/art/');
+ expect(sprite(byName(prefab.entities, 'bg')).texture).toBe('assets/art/hero_bg.png');
+ });
+
+ it('roots the prefab on one entity everything hangs from', () => {
+ const { prefab } = importPsd(fixture(), 'hero');
+ expect(prefab.rootEntityId).toBe('root');
+ const root = prefab.entities.find((e) => e.prefabEntityId === 'root')!;
+ expect(root.parent).toBeNull();
+ // Every top-level layer, including the group, hangs off it.
+ expect(root.children).toHaveLength(4);
+ });
+
+ // Two layers may share a name in Photoshop; two files may not.
+ it('gives same-named layers distinct file names', () => {
+ const psd: Psd = {
+ width: 8, height: 8,
+ children: [
+ { name: 'same', left: 0, top: 0, right: 4, bottom: 4, imageData: rgba(4, 4, [1, 1, 1, 255]) },
+ { name: 'same', left: 4, top: 4, right: 8, bottom: 8, imageData: rgba(4, 4, [2, 2, 2, 255]) },
+ ],
+ };
+ const { images } = importPsd(new Uint8Array(writePsd(psd, { generateThumbnail: false })), 'dup');
+ expect(images.map((i) => i.file)).toEqual(['dup_same.png', 'dup_same-2.png']);
+ });
+
+ it('makes a layer name that is no filename into one', () => {
+ const psd: Psd = {
+ width: 8, height: 8,
+ children: [{ name: ' 头/部 ', left: 0, top: 0, right: 4, bottom: 4, imageData: rgba(4, 4, [1, 1, 1, 255]) }],
+ };
+ const { images, prefab } = importPsd(new Uint8Array(writePsd(psd, { generateThumbnail: false })), 'x');
+ expect(images[0]!.file).toMatch(/^x_[\w.-]+\.png$/);
+ // The ENTITY keeps the artist's own name; only the file is sanitised.
+ expect(prefab.entities.some((e) => e.name === ' 头/部 ')).toBe(true);
+ });
+
+ // Every one of these is a thing the products genuinely cannot carry. Saying so
+ // is the difference between an import that lost something and one that lied.
+ it('reports what a Sprite cannot carry instead of dropping it silently', () => {
+ const psd: Psd = {
+ width: 8, height: 8,
+ children: [
+ { name: 'lit', left: 0, top: 0, right: 4, bottom: 4, imageData: rgba(4, 4, [1, 1, 1, 255]), blendMode: 'screen' },
+ { name: 'empty', left: 0, top: 0, right: 0, bottom: 0 },
+ ],
+ };
+ const { warnings, images } = importPsd(new Uint8Array(writePsd(psd, { generateThumbnail: false })), 'x');
+ expect(warnings.some((w) => w.includes('"lit"') && w.includes('screen'))).toBe(true);
+ expect(warnings.some((w) => w.includes('"empty"') && w.includes('no pixels'))).toBe(true);
+ // The blend mode is only a warning: the layer itself still comes across.
+ expect(images.map((i) => i.file)).toEqual(['x_lit.png']);
+ });
+});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 408f651a8..121cf17c5 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -153,6 +153,9 @@ importers:
pipeline:
dependencies:
+ ag-psd:
+ specifier: ^31.0.2
+ version: 31.0.2
draco3dgltf:
specifier: ^1.5.7
version: 1.5.7
@@ -1466,6 +1469,9 @@ packages:
engines: {node: '>=0.4.0'}
hasBin: true
+ resolution: {integrity: sha512-5s5PvqbomPIIJ9YjL6robz55rT4RYPiQkww4brisyZEb5jzlHB1EKh47IJg7gIFj0RUrD0cMgdntM907qaZjXA==}
+
resolution: {integrity: sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==}
engines: {node: '>= 6.0.0'}
@@ -2918,6 +2924,9 @@ packages:
resolution: {integrity: sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==}
+ resolution: {integrity: sha512-w+eufiZ1WuJYgPXbV/PO3NCMEc3xqylkKHzp8bxp1uW4qaSNQUkwmLLEc3kKsfz8lpV1F8Ht3U1Cm+9Srog2ug==}
+
resolution: {integrity: sha512-60zvsJReQPX5/QP0Kzfd/VrpjScIQ7SHBW6bFCYfEP+fp0Eppr1SHhIO5nd1PjZtvclzSzES9D/p5nFJurwfWg==}
@@ -4862,6 +4871,11 @@ snapshots:
+ dependencies:
+ base64-js: 1.5.1
+ pako: 2.1.0
+
dependencies:
debug: 4.4.3
@@ -6435,6 +6449,8 @@ snapshots:
+
diff --git a/tools/assetMetaTable.js b/tools/assetMetaTable.js
index 6dc95da13..59b700d77 100644
--- a/tools/assetMetaTable.js
+++ b/tools/assetMetaTable.js
@@ -70,6 +70,10 @@ export const EXT_TO_TYPE = Object.freeze({
// The same shape for lighting: a `.hdr` panorama is import-only and produces
// the `.esenv` + atlas a scene references.
'.hdr': 'panorama',
+ // And for 2D art: a layered document produces one image per layer plus the
+ // prefab that stacks them, and those are what a scene references.
+ '.psd': 'layered',
+ '.psb': 'layered',
'.esenv': 'environment',
'.esmesh': 'mesh',
'.esanim': 'animclip',