Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: add a subject-framing control to image-to-3D so extremities survive (#5755)

Adam Eivybec37274a230
diff --git a/client/src/components/media/ImageTo3dRenderOptions.jsx b/client/src/components/media/ImageTo3dRenderOptions.jsx
index bd1e2db079..d6754698e0 100644
--- a/client/src/components/media/ImageTo3dRenderOptions.jsx
+++ b/client/src/components/media/ImageTo3dRenderOptions.jsx
@@ -1,6 +1,7 @@
import FormField from '../ui/FormField';
import {
ALPHA_MODE_PRESETS, DETAIL_PRESETS, SEED_MAX, STEPS_PRESETS,
+ SUBJECT_SCALE_DEFAULT, SUBJECT_SCALE_SLIDER_MIN, SUBJECT_SCALE_SLIDER_STEP,
} from '../../lib/imageTo3dRenderOptions';
// Per-run sampler knobs for image-to-3D generation, shared by the /3d
@@ -28,6 +29,8 @@ import {
// - detail: 'auto' = derive the pipeline tier from hardware, else a named tier.
// - alphaMode: '' = leave PortOS's force-opaque normalization on (the default);
// any explicit value turns it off so a transparent subject can stay transparent.
+// - subjectScale: 1 = the source's own framing (the default); below 1 the server
+// centers it on a square canvas at that fraction so extremities gain margin.
const FIELD_LABEL_CLASS = 'mb-1 block text-xs text-gray-400';
const FIELD_INPUT_CLASS = 'w-full rounded-md border border-port-border bg-port-bg px-2 py-1.5 text-xs text-gray-200 disabled:opacity-40';
@@ -45,12 +48,18 @@ export default function ImageTo3dRenderOptions({
onAlphaModeChange,
normalMap = true,
onNormalMapChange,
+ subjectScale = SUBJECT_SCALE_DEFAULT,
+ onSubjectScaleChange,
+ // The gallery image this render will consume, so the framing slider can show what
+ // it is about to do. Optional: the /3d workspace has no source until one is picked.
+ sourcePreviewUrl = null,
disabled = false,
stepsSupported = true,
detailSupported = true,
alphaModeSupported = true,
normalMapSupported = true,
}) {
+ const framingPercent = Math.round(subjectScale * 100);
return (
<div className="flex flex-col gap-2">
<div className="grid gap-3 sm:grid-cols-2">
@@ -175,6 +184,50 @@ export default function ImageTo3dRenderOptions({
</div>
</div>
</div>
+ {/* Subject framing. The preview is the point of the control: a bare percentage
+ says nothing about whether THIS source already has margin, and the whole
+ reason to reframe is that a pose running to the edge loses its fingertips.
+ It mirrors the server's geometry exactly — a square box with the source
+ contained in a centered sub-box of `subjectScale` of its side — so no
+ round-trip is needed to show the framing the render will actually get. */}
+ <div className="flex items-center gap-3 rounded-md border border-port-border bg-port-bg/40 p-2">
+ <div className="relative h-14 w-14 shrink-0 overflow-hidden rounded border border-port-border bg-port-bg">
+ {sourcePreviewUrl ? (
+ <div className="absolute inset-0 flex items-center justify-center">
+ <img
+ src={sourcePreviewUrl}
+ alt={`Framing preview at ${framingPercent}% of the canvas`}
+ className="object-contain"
+ style={{ width: `${framingPercent}%`, height: `${framingPercent}%` }}
+ />
+ </div>
+ ) : (
+ <span className="flex h-full items-center justify-center px-1 text-center text-[10px] leading-tight text-gray-600">
+ No source
+ </span>
+ )}
+ </div>
+ <FormField
+ label={`Subject framing — ${framingPercent}%`}
+ labelClassName={FIELD_LABEL_CLASS}
+ className="min-w-0 flex-1"
+ hint={subjectScale === SUBJECT_SCALE_DEFAULT
+ ? 'Full frame — the source is sent exactly as it is.'
+ : 'Centered on a square canvas with margin around the subject, so outstretched hands and feet keep context.'}
+ >
+ <input
+ id="image-to-3d-subject-scale"
+ type="range"
+ min={SUBJECT_SCALE_SLIDER_MIN}
+ max={SUBJECT_SCALE_DEFAULT}
+ step={SUBJECT_SCALE_SLIDER_STEP}
+ value={subjectScale}
+ onChange={(e) => onSubjectScaleChange(Number(e.target.value))}
+ disabled={disabled}
+ className="w-full accent-port-accent disabled:opacity-40"
+ />
+ </FormField>
+ </div>
<p className="text-xs leading-relaxed text-gray-500">
<span className="font-medium text-gray-400">Best source images:</span> one subject,
front or ¾ view, filling the frame, with no parts hidden behind others (tails, wings,
diff --git a/client/src/components/media/ImageTo3dRenderOptions.test.jsx b/client/src/components/media/ImageTo3dRenderOptions.test.jsx
index 2dcb3a7a9a..9d2856505d 100644
--- a/client/src/components/media/ImageTo3dRenderOptions.test.jsx
+++ b/client/src/components/media/ImageTo3dRenderOptions.test.jsx
@@ -48,10 +48,37 @@ describe('ImageTo3dRenderOptions', () => {
expect(keying.closest('label')).toHaveAttribute('title', expect.stringMatching(/chroma backdrop/i));
});
+ // The preview is the reason the control is a slider and not a number: a percentage
+ // alone says nothing about whether THIS source already has margin around its
+ // extremities, which is the only question the knob answers.
+ it('previews the framing against the actual source at the chosen scale', () => {
+ setup({ subjectScale: 0.65, onSubjectScaleChange: vi.fn(), sourcePreviewUrl: '/data/images/example.png' });
+ expect(screen.getByLabelText(/subject framing — 65%/i)).toHaveValue('0.65');
+ const preview = screen.getByRole('img', { name: /framing preview at 65%/i });
+ expect(preview).toHaveAttribute('src', '/data/images/example.png');
+ // Mirrors the server geometry: the source occupies `subjectScale` of the square.
+ expect(preview).toHaveStyle({ width: '65%', height: '65%' });
+ });
+
+ it('says the source passes through untouched at the default scale', () => {
+ setup({ onSubjectScaleChange: vi.fn(), sourcePreviewUrl: '/data/images/example.png' });
+ expect(screen.getByLabelText(/subject framing — 100%/i)).toHaveValue('1');
+ expect(screen.getByText(/full frame/i)).toBeInTheDocument();
+ });
+
+ it('still renders the framing slider before a source image is picked', () => {
+ // The /3d workspace mounts the options with no selection yet; the control must
+ // stay usable rather than vanishing until an image is chosen.
+ setup({ onSubjectScaleChange: vi.fn() });
+ expect(screen.getByLabelText(/subject framing/i)).toBeEnabled();
+ expect(screen.queryByRole('img')).toBeNull();
+ });
+
it('disables everything when the whole form is disabled', () => {
- setup({ disabled: true });
+ setup({ disabled: true, onSubjectScaleChange: vi.fn() });
expect(screen.getByLabelText('Quality')).toBeDisabled();
expect(screen.getByLabelText('Seed')).toBeDisabled();
+ expect(screen.getByLabelText(/subject framing/i)).toBeDisabled();
// Both checkboxes, not just the keying one — `disabled` must reach every control.
for (const box of screen.getAllByRole('checkbox')) expect(box).toBeDisabled();
});
diff --git a/client/src/lib/imageTo3dRenderOptions.js b/client/src/lib/imageTo3dRenderOptions.js
index 5f02880916..fd4eb226bf 100644
--- a/client/src/lib/imageTo3dRenderOptions.js
+++ b/client/src/lib/imageTo3dRenderOptions.js
@@ -1,6 +1,7 @@
/**
* Pure helpers for the image-to-3D per-run render options (steps / seed /
- * background keying) — the client mirror of the server's accepted bounds.
+ * background keying / subject framing) — the client mirror of the server's accepted
+ * bounds.
*
* `SEED_MAX` is a hand-maintained mirror of the server's `RENDER_SEED_MAX`
* (`server/services/imageTo3d/renderOptions.js`) pinned by
@@ -15,6 +16,25 @@
export const SEED_MAX = 2147483647;
+/**
+ * Subject framing — the client mirror of the server's `subjectScale` bounds, pinned
+ * by the same parity suite.
+ *
+ * `SUBJECT_SCALE_DEFAULT` is the identity: the source goes to the decoder at its own
+ * framing, which is what every render did before this control existed. Below it, the
+ * server centres the source on a square canvas at that fraction, leaving margin for
+ * the extremities that otherwise reach the decoder flush with the edge and come back
+ * clipped.
+ *
+ * The slider FLOOR is deliberately tighter than the server's open-at-zero bound: the
+ * server accepts anything in (0, 1] because an API caller may have a reason to, but a
+ * subject shrunk below a third of the frame is throwing away resolution the decoder
+ * needs more than it needs margin, so the UI doesn't offer it.
+ */
+export const SUBJECT_SCALE_DEFAULT = 1;
+export const SUBJECT_SCALE_SLIDER_MIN = 0.35;
+export const SUBJECT_SCALE_SLIDER_STEP = 0.05;
+
/** The steps presets: the pipeline's own default, and two slower/higher-detail
* tiers. Values stay strings because they live in <select> state. */
export const STEPS_PRESETS = [
@@ -62,7 +82,9 @@ export const ALPHA_MODE_PRESETS = [
* seed → the server rolls a fresh random one for that run. Range/int validation
* is the server's job — the route 400s with a readable message.
*/
-export function renderOptionsBody({ steps, seed, keyBackground, detail, alphaMode, normalMap }) {
+export function renderOptionsBody({
+ steps, seed, keyBackground, detail, alphaMode, normalMap, subjectScale,
+}) {
return {
...(steps !== '' && { steps: Number(steps) }),
...(seed !== '' && { seed: Number(seed) }),
@@ -77,6 +99,12 @@ export function renderOptionsBody({ steps, seed, keyBackground, detail, alphaMod
// that the wire body states what the run asked for, and a future default flip
// must not silently change what an existing client means.
normalMap,
+ // Sent always, for the same reason as `normalMap`. Guarded rather than trusted:
+ // the server's range is open at zero, so a NaN or 0 out of a mis-parsed slider
+ // would 400 the render instead of quietly meaning "don't reframe".
+ subjectScale: typeof subjectScale === 'number' && subjectScale > 0 && subjectScale <= 1
+ ? subjectScale
+ : SUBJECT_SCALE_DEFAULT,
};
}
@@ -103,6 +131,12 @@ export function fieldsFromRun(run) {
alphaMode: typeof run?.alphaMode === 'string' ? run.alphaMode : '',
// A run predating the field has none; default to OFF, matching the server.
normalMap: typeof run?.normalMap === 'boolean' ? run.normalMap : false,
+ // Carries over like `steps` — a deliberate framing choice, not per-run randomness.
+ // A run predating the field falls back to the identity, matching the server.
+ subjectScale: typeof run?.subjectScale === 'number'
+ && run.subjectScale > 0 && run.subjectScale <= 1
+ ? run.subjectScale
+ : SUBJECT_SCALE_DEFAULT,
};
}
diff --git a/client/src/pages/Media3D.jsx b/client/src/pages/Media3D.jsx
index f959aaccff..cb036ef960 100644
--- a/client/src/pages/Media3D.jsx
+++ b/client/src/pages/Media3D.jsx
@@ -14,7 +14,7 @@ import useUrlParams from '../hooks/useUrlParams';
import MediaImage from '../components/MediaImage';
import { imageTo3dStatusMeta } from '../components/media/imageTo3dStatus';
import ImageTo3dRenderOptions from '../components/media/ImageTo3dRenderOptions';
-import { renderOptionsBody } from '../lib/imageTo3dRenderOptions';
+import { renderOptionsBody, SUBJECT_SCALE_DEFAULT } from '../lib/imageTo3dRenderOptions';
import { isTargetReady, unavailableReasonLabel } from '../lib/imageTo3dReasons';
// Poll cadence while a render is in flight (a real TRELLIS.2 render is multi-minute).
@@ -44,6 +44,7 @@ export default function Media3D() {
const [detail, setDetail] = useState('auto');
const [alphaMode, setAlphaMode] = useState('');
const [normalMap, setNormalMap] = useState(false);
+ const [subjectScale, setSubjectScale] = useState(SUBJECT_SCALE_DEFAULT);
// Existing image-to-3D records (newest-first) so the page doubles as a library:
// each links to its `/3d/:id` detail view.
const [records, setRecords] = useState([]);
@@ -131,7 +132,9 @@ export default function Media3D() {
name: nameFromImageFilename(selectedImage.filename),
filename: selectedImage.filename,
target: selectedTarget.id,
- ...renderOptionsBody({ steps, seed, keyBackground, detail, alphaMode, normalMap }),
+ ...renderOptionsBody({
+ steps, seed, keyBackground, detail, alphaMode, normalMap, subjectScale,
+ }),
},
{ silent: true },
).catch((err) => {
@@ -140,7 +143,7 @@ export default function Media3D() {
});
if (created && mountedRef.current) { setModelId(created.id); setGenerating(true); patchRecord(created); }
}, [selectedImage, selectedTarget, steps, seed, keyBackground, detail, alphaMode, normalMap,
- updateParams, mountedRef, patchRecord]);
+ subjectScale, updateParams, mountedRef, patchRecord]);
// Why the Generate action is blocked, or null when it's ready to run. The runner
// (POST create → on-device render → landed .glb) is wired, so the terminal state
@@ -257,6 +260,9 @@ export default function Media3D() {
onSeedChange={setSeed}
keyBackground={keyBackground}
onKeyBackgroundChange={setKeyBackground}
+ subjectScale={subjectScale}
+ onSubjectScaleChange={setSubjectScale}
+ sourcePreviewUrl={selectedImage?.previewUrl || null}
disabled={generating}
/>
diff --git a/client/src/pages/Media3DDetail.jsx b/client/src/pages/Media3DDetail.jsx
index f436051a2c..5bd41ed3e1 100644
--- a/client/src/pages/Media3DDetail.jsx
+++ b/client/src/pages/Media3DDetail.jsx
@@ -10,7 +10,9 @@ import MediaImage from '../components/MediaImage';
import InlineConfirmRow from '../components/ui/InlineConfirmRow';
import ImageTo3dRenderOptions from '../components/media/ImageTo3dRenderOptions';
import RigPanel from '../components/media/RigPanel';
-import { fieldsFromRun, renderOptionsBody, runWantsTransparency } from '../lib/imageTo3dRenderOptions';
+import {
+ fieldsFromRun, renderOptionsBody, runWantsTransparency, SUBJECT_SCALE_DEFAULT,
+} from '../lib/imageTo3dRenderOptions';
import { imageTo3dStatusMeta } from '../components/media/imageTo3dStatus';
import toast from '../components/ui/Toast';
import PageSkeleton from '../components/ui/PageSkeleton';
@@ -40,6 +42,7 @@ export default function Media3DDetail() {
const [detail, setDetail] = useState('auto');
const [alphaMode, setAlphaMode] = useState('');
const [normalMap, setNormalMap] = useState(false);
+ const [subjectScale, setSubjectScale] = useState(SUBJECT_SCALE_DEFAULT);
const optionsSeededFor = useRef(null);
const load = useCallback(async ({ initial = false } = {}) => {
@@ -82,6 +85,7 @@ export default function Media3DDetail() {
setDetail(fields.detail);
setAlphaMode(fields.alphaMode);
setNormalMap(fields.normalMap);
+ setSubjectScale(fields.subjectScale);
}, [record]);
const handleRegenerate = useCallback(async () => {
@@ -89,7 +93,7 @@ export default function Media3DDetail() {
setBusy(true);
const next = await generateImageTo3dModel(
id,
- renderOptionsBody({ steps, seed, keyBackground, detail, alphaMode, normalMap }),
+ renderOptionsBody({ steps, seed, keyBackground, detail, alphaMode, normalMap, subjectScale }),
{ silent: true },
).catch((err) => {
toast.error(err?.message || 'Could not start the render.');
@@ -97,7 +101,8 @@ export default function Media3DDetail() {
});
if (mountedRef.current) setBusy(false);
if (next && mountedRef.current) setRecord(next);
- }, [busy, record?.status, id, steps, seed, keyBackground, detail, alphaMode, normalMap, mountedRef]);
+ }, [busy, record?.status, id, steps, seed, keyBackground, detail, alphaMode, normalMap,
+ subjectScale, mountedRef]);
const handleDelete = useCallback(async () => {
const ok = await deleteImageTo3dModel(id, { silent: true }).then(() => true).catch((err) => {
@@ -180,6 +185,9 @@ export default function Media3DDetail() {
{Number.isInteger(latestRun?.seed) ? ` · seed ${latestRun.seed}` : ''}
{Number.isInteger(latestRun?.steps) ? ` · ${latestRun.steps} steps` : ''}
{latestRun?.sourceKeyed ? ' · background keyed' : ''}
+ {latestRun?.sourceFramed && Number.isFinite(latestRun?.subjectScale)
+ ? ` · framed at ${Math.round(latestRun.subjectScale * 100)}%`
+ : ''}
{' '}· updated {timeAgo(record.updatedAt)}
</p>
</header>
@@ -202,6 +210,9 @@ export default function Media3DDetail() {
normalMapSupported={record.supportsRenderOptions?.normalMap !== false}
normalMap={normalMap}
onNormalMapChange={setNormalMap}
+ subjectScale={subjectScale}
+ onSubjectScaleChange={setSubjectScale}
+ sourcePreviewUrl={record.sourceImage?.path || null}
disabled={busy || isGenerating}
/>
</div>
diff --git a/client/src/pages/Media3DDetail.test.jsx b/client/src/pages/Media3DDetail.test.jsx
index c108a2ecf9..5ea37aee4f 100644
--- a/client/src/pages/Media3DDetail.test.jsx
+++ b/client/src/pages/Media3DDetail.test.jsx
@@ -102,7 +102,7 @@ describe('Media3DDetail', () => {
// normalMap is sent explicitly rather than omitted. It defaults OFF (the bake
// can lose a render outright), and stating it keeps the body honest about what
// the run asked for even if that default ever moves.
- { steps: 24, keyBackground: false, normalMap: false },
+ { steps: 24, keyBackground: false, normalMap: false, subjectScale: 1 },
{ silent: true },
));
});
@@ -125,7 +125,7 @@ describe('Media3DDetail', () => {
fireEvent.click(screen.getByRole('button', { name: /re-render/i }));
await waitFor(() => expect(generateImageTo3dModel).toHaveBeenCalledWith(
'image3d-1',
- { steps: 48, keyBackground: false, normalMap: false },
+ { steps: 48, keyBackground: false, normalMap: false, subjectScale: 1 },
{ silent: true },
));
});
@@ -150,7 +150,32 @@ describe('Media3DDetail', () => {
fireEvent.click(screen.getByRole('button', { name: /re-render/i }));
await waitFor(() => expect(generateImageTo3dModel).toHaveBeenCalledWith(
'image3d-1',
- { keyBackground: false, detail: 'fast', alphaMode: 'auto', normalMap: false },
+ { keyBackground: false, detail: 'fast', alphaMode: 'auto', normalMap: false, subjectScale: 1 },
+ { silent: true },
+ ));
+ });
+
+ it('carries the subject framing over and reports it on the finished run', async () => {
+ // A framing that produced a good mesh is exactly what a re-render wants to keep;
+ // and the meta line has to say the render was reframed, or the user cannot tell
+ // whether the last result came from the source's own framing or this knob.
+ getImageTo3dModel.mockResolvedValue(record({
+ runs: [{
+ operationId: 'op-1', status: 'completed', percent: 100,
+ subjectScale: 0.65, sourceFramed: true,
+ }],
+ }));
+ generateImageTo3dModel.mockResolvedValue(record({ status: 'generating' }));
+ renderAt();
+ await screen.findByText('Example Beacon');
+
+ await waitFor(() => expect(screen.getByLabelText(/subject framing — 65%/i)).toHaveValue('0.65'));
+ expect(screen.getByText(/framed at 65%/i)).toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole('button', { name: /re-render/i }));
+ await waitFor(() => expect(generateImageTo3dModel).toHaveBeenCalledWith(
+ 'image3d-1',
+ { keyBackground: false, normalMap: false, subjectScale: 0.65 },
{ silent: true },
));
});
diff --git a/client/src/services/apiImageTo3d.js b/client/src/services/apiImageTo3d.js
index 4a1d6d9503..8df31513e3 100644
--- a/client/src/services/apiImageTo3d.js
+++ b/client/src/services/apiImageTo3d.js
@@ -21,9 +21,10 @@ export const createImageTo3dModel = (input, options) =>
});
// Re-run the render for an existing record (status → generating again).
-// `input` carries the optional per-run knobs ({ steps, seed, keyBackground }) —
-// they apply to this run only: absent steps → the pipeline default, absent
-// seed → the server rolls a fresh random one, absent keyBackground → no keying.
+// `input` carries the optional per-run knobs ({ steps, seed, keyBackground,
+// subjectScale, … }) — they apply to this run only: absent steps → the pipeline
+// default, absent seed → the server rolls a fresh random one, absent keyBackground →
+// no keying, absent subjectScale → the source keeps its own framing.
export const generateImageTo3dModel = (id, input = {}, options) =>
request(`/image-to-3d/models/${encodeURIComponent(id)}/generate`, {
method: 'POST',
diff --git a/server/lib/imageRgba.js b/server/lib/imageRgba.js
index 95464a214c..abb1a5d4b0 100644
--- a/server/lib/imageRgba.js
+++ b/server/lib/imageRgba.js
@@ -7,9 +7,19 @@
import sharp from 'sharp';
-/** Decode an image to a raw RGBA frame `{ data, width, height }`. */
-export async function decodeRgbaFrame(src) {
- const { data, info } = await sharp(src)
+/**
+ * Decode an image to a raw RGBA frame `{ data, width, height }`.
+ *
+ * `autoOrient` applies the source's EXIF orientation tag before the pixels are
+ * handed back, so `width`/`height` describe the image as a viewer would see it.
+ * It is OPT-IN because raw output carries no EXIF of its own: a lane that
+ * decodes, edits and re-encodes silently DROPS the tag, so a rotated JPEG comes
+ * back sideways unless the rotation was baked in here. It stays off by default
+ * only so existing callers keep their pixel-for-pixel behaviour.
+ */
+export async function decodeRgbaFrame(src, { autoOrient = false } = {}) {
+ const pipeline = sharp(src);
+ const { data, info } = await (autoOrient ? pipeline.rotate() : pipeline)
.ensureAlpha()
.raw()
.toBuffer({ resolveWithObject: true });
diff --git a/server/routes/imageTo3d.js b/server/routes/imageTo3d.js
index 9898021409..4dbc573f3f 100644
--- a/server/routes/imageTo3d.js
+++ b/server/routes/imageTo3d.js
@@ -17,6 +17,7 @@ import {
} from '../services/imageTo3d/models.js';
import {
RENDER_STEPS_MIN, RENDER_STEPS_MAX, RENDER_SEED_MAX, DETAIL_TIERS, ALPHA_MODES,
+ SUBJECT_SCALE_MIN_EXCLUSIVE, SUBJECT_SCALE_MAX,
} from '../services/imageTo3d/renderOptions.js';
import { createInstallLogger } from '../lib/installLogger.js';
import { openSseStream } from '../lib/sseDownload.js';
@@ -29,7 +30,7 @@ const galleryFilenameSchema = z.string().trim().min(1).max(256)
// PER-RUN sampler knobs, shared by create and re-generate. Nothing persists
// between runs: absent steps → the pipeline default, absent seed → a fresh
// random roll for that run, absent keyBackground → no keying (the pipeline's own
-// learned matte runs instead).
+// learned matte runs instead), absent subjectScale → the source's own framing.
const renderOptionsSchema = z.object({
steps: z.number().int().min(RENDER_STEPS_MIN).max(RENDER_STEPS_MAX).optional(),
seed: z.number().int().min(0).max(RENDER_SEED_MAX).optional(),
@@ -40,6 +41,13 @@ const renderOptionsSchema = z.object({
detail: z.enum([...DETAIL_TIERS]).optional(),
alphaMode: z.enum([...ALPHA_MODES]).optional(),
normalMap: z.boolean().optional(),
+ // Open at zero, closed at one — `1` is the identity (no reframing) and the
+ // default; bounds come from renderOptions.js so the route can't accept a value
+ // the normalizer would silently discard.
+ subjectScale: z.number()
+ .gt(SUBJECT_SCALE_MIN_EXCLUSIVE)
+ .max(SUBJECT_SCALE_MAX)
+ .optional(),
});
const createModelSchema = z.object({
diff --git a/server/routes/imageTo3d.test.js b/server/routes/imageTo3d.test.js
index 7c2b77fb32..65886cc627 100644
--- a/server/routes/imageTo3d.test.js
+++ b/server/routes/imageTo3d.test.js
@@ -497,6 +497,25 @@ describe('image-to-3d model records', () => {
expect(bad.status).toBe(400);
});
+ it('POST /models/:id/generate takes a subject scale in (0, 1] and 400s outside it', async () => {
+ models.startGeneration.mockResolvedValue({ id: 'image3d-1', status: 'generating' });
+ const ok = await request(makeApp())
+ .post('/api/image-to-3d/models/image3d-1/generate')
+ .send({ subjectScale: 0.65 });
+ expect(ok.status).toBe(202);
+ expect(models.startGeneration).toHaveBeenCalledWith('image3d-1', { options: { subjectScale: 0.65 } });
+
+ // 0 scales the subject out of existence; above 1 crops it — which is the exact
+ // failure the knob exists to prevent, so it must not be reachable by accident.
+ for (const subjectScale of [0, -0.5, 1.5]) {
+ // eslint-disable-next-line no-await-in-loop
+ const bad = await request(makeApp())
+ .post('/api/image-to-3d/models/image3d-1/generate')
+ .send({ subjectScale });
+ expect(bad.status, `subjectScale ${subjectScale}`).toBe(400);
+ }
+ });
+
it('DELETE /models/:id soft-deletes', async () => {
models.deleteModel.mockResolvedValue({ ok: true });
const res = await request(makeApp()).delete('/api/image-to-3d/models/image3d-1');
diff --git a/server/services/imageTo3d/models.js b/server/services/imageTo3d/models.js
index 3a87705e03..337fc4d30f 100644
--- a/server/services/imageTo3d/models.js
+++ b/server/services/imageTo3d/models.js
@@ -64,7 +64,10 @@ const assetDiskPath = (id) => join(recordDir(id), 'model.glb');
*/
const fullMeshDiskPath = (id) => join(recordDir(id), 'model.obj');
/** Where a background-keyed copy of the source lands (never the gallery file). */
-const keyedSourcePath = (id) => join(recordDir(id), 'source-keyed.png');
+// The prepared (keyed and/or subject-framed) copy of the source. Filename retained
+// from when keying was the only preparation step, so upgrading an install doesn't
+// strand an orphan beside the new one in every existing record directory.
+const preparedSourcePath = (id) => join(recordDir(id), 'source-keyed.png');
/**
* Remove a record's render directory (the exported GLB + its folder). Used to
@@ -150,31 +153,41 @@ async function failGeneration(id, operationId, error) {
async function executeRender({ id, operationId, adapter, sourcePath, caps, options }) {
const outputPath = assetDiskPath(id);
- // keyBackground is consumed here; the sampler knobs ride through to the
- // adapter as-is, so a future knob added to the options shape flows without
- // touching this call chain.
- const { keyBackground, ...samplerOptions } = options;
+ // keyBackground and subjectScale are consumed here (they preprocess the SOURCE,
+ // and no runner takes them); the sampler knobs ride through to the adapter as-is,
+ // so a future knob added to the options shape flows without touching this call
+ // chain.
+ const { keyBackground, subjectScale, ...samplerOptions } = options;
let lastPersistedPercent = -1;
let heavyClaim = null;
try {
await ensureDir(recordDir(id));
- // Key a solid background out of the source (into THIS record's render dir — the
- // shared gallery file is never touched). Opt-in, because handing the pipeline an
- // alpha channel makes it consume that INSTEAD OF running its own learned matte —
- // see sourceKeying.js. Runs BEFORE the heavy-job claim: it is CPU-only
- // preprocessing, so other heavy jobs shouldn't queue behind it and resident models
- // shouldn't be evicted for it. Best-effort: a keying failure must never fail a
- // render the model could still attempt raw.
- const keyedPath = keyBackground
- ? await prepareSourceImage({ sourcePath, targetPath: keyedSourcePath(id) })
+ // Preprocess the source (into THIS record's render dir — the shared gallery file
+ // is never touched): key a solid background out, and/or centre the subject on a
+ // square canvas so its extremities get margin. Both opt-in — keying because
+ // handing the pipeline an alpha channel makes it consume that INSTEAD OF running
+ // its own learned matte, framing because resampling a source that is already
+ // well-framed only costs detail. See sourceKeying.js. Runs BEFORE the heavy-job
+ // claim: it is CPU-only preprocessing, so other heavy jobs shouldn't queue behind
+ // it and resident models shouldn't be evicted for it. Best-effort: a preparation
+ // failure must never fail a render the model could still attempt raw.
+ const needsPreparedSource = keyBackground || subjectScale < 1;
+ const prepared = needsPreparedSource
+ ? await prepareSourceImage({
+ sourcePath, targetPath: preparedSourcePath(id), keyBackground, subjectScale,
+ })
.catch((err) => {
- console.error(`❌ Image-to-3D background keying failed for ${id}: ${err.message}`);
+ console.error(`❌ Image-to-3D source preparation failed for ${id}: ${err.message}`);
return null;
})
: null;
- if (keyedPath) console.log(`🎨 Image-to-3D keyed a solid background for ${id}`);
+ if (prepared?.keyed) console.log(`🎨 Image-to-3D keyed a solid background for ${id}`);
+ if (prepared?.framed) console.log(`🖼️ Image-to-3D framed ${id} at ${subjectScale} of the canvas`);
// Record what the render actually consumed (best-effort, like percent below).
- patchRun(id, operationId, { sourceKeyed: Boolean(keyedPath) });
+ patchRun(id, operationId, {
+ sourceKeyed: Boolean(prepared?.keyed),
+ sourceFramed: Boolean(prepared?.framed),
+ });
heavyClaim = await claimHeavyLocalJob({ kind: 'image-to-3D generation', id: operationId });
if (!heavyClaim.ok) {
throw new ServerError(heavyClaim.message, { status: 409, code: 'HEAVY_LOCAL_JOB_BUSY', context: { holder: heavyClaim.holder } });
@@ -196,7 +209,7 @@ async function executeRender({ id, operationId, adapter, sourcePath, caps, optio
// the kill handle so deleteModel can SIGTERM this render if the record is deleted
// mid-flight.
const { promise, kill } = adapter.run({
- imagePath: keyedPath ?? sourcePath,
+ imagePath: prepared?.path ?? sourcePath,
outputPath,
env,
// The per-run sampler knobs resolved in beginRender: `seed` is always a
@@ -308,7 +321,7 @@ export async function createModel(input, { caps } = {}) {
// render — createModel and startGeneration share `beginRender`, so the create
// path does NOT re-resolve the gallery image, re-assert readiness, or re-fetch
// the row it just wrote. `input` carries the optional per-run knobs
- // (steps/seed/keyBackground); beginRender normalizes them.
+ // (steps/seed/keyBackground/subjectScale); beginRender normalizes them.
return beginRender(created, adapter, sourcePath, hostCaps, input);
}
@@ -373,6 +386,7 @@ async function beginRender(record, adapter, sourcePath, caps, requestOptions) {
steps: options.steps,
seed: options.seed,
keyBackground: options.keyBackground,
+ subjectScale: options.subjectScale,
// Recorded so the detail view can render the knobs this run actually
// used — and so the viewer knows whether transparency was requested,
// which decides if its force-opaque pass should apply.
diff --git a/server/services/imageTo3d/models.test.js b/server/services/imageTo3d/models.test.js
index e2ceb1c609..1ca63c62ca 100644
--- a/server/services/imageTo3d/models.test.js
+++ b/server/services/imageTo3d/models.test.js
@@ -418,7 +418,9 @@ describe('render options and source keying', () => {
});
it('a keyed source image is what the render consumes', async () => {
- prepareSourceImage.mockImplementation(async ({ targetPath }) => targetPath);
+ prepareSourceImage.mockImplementation(async ({ targetPath }) => ({
+ path: targetPath, keyed: true, framed: false,
+ }));
await createModel({ name: 'Beacon', filename: 'example.png', keyBackground: true });
await vi.waitFor(() => expect(current.status).toBe('ready'));
diff --git a/server/services/imageTo3d/renderOptions.js b/server/services/imageTo3d/renderOptions.js
index 150672f415..929f280f8a 100644
--- a/server/services/imageTo3d/renderOptions.js
+++ b/server/services/imageTo3d/renderOptions.js
@@ -22,6 +22,9 @@
* - `normalMap: false` (the default) → skip the normal-map bake. Opt in to recover
* shading detail the decimation discards, accepting the hard-crash risk noted
* below.
+ * - `subjectScale: 1` (the default) → hand the pipeline the source at its own
+ * framing. Below 1, centre the subject on a square canvas at that fraction so a
+ * pose that runs to the edge gains margin around its extremities.
*/
import { randomInt } from 'node:crypto';
@@ -87,14 +90,44 @@ export const isValidRenderSteps = (value) => intInRange(value, RENDER_STEPS_MIN,
/** Whether a value is a valid seed (null/undefined are "unset"). */
export const isValidRenderSeed = (value) => intInRange(value, 0, RENDER_SEED_MAX);
+/**
+ * Subject framing: the fraction of the square output canvas the source image is
+ * scaled to occupy, centered, before the decoder sees it.
+ *
+ * `1` is the identity — no canvas, no resize, the source passes through byte for
+ * byte — and it is the default, so no existing render changes behaviour. Below 1
+ * the source is resized so its longest side is `subjectScale x canvasSize` and
+ * composited centered on the square canvas, which is what buys a full-body pose
+ * with outstretched limbs the empty margin its extremities need to survive
+ * reconstruction: a subject running to the edge of the frame hands the decoder
+ * zero context beyond the fingertips, and fingertips are what come back clipped.
+ *
+ * The range is open at zero and closed at one: 0 would scale the subject out of
+ * existence, and above 1 would crop it, which is the failure this option exists
+ * to avoid rather than a framing anyone wants.
+ */
+export const SUBJECT_SCALE_MIN_EXCLUSIVE = 0;
+export const SUBJECT_SCALE_MAX = 1;
+export const DEFAULT_SUBJECT_SCALE = 1;
+
+/** Whether a value is a usable subject scale — a finite number in (0, 1]. */
+export const isValidSubjectScale = (value) => (
+ typeof value === 'number'
+ && Number.isFinite(value)
+ && value > SUBJECT_SCALE_MIN_EXCLUSIVE
+ && value <= SUBJECT_SCALE_MAX
+);
+
/**
* Normalize a request's options into the per-run shape. Invalid/absent values
* collapse to the unset sentinel (`null`) rather than throwing — the route
* schema is the loud gate; this is the internal-caller normalizer.
* @param {{steps?: number|null, seed?: number|null, keyBackground?: boolean,
- * detail?: string, alphaMode?: string|null, normalMap?: boolean}} [input]
+ * detail?: string, alphaMode?: string|null, normalMap?: boolean,
+ * subjectScale?: number}} [input]
* @returns {{steps: number|null, seed: number|null, keyBackground: boolean,
- * detail: string, alphaMode: string|null, normalMap: boolean}}
+ * detail: string, alphaMode: string|null, normalMap: boolean,
+ * subjectScale: number}}
*/
export function normalizeRenderOptions(input = {}) {
return {
@@ -126,6 +159,13 @@ export function normalizeRenderOptions(input = {}) {
// An earlier revision defaulted this ON and claimed it "cannot fail a render".
// That was false as written, and it was the claim the opt-out decision rested on.
normalMap: input.normalMap === true,
+ // Defaults to the identity (`1` = no reframing), so every render that predates
+ // this knob keeps handing the decoder its untouched source. Collapses to the
+ // default rather than null for the same reason `detail` collapses to 'auto': it
+ // is a real, choosable value, and a run entry recording `1` is what happened.
+ subjectScale: isValidSubjectScale(input.subjectScale)
+ ? input.subjectScale
+ : DEFAULT_SUBJECT_SCALE,
};
}
diff --git a/server/services/imageTo3d/renderOptions.parity.test.js b/server/services/imageTo3d/renderOptions.parity.test.js
index ec30f397d9..76275612aa 100644
--- a/server/services/imageTo3d/renderOptions.parity.test.js
+++ b/server/services/imageTo3d/renderOptions.parity.test.js
@@ -17,13 +17,19 @@ import {
ALPHA_MODES,
DETAIL_TIERS,
RENDER_SEED_MAX,
+ DEFAULT_SUBJECT_SCALE,
isValidRenderSteps,
+ isValidSubjectScale,
} from './renderOptions.js';
import {
ALPHA_MODE_PRESETS as CLIENT_ALPHA_MODE_PRESETS,
DETAIL_PRESETS as CLIENT_DETAIL_PRESETS,
SEED_MAX as CLIENT_SEED_MAX,
STEPS_PRESETS as CLIENT_STEPS_PRESETS,
+ SUBJECT_SCALE_DEFAULT as CLIENT_SUBJECT_SCALE_DEFAULT,
+ SUBJECT_SCALE_SLIDER_MIN as CLIENT_SUBJECT_SCALE_SLIDER_MIN,
+ SUBJECT_SCALE_SLIDER_STEP as CLIENT_SUBJECT_SCALE_SLIDER_STEP,
+ renderOptionsBody as clientRenderOptionsBody,
} from '../../../client/src/lib/imageTo3dRenderOptions.js';
describe('image-to-3D render-option parity (server bounds ↔ client mirror)', () => {
@@ -65,6 +71,27 @@ describe('image-to-3D render-option parity (server bounds ↔ client mirror)', (
expect((choices.match(/"/g) || []).length / 2).toBe(ALPHA_MODES.length);
});
+ it('the client subject-scale default is the server identity', () => {
+ // A drift here would reframe every render the user never asked to reframe.
+ expect(CLIENT_SUBJECT_SCALE_DEFAULT).toBe(DEFAULT_SUBJECT_SCALE);
+ });
+
+ it('every value the subject-scale slider can emit is one the server accepts', () => {
+ // Walk the slider's own min/step/max rather than sampling: a floating-point step
+ // that overshoots the server's closed upper bound would 400 the render only at
+ // the very end of the track, which is exactly where nobody tests by hand.
+ for (
+ let value = CLIENT_SUBJECT_SCALE_SLIDER_MIN;
+ value <= CLIENT_SUBJECT_SCALE_DEFAULT;
+ value += CLIENT_SUBJECT_SCALE_SLIDER_STEP
+ ) {
+ const emitted = clientRenderOptionsBody({
+ steps: '', seed: '', keyBackground: false, detail: 'auto', alphaMode: '', normalMap: false, subjectScale: value,
+ }).subjectScale;
+ expect(isValidSubjectScale(emitted), `slider value ${value}`).toBe(true);
+ }
+ });
+
it('every non-default client steps preset is a value the server accepts', () => {
const numeric = CLIENT_STEPS_PRESETS
.map((preset) => preset.value)
diff --git a/server/services/imageTo3d/renderOptions.test.js b/server/services/imageTo3d/renderOptions.test.js
index 9d0cb6bb8b..fba7b59f38 100644
--- a/server/services/imageTo3d/renderOptions.test.js
+++ b/server/services/imageTo3d/renderOptions.test.js
@@ -14,21 +14,24 @@ import {
DEFAULT_DETAIL_TIER,
DETAIL_TIERS,
RENDER_OPTION_KEYS,
+ DEFAULT_SUBJECT_SCALE,
+ SUBJECT_SCALE_MAX,
+ isValidSubjectScale,
} from './renderOptions.js';
describe('normalizeRenderOptions', () => {
it('defaults to unset steps/seed with keying disabled', () => {
- expect(normalizeRenderOptions()).toEqual({ steps: null, seed: null, keyBackground: false, detail: 'auto', alphaMode: null, normalMap: false });
- expect(normalizeRenderOptions({})).toEqual({ steps: null, seed: null, keyBackground: false, detail: 'auto', alphaMode: null, normalMap: false });
+ expect(normalizeRenderOptions()).toEqual({ steps: null, seed: null, keyBackground: false, detail: 'auto', alphaMode: null, normalMap: false, subjectScale: 1 });
+ expect(normalizeRenderOptions({})).toEqual({ steps: null, seed: null, keyBackground: false, detail: 'auto', alphaMode: null, normalMap: false, subjectScale: 1 });
});
it('keeps valid values and collapses invalid ones to the unset sentinel', () => {
expect(normalizeRenderOptions({ steps: 24, seed: 0, keyBackground: false }))
- .toEqual({ steps: 24, seed: 0, keyBackground: false, detail: 'auto', alphaMode: null, normalMap: false });
+ .toEqual({ steps: 24, seed: 0, keyBackground: false, detail: 'auto', alphaMode: null, normalMap: false, subjectScale: 1 });
expect(normalizeRenderOptions({ steps: RENDER_STEPS_MAX + 1, seed: RENDER_SEED_MAX + 1 }))
- .toEqual({ steps: null, seed: null, keyBackground: false, detail: 'auto', alphaMode: null, normalMap: false });
+ .toEqual({ steps: null, seed: null, keyBackground: false, detail: 'auto', alphaMode: null, normalMap: false, subjectScale: 1 });
expect(normalizeRenderOptions({ steps: 12.5, seed: '42' }))
- .toEqual({ steps: null, seed: null, keyBackground: false, detail: 'auto', alphaMode: null, normalMap: false });
+ .toEqual({ steps: null, seed: null, keyBackground: false, detail: 'auto', alphaMode: null, normalMap: false, subjectScale: 1 });
});
// Pinned on its own, not just as a field of a shape assertion, so flipping the
@@ -159,6 +162,36 @@ describe('normalMap', () => {
});
});
+describe('subjectScale', () => {
+ it('defaults to the identity, so no existing render is reframed', () => {
+ // The whole opt-in premise: reframing resamples the source, which costs detail.
+ // A run that never asked for it must reach the decoder untouched.
+ expect(normalizeRenderOptions().subjectScale).toBe(DEFAULT_SUBJECT_SCALE);
+ expect(DEFAULT_SUBJECT_SCALE).toBe(SUBJECT_SCALE_MAX);
+ });
+
+ it.each([0.35, 0.5, 0.65, 0.999, 1])('keeps the in-range value %s', (value) => {
+ expect(normalizeRenderOptions({ subjectScale: value }).subjectScale).toBe(value);
+ });
+
+ it.each([0, -0.5, 1.0001, 2, NaN, Infinity, '0.65', null, {}])(
+ 'collapses the out-of-range value %s to the identity',
+ (bad) => {
+ // Open at zero (0 scales the subject out of existence) and closed at one
+ // (above 1 CROPS, which is the failure this knob exists to avoid).
+ expect(normalizeRenderOptions({ subjectScale: bad }).subjectScale)
+ .toBe(DEFAULT_SUBJECT_SCALE);
+ },
+ );
+
+ it('validates the boundary itself', () => {
+ expect(isValidSubjectScale(0)).toBe(false);
+ expect(isValidSubjectScale(Number.MIN_VALUE)).toBe(true);
+ expect(isValidSubjectScale(1)).toBe(true);
+ expect(isValidSubjectScale(1.000001)).toBe(false);
+ });
+});
+
describe('RENDER_OPTION_KEYS', () => {
it('matches exactly what normalizeRenderOptions returns', () => {
expect(RENDER_OPTION_KEYS).toEqual(Object.keys(normalizeRenderOptions()));
diff --git a/server/services/imageTo3d/sourceKeying.js b/server/services/imageTo3d/sourceKeying.js
index 1626ea4d40..988601457e 100644
--- a/server/services/imageTo3d/sourceKeying.js
+++ b/server/services/imageTo3d/sourceKeying.js
@@ -16,10 +16,18 @@
* false and this module runs only when a run asks for it.
*
* The pixel work is pure (raw RGBA buffers in/out) so it's unit-testable on tiny
- * synthetic images; `prepareSourceImage` is the one sharp/file boundary. The keyed
+ * synthetic images; `prepareSourceImage` is the one sharp/file boundary. The prepared
* copy is written into the RECORD's render directory — the shared gallery file is
* never mutated (other features reference it).
*
+ * The same boundary also owns the OTHER opt-in source preprocessing step, subject
+ * framing (`subjectScale`): centring the subject on a square canvas at a fraction of
+ * its size, so a full-body pose with outstretched limbs reaches the decoder with
+ * empty margin beyond its extremities instead of running to the edge of the frame.
+ * Extremities with no margin are what come back clipped or fused. It shares this
+ * function because it shares the decode, the record-local output file, and the cache
+ * — and because it must run AFTER keying, never before (see `prepareSourceImage`).
+ *
* A deliberately simpler edge model than the sprites lane's chroma unmix
* (`services/sprites/chromaKey.js`): that lane reverses source-over compositing
* against a known pure-channel key; this one only needs "background gone, 1px
@@ -48,9 +56,11 @@ import sharp from 'sharp';
import {
hasMeaningfulAlpha as hasMeaningfulAlphaShared,
} from '../../lib/borderKey.js';
+import { DEFAULT_SUBJECT_SCALE, isValidSubjectScale } from './renderOptions.js';
import { atomicWrite, readJSONFile, sha256File } from '../../lib/fileUtils.js';
import { decodeRgbaFrame, encodePng } from '../../lib/imageRgba.js';
import {
+ detectSolidBorderColor,
KEY_TOLERANCE,
KEY_TIGHT_TOLERANCE,
KEY_MIN_BORDER_COVERAGE,
@@ -80,8 +90,16 @@ export const KEY_MAX_PIXELS = 16_000_000;
// Bump the leading version when the kernel changes. The numeric inputs are
// included so changing a tolerance invalidates fresh keyed output without
// relying on a developer to remember a second, separate cache edit.
+//
+// v2: the prepared source is now key-then-frame rather than key-only, and the
+// decode honours EXIF orientation — both change the bytes for the same input, so
+// every v1 artifact has to be recomputed. The framing SCALE is per-run rather
+// than a module constant, so it cannot ride in this string; it is written into
+// the cache metadata beside the version and compared there (see
+// `freshPreparedSource`), which is what stops a re-render at a new scale from
+// silently reusing the previously prepared image.
export const KEYING_CACHE_VERSION = [
- 'source-keying-v1',
+ 'source-keying-v2',
KEY_TOLERANCE,
KEY_TIGHT_TOLERANCE,
KEY_MIN_BORDER_COVERAGE,
@@ -130,56 +148,176 @@ const runKeySolidBackground = (frame) => {
});
};
-const keyedCacheMetadataPath = (targetPath) => `${targetPath}.meta.json`;
+const preparedCacheMetadataPath = (targetPath) => `${targetPath}.meta.json`;
+
+/** The neutral pad colour for an opaque source whose own border isn't solid. */
+const FRAME_FALLBACK_BACKGROUND = [255, 255, 255];
+
+const padColor = ([r, g, b]) => ({ r, g, b, alpha: 1 });
+
+/**
+ * Where a source lands on the square subject-framing canvas.
+ *
+ * The canvas is the source's LONGEST side, so framing never upsamples: the
+ * subject is scaled down to `subjectScale` of that and centred, and the margin is
+ * the remainder. A landscape and a portrait source of the same longest side
+ * therefore produce the same canvas and the same margin beyond the subject's
+ * extremities, which is the whole point — the decoder wants context past the
+ * fingertips, not a particular output resolution.
+ *
+ * Pure (numbers in, numbers out) so the arithmetic is unit-testable without sharp.
+ * Both dimensions floor at 1px: a scale small enough to round a thin source's short
+ * side to zero would otherwise hand sharp an invalid resize.
+ *
+ * @param {{width: number, height: number, subjectScale: number}} opts
+ * @returns {{canvasSize: number, innerWidth: number, innerHeight: number, left: number, top: number}}
+ */
+export function subjectFrameLayout({ width, height, subjectScale }) {
+ const canvasSize = Math.max(width, height);
+ const innerWidth = Math.max(1, Math.round(width * subjectScale));
+ const innerHeight = Math.max(1, Math.round(height * subjectScale));
+ return {
+ canvasSize,
+ innerWidth,
+ innerHeight,
+ left: Math.round((canvasSize - innerWidth) / 2),
+ top: Math.round((canvasSize - innerHeight) / 2),
+ };
+}
+
+/**
+ * Composite an RGBA frame centred on the square framing canvas and return PNG bytes.
+ *
+ * The canvas background is the one detail that cannot be got wrong: a KEYED or
+ * already-transparent source must not gain an opaque backdrop (that would undo the
+ * matte the pipeline is about to consume), and an ordinary photo must not gain a
+ * transparent one (TRELLIS.2 reads any non-opaque alpha as "already matted" and
+ * skips RMBG-2.0, so a transparent pad would silently disable its own background
+ * removal — exactly the trap `keyBackground` documents). For the opaque case the
+ * pad takes the source's own measured border colour when it has one, so the added
+ * margin is indistinguishable from the background already there.
+ */
+async function frameSubject(frame, { subjectScale, transparent }) {
+ const layout = subjectFrameLayout({ width: frame.width, height: frame.height, subjectScale });
+ const resized = await sharp(frame.data, {
+ raw: { width: frame.width, height: frame.height, channels: 4 },
+ })
+ // Explicit target dimensions, already aspect-derived above — `fill` just honors
+ // them rather than re-deriving a fit, so the layout math has a single owner.
+ .resize(layout.innerWidth, layout.innerHeight, { fit: 'fill' })
+ .raw()
+ .toBuffer();
+ const background = transparent
+ ? { r: 0, g: 0, b: 0, alpha: 0 }
+ : padColor(detectSolidBorderColor(frame) ?? FRAME_FALLBACK_BACKGROUND);
+ return sharp({
+ create: {
+ width: layout.canvasSize, height: layout.canvasSize, channels: 4, background,
+ },
+ })
+ .composite([{
+ input: resized,
+ raw: { width: layout.innerWidth, height: layout.innerHeight, channels: 4 },
+ left: layout.left,
+ top: layout.top,
+ }])
+ .png()
+ .toBuffer();
+}
-const hasFreshKeyedSource = async (sourcePath, targetPath) => {
+const freshPreparedSource = async (sourcePath, targetPath, request) => {
const sourceStats = await stat(sourcePath);
const targetStats = await stat(targetPath).catch(() => null);
- if (!targetStats?.isFile() || targetStats.mtimeMs <= sourceStats.mtimeMs) return false;
+ if (!targetStats?.isFile() || targetStats.mtimeMs <= sourceStats.mtimeMs) return null;
- const metadata = await readJSONFile(keyedCacheMetadataPath(targetPath), null, { logError: false });
- if (metadata?.version !== KEYING_CACHE_VERSION || !metadata.sourceSha256) return false;
- return metadata.sourceSha256 === await sha256File(sourcePath);
+ const metadata = await readJSONFile(preparedCacheMetadataPath(targetPath), null, { logError: false });
+ if (metadata?.version !== KEYING_CACHE_VERSION || !metadata.sourceSha256) return null;
+ // The per-run framing/keying request is part of the cache identity: the same
+ // source at a different subjectScale is a DIFFERENT prepared image.
+ if (metadata.keyBackground !== request.keyBackground) return null;
+ if (metadata.subjectScale !== request.subjectScale) return null;
+ if (metadata.sourceSha256 !== await sha256File(sourcePath)) return null;
+ return { path: targetPath, keyed: metadata.keyed === true, framed: metadata.framed === true };
};
/**
- * Resolve whether a render should consume a keyed copy of its source. Reads
- * `sourcePath`; when it has no meaningful alpha and sits on a solid background,
- * writes a keyed PNG to `targetPath` and returns that path. Returns null in
- * every non-keyable case (real alpha already present — the pipeline uses it
- * directly — or no solid background, or the sanity gates tripped): the caller
- * renders the original.
+ * Resolve whether a render should consume a PREPARED copy of its source, and
+ * write one when it should.
+ *
+ * Two independent, independently-opt-in steps, in this order:
+ * 1. `keyBackground` — flood-fill a solid backdrop to transparency (see the
+ * module header for why that is opt-in and usually a downgrade).
+ * 2. `subjectScale < 1` — centre the result on a square canvas at that fraction
+ * so extremities gain margin (see `frameSubject`).
*
- * I/O failures (unreadable file) reject; the caller treats keying as
- * best-effort (a keying failure must never fail a render the model could still
+ * ORDER MATTERS and is not interchangeable: reframing first would move the border
+ * pixels the flood fill samples, so the keyer's own "is this background solid"
+ * gate would be measuring the pad colour instead of the image's.
+ *
+ * Returns null in every case where the render should consume the ORIGINAL: neither
+ * step was requested, the source is too large to process affordably, or keying was
+ * asked for and declined (real alpha already present — the pipeline uses it
+ * directly — or no solid background, or the sanity gates tripped) with no framing
+ * to do either.
+ *
+ * I/O failures (unreadable file) reject; the caller treats preparation as
+ * best-effort (a failure here must never fail a render the model could still
* attempt on the raw image).
*
- * @param {{sourcePath: string, targetPath: string}} opts
- * @returns {Promise<string|null>} the keyed image path, or null to use the original
+ * @param {{sourcePath: string, targetPath: string, keyBackground?: boolean,
+ * subjectScale?: number}} opts
+ * @returns {Promise<{path: string, keyed: boolean, framed: boolean}|null>}
*/
-export async function prepareSourceImage({ sourcePath, targetPath }) {
- if (await hasFreshKeyedSource(sourcePath, targetPath)) return targetPath;
+export async function prepareSourceImage({
+ sourcePath,
+ targetPath,
+ keyBackground = true,
+ subjectScale = DEFAULT_SUBJECT_SCALE,
+}) {
+ const scale = isValidSubjectScale(subjectScale) ? subjectScale : DEFAULT_SUBJECT_SCALE;
+ const wantsFraming = scale < DEFAULT_SUBJECT_SCALE;
+ const wantsKeying = keyBackground === true;
+ if (!wantsKeying && !wantsFraming) return null;
+
+ const request = { keyBackground: wantsKeying, subjectScale: scale };
+ const cached = await freshPreparedSource(sourcePath, targetPath, request);
+ if (cached) return cached;
// Header-only probe: bail before the full decode when the source is too
- // large to key affordably (KEY_MAX_PIXELS), and when it has no alpha channel
+ // large to process affordably (KEY_MAX_PIXELS), and when it has no alpha channel
// at all, skip the full-buffer meaningful-alpha scan below (ensureAlpha
// fabricates the channel).
const { hasAlpha, width, height } = await sharp(sourcePath).metadata();
if (!width || !height || width * height > KEY_MAX_PIXELS) return null;
- const frame = await decodeRgbaFrame(sourcePath);
- if (hasAlpha && hasMeaningfulAlpha(frame.data)) return null;
- const result = await runKeySolidBackground(frame);
- if (!result) return null;
- await atomicWrite(targetPath, await encodePng({
- data: result.data,
- width: frame.width,
- height: frame.height,
- }));
- await atomicWrite(keyedCacheMetadataPath(targetPath), {
+ // Measure AFTER EXIF transposition: raw pixels carry no orientation tag and the
+ // PNG written below records none, so a rotated source framed on its stored
+ // dimensions would be both mis-measured and handed to the decoder sideways.
+ const frame = await decodeRgbaFrame(sourcePath, { autoOrient: true });
+ const sourceHasAlpha = hasAlpha === true && hasMeaningfulAlpha(frame.data);
+
+ const keyed = wantsKeying && !sourceHasAlpha ? await runKeySolidBackground(frame) : null;
+ const current = keyed
+ ? { data: keyed.data, width: frame.width, height: frame.height }
+ : frame;
+ const framed = wantsFraming
+ ? await frameSubject(current, {
+ subjectScale: scale,
+ // A keyed or natively-transparent subject pads transparent; anything else
+ // pads opaque, so the pipeline's own matting still runs.
+ transparent: Boolean(keyed) || sourceHasAlpha,
+ })
+ : null;
+ if (!keyed && !framed) return null;
+
+ await atomicWrite(targetPath, framed ?? await encodePng(current));
+ await atomicWrite(preparedCacheMetadataPath(targetPath), {
version: KEYING_CACHE_VERSION,
sourceSha256: await sha256File(sourcePath),
+ ...request,
+ keyed: Boolean(keyed),
+ framed: Boolean(framed),
}).catch((error) => {
- console.error(`❌ Image-to-3D keying cache metadata failed for ${targetPath}: ${error.message}`);
+ console.error(`❌ Image-to-3D source cache metadata failed for ${targetPath}: ${error.message}`);
});
- return targetPath;
+ return { path: targetPath, keyed: Boolean(keyed), framed: Boolean(framed) };
}
diff --git a/server/services/imageTo3d/sourceKeying.test.js b/server/services/imageTo3d/sourceKeying.test.js
index 8dc97f288c..7a6bc345b9 100644
--- a/server/services/imageTo3d/sourceKeying.test.js
+++ b/server/services/imageTo3d/sourceKeying.test.js
@@ -9,6 +9,7 @@ import {
keySolidBackground,
KEYING_CACHE_VERSION,
prepareSourceImage,
+ subjectFrameLayout,
} from './sourceKeying.js';
import { sha256File } from '../../lib/fileUtils.js';
@@ -143,7 +144,7 @@ describe('prepareSourceImage', () => {
const sourcePath = await writePng('green.png', subjectOnGreen());
const targetPath = join(await tempDir(), 'keyed.png');
const result = await prepareSourceImage({ sourcePath, targetPath });
- expect(result).toBe(targetPath);
+ expect(result).toEqual({ path: targetPath, keyed: true, framed: false });
const { data, info } = await sharp(targetPath).ensureAlpha().raw()
.toBuffer({ resolveWithObject: true });
@@ -177,12 +178,16 @@ describe('prepareSourceImage', () => {
await writeFile(`${cachedTarget}.meta.json`, JSON.stringify({
version: KEYING_CACHE_VERSION,
sourceSha256,
+ keyBackground: true,
+ subjectScale: 1,
+ keyed: true,
+ framed: false,
}));
const fresh = new Date(Date.now() + 60_000);
await utimes(cachedTarget, fresh, fresh);
const result = await prepareSourceImage({ sourcePath, targetPath: cachedTarget });
- expect(result).toBe(cachedTarget);
+ expect(result).toEqual({ path: cachedTarget, keyed: true, framed: false });
const { data } = await sharp(cachedTarget).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
expect([...data.slice(0, 4)]).toEqual([255, 0, 0, 255]);
});
@@ -193,6 +198,10 @@ describe('prepareSourceImage', () => {
await writeFile(`${cachedTarget}.meta.json`, JSON.stringify({
version: KEYING_CACHE_VERSION,
sourceSha256: await sha256File(sourcePath),
+ keyBackground: true,
+ subjectScale: 1,
+ keyed: true,
+ framed: false,
}));
const targetTime = new Date(Date.now() + 60_000);
await utimes(cachedTarget, targetTime, targetTime);
@@ -204,7 +213,7 @@ describe('prepareSourceImage', () => {
await utimes(sourcePath, oldSourceTime, oldSourceTime);
const result = await prepareSourceImage({ sourcePath, targetPath: cachedTarget });
- expect(result).toBe(cachedTarget);
+ expect(result).toEqual({ path: cachedTarget, keyed: true, framed: false });
const { data } = await sharp(cachedTarget).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
expect(alphaAt({ data, width: 20, height: 20 }, 0, 0)).toBe(0);
expect(JSON.parse(await readFile(`${cachedTarget}.meta.json`, 'utf8')).sourceSha256)
@@ -219,10 +228,226 @@ describe('prepareSourceImage', () => {
await utimes(targetPath, fresh, fresh);
const result = await prepareSourceImage({ sourcePath, targetPath });
- expect(result).toBe(targetPath);
+ expect(result).toEqual({ path: targetPath, keyed: true, framed: false });
const { data } = await sharp(targetPath).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
expect(alphaAt({ data, width: 20, height: 20 }, 0, 0)).toBe(0);
+ expect(JSON.parse(await readFile(`${targetPath}.meta.json`, 'utf8'))).toEqual({
+ version: KEYING_CACHE_VERSION,
+ sourceSha256: await sha256File(sourcePath),
+ keyBackground: true,
+ subjectScale: 1,
+ keyed: true,
+ framed: false,
+ });
+ });
+});
+
+describe('subjectFrameLayout', () => {
+ // The margin is the whole product outcome: a subject at 65% of a square canvas
+ // leaves ~17.5% of the canvas empty beyond each of its extremities, which is the
+ // context the decoder needs to resolve a fingertip instead of clipping it.
+ it('centers a landscape source on a canvas of its longest side', () => {
+ expect(subjectFrameLayout({ width: 100, height: 50, subjectScale: 0.6 })).toEqual({
+ canvasSize: 100, innerWidth: 60, innerHeight: 30, left: 20, top: 35,
+ });
+ });
+
+ it('centers a portrait source with the same margins, transposed', () => {
+ expect(subjectFrameLayout({ width: 50, height: 100, subjectScale: 0.6 })).toEqual({
+ canvasSize: 100, innerWidth: 30, innerHeight: 60, left: 35, top: 20,
+ });
+ });
+
+ it('never upsamples — the canvas is the source’s longest side, not a fixed size', () => {
+ const { canvasSize, innerWidth } = subjectFrameLayout({ width: 37, height: 12, subjectScale: 1 });
+ expect(canvasSize).toBe(37);
+ expect(innerWidth).toBe(37);
+ });
+
+ it('floors both dimensions at 1px so a thin source can’t produce an invalid resize', () => {
+ // 4 x 0.05 rounds to 0, which sharp rejects outright.
+ expect(subjectFrameLayout({ width: 400, height: 4, subjectScale: 0.05 }))
+ .toMatchObject({ innerWidth: 20, innerHeight: 1 });
+ });
+});
+
+describe('prepareSourceImage subject framing', () => {
+ let dir;
+ const tempDir = async () => {
+ dir = dir || await mkdtemp(join(tmpdir(), 'portos-framing-'));
+ return dir;
+ };
+ afterAll(async () => { if (dir) await rm(dir, { recursive: true, force: true }); });
+
+ const writePng = async (name, image) => {
+ const path = join(await tempDir(), name);
+ await sharp(Buffer.from(image.data), {
+ raw: { width: image.width, height: image.height, channels: 4 },
+ }).png().toFile(path);
+ return path;
+ };
+
+ const readRgba = async (path) => {
+ const { data, info } = await sharp(path).ensureAlpha().raw()
+ .toBuffer({ resolveWithObject: true });
+ return { data, width: info.width, height: info.height };
+ };
+
+ const pixelAt = (image, x, y) => {
+ const i = (y * image.width + x) * 4;
+ return [image.data[i], image.data[i + 1], image.data[i + 2], image.data[i + 3]];
+ };
+
+ // A 40x20 landscape photo-like source: no alpha, and a busy border so keying
+ // would decline it even if it were asked for.
+ const landscapePhoto = () => makeImage(40, 20, (x, y) => [
+ (x * 37 + y * 91) % 256, (x * 13 + y * 7) % 256, (x * 71 + y * 3) % 256,
+ ]);
+
+ it('is a pass-through at the default scale with keying off — the original is used', async () => {
+ // The strongest form of "byte-identical": nothing is written at all, so the
+ // render consumes the untouched gallery file.
+ const sourcePath = await writePng('identity.png', landscapePhoto());
+ const targetPath = join(await tempDir(), 'identity-out.png');
+ expect(await prepareSourceImage({
+ sourcePath, targetPath, keyBackground: false, subjectScale: 1,
+ })).toBeNull();
+ await expect(readFile(targetPath)).rejects.toThrow();
+ });
+
+ it.each([0, 1.5, -0.2, NaN, '0.5', null])(
+ 'treats the out-of-range scale %s as the identity rather than framing on it',
+ async (bad) => {
+ const sourcePath = await writePng(`bad-${String(bad)}.png`, landscapePhoto());
+ expect(await prepareSourceImage({
+ sourcePath,
+ targetPath: join(await tempDir(), `bad-${String(bad)}-out.png`),
+ keyBackground: false,
+ subjectScale: bad,
+ })).toBeNull();
+ },
+ );
+
+ it('frames an opaque source on a square canvas without keying it', async () => {
+ const sourcePath = await writePng('frame-opaque.png', landscapePhoto());
+ const targetPath = join(await tempDir(), 'frame-opaque-out.png');
+ const result = await prepareSourceImage({
+ sourcePath, targetPath, keyBackground: false, subjectScale: 0.5,
+ });
+ expect(result).toEqual({ path: targetPath, keyed: false, framed: true });
+
+ const framed = await readRgba(targetPath);
+ // Canvas = the source's longest side (40), subject 20x10 centered at (10, 15).
+ expect([framed.width, framed.height]).toEqual([40, 40]);
+ // An opaque source must stay opaque: a transparent pad would read to TRELLIS.2
+ // as "already matted" and silently disable its own background removal.
+ expect(pixelAt(framed, 0, 0)[3]).toBe(255);
+ expect(pixelAt(framed, 20, 20)[3]).toBe(255);
+ // The margin is real: the corners are pad, not subject.
+ expect(pixelAt(framed, 1, 1).slice(0, 3)).toEqual([255, 255, 255]);
+ });
+
+ it('pads with the source’s own solid border color, so the margin is invisible', async () => {
+ const sourcePath = await writePng('frame-green.png', subjectOnGreen());
+ const targetPath = join(await tempDir(), 'frame-green-out.png');
+ const result = await prepareSourceImage({
+ sourcePath, targetPath, keyBackground: false, subjectScale: 0.5,
+ });
+ expect(result).toEqual({ path: targetPath, keyed: false, framed: true });
+ const framed = await readRgba(targetPath);
+ expect(pixelAt(framed, 0, 0)).toEqual([...GREEN, 255]);
+ });
+
+ it('preserves alpha for an alpha-bearing source and pads transparent', async () => {
+ // A transparent source is already matted, so keying declines it — but framing
+ // still applies, and the pad MUST stay transparent or the matte is undone.
+ const withAlpha = makeImage(20, 20, (x, y) => (
+ x >= 5 && x < 15 && y >= 5 && y < 15 ? [...BROWN, 255] : [0, 0, 0, 0]
+ ));
+ const sourcePath = await writePng('frame-alpha.png', withAlpha);
+ const targetPath = join(await tempDir(), 'frame-alpha-out.png');
+ const result = await prepareSourceImage({
+ sourcePath, targetPath, keyBackground: true, subjectScale: 0.5,
+ });
+ expect(result).toEqual({ path: targetPath, keyed: false, framed: true });
+
+ const framed = await readRgba(targetPath);
+ expect([framed.width, framed.height]).toEqual([20, 20]);
+ expect(pixelAt(framed, 0, 0)[3]).toBe(0);
+ // Subject center: the 10x10 block resized to 5x5 and centered at (5, 5). Near-
+ // rather than fully-opaque because a 2x downscale of a hard alpha edge on a
+ // 5px block resamples some of the transparent surround into it — the contrast
+ // that matters is against the fully-transparent pad above.
+ expect(pixelAt(framed, 10, 10)[3]).toBeGreaterThan(200);
+ });
+
+ it('keys first and frames second, so the flood fill still samples the real border', async () => {
+ // Order is not interchangeable: framing first would move the border pixels the
+ // keyer measures, and its "is this background solid" gate would be reading the
+ // pad color instead of the image's.
+ const sourcePath = await writePng('key-then-frame.png', subjectOnGreen());
+ const targetPath = join(await tempDir(), 'key-then-frame-out.png');
+ const result = await prepareSourceImage({
+ sourcePath, targetPath, keyBackground: true, subjectScale: 0.5,
+ });
+ expect(result).toEqual({ path: targetPath, keyed: true, framed: true });
+
+ const framed = await readRgba(targetPath);
+ // Keyed → the pad joins the keyed background as transparent, subject stays opaque.
+ expect(pixelAt(framed, 0, 0)[3]).toBe(0);
+ expect(pixelAt(framed, 10, 10)[3]).toBeGreaterThan(200);
+ });
+
+ it('measures an EXIF-rotated source after transposition', async () => {
+ // Stored 40x20 (left half red, right half blue) with orientation 6 — a 90° CW
+ // display rotation, so the viewer sees 20x40 with red on TOP. Framing on the
+ // STORED dimensions would put the subject in a landscape band and leave the
+ // sampled points below on empty pad, and the PNG written here carries no
+ // orientation tag of its own to fix it downstream.
+ const sourcePath = join(await tempDir(), 'exif.jpg');
+ await sharp(Buffer.from(makeImage(40, 20, (x) => (x < 20 ? [220, 20, 20] : [20, 20, 220])).data), {
+ raw: { width: 40, height: 20, channels: 4 },
+ }).withMetadata({ orientation: 6 }).jpeg({ quality: 100 }).toFile(sourcePath);
+
+ const targetPath = join(await tempDir(), 'exif-out.png');
+ const result = await prepareSourceImage({
+ sourcePath, targetPath, keyBackground: false, subjectScale: 0.5,
+ });
+ expect(result).toEqual({ path: targetPath, keyed: false, framed: true });
+
+ const framed = await readRgba(targetPath);
+ expect([framed.width, framed.height]).toEqual([40, 40]);
+ // Subject 10x20 centered at (15, 10): red in its top half, blue in its bottom.
+ const [topR, , topB] = pixelAt(framed, 20, 13);
+ const [botR, , botB] = pixelAt(framed, 20, 27);
+ expect(topR).toBeGreaterThan(topB);
+ expect(botB).toBeGreaterThan(botR);
+ });
+
+ it('re-frames rather than reusing the cache when the scale changes', async () => {
+ // KEYING_CACHE_VERSION alone cannot carry a PER-RUN parameter, so the framing
+ // request is part of the cache identity in the metadata. Without this a
+ // re-render at a new scale silently serves the previously prepared image.
+ const sourcePath = await writePng('cache-scale.png', landscapePhoto());
+ const targetPath = join(await tempDir(), 'cache-scale-out.png');
+
+ await prepareSourceImage({ sourcePath, targetPath, keyBackground: false, subjectScale: 0.5 });
+ const first = await readFile(targetPath);
+ expect(JSON.parse(await readFile(`${targetPath}.meta.json`, 'utf8'))).toMatchObject({
+ version: KEYING_CACHE_VERSION, keyBackground: false, subjectScale: 0.5, framed: true,
+ });
+
+ await prepareSourceImage({ sourcePath, targetPath, keyBackground: false, subjectScale: 0.8 });
+ expect(await readFile(targetPath)).not.toEqual(first);
expect(JSON.parse(await readFile(`${targetPath}.meta.json`, 'utf8')))
- .toEqual({ version: KEYING_CACHE_VERSION, sourceSha256: await sha256File(sourcePath) });
+ .toMatchObject({ subjectScale: 0.8 });
+
+ // And the SAME request is still served from cache — the identity check must not
+ // have degenerated into "always recompute".
+ const fresh = new Date(Date.now() + 60_000);
+ await utimes(targetPath, fresh, fresh);
+ const cached = await readFile(targetPath);
+ await prepareSourceImage({ sourcePath, targetPath, keyBackground: false, subjectScale: 0.8 });
+ expect(await readFile(targetPath)).toEqual(cached);
});
});