Line data Source code
1 : import type { Layer, LayerMaskData, LinkedFile, Psd } from 'ag-psd'
2 :
3 : import type { Compositor } from '#/compositor'
4 : import type { ContentEntry, ContentStore } from '#/content'
5 : import type { Document } from '#/document'
6 : import type { Editor } from '#/editor/editor'
7 : import type { RasterData, SceneNode, Transform } from '#/node'
8 : import type { CompactRect as Rect } from '@comfyorg/shared-frontend-utils/geometry'
9 : import { getNodeKind } from '#/nodeKind'
10 : import type { RenderNodeCtx } from '#/nodeKind'
11 : import { placeBitmap } from '#/render/place'
12 : import { PSD_BLEND_MODES, fillToVectorContent } from './psdMapping'
13 :
14 : export interface PsdGuides {
15 : horizontal: number[]
16 : vertical: number[]
17 : }
18 :
19 : export interface PlacedLeaf {
20 : canvas: HTMLCanvasElement
21 : left: number
22 : top: number
23 : }
24 :
25 : export interface PsdExportDeps {
26 : rasterizeLeaf: (node: SceneNode) => PlacedLeaf | null
27 : maskCanvas: (node: SceneNode) => PlacedLeaf | null
28 : composite: () => HTMLCanvasElement
29 : contentCanvas?: (id: string) => HTMLCanvasElement | null
30 : canvasPng?: (canvas: HTMLCanvasElement) => Promise<Uint8Array>
31 : guides?: PsdGuides
32 : }
33 :
34 2 : const clamp01 = (v: number) => Math.max(0, Math.min(1, v))
35 :
36 0 : export function makeGuid(): string {
37 0 : if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function')
38 0 : return crypto.randomUUID()
39 0 : let out = ''
40 0 : for (let i = 0; i < 36; i++) {
41 0 : if (i === 8 || i === 13 || i === 18 || i === 23) out += '-'
42 0 : else out += Math.floor(Math.random() * 16).toString(16)
43 : }
44 0 : return out
45 : }
46 :
47 0 : export function transformCorners(t: Transform): number[] {
48 0 : const cx = t.x + t.w / 2
49 0 : const cy = t.y + t.h / 2
50 0 : const cos = Math.cos(t.rotation)
51 0 : const sin = Math.sin(t.rotation)
52 0 : const pt = (dx: number, dy: number) => [
53 : cx + dx * cos - dy * sin,
54 : cy + dx * sin + dy * cos
55 : ]
56 0 : const hw = t.w / 2
57 0 : const hh = t.h / 2
58 0 : return [...pt(-hw, -hh), ...pt(hw, -hh), ...pt(hw, hh), ...pt(-hw, hh)]
59 : }
60 :
61 0 : function maskData(
62 : node: SceneNode,
63 : deps: PsdExportDeps
64 : ): LayerMaskData | undefined {
65 0 : if (!node.mask) return undefined
66 0 : const placed = deps.maskCanvas(node)
67 0 : if (!placed) return undefined
68 0 : return {
69 : canvas: placed.canvas,
70 : left: placed.left,
71 : top: placed.top,
72 : right: placed.left + placed.canvas.width,
73 : bottom: placed.top + placed.canvas.height,
74 : defaultColor: 0,
75 : disabled: !node.mask.enabled
76 : }
77 : }
78 :
79 0 : async function applyPlacedLayer(
80 : layer: Layer,
81 : node: RasterData,
82 : deps: PsdExportDeps,
83 : linkedFiles: LinkedFile[]
84 : ): Promise<void> {
85 0 : if (!deps.contentCanvas || !deps.canvasPng) return
86 0 : const source = deps.contentCanvas(node.contentId)
87 0 : if (!source) return
88 0 : let data: Uint8Array
89 0 : try {
90 0 : data = await deps.canvasPng(source)
91 : } catch {
92 0 : return
93 : }
94 0 : const id = makeGuid()
95 0 : const corners = transformCorners(node.transform)
96 0 : linkedFiles.push({
97 : id,
98 : name: `${node.name || 'layer'}.png`,
99 : type: 'png ',
100 : data
101 : })
102 0 : layer.placedLayer = {
103 : id,
104 : placed: makeGuid(),
105 : type: 'raster',
106 : transform: corners,
107 : nonAffineTransform: corners,
108 : width: source.width,
109 : height: source.height
110 : }
111 : }
112 :
113 0 : async function buildLayer(
114 : node: SceneNode,
115 : deps: PsdExportDeps,
116 : linkedFiles: LinkedFile[]
117 : ): Promise<Layer> {
118 0 : const layer: Layer = {
119 : name: node.name,
120 : hidden: !node.visible,
121 : opacity: clamp01(node.opacity),
122 : blendMode: PSD_BLEND_MODES[node.mode.blend] ?? 'normal',
123 : mask: maskData(node, deps)
124 : }
125 0 : if (node.kind === 'group') {
126 0 : const g = node
127 0 : if (g.passThrough) layer.blendMode = 'pass through'
128 0 : layer.opened = true
129 0 : layer.children = []
130 0 : for (const child of g.children) {
131 0 : layer.children.push(await buildLayer(child, deps, linkedFiles))
132 : }
133 0 : return layer
134 : }
135 0 : const placed = deps.rasterizeLeaf(node)
136 0 : if (placed) {
137 0 : layer.canvas = placed.canvas
138 0 : layer.left = placed.left
139 0 : layer.top = placed.top
140 0 : layer.right = placed.left + placed.canvas.width
141 0 : layer.bottom = placed.top + placed.canvas.height
142 : }
143 0 : switch (node.kind) {
144 : case 'fill':
145 0 : layer.vectorFill = fillToVectorContent(node.fill)
146 0 : break
147 : case 'raster':
148 0 : await applyPlacedLayer(layer, node, deps, linkedFiles)
149 : }
150 0 : return layer
151 : }
152 :
153 : export interface PsdRenderHost {
154 : document(): Document
155 : render(): void
156 : readbackCanvas(): HTMLCanvasElement
157 : }
158 :
159 : export interface PsdContentSource {
160 : get(id: string): ContentEntry | undefined
161 : }
162 :
163 0 : export function leafPlacedBounds(t: Transform, doc: Document): Rect {
164 0 : if (!(t.w > 0 && t.h > 0)) return { x: 0, y: 0, w: doc.width, h: doc.height }
165 0 : const corners = transformCorners(t)
166 0 : const xs = [corners[0], corners[2], corners[4], corners[6]]
167 0 : const ys = [corners[1], corners[3], corners[5], corners[7]]
168 0 : const x = Math.floor(Math.min(...xs))
169 0 : const y = Math.floor(Math.min(...ys))
170 0 : return {
171 : x,
172 : y,
173 : w: Math.max(1, Math.ceil(Math.max(...xs)) - x),
174 : h: Math.max(1, Math.ceil(Math.max(...ys)) - y)
175 : }
176 : }
177 :
178 0 : export function rasterizeLeafPlaced(
179 : node: SceneNode,
180 : doc: Document,
181 : content: PsdContentSource
182 : ): PlacedLeaf | null {
183 0 : const bounds = leafPlacedBounds(node.transform, doc)
184 0 : const captured: HTMLCanvasElement[] = []
185 0 : const ctx: RenderNodeCtx = {
186 : compositor: null as unknown as Compositor,
187 : content: content as ContentStore,
188 : renderChild: () => null,
189 : placed: (_key, _stamp, bitmap, tf, linear) => {
190 0 : const canvas = placeBitmap(
191 : bitmap,
192 : { ...tf, x: tf.x - bounds.x, y: tf.y - bounds.y },
193 : bounds.w,
194 : bounds.h
195 : )
196 0 : if (canvas) captured.push(canvas)
197 0 : return canvas ? { source: canvas, rect: bounds, linear: !!linear } : null
198 : },
199 : region: { x: 0, y: 0, w: bounds.w, h: bounds.h },
200 : devicePixelRatio: 1
201 : }
202 0 : try {
203 0 : getNodeKind(node.kind).renderNode(node, ctx)
204 : } catch {
205 0 : return null
206 : }
207 0 : const canvas = captured.at(-1)
208 0 : return canvas ? { canvas, left: bounds.x, top: bounds.y } : null
209 : }
210 :
211 0 : export function maskToPlacedCanvas(
212 : node: SceneNode,
213 : doc: Document,
214 : content: PsdContentSource
215 : ): PlacedLeaf | null {
216 0 : const m = node.mask
217 0 : if (!m) return null
218 0 : const entry = content.get(m.contentId)
219 0 : if (!entry) return null
220 0 : const bounds = leafPlacedBounds(node.transform, doc)
221 0 : const c = document.createElement('canvas')
222 0 : c.width = bounds.w
223 0 : c.height = bounds.h
224 0 : const ctx = c.getContext('2d')
225 0 : if (!ctx) return null
226 0 : ctx.fillStyle = '#000000'
227 0 : ctx.fillRect(0, 0, bounds.w, bounds.h)
228 0 : const tf =
229 : node.transform.w > 0 && node.transform.h > 0
230 : ? node.transform
231 : : { x: 0, y: 0, w: doc.width, h: doc.height, rotation: 0 }
232 0 : ctx.translate(tf.x - bounds.x + tf.w / 2, tf.y - bounds.y + tf.h / 2)
233 0 : ctx.rotate(tf.rotation)
234 0 : ctx.drawImage(entry.canvas, -tf.w / 2, -tf.h / 2, tf.w, tf.h)
235 0 : return { canvas: c, left: bounds.x, top: bounds.y }
236 : }
237 :
238 0 : async function canvasPngBytes(canvas: HTMLCanvasElement): Promise<Uint8Array> {
239 0 : const blob = await new Promise<Blob>((res, rej) =>
240 : canvas.toBlob(
241 : (b) => (b ? res(b) : rej(new Error('toBlob null'))),
242 : 'image/png'
243 : )
244 : )
245 0 : return new Uint8Array(await blob.arrayBuffer())
246 : }
247 :
248 0 : export async function buildPsdFromEditor(
249 : host: PsdRenderHost,
250 : content: PsdContentSource,
251 : opts?: {
252 : guides?: PsdGuides
253 : }
254 : ): Promise<Psd> {
255 0 : const doc = host.document()
256 0 : host.render()
257 0 : return buildPsd(doc, {
258 : rasterizeLeaf: (n) => rasterizeLeafPlaced(n, doc, content),
259 : maskCanvas: (n) => maskToPlacedCanvas(n, doc, content),
260 : composite: () => host.readbackCanvas(),
261 : contentCanvas: (id) => content.get(id)?.canvas ?? null,
262 : canvasPng: canvasPngBytes,
263 : guides: opts?.guides
264 : })
265 : }
266 :
267 0 : export async function buildPsd(
268 : doc: Document,
269 : deps: PsdExportDeps
270 : ): Promise<Psd> {
271 0 : const linkedFiles: LinkedFile[] = []
272 0 : const children: Layer[] = []
273 0 : for (const node of doc.root.children) {
274 0 : children.push(await buildLayer(node, deps, linkedFiles))
275 : }
276 0 : const psd: Psd = {
277 : width: doc.width,
278 : height: doc.height,
279 : canvas: deps.composite(),
280 : children
281 : }
282 0 : if (linkedFiles.length) psd.linkedFiles = linkedFiles
283 0 : if (
284 : deps.guides &&
285 : (deps.guides.horizontal.length || deps.guides.vertical.length)
286 : ) {
287 0 : psd.imageResources = {
288 : gridAndGuidesInformation: {
289 : guides: [
290 : ...deps.guides.horizontal.map((location) => ({
291 : location,
292 : direction: 'horizontal' as const
293 : })),
294 : ...deps.guides.vertical.map((location) => ({
295 : location,
296 : direction: 'vertical' as const
297 : }))
298 : ]
299 : }
300 : }
301 : }
302 0 : return psd
303 : }
304 :
305 0 : function readbackCanvas(compositor: Compositor): HTMLCanvasElement {
306 0 : const img = compositor.readback()
307 0 : const canvas = document.createElement('canvas')
308 0 : canvas.width = img.width
309 0 : canvas.height = img.height
310 0 : const ctx = canvas.getContext('2d')
311 0 : if (!ctx) throw new Error('2d context unavailable')
312 0 : ctx.putImageData(img, 0, 0)
313 0 : return canvas
314 : }
315 :
316 0 : export async function buildSessionPsdBlob(session: {
317 : editor: Editor
318 : content: PsdContentSource
319 : compositor: Compositor
320 : }): Promise<Blob> {
321 0 : const { editor, content, compositor } = session
322 0 : if (editor.floating()) editor.anchorFloating()
323 0 : const guides = editor.guides()
324 0 : const psd = await buildPsdFromEditor(
325 : {
326 : document: () => editor.document(),
327 : render: () => editor.render(),
328 : readbackCanvas: () => readbackCanvas(compositor)
329 : },
330 : content,
331 : {
332 : guides: {
333 : horizontal: guides.filter((g) => g.axis === 'y').map((g) => g.pos),
334 : vertical: guides.filter((g) => g.axis === 'x').map((g) => g.pos)
335 : }
336 : }
337 : )
338 0 : const { writePsd } = await import('ag-psd')
339 0 : return new Blob([writePsd(psd)], { type: 'image/vnd.adobe.photoshop' })
340 : }
|