Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Layers: Re-render from layers paints the arrangement again as one picture, layers and text in place

Claude6242169e0763
diff --git a/src/components/layers/apply.ts b/src/components/layers/apply.ts
index c2cf56cd..ec9ae612 100644
--- a/src/components/layers/apply.ts
+++ b/src/components/layers/apply.ts
@@ -158,6 +158,12 @@ export function applyMeasured(doc: LayerDoc, job: LayerJob, m: MeasuredJob, opts
return { doc: addNodes(grown, [fill], 0), message: "Canvas expanded", select: fill.id };
}
+ if (job.tool === "rerender") {
+ // One repaint of the whole arrangement: a new layer over the canvas as it is now, the layers kept underneath.
+ const n = newNode(newId(), "Re-render", [0, 0, doc.width, doc.height], out.url, natural, job.label, at, null, prompt);
+ return { doc: addNodes(doc, [n]), message: "Re-render added on top — hide it to see your layers", select: n.id };
+ }
+
if (job.tool === "generate-layer") {
const crop = out.alpha ?? null;
const [cw, ch] = crop ? [crop[2], crop[3]] : natural;
diff --git a/src/components/layers/editor-context.tsx b/src/components/layers/editor-context.tsx
index 281e3783..910a536d 100644
--- a/src/components/layers/editor-context.tsx
+++ b/src/components/layers/editor-context.tsx
@@ -92,7 +92,7 @@ export interface EditorCtx {
setSplitTarget: (id: string | null) => void;
}
-export type ToolId = "decompose" | "edit-text" | "remove-bg" | "regional" | "inpaint" | "upscale" | "enhance" | "relight" | "angles" | "expand" | "grade";
+export type ToolId = "decompose" | "edit-text" | "remove-bg" | "regional" | "inpaint" | "upscale" | "enhance" | "relight" | "angles" | "expand" | "grade" | "rerender";
/** The tool form that started each kind of job (none: the layer card or the Generate layer dialog). */
export const TOOL_FOR_JOB: Record<LayerTool, ToolId | null> = {
@@ -110,6 +110,7 @@ export const TOOL_FOR_JOB: Record<LayerTool, ToolId | null> = {
expand: "expand",
inpaint: "inpaint",
enhance: "enhance",
+ rerender: "rerender",
};
/**
diff --git a/src/components/layers/layers-editor.tsx b/src/components/layers/layers-editor.tsx
index 25007e7b..cbe151d8 100644
--- a/src/components/layers/layers-editor.tsx
+++ b/src/components/layers/layers-editor.tsx
@@ -308,7 +308,7 @@ function Editor({ view, refetch, models }: { view: LayerProjectView; refetch: ()
let image = given;
let jobFrame = givenFrame;
let aspect: string | undefined;
- const needsImage = !(input.tool === "generate-layer");
+ const needsImage = input.tool !== "generate-layer" && input.tool !== "rerender";
if (target.kind === "node") {
const n = target.node;
jobFrame ??= [n.x, n.y, n.w, n.h];
diff --git a/src/components/layers/tools.tsx b/src/components/layers/tools.tsx
index 85f2d1b9..3fa57646 100644
--- a/src/components/layers/tools.tsx
+++ b/src/components/layers/tools.tsx
@@ -46,6 +46,7 @@ import {
enhanceModels,
expandPads,
getNode,
+ layersLayout,
INPAINT_SEES_TINT,
INPAINT_TINT,
jobStatusText,
@@ -72,6 +73,7 @@ import {
type LayerJobInput,
type LayerNode,
type LayerTool,
+ type PlacedText,
type TextBlock,
} from "@/lib/layers";
import { radioKeys, radioTab } from "@/components/studio/radio-keys";
@@ -97,6 +99,7 @@ export const TOOLS: { id: ToolId; label: string; icon: typeof Layers; isNew?: bo
{ id: "angles", label: "Angles", icon: Rotate3d, hint: "See it from another camera angle" },
{ id: "expand", label: "Expand & Crop", icon: Crop, isNew: true, hint: "Resize the canvas, fill it with AI" },
{ id: "grade", label: "Color grading", icon: SlidersHorizontal, hint: "Film looks and colour, in your browser" },
+ { id: "rerender", label: "Re-render from layers", icon: RefreshCw, isNew: true, hint: "Paint the arrangement again as one picture" },
];
// ---------------------------------------------------------------------------
@@ -1325,6 +1328,85 @@ function GradeTool() {
// ---------------------------------------------------------------------------
// The rail
+// ---------------------------------------------------------------------------
+// Re-render from layers
+
+/**
+ * The arrangement painted again as one coherent picture: every visible layer's box and name, and the text read off the
+ * picture word for word, as a layout for a model that places boxes (MOSS-Image on both engines; Ideogram 4.5 and FLUX.3 in
+ * the cloud). The result lands as a new layer on top.
+ */
+function RerenderTool() {
+ const { doc, jobs, isDemo, endJob, setHighlight } = useEditor();
+ const { modelId, model, setModelId } = useToolModel("rerender");
+ const detector = useToolModel("text-detect");
+ const { busy, go } = useRun();
+ const [words, setWords] = useState("");
+ const [keepText, setKeepText] = useState(true);
+ const job = latestJob(jobs, ["rerender"], null);
+ const detect = latestJob(jobs, ["text-detect"], null);
+ const detecting = !!detect && isRunning(detect);
+ const [text, setText] = useState<{ id: string; lines: PlacedText[] } | null>(null);
+ // The lines of the newest reading of the whole picture, placed in the document (as Edit text lists them).
+ useEffect(() => {
+ if (!detect || detect.result?.status !== "succeeded" || text?.id === detect.id) return;
+ const out = detect.result.outputs[0];
+ const sent = typeof detect.settings?.image === "string" ? detect.settings.image : undefined;
+ const measure = out?.kind === "image" ? out.url : needsDetectedSize(out?.meta) ? sent : undefined;
+ let gone = false;
+ void (measure ? loadImage(measure).then((img) => sizeOf(img)) : Promise.resolve(undefined))
+ .catch(() => undefined)
+ .then((natural) => {
+ if (gone) return;
+ const blocks: TextBlock[] = out ? textBlocksFrom(out.meta, natural) : [];
+ setText({ id: detect.id, lines: placeTextBlocks(blocks, detect.frame).map((r) => ({ text: r.from, box: r.box })) });
+ if (detect.state === "pending") endJob(detect.id, "applied");
+ });
+ return () => {
+ gone = true;
+ };
+ }, [detect, endJob, text?.id]);
+ useEffect(() => () => setHighlight(null), [setHighlight]);
+ const plan = useMemo(() => layersLayout(doc, keepText ? (text?.lines ?? []) : [], words), [doc, keepText, text, words]);
+ const { counts } = plan;
+ const boxes = counts.layers + counts.text;
+ const run = () => void go({ tool: "rerender", target: { kind: "whole" }, modelId, prompt: words.trim() || undefined, settings: { layout: plan.draft }, label: "Re-render from layers" });
+ const read = () => void go({ tool: "text-detect", target: { kind: "whole" }, modelId: detector.modelId, label: "Detect text" });
+ const plural = (n: number, one: string) => `${n} ${one}${n === 1 ? "" : "s"}`;
+ return (
+ <div className="space-y-4">
+ <HowItWorks>Paints the whole picture again as one image, with every visible layer where it is now. Each layer&apos;s name says what it is, and text read off the picture is kept word for word. The result arrives as a new layer on top.</HowItWorks>
+ <p className="text-[12px] text-muted-foreground" role="status">
+ {boxes ? `${plural(counts.layers, "layer")} and ${plural(counts.text, "line")} of text in place` : "Show at least one layer to re-render"}
+ {counts.backdrop ? ` · ${plural(counts.backdrop, "backdrop layer")} described in words` : ""}
+ </p>
+ <Field label="Describe the picture (optional)">
+ <Textarea value={words} onChange={(e) => setWords(e.target.value)} rows={3} maxLength={1500} placeholder="e.g. a warm studio product shot, soft window light" className="min-h-20 text-[13px]" aria-label="Describe the picture" />
+ </Field>
+ {text?.lines.length ? (
+ <label className="flex items-center justify-between gap-2 text-[12px] text-muted-foreground">
+ Keep the text word for word ({plural(text.lines.length, "line")})
+ <Switch checked={keepText} onCheckedChange={setKeepText} aria-label="Keep the text word for word" />
+ </label>
+ ) : (
+ <div className="space-y-1">
+ <Button variant="secondary" size="sm" className="w-full rounded-full" onClick={read} disabled={busy || detecting || !detector.model}>
+ {detecting ? <Loader2 className="animate-spin" /> : <Type />} {detecting ? "Reading the text…" : "Read the text first"}
+ </Button>
+ <p className="text-center font-mono text-[11px] text-muted-foreground">{costLabel(detector.model, isDemo(detector.model))}</p>
+ {text && !text.lines.length && <p className="text-center text-[12px] text-muted-foreground">No text was found on this image.</p>}
+ </div>
+ )}
+ <ModelSelect tool="rerender" value={modelId} onChange={setModelId} />
+ {model?.engine === "cloud" && model.id !== "moss-image" && <p className="text-[11px] text-pretty text-muted-foreground">{model.name} places the boxes from its prompt; MOSS-Image follows them most closely.</p>}
+ <JobState job={job} failedTitle="Couldn't re-render the picture" onRetry={run} />
+ <RunRow cost={costLabel(model, isDemo(model))} busy={busy} disabled={!boxes || !model || (!!job && isRunning(job))} onClick={run}>
+ <RefreshCw /> Re-render
+ </RunRow>
+ </div>
+ );
+}
+
export function ToolRail() {
const { tool, openTool, mask, selected, setSplitTarget, jobs } = useEditor();
const current = TOOLS.find((t) => t.id === tool);
@@ -1372,6 +1454,7 @@ export function ToolRail() {
{tool === "angles" && <AnglesTool />}
{tool === "expand" && <ExpandTool />}
{tool === "grade" && <GradeTool />}
+ {tool === "rerender" && <RerenderTool />}
</div>
</div>
</>
diff --git a/src/lib/layers.ts b/src/lib/layers.ts
index a1888562..981ec1c0 100644
--- a/src/lib/layers.ts
+++ b/src/lib/layers.ts
@@ -10,6 +10,7 @@
* hug what you see.
*/
import type { Pricing } from "./catalog/types";
+import type { LayoutDraft, LayoutItem } from "./layout-prompt";
export type Box = [x: number, y: number, w: number, h: number];
@@ -100,7 +101,8 @@ export type LayerTool =
| "angles"
| "expand"
| "inpaint"
- | "enhance";
+ | "enhance"
+ | "rerender";
export interface LayerProject {
id: string;
@@ -201,6 +203,8 @@ export interface LayerJobInput {
aspect?: string;
/** Enhancer: one of {@link ENHANCE_LOOKS}. */
look?: EnhanceLook;
+ /** Re-render from layers: the layers and text as a layout ({@link layersLayout}). */
+ layout?: LayoutDraft | Record<string, unknown>;
};
}
@@ -220,6 +224,7 @@ export const TOOL_LABELS: Record<LayerTool, string> = {
expand: "Expand",
inpaint: "Inpaint",
enhance: "Enhance",
+ rerender: "Re-render from layers",
};
/**
@@ -255,6 +260,9 @@ export const TOOL_MODELS: Record<LayerTool, { cloud: string[]; open: string[] }>
inpaint: { cloud: ["nano-banana-pro", "bria-fibo-2", "z-image-inpaint"], open: ["oss-qwen-image-21", "oss-flux-fill"] },
// The retouch looks; Detail runs on {@link ENHANCE_DETAIL_MODELS}.
enhance: { cloud: ["nano-banana-pro", "seedream-5-pro"], open: ["oss-qwen-image-21", "oss-qwen-image-21-turbo", "oss-krea2-edit"] },
+ // One repaint of the arrangement from its boxes: MOSS-Image on both engines (fal hosts it), and the cloud's other models
+ // that read layout boxes in their prompt (Ideogram 4.5, FLUX.3).
+ rerender: { cloud: ["moss-image", "ideogram-4-5", "flux-3"], open: ["oss-moss-image"] },
};
// ---------------------------------------------------------------------------
@@ -1170,7 +1178,81 @@ export function jobStatusText(r: LayerJobResult | null | undefined): string {
}
/** Tools whose result changes the document when it lands (text detection only fills the Edit text list). */
-export const APPLIES_TO_DOC = new Set<LayerTool>(["decompose", "split", "regenerate", "generate-layer", "text-edit", "bg-remove", "regional", "upscale", "relight", "angles", "expand", "inpaint", "enhance"]);
+export const APPLIES_TO_DOC = new Set<LayerTool>(["decompose", "split", "regenerate", "generate-layer", "text-edit", "bg-remove", "regional", "upscale", "relight", "angles", "expand", "inpaint", "enhance", "rerender"]);
+
+// ---------------------------------------------------------------------------
+// Re-render from layers (research new-models-7.md §4.10): the arrangement as a layout, painted again as one picture
+
+/** Boxes a re-render sends at most: the largest layers, and the first lines of text. */
+export const RERENDER_MAX_LAYERS = 32;
+export const RERENDER_MAX_TEXT = 16;
+/** A layer covering this much of the canvas is the backdrop: said in the caption, not boxed. */
+const BACKDROP_SHARE = 0.9;
+
+/** A line of text on the picture, placed in the document (doc px), as Edit text lists it. */
+export interface PlacedText {
+ text: string;
+ box: Box | null;
+}
+
+export interface LayersLayout {
+ draft: LayoutDraft;
+ /** The words for the whole picture: the person's, else made from the layers' names. */
+ caption: string;
+ /** Layers in the draft, lines of text in it, and the backdrop layers named in the caption. */
+ counts: { layers: number; text: number; backdrop: number };
+}
+
+const r6 = (n: number) => Math.round(n * 1e6) / 1e6;
+
+/** What a layer shows, in words: its prompt, else its name ("a picture element" for a generic one). */
+function layerWords(n: Pick<LayerNode, "name" | "prompt">): string {
+ const p = n.prompt?.trim();
+ if (p) return p.replace(/[.\s]+$/, "");
+ const name = n.name.trim();
+ return !name || GENERIC_NAME.test(name) ? "a picture element, kept as it looks now" : name;
+}
+
+/**
+ * The document as a layout for one repaint: each visible layer's box (its rotation-aware bounds, kept on the canvas) with
+ * its name or prompt as an object item (a person or animal as a character), bottom to top; each line of text read off the
+ * picture as a text item with its exact words. A layer that fills the canvas is the backdrop, named in the caption. The
+ * boxes are 0-1 fractions of the canvas, so the model's own size places them.
+ */
+export function layersLayout(doc: Pick<LayerDoc, "width" | "height" | "nodes">, text: PlacedText[] = [], words = ""): LayersLayout {
+ const { width: W, height: H } = doc;
+ const canvas: Box = [0, 0, W, H];
+ const frac = (b: Box): [number, number, number, number] => [r6(b[0] / W), r6(b[1] / H), r6((b[0] + b[2]) / W), r6((b[1] + b[3]) / H)];
+ const backdrop: string[] = [];
+ const layers: { z: number; area: number; item: LayoutItem }[] = [];
+ for (const n of doc.nodes) {
+ if (n.hidden || (n.opacity ?? 1) <= 0.05 || n.role === "original") continue;
+ const box = intersect(rotatedBounds(n.x, n.y, n.w, n.h, n.rotation), canvas);
+ if (!box) continue;
+ const area = (box[2] * box[3]) / (W * H);
+ const what = layerWords(n);
+ if (area >= BACKDROP_SHARE) {
+ backdrop.push(what);
+ continue;
+ }
+ const label = PERSON.test(`${n.name} ${n.prompt ?? ""}`) ? "character" : "object";
+ layers.push({ z: n.z, area, item: { label, caption: what.charAt(0).toUpperCase() + what.slice(1), box: frac(box) } });
+ }
+ const kept = [...layers].sort((a, b) => b.area - a.area).slice(0, RERENDER_MAX_LAYERS).sort((a, b) => a.z - b.z);
+ const lines = text
+ .flatMap((t) => {
+ const line = t.text.replace(/\s+/g, " ").trim();
+ const box = t.box && intersect(t.box, canvas);
+ return line && box ? [{ label: "text" as const, caption: "Lettering in the same typeface, colour and size as now", text: line, box: frac(box) }] : [];
+ })
+ .slice(0, RERENDER_MAX_TEXT);
+ const named = kept.map((k) => k.item.caption.toLowerCase()).filter((c) => !c.startsWith("a picture element"));
+ const behind = backdrop.length ? ` Behind everything: ${backdrop.join("; ")}.` : "";
+ const auto = `One coherent picture that keeps this arrangement${named.length ? `: ${named.slice(0, 8).join(", ")}` : ""}.${behind} Every element sits where it is now, with one light, perspective and colour grade across the whole picture.`;
+ const caption = words.trim() ? `${words.trim().replace(/[.\s]+$/, "")}.${behind}` : auto;
+ const draft: LayoutDraft = { summary: { caption, meta: ["re-render"], canvas: "single" }, items: [...kept.map((k) => k.item), ...lines] };
+ return { draft, caption, counts: { layers: kept.length, text: lines.length, backdrop: backdrop.length } };
+}
// ---------------------------------------------------------------------------
// Zip (stored): built in the browser from rendered PNGs
diff --git a/src/server/layers.ts b/src/server/layers.ts
index 1d34fdb4..485f5063 100644
--- a/src/server/layers.ts
+++ b/src/server/layers.ts
@@ -2,6 +2,7 @@ import "server-only";
import { nanoid } from "nanoid";
import { z } from "zod";
import { getModel } from "@/lib/catalog";
+import { LAYOUT_PARAM, readLayout } from "@/lib/layout-prompt";
import type { Engine, Generation, GenerationRequest, ModelDef } from "@/lib/catalog/types";
import {
ANGLES,
@@ -17,6 +18,8 @@ import {
layersModelFor,
MAX_NODES,
RELIGHT_DIRECTIONS,
+ RERENDER_MAX_LAYERS,
+ RERENDER_MAX_TEXT,
RELIGHT_LIGHTS,
relightPrompt,
textChanges,
@@ -142,7 +145,7 @@ export function parseDoc(v: unknown): LayerDoc | null {
return doc;
}
-const TOOLS = ["decompose", "split", "regenerate", "generate-layer", "text-detect", "text-edit", "bg-remove", "regional", "upscale", "relight", "angles", "expand", "inpaint", "enhance"] as const satisfies readonly LayerTool[];
+const TOOLS = ["decompose", "split", "regenerate", "generate-layer", "text-detect", "text-edit", "bg-remove", "regional", "upscale", "relight", "angles", "expand", "inpaint", "enhance", "rerender"] as const satisfies readonly LayerTool[];
export const JobInputSchema = z.object({
tool: z.enum(TOOLS),
@@ -173,6 +176,8 @@ export const JobInputSchema = z.object({
feather: num.min(0).max(500).optional(),
aspect: z.string().regex(/^\d+(\.\d+)?:\d+(\.\d+)?$/).max(20).optional(),
look: z.enum(["skin", "glow", "sharpen", "detail"]).optional(),
+ // Re-render from layers: the arrangement as a layout draft (read and checked when the job is planned).
+ layout: z.record(z.string(), z.unknown()).optional(),
})
.optional(),
});
@@ -194,6 +199,18 @@ const RES_TIER = { "1K": "auto_1K", "1.5K": "auto_1.5K", "2K": "auto_2K" } as co
/** Qwen-Image-Layered's longest side per tier (640 is the trained bucket; larger is slower). */
const OPEN_MAX_SIZE = { "1K": 640, "1.5K": 832, "2K": 1024 } as const;
+/** The aspect ratio in `list` nearest to `aspect` ("1400:900"), compared on a log scale; `aspect` itself when there's no list. */
+export function nearestAspect(aspect: string | undefined, list: readonly string[] | undefined): string | undefined {
+ const value = (a: string) => {
+ const [w, h] = a.split(":").map(Number);
+ return w > 0 && h > 0 ? w / h : NaN;
+ };
+ if (!aspect || !Number.isFinite(value(aspect))) return list?.[0];
+ if (!list?.length) return aspect;
+ const v = Math.log(value(aspect));
+ return [...list].filter((a) => Number.isFinite(value(a))).sort((a, b) => Math.abs(Math.log(value(a)) - v) - Math.abs(Math.log(value(b)) - v))[0];
+}
+
const pick = (list: [string, string][], label: string | undefined) => list.find(([l]) => l === label)?.[1] ?? list[0][1];
/**
@@ -357,6 +374,17 @@ export function jobSteps(input: LayerJobInput, opts: { batchTitle?: string } = {
if (s.keepAlpha) cutout("enhance");
break;
}
+ case "rerender": {
+ const layout = readLayout(s.layout);
+ if (!layout?.items.length) throw new LayersError("Show at least one layer or line of text to re-render", 400);
+ if (layout.items.length > RERENDER_MAX_LAYERS + RERENDER_MAX_TEXT) throw new LayersError("Too many boxes to re-render: hide some layers first", 400);
+ const model = toolModel(tool, engine, input.modelId);
+ // The picture's own shape, or the nearest one the model makes (the boxes are fractions, so they stay in place).
+ const aspectRatio = nearestAspect(s.aspect, model.options.aspectRatios);
+ // The plan compiles the layout for this model at the size it renders, and keeps prompt rewriting off.
+ add("rerender", base(model, { op: "t2i", prompt: prompt || layout.summary.caption, params: { ...(aspectRatio && { aspectRatio }), numOutputs: 1, extra: { [LAYOUT_PARAM]: layout } } }));
+ break;
+ }
case "expand": {
const model = toolModel(tool, engine, input.modelId);
const fill = "Continue the scene naturally beyond every edge with matching perspective, lighting, textures and grain.";
diff --git a/tests/layers.test.ts b/tests/layers.test.ts
index fbc2973f..ba1437c4 100644
--- a/tests/layers.test.ts
+++ b/tests/layers.test.ts
@@ -550,6 +550,7 @@ describe("tools and prices", () => {
expand: ["edit", "outpaint"],
inpaint: ["inpaint", "edit"],
enhance: ["edit"],
+ rerender: ["t2i"],
};
it("offers catalog models of the right engine and operation for every tool", () => {