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

bake a normal map from the pre-decimation mesh so shading keeps discarded detail

Adam Eivy3a4c11afe74f
diff --git a/client/src/components/media/ImageTo3dRenderOptions.jsx b/client/src/components/media/ImageTo3dRenderOptions.jsx
index 976d73a998..d43d3c6e21 100644
--- a/client/src/components/media/ImageTo3dRenderOptions.jsx
+++ b/client/src/components/media/ImageTo3dRenderOptions.jsx
@@ -41,10 +41,13 @@ export default function ImageTo3dRenderOptions({
onDetailChange,
alphaMode = '',
onAlphaModeChange,
+ normalMap = true,
+ onNormalMapChange,
disabled = false,
stepsSupported = true,
detailSupported = true,
alphaModeSupported = true,
+ normalMapSupported = true,
}) {
return (
<div className="flex flex-col gap-2">
@@ -125,16 +128,37 @@ export default function ImageTo3dRenderOptions({
/>
</FormField>
<div className="flex items-end pb-1.5">
- <label className="inline-flex cursor-pointer items-center gap-2 text-xs text-gray-300">
- <input
- type="checkbox"
- checked={keyBackground}
- onChange={(e) => onKeyBackgroundChange(e.target.checked)}
- disabled={disabled}
- className="h-3.5 w-3.5 rounded border-port-border bg-port-bg accent-port-accent disabled:opacity-40"
- />
- Key out solid background
- </label>
+ <div className="flex flex-col gap-1.5">
+ <label className="inline-flex cursor-pointer items-center gap-2 text-xs text-gray-300">
+ <input
+ type="checkbox"
+ checked={keyBackground}
+ onChange={(e) => onKeyBackgroundChange(e.target.checked)}
+ disabled={disabled}
+ className="h-3.5 w-3.5 rounded border-port-border bg-port-bg accent-port-accent disabled:opacity-40"
+ />
+ Key out solid background
+ </label>
+ {/* Defaults on: it recovers shading detail the bake decimation discards
+ for ~2s on a multi-minute render, and cannot fail the render. The
+ control exists so a bad map is recoverable, not because it is a
+ routine choice. */}
+ <label
+ className="inline-flex cursor-pointer items-center gap-2 text-xs text-gray-300"
+ title={normalMapSupported
+ ? 'Bake a normal map from the full-resolution mesh so lighting keeps detail the exported triangles no longer carry'
+ : 'This model does not bake a normal map'}
+ >
+ <input
+ type="checkbox"
+ checked={normalMapSupported ? normalMap : false}
+ onChange={(e) => onNormalMapChange(e.target.checked)}
+ disabled={disabled || !normalMapSupported}
+ className="h-3.5 w-3.5 rounded border-port-border bg-port-bg accent-port-accent disabled:opacity-40"
+ />
+ Bake normal map
+ </label>
+ </div>
</div>
</div>
<p className="text-xs leading-relaxed text-gray-500">
diff --git a/client/src/lib/imageTo3dRenderOptions.js b/client/src/lib/imageTo3dRenderOptions.js
index cd54453d64..cc364c2cfb 100644
--- a/client/src/lib/imageTo3dRenderOptions.js
+++ b/client/src/lib/imageTo3dRenderOptions.js
@@ -62,7 +62,7 @@ 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 }) {
+export function renderOptionsBody({ steps, seed, keyBackground, detail, alphaMode, normalMap }) {
return {
...(steps !== '' && { steps: Number(steps) }),
...(seed !== '' && { seed: Number(seed) }),
@@ -72,6 +72,9 @@ export function renderOptionsBody({ steps, seed, keyBackground, detail, alphaMod
// they are, unlike alphaMode below.
...(detail && detail !== 'auto' && { detail }),
...(alphaMode !== '' && alphaMode != null && { alphaMode }),
+ // Sent always, not omitted-when-default: the server default is TRUE, so omitting
+ // it could not express "off".
+ normalMap,
};
}
@@ -93,6 +96,8 @@ export function fieldsFromRun(run) {
// the same defaults a fresh form starts at.
detail: DETAIL_PRESETS.some((p) => p.value === run?.detail) ? run.detail : 'auto',
alphaMode: typeof run?.alphaMode === 'string' ? run.alphaMode : '',
+ // A run predating the field has none; default to on, matching the server.
+ normalMap: typeof run?.normalMap === 'boolean' ? run.normalMap : true,
};
}
diff --git a/client/src/pages/Media3D.jsx b/client/src/pages/Media3D.jsx
index 759618c98a..5302d0e6da 100644
--- a/client/src/pages/Media3D.jsx
+++ b/client/src/pages/Media3D.jsx
@@ -202,6 +202,7 @@ export default function Media3D() {
const [keyBackground, setKeyBackground] = useState(true);
const [detail, setDetail] = useState('auto');
const [alphaMode, setAlphaMode] = useState('');
+ const [normalMap, setNormalMap] = useState(true);
// 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([]);
@@ -298,7 +299,7 @@ export default function Media3D() {
name: nameFromImageFilename(selectedImage.filename),
filename: selectedImage.filename,
target: selectedTarget.id,
- ...renderOptionsBody({ steps, seed, keyBackground, detail, alphaMode }),
+ ...renderOptionsBody({ steps, seed, keyBackground, detail, alphaMode, normalMap }),
},
{ silent: true },
).catch((err) => {
@@ -406,6 +407,9 @@ export default function Media3D() {
onDetailChange={setDetail}
alphaMode={alphaMode}
onAlphaModeChange={setAlphaMode}
+ normalMapSupported={selectedTarget?.supportsRenderOptions?.normalMap !== false}
+ normalMap={normalMap}
+ onNormalMapChange={setNormalMap}
steps={steps}
onStepsChange={setSteps}
seed={seed}
diff --git a/client/src/pages/Media3DDetail.jsx b/client/src/pages/Media3DDetail.jsx
index b3389dba0d..5308af7a36 100644
--- a/client/src/pages/Media3DDetail.jsx
+++ b/client/src/pages/Media3DDetail.jsx
@@ -37,6 +37,7 @@ export default function Media3DDetail() {
const [keyBackground, setKeyBackground] = useState(true);
const [detail, setDetail] = useState('auto');
const [alphaMode, setAlphaMode] = useState('');
+ const [normalMap, setNormalMap] = useState(true);
const optionsSeededFor = useRef(null);
const load = useCallback(async ({ initial = false } = {}) => {
@@ -78,6 +79,7 @@ export default function Media3DDetail() {
setKeyBackground(fields.keyBackground);
setDetail(fields.detail);
setAlphaMode(fields.alphaMode);
+ setNormalMap(fields.normalMap);
}, [record]);
const handleRegenerate = useCallback(async () => {
@@ -85,7 +87,7 @@ export default function Media3DDetail() {
setBusy(true);
const next = await generateImageTo3dModel(
id,
- renderOptionsBody({ steps, seed, keyBackground, detail, alphaMode }),
+ renderOptionsBody({ steps, seed, keyBackground, detail, alphaMode, normalMap }),
{ silent: true },
).catch((err) => {
toast.error(err?.message || 'Could not start the render.');
@@ -189,6 +191,9 @@ export default function Media3DDetail() {
onDetailChange={setDetail}
alphaMode={alphaMode}
onAlphaModeChange={setAlphaMode}
+ normalMapSupported={record.supportsRenderOptions?.normalMap !== false}
+ normalMap={normalMap}
+ onNormalMapChange={setNormalMap}
disabled={busy || isGenerating}
/>
</div>
diff --git a/server/routes/imageTo3d.js b/server/routes/imageTo3d.js
index ad847899cd..6af2724519 100644
--- a/server/routes/imageTo3d.js
+++ b/server/routes/imageTo3d.js
@@ -37,6 +37,7 @@ const renderOptionsSchema = z.object({
// normalizer would silently discard.
detail: z.enum([...DETAIL_TIERS]).optional(),
alphaMode: z.enum([...ALPHA_MODES]).optional(),
+ normalMap: z.boolean().optional(),
});
const createModelSchema = z.object({
diff --git a/server/services/imageTo3d/models.js b/server/services/imageTo3d/models.js
index 54e55ea79c..1b3f613804 100644
--- a/server/services/imageTo3d/models.js
+++ b/server/services/imageTo3d/models.js
@@ -371,6 +371,7 @@ async function beginRender(record, adapter, sourcePath, caps, requestOptions) {
// which decides if its force-opaque pass should apply.
detail: options.detail,
alphaMode: options.alphaMode,
+ normalMap: options.normalMap,
startedAt,
completedAt: null,
error: null,
diff --git a/server/services/imageTo3d/renderOptions.js b/server/services/imageTo3d/renderOptions.js
index e309f036d8..9d4475c90d 100644
--- a/server/services/imageTo3d/renderOptions.js
+++ b/server/services/imageTo3d/renderOptions.js
@@ -17,6 +17,8 @@
* what every lane did before the knob existed.
* - `alphaMode: null` → don't instruct the exporter, and keep PortOS's
* force-opaque normalization.
+ * - `normalMap: true` (the default) → bake a tangent-space normal map from the
+ * pre-decimation mesh, so shading keeps detail the triangles no longer carry.
*/
import { randomInt } from 'node:crypto';
@@ -87,9 +89,9 @@ export const isValidRenderSeed = (value) => intInRange(value, 0, RENDER_SEED_MAX
* 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}} [input]
+ * detail?: string, alphaMode?: string|null, normalMap?: boolean}} [input]
* @returns {{steps: number|null, seed: number|null, keyBackground: boolean,
- * detail: string, alphaMode: string|null}}
+ * detail: string, alphaMode: string|null, normalMap: boolean}}
*/
export function normalizeRenderOptions(input = {}) {
return {
@@ -102,6 +104,11 @@ export function normalizeRenderOptions(input = {}) {
// `alphaMode` stays null-when-unset, because "don't ask the exporter" is a
// genuinely different instruction from any of the concrete modes.
alphaMode: isValidAlphaMode(input.alphaMode) ? input.alphaMode : null,
+ // Defaults ON, unlike every other knob here. It recovers shading detail the bake
+ // decimation discards, measured at ~2s against a multi-minute render, and it
+ // cannot fail a render (the bake is wrapped and degrades to no map). So the
+ // useful default is on, with this as the escape hatch if a map ever looks wrong.
+ normalMap: input.normalMap !== false,
};
}
@@ -166,7 +173,8 @@ export function validateRenderOptions(label, { steps = null, seed = null } = {})
* everything is honored, so existing targets need no entry.
*
* @param {object} options
- * @param {{steps?: boolean, detail?: boolean, alphaMode?: boolean}} [support]
+ * @param {{steps?: boolean, detail?: boolean, alphaMode?: boolean,
+ * normalMap?: boolean}} [support]
* @returns {object}
*/
export function honorTargetRenderSupport(options, support) {
@@ -179,5 +187,6 @@ export function honorTargetRenderSupport(options, support) {
// subprocess never received.
...(support.detail === false ? { detail: DEFAULT_DETAIL_TIER } : {}),
...(support.alphaMode === false ? { alphaMode: null } : {}),
+ ...(support.normalMap === false ? { normalMap: false } : {}),
};
}
diff --git a/server/services/imageTo3d/renderOptions.test.js b/server/services/imageTo3d/renderOptions.test.js
index 1a4fbea356..aa25b6b3fb 100644
--- a/server/services/imageTo3d/renderOptions.test.js
+++ b/server/services/imageTo3d/renderOptions.test.js
@@ -18,17 +18,17 @@ import {
describe('normalizeRenderOptions', () => {
it('defaults to unset steps/seed with keying enabled', () => {
- expect(normalizeRenderOptions()).toEqual({ steps: null, seed: null, keyBackground: true, detail: 'auto', alphaMode: null });
- expect(normalizeRenderOptions({})).toEqual({ steps: null, seed: null, keyBackground: true, detail: 'auto', alphaMode: null });
+ expect(normalizeRenderOptions()).toEqual({ steps: null, seed: null, keyBackground: true, detail: 'auto', alphaMode: null, normalMap: true });
+ expect(normalizeRenderOptions({})).toEqual({ steps: null, seed: null, keyBackground: true, detail: 'auto', alphaMode: null, normalMap: true });
});
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 });
+ .toEqual({ steps: 24, seed: 0, keyBackground: false, detail: 'auto', alphaMode: null, normalMap: true });
expect(normalizeRenderOptions({ steps: RENDER_STEPS_MAX + 1, seed: RENDER_SEED_MAX + 1 }))
- .toEqual({ steps: null, seed: null, keyBackground: true, detail: 'auto', alphaMode: null });
+ .toEqual({ steps: null, seed: null, keyBackground: true, detail: 'auto', alphaMode: null, normalMap: true });
expect(normalizeRenderOptions({ steps: 12.5, seed: '42' }))
- .toEqual({ steps: null, seed: null, keyBackground: true, detail: 'auto', alphaMode: null });
+ .toEqual({ steps: null, seed: null, keyBackground: true, detail: 'auto', alphaMode: null, normalMap: true });
});
});
@@ -121,6 +121,26 @@ describe('detail tier and alpha mode', () => {
});
});
+describe('normalMap', () => {
+ it('is the one option that defaults ON', () => {
+ // Every other knob defaults to "unset" so the subprocess picks. This one defaults
+ // on because it recovers detail the bake decimation discards for ~2s on a
+ // multi-minute render, and cannot fail the render.
+ expect(normalizeRenderOptions().normalMap).toBe(true);
+ });
+
+ it('honors an explicit false — the only way to express "off"', () => {
+ expect(normalizeRenderOptions({ normalMap: false }).normalMap).toBe(false);
+ });
+
+ it('treats a non-boolean as the default rather than as off', () => {
+ // A missing/garbage value must not silently disable a quality default.
+ for (const bad of [undefined, null, 'false', 0]) {
+ expect(normalizeRenderOptions({ normalMap: bad }).normalMap).toBe(true);
+ }
+ });
+});
+
describe('RENDER_OPTION_KEYS', () => {
it('matches exactly what normalizeRenderOptions returns', () => {
expect(RENDER_OPTION_KEYS).toEqual(Object.keys(normalizeRenderOptions()));
diff --git a/server/services/imageTo3d/targets.js b/server/services/imageTo3d/targets.js
index 597b7a50f8..c7b08139da 100644
--- a/server/services/imageTo3d/targets.js
+++ b/server/services/imageTo3d/targets.js
@@ -143,7 +143,7 @@ export const IMAGE_TO_3D_TARGETS = Object.freeze({
// Upstream's CUDA entrypoint takes no pipeline-type override and PortOS's
// runner for it emits no alpha-mode flag, so both controls are declared
// unsupported rather than rendered as settings the runner would drop.
- supportsRenderOptions: Object.freeze({ detail: false, alphaMode: false }),
+ supportsRenderOptions: Object.freeze({ detail: false, alphaMode: false, normalMap: false }),
upstream: 'https://github.com/microsoft/TRELLIS.2',
weightsRepo: 'microsoft/TRELLIS.2-4B',
installNotes:
@@ -197,7 +197,7 @@ export const IMAGE_TO_3D_TARGETS = Object.freeze({
// that OOMs mid-render. Exposing it needs a VRAM-safety story first — until
// then the honest answer is that the runner does not honor a caller's choice.
// `alphaMode: false` because its runner emits no such flag.
- supportsRenderOptions: Object.freeze({ steps: false, detail: false, alphaMode: false }),
+ supportsRenderOptions: Object.freeze({ steps: false, detail: false, alphaMode: false, normalMap: false }),
installNotes:
'Creating a dedicated `pixal3d` conda environment (kept separate so Pixal3D\u2019s '
+ 'pinned dependencies cannot disturb the TRELLIS.2 target), cloning both repos, '
diff --git a/server/services/imageTo3d/targets.test.js b/server/services/imageTo3d/targets.test.js
index 6cd003c8d7..c60664da64 100644
--- a/server/services/imageTo3d/targets.test.js
+++ b/server/services/imageTo3d/targets.test.js
@@ -336,10 +336,10 @@ describe('renderOptionSupportFor', () => {
// resolutions — they are picked from the card's VRAM, so honoring a caller's
// choice could hand a 12 GB card a config that OOMs mid-render.
expect(renderOptionSupportFor('pixal3dCuda'))
- .toEqual({ steps: false, detail: false, alphaMode: false });
+ .toEqual({ steps: false, detail: false, alphaMode: false, normalMap: false });
// Upstream's CUDA entrypoint takes no pipeline-type override at all.
expect(renderOptionSupportFor('trellis2Cuda'))
- .toEqual({ detail: false, alphaMode: false });
+ .toEqual({ detail: false, alphaMode: false, normalMap: false });
});
it('returns null for a target that honors every knob, and for an unknown id', () => {
diff --git a/server/services/imageTo3d/trellis2.js b/server/services/imageTo3d/trellis2.js
index 7fd225b6ea..95164dab0a 100644
--- a/server/services/imageTo3d/trellis2.js
+++ b/server/services/imageTo3d/trellis2.js
@@ -918,6 +918,7 @@ export function runTrellis2Generate({
fillHoles = false,
remesh = false,
alphaMode = null,
+ normalMap = false,
onProgress,
spawnImpl = spawn,
exists = existsSync,
@@ -948,6 +949,7 @@ export function runTrellis2Generate({
fillHoles,
remesh,
alphaMode,
+ normalMap,
},
});
// Force-opaque normalization is skipped exactly when the caller asked the
diff --git a/server/services/imageTo3d/trellis2GenerateRunner.py b/server/services/imageTo3d/trellis2GenerateRunner.py
index a24c2c6c5b..2783ea3df5 100644
--- a/server/services/imageTo3d/trellis2GenerateRunner.py
+++ b/server/services/imageTo3d/trellis2GenerateRunner.py
@@ -124,6 +124,8 @@ def _parse_adapter_args(argv):
parser.add_argument("--mesh-cluster-smooth-strength", type=float, default=None)
parser.add_argument("--alpha-mode", default=None,
choices=["OPAQUE", "auto", "BLEND", "MASK"])
+ parser.add_argument("--normal-map", action="store_true")
+ parser.add_argument("--normal-map-max-source-faces", type=int, default=None)
known, rest = parser.parse_known_args(argv)
if rest and rest[0] == "--":
rest = rest[1:]
@@ -184,11 +186,19 @@ def _patch_decimation_target(target):
def simplify(points, faces, ratio=None, **kwargs):
n_faces = len(faces)
- # At or under target already -> upstream would still call us (its own
- # guard compares against 200K, not against `target`), so no-op rather
- # than decimate a mesh that is already small enough.
+ # generate.py prints "Simplifying mesh: N -> ~200,000 faces" BEFORE calling
+ # this, unconditionally and from its own hardcoded clamp. That line is now a
+ # lie, so say what actually happens — otherwise the log reads as though the
+ # detail was discarded on exactly the renders where it was kept.
if n_faces <= target:
+ print(f"[portos] keeping all {n_faces:,} faces (target {target:,}) "
+ "- ignore the '-> ~200,000 faces' line above", flush=True)
+ # Upstream would still call us here (its guard compares against 200K, not
+ # against `target`), so no-op rather than decimate a mesh already small
+ # enough.
return points, faces
+ print(f"[portos] decimating {n_faces:,} -> {target:,} faces "
+ "- ignore the '-> ~200,000 faces' line above", flush=True)
return original_simplify(points, faces, 1.0 - (target / n_faces), **kwargs)
fast_simplification.simplify = simplify
@@ -205,6 +215,94 @@ def _patch_decimation_target(target):
o_voxel.postprocess.to_glb = to_glb
+# Filled in by the simplify interception above; read by the normal-map bake. A
+# module-level dict rather than a parameter because the producer (a patched
+# third-party function) and the consumer (a patched third-party function) cannot
+# pass anything to each other directly.
+_CAPTURED = {}
+
+
+def _patch_capture_source_mesh():
+ """Record the mesh generate.py hands to `fast_simplification.simplify`.
+
+ That call is the ONLY place the pre-decimation mesh is observable: generate.py
+ simplifies first and passes the result to `to_glb`, so `to_glb`'s own notion of
+ "original" is already the decimated mesh and holds no high-resolution surface to
+ sample from.
+
+ Installed independently of the decimation patch. Bundling the capture into that
+ wrapper made `--normal-map` silently degrade to a no-op unless
+ `--decimation-target` happened to be passed too — a dependency between two
+ unrelated flags that nothing in the CLI expressed.
+ """
+ import fast_simplification
+
+ # Installed BEFORE the decimation patch, which matters twice over:
+ # * `pristine` is then the genuine unpatched callable. The bake uses it to
+ # enforce its own source-face cap; going through the decimation wrapper
+ # instead would retarget that to the viewer mesh's face count and flatten
+ # the very detail the bake exists to recover.
+ # * this wrapper ends up INNERMOST, so it still observes the full mesh —
+ # the decimation wrapper only rewrites the ratio, never the vertices or
+ # faces it forwards.
+ pristine = fast_simplification.simplify
+ _CAPTURED["simplify"] = pristine
+
+ def simplify(points, faces, *args, **kwargs):
+ _CAPTURED["source"] = (points, faces)
+ return pristine(points, faces, *args, **kwargs)
+
+ fast_simplification.simplify = simplify
+
+
+def _patch_normal_map(max_source_faces, verbose=True):
+ """Bake a tangent-space normal map onto the exported mesh after `to_glb`.
+
+ Wraps `to_glb` rather than running after generate.py finishes, because the
+ in-memory trimesh object is the last point where the material can be given a
+ texture — once generate.py has called `.export()`, adding one means rewriting
+ the GLB container.
+
+ A bake failure must NOT fail the render: the mesh and its base colour are
+ already correct at this point, and a normal map is an enhancement. So this
+ logs and returns the un-augmented GLB, which is exactly today's output.
+ """
+ import o_voxel.postprocess
+
+ original_to_glb = o_voxel.postprocess.to_glb
+
+ def to_glb(*args, **kwargs):
+ glb = original_to_glb(*args, **kwargs)
+ source = _CAPTURED.get("source")
+ if source is None:
+ print("[portos] normal map skipped - no pre-decimation mesh was captured "
+ "(the render never went through the simplify path)", flush=True)
+ return glb
+ try:
+ # INSIDE the guard, deliberately. The bake module pulls numpy, torch,
+ # mtlbvh, mtldiffrast and PIL; on an install missing any of them an
+ # ImportError raised out here would kill a render that had already
+ # produced a correct mesh and texture. Import failure is just one more
+ # reason the enhancement is unavailable.
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
+ from trellis2NormalBake import bake_normal_map, DEFAULT_MAX_SOURCE_FACES
+ return bake_normal_map(
+ glb,
+ source[0],
+ source[1],
+ texture_size=kwargs.get("texture_size", 2048),
+ max_source_faces=max_source_faces or DEFAULT_MAX_SOURCE_FACES,
+ simplify=_CAPTURED.get("simplify"),
+ verbose=verbose,
+ )
+ except Exception as exc: # noqa: BLE001 - see docstring: never fail the render
+ print(f"[portos] normal map bake failed ({type(exc).__name__}: {exc}) - "
+ "exporting without it", flush=True)
+ return glb
+
+ o_voxel.postprocess.to_glb = to_glb
+
+
def _patch_to_glb_quality(**overrides):
"""Forward o_voxel `to_glb` knobs upstream never passes.
@@ -272,6 +370,10 @@ def main():
sys.path.insert(0, trellis_root)
_patch_texture_size_choices()
+ # Before the decimation patch — see _patch_capture_source_mesh for why both the
+ # pristine-callable and the innermost-wrapper properties depend on this order.
+ if adapter.normal_map:
+ _patch_capture_source_mesh()
if adapter.decimation_target is not None:
_patch_decimation_target(adapter.decimation_target)
_patch_to_glb_quality(
@@ -280,6 +382,8 @@ def main():
mesh_cluster_smooth_strength=adapter.mesh_cluster_smooth_strength,
alpha_mode=adapter.alpha_mode,
)
+ if adapter.normal_map:
+ _patch_normal_map(adapter.normal_map_max_source_faces)
if adapter.fill_holes:
_enable_fill_holes(generate_dir)
diff --git a/server/services/imageTo3d/trellis2GenerateRunner.test.js b/server/services/imageTo3d/trellis2GenerateRunner.test.js
index 5a8780fe84..0deae34ef9 100644
--- a/server/services/imageTo3d/trellis2GenerateRunner.test.js
+++ b/server/services/imageTo3d/trellis2GenerateRunner.test.js
@@ -208,6 +208,28 @@ describe.skipIf(!pyBin)('trellis2GenerateRunner', () => {
expect(r.to_glb[0]).not.toHaveProperty('alpha_mode');
});
+ it('captures the pre-decimation mesh for the normal bake without --decimation-target', () => {
+ // --normal-map used to silently no-op unless --decimation-target happened to be
+ // passed too, because the capture lived inside the decimation patch. Nothing in
+ // the CLI expressed that dependency.
+ writeStubs();
+ const out = run(['--normal-map', '--', join(dir, 'generate.py'), 'a.png']);
+ expect(out).not.toMatch(/no pre-decimation mesh was captured/);
+ // Bake runs against the stub's fake mesh and fails; that must not fail the render.
+ expect(resultOf(out).to_glb).toHaveLength(1);
+ });
+
+ it('never fails the render when the normal bake throws', () => {
+ // The mesh and its base colour are already correct by then — a normal map is an
+ // enhancement, so a bake failure degrades to today's output rather than losing
+ // a render the user already waited minutes for.
+ writeStubs();
+ const out = run(['--normal-map', '--decimation-target', '1000000',
+ '--', join(dir, 'generate.py'), 'a.png']);
+ expect(out).toMatch(/normal map bake failed|normal map:/);
+ expect(resultOf(out).to_glb[0].exported).toBe(1000000);
+ });
+
it('fails loudly when --fill-holes is asked for but the gate is absent', () => {
// Must not degrade to "render without hole filling" — that is exactly the
// output the flag exists to avoid, so silence here would be a lie.
diff --git a/server/services/imageTo3d/trellis2MeshQuality.js b/server/services/imageTo3d/trellis2MeshQuality.js
index 26fef533ac..f3f013bc6e 100644
--- a/server/services/imageTo3d/trellis2MeshQuality.js
+++ b/server/services/imageTo3d/trellis2MeshQuality.js
@@ -104,6 +104,20 @@ export const isValidDecimationTarget = (value) => (
*/
export const TRELLIS2_ALPHA_MODES = ['OPAQUE', 'auto', 'BLEND', 'MASK'];
+/**
+ * Cap on the source mesh the normal-map bake samples from.
+ *
+ * The bake builds a BVH over the pre-decimation mesh, and at `1024_cascade` that is
+ * ~22.7M faces — beyond any published Apple-Silicon result (mtlbvh's fix commit
+ * reports a clean run at 8.6M; its regression test covers 498K). Above this the
+ * source is decimated to the cap for the bake ONLY, which still leaves ~8x the
+ * geometry of the exported mesh, so nearly all the recoverable relief survives.
+ *
+ * A documented ceiling rather than an attempt to find the real limit at the cost of
+ * someone's render.
+ */
+export const TRELLIS2_NORMAL_SOURCE_FACE_CAP = 8000000;
+
/**
* Emit the runner's PortOS-only flags, terminated by `--`.
*
@@ -118,7 +132,8 @@ export const TRELLIS2_ALPHA_MODES = ['OPAQUE', 'auto', 'BLEND', 'MASK'];
* @param {{decimationTarget?: number|null, fillHoles?: boolean, remesh?: boolean,
* meshClusterRefineIterations?: number|null,
* meshClusterSmoothStrength?: number|null,
- * alphaMode?: string|null}} [opts]
+ * alphaMode?: string|null, normalMap?: boolean,
+ * normalMapMaxSourceFaces?: number|null}} [opts]
* @returns {string[]}
*/
export function trellis2MeshQualityArgs({
@@ -128,6 +143,8 @@ export function trellis2MeshQualityArgs({
meshClusterRefineIterations = null,
meshClusterSmoothStrength = null,
alphaMode = null,
+ normalMap = false,
+ normalMapMaxSourceFaces = null,
} = {}) {
if (decimationTarget !== null && !isValidDecimationTarget(decimationTarget)) {
throw new Error(
@@ -149,6 +166,11 @@ export function trellis2MeshQualityArgs({
...(meshClusterSmoothStrength !== null
? ['--mesh-cluster-smooth-strength', String(meshClusterSmoothStrength)] : []),
...(alphaMode !== null ? ['--alpha-mode', alphaMode] : []),
+ ...(normalMap ? ['--normal-map'] : []),
+ // Only meaningful alongside --normal-map; emitted independently so an explicit
+ // cap is still recorded in the argv the run entry reflects.
+ ...(normalMapMaxSourceFaces !== null
+ ? ['--normal-map-max-source-faces', String(normalMapMaxSourceFaces)] : []),
'--',
];
}
diff --git a/server/services/imageTo3d/trellis2MeshQuality.test.js b/server/services/imageTo3d/trellis2MeshQuality.test.js
index faa20a1d15..574bf01bfb 100644
--- a/server/services/imageTo3d/trellis2MeshQuality.test.js
+++ b/server/services/imageTo3d/trellis2MeshQuality.test.js
@@ -5,6 +5,7 @@ import {
TRELLIS2_DECIMATION_HIGH,
TRELLIS2_DECIMATION_MAX,
TRELLIS2_DECIMATION_UPSTREAM_CLAMP,
+ TRELLIS2_NORMAL_SOURCE_FACE_CAP,
isValidDecimationTarget,
selectTrellis2DecimationTarget,
trellis2FillHolesScript,
@@ -91,6 +92,21 @@ describe('trellis2MeshQualityArgs', () => {
.toEqual(['--']);
});
+ it('emits the normal-map flags only when asked', () => {
+ expect(trellis2MeshQualityArgs({ normalMap: true })).toEqual(['--normal-map', '--']);
+ expect(trellis2MeshQualityArgs({ normalMap: false })).toEqual(['--']);
+ expect(trellis2MeshQualityArgs({ normalMap: true, normalMapMaxSourceFaces: 8000000 }))
+ .toEqual(['--normal-map', '--normal-map-max-source-faces', '8000000', '--']);
+ });
+
+ it('keeps the normal source cap at or under the evidence ceiling', () => {
+ // The bake builds a BVH over the pre-decimation mesh. The cap is what keeps that
+ // inside sizes with a published Apple-Silicon result behind them.
+ expect(TRELLIS2_NORMAL_SOURCE_FACE_CAP).toBeLessThanOrEqual(TRELLIS2_DECIMATION_MAX);
+ // And well above the viewer mesh, or the bake would have no detail to recover.
+ expect(TRELLIS2_NORMAL_SOURCE_FACE_CAP).toBeGreaterThan(TRELLIS2_DECIMATION_HIGH * 4);
+ });
+
it('throws rather than clamping an out-of-range decimation target', () => {
// Clamping would make the run ledger record a target the subprocess never got.
expect(() => trellis2MeshQualityArgs({ decimationTarget: 0 }))
diff --git a/server/services/imageTo3d/trellis2NormalBake.py b/server/services/imageTo3d/trellis2NormalBake.py
index 8acd8dc873..9ab5206eca 100644
--- a/server/services/imageTo3d/trellis2NormalBake.py
+++ b/server/services/imageTo3d/trellis2NormalBake.py
@@ -97,6 +97,30 @@ def compute_uv_tangents(vertices, faces, uvs):
return out.astype(np.float32)
+def decoder_to_export_space(arr):
+ """Apply the axis swap `to_glb` performs on its way out.
+
+ `o_voxel.postprocess.to_glb` converts to glTF's Y-up before returning:
+
+ vertices[:, 1], vertices[:, 2] = vertices[:, 2], -vertices[:, 1]
+
+ and does the same to its normals. So the mesh this module receives is already in
+ export space while the captured source mesh is still in decoder space. Sampling
+ one against the other without this produces a unit-length but essentially random
+ normal map — measured on the reference render as a mean tangent-space z of ~0.06
+ where a correct map sits near +0.9, with every mapped texel carrying tilt.
+
+ Applied to the source (429K vertices) rather than to the per-texel query positions
+ (2.6M) because it is the cheaper side, and to the source NORMALS too, so the
+ encoded orientation is expressed in the same frame the exported mesh lives in.
+ """
+ out = np.array(arr, dtype=np.float32, copy=True)
+ y = out[:, 1].copy()
+ out[:, 1] = out[:, 2]
+ out[:, 2] = -y
+ return out
+
+
def _extract_mesh(glb):
"""Pull the single UV-mapped mesh out of whatever to_glb returned.
@@ -133,10 +157,13 @@ def bake_normal_map(
pass).
"""
import torch
- import mtlbvh
+ import o_voxel.postprocess as pp
import mtldiffrast.torch as dr
from PIL import Image
+ if not (getattr(pp, '_HAS_DR', False) and getattr(pp, '_BVH', None)):
+ raise RuntimeError('normal bake needs the Metal rasterizer and BVH backends')
+
mesh, uvs = _extract_mesh(glb)
lo_v = np.asarray(mesh.vertices, dtype=np.float32)
lo_f = np.asarray(mesh.faces, dtype=np.int32)
@@ -151,16 +178,32 @@ def bake_normal_map(
src_f = np.asarray(src_f, dtype=np.int32)
# The source's own smooth normals are what gets encoded. Face normals would give a
- # faceted map that reads as decoder noise at this triangle density.
- src_vn = compute_vertex_normals(src_v, src_f)
-
- device = torch.device('mps' if torch.backends.mps.is_available() else 'cpu')
- ctx = dr.MtlRasterizeContext()
+ # faceted map that reads as decoder noise at this triangle density. Computed in
+ # decoder space, then both mesh and normals are moved into export space so the
+ # BVH and the query positions agree.
+ src_vn = decoder_to_export_space(compute_vertex_normals(src_v, src_f))
+ src_v = decoder_to_export_space(src_v)
+
+ # Mirror o_voxel's own device choice rather than reaching for MPS. Its comment
+ # states the reasoning: on the Metal path "all GPU compute goes through Metal
+ # kernels directly (mtldiffrast, mtlbvh, cumesh, flex_gemm) [and] CPU tensors on
+ # Apple Silicon unified memory are directly GPU-accessible — no MPS overhead
+ # needed", so it runs this whole stage on CPU tensors. Using MPS here would also
+ # mix devices against the BVH, which is the failure mode trellis-mac's own
+ # comments repeatedly warn about.
+ device = torch.device('cpu') if getattr(pp, '_BACKEND', None) == 'metal' else torch.device('cuda')
+ ctx = dr.MtlRasterizeContext() if getattr(pp, '_BACKEND', None) == 'metal' \
+ else dr.RasterizeCudaContext()
# Rasterize the EXPORTED mesh in UV space, exactly as the colour bake does: UVs to
# clip space, z=0, w=1. Chunked over faces with the same face-id-in-alpha trick, so
# a large atlas does not allocate one giant intermediate.
- uv_t = torch.as_tensor(uvs, device=device)
+ # `to_glb` also flips V on its way out (`uvs[:, 1] = 1 - uvs[:, 1]`) to reconcile
+ # glTF's bottom-up V with PNG's top-down rows. Its own base-colour bake rasterized
+ # with the UNflipped UVs, so this has to undo the flip or the normal map comes out
+ # mirrored vertically against the base colour it accompanies.
+ uv_t = torch.as_tensor(uvs, device=device).clone()
+ uv_t[:, 1] = 1.0 - uv_t[:, 1]
lo_f_t = torch.as_tensor(lo_f, device=device, dtype=torch.int32)
uv_clip = torch.cat([
uv_t * 2 - 1,
@@ -180,8 +223,15 @@ def bake_normal_map(
# Per-texel geometry of the low-res surface: position (where to sample the source),
# plus the tangent frame the result has to be expressed in.
lo_v_t = torch.as_tensor(lo_v, device=device)
- lo_vn_t = torch.as_tensor(compute_vertex_normals(lo_v, lo_f), device=device)
- lo_vt_t = torch.as_tensor(compute_uv_tangents(lo_v, lo_f, uvs), device=device)
+ # Prefer the normals `to_glb` already produced and converted — they are what a
+ # renderer will actually shade with, so the tangent basis must be built from them
+ # rather than from a re-derivation that can disagree at seams.
+ lo_vn = np.asarray(mesh.vertex_normals, dtype=np.float32) \
+ if getattr(mesh, 'vertex_normals', None) is not None \
+ else compute_vertex_normals(lo_v, lo_f)
+ lo_vn_t = torch.as_tensor(lo_vn, device=device)
+ lo_vt_t = torch.as_tensor(
+ compute_uv_tangents(lo_v, lo_f, uv_t.cpu().numpy()), device=device)
pos = dr.interpolate(lo_v_t.unsqueeze(0), rast, lo_f_t)[0][0][mask]
n_lo = torch.nn.functional.normalize(
dr.interpolate(lo_vn_t.unsqueeze(0), rast, lo_f_t)[0][0][mask], dim=-1)
@@ -192,7 +242,9 @@ def bake_normal_map(
t_lo = torch.nn.functional.normalize(t_lo - n_lo * (t_lo * n_lo).sum(-1, keepdim=True), dim=-1)
b_lo = torch.cross(n_lo, t_lo, dim=-1)
- bvh = mtlbvh.MtlBVH(torch.as_tensor(src_v), torch.as_tensor(src_f))
+ # The SAME BVH class o_voxel uses (cumesh auto-selects Metal vs CUDA), so this
+ # pass cannot diverge from the base-colour bake's notion of the surface.
+ bvh = pp._BVH(torch.as_tensor(src_v, device=device), torch.as_tensor(src_f, device=device))
src_vn_t = torch.as_tensor(src_vn, device=pos.device)
src_f_t = torch.as_tensor(src_f, device=pos.device, dtype=torch.long)
@@ -204,6 +256,16 @@ def bake_normal_map(
# high-resolution orientation the exported triangles can no longer express.
n_hi = torch.nn.functional.normalize(
(src_vn_t[src_f_t[face_id.long()]] * uvw.unsqueeze(-1)).sum(dim=1), dim=-1)
+ # Re-orient into the low-res normal's hemisphere. The O-Voxel decoder
+ # deliberately produces open surfaces and non-manifold geometry, so its face
+ # winding is not globally consistent and area-weighted vertex normals point
+ # inward across whole patches. Measured on the reference render: median
+ # dot(n_hi, n_lo) was +0.976 while the MEAN was +0.127, i.e. most texels were
+ # right and a large minority were inverted. The exported surface defines
+ # outward here by construction, so agreeing with it is not a heuristic — a
+ # tangent-space normal in the opposite hemisphere encodes nothing meaningful.
+ flip = torch.where((n_hi * n_lo[sl]).sum(-1, keepdim=True) < 0, -1.0, 1.0)
+ n_hi = n_hi * flip
# Project into the low-res tangent basis.
out[sl] = torch.stack([
(n_hi * t_lo[sl]).sum(-1),
diff --git a/server/services/imageTo3d/trellis2NormalBake.test.js b/server/services/imageTo3d/trellis2NormalBake.test.js
new file mode 100644
index 0000000000..01b4927c88
--- /dev/null
+++ b/server/services/imageTo3d/trellis2NormalBake.test.js
@@ -0,0 +1,181 @@
+import { execFileSync } from '../../lib/childProcess.js';
+import { existsSync } from 'node:fs';
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { describe, expect, it } from 'vitest';
+import { resolveTestPython } from '../../lib/testHelper.js';
+import { trellis2VenvPython } from './trellis2.js';
+
+// The bake's helpers are numpy-based, and the interpreter `resolveTestPython` finds is
+// a bare system python3 that generally has no numpy. So probe for an interpreter that
+// can actually import it, preferring the plain one and falling back to the TRELLIS.2
+// venv (which necessarily has numpy) when this host has an install. Neither is a
+// requirement: on a machine with neither, the suite skips rather than failing, the same
+// posture as the other Python-driven suites here.
+function resolveNumpyPython() {
+ const candidates = [resolveTestPython(), trellis2VenvPython()].filter(Boolean);
+ for (const bin of candidates) {
+ if (bin.includes('/') && !existsSync(bin)) continue;
+ try {
+ execFileSync(bin, ['-c', 'import numpy'], { stdio: 'ignore' });
+ return bin;
+ } catch {
+ // Not this one — keep looking.
+ }
+ }
+ return null;
+}
+
+const pyBin = resolveNumpyPython();
+const MODULE_DIR = new URL('.', import.meta.url).pathname;
+
+describe.skipIf(!pyBin)('trellis2NormalBake helpers', () => {
+ const run = (body) => {
+ const dir = mkdtempSync(join(tmpdir(), 'portos-nbake-'));
+ const script = join(dir, 'case.py');
+ try {
+ writeFileSync(script, [
+ 'import sys, json',
+ `sys.path.insert(0, ${JSON.stringify(MODULE_DIR)})`,
+ 'import numpy as np',
+ 'import trellis2NormalBake as nb',
+ body,
+ ].join('\n'));
+ return JSON.parse(execFileSync(pyBin, [script], { encoding: 'utf8' }));
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ };
+
+ describe('decoder_to_export_space', () => {
+ // The axis swap to_glb performs on its way out. Getting it wrong produced a
+ // unit-length but essentially random normal map (measured: mean tangent-space z
+ // of ~0.06 against a correct ~0.98), so it gets a direct test rather than only
+ // being exercised through the GPU path.
+ it('maps (x, y, z) to (x, z, -y), matching to_glb', () => {
+ const r = run(`
+pts = np.array([[1, 2, 3], [0, 1, 0], [-1, -2, -3]], dtype=np.float32)
+print(json.dumps(nb.decoder_to_export_space(pts).tolist()))
+`);
+ expect(r).toEqual([[1, 3, -2], [0, 0, -1], [-1, -3, 2]]);
+ });
+
+ it('does not mutate its input', () => {
+ // The source array is reused by the caller for the BVH; an in-place swap would
+ // corrupt it. to_glb's own comment flags the same hazard ("must copy to avoid
+ // in-place corruption").
+ const r = run(`
+pts = np.array([[1, 2, 3]], dtype=np.float32)
+out = nb.decoder_to_export_space(pts)
+print(json.dumps({"input": pts.tolist(), "output": out.tolist()}))
+`);
+ expect(r.input).toEqual([[1, 2, 3]]);
+ expect(r.output).toEqual([[1, 3, -2]]);
+ });
+
+ it('is length-preserving, as a rotation must be', () => {
+ const r = run(`
+rng = np.random.default_rng(7)
+pts = rng.normal(size=(500, 3)).astype(np.float32)
+a = np.linalg.norm(pts, axis=-1)
+b = np.linalg.norm(nb.decoder_to_export_space(pts), axis=-1)
+print(json.dumps({"max_delta": float(np.abs(a - b).max())}))
+`);
+ expect(r.max_delta).toBeLessThan(1e-5);
+ });
+ });
+
+ describe('compute_vertex_normals', () => {
+ it('returns unit normals for a planar quad', () => {
+ const r = run(`
+v = np.array([[0,0,0],[1,0,0],[1,1,0],[0,1,0]], dtype=np.float32)
+f = np.array([[0,1,2],[0,2,3]], dtype=np.int32)
+n = nb.compute_vertex_normals(v, f)
+print(json.dumps({"normals": n.tolist(), "lengths": np.linalg.norm(n, axis=-1).tolist()}))
+`);
+ for (const n of r.normals) expect(n).toEqual([0, 0, 1]);
+ for (const l of r.lengths) expect(l).toBeCloseTo(1, 5);
+ });
+
+ it('weights by area, so slivers cannot outvote a large face', () => {
+ // The decoder emits wildly uneven triangle areas; uniform averaging lets a
+ // cluster of slivers dominate the face that actually describes the surface.
+ const r = run(`
+v = np.array([[0,0,0],[10,0,0],[0,10,0],[0,0,0.001]], dtype=np.float32)
+f = np.array([[0,1,2],[0,1,3]], dtype=np.int32)
+print(json.dumps({"z": float(abs(nb.compute_vertex_normals(v, f)[0][2]))}))
+`);
+ expect(r.z).toBeGreaterThan(0.99);
+ });
+
+ it('yields a finite zero vector for an unreferenced vertex', () => {
+ // np.add.at leaves it at zero; normalizing must not divide by zero and produce
+ // NaN, which would poison every texel that interpolates it.
+ const r = run(`
+v = np.array([[0,0,0],[1,0,0],[0,1,0],[5,5,5]], dtype=np.float32)
+f = np.array([[0,1,2]], dtype=np.int32)
+n = nb.compute_vertex_normals(v, f)
+print(json.dumps({"finite": bool(np.all(np.isfinite(n))), "orphan": n[3].tolist()}))
+`);
+ expect(r.finite).toBe(true);
+ expect(r.orphan).toEqual([0, 0, 0]);
+ });
+ });
+
+ describe('compute_uv_tangents', () => {
+ it('points along +X for an axis-aligned UV map', () => {
+ const r = run(`
+v = np.array([[0,0,0],[1,0,0],[1,1,0],[0,1,0]], dtype=np.float32)
+f = np.array([[0,1,2],[0,2,3]], dtype=np.int32)
+uv = np.array([[0,0],[1,0],[1,1],[0,1]], dtype=np.float32)
+t = nb._unit(nb.compute_uv_tangents(v, f, uv))
+print(json.dumps({"first": t[0].tolist()}))
+`);
+ expect(r.first[0]).toBeCloseTo(1, 4);
+ expect(Math.abs(r.first[1])).toBeLessThan(1e-4);
+ });
+
+ it('survives a degenerate UV triangle without NaN', () => {
+ // Zero-area-in-texture-space faces have no defined tangent. Left unguarded the
+ // reciprocal explodes and poisons every vertex the face touches.
+ const r = run(`
+v = np.array([[0,0,0],[1,0,0],[1,1,0],[0,1,0]], dtype=np.float32)
+f = np.array([[0,1,2],[0,2,3]], dtype=np.int32)
+uv = np.zeros((4, 2), dtype=np.float32)
+t = nb.compute_uv_tangents(v, f, uv)
+print(json.dumps({"finite": bool(np.all(np.isfinite(t)))}))
+`);
+ expect(r.finite).toBe(true);
+ });
+ });
+
+ describe('_extract_mesh', () => {
+ it('rejects a mesh with no UVs rather than baking against nothing', () => {
+ // A silent fallback here would attach a plausible-looking but meaningless map.
+ const r = run(`
+class V: uv = None
+class M:
+ visual = V()
+try:
+ nb._extract_mesh(M())
+ print(json.dumps({"raised": None}))
+except ValueError as e:
+ print(json.dumps({"raised": str(e)}))
+`);
+ expect(r.raised).toMatch(/requires the exported mesh to carry UVs/);
+ });
+
+ it('refuses an ambiguous multi-mesh scene', () => {
+ const r = run(`
+class S: geometry = {"a": object(), "b": object()}
+try:
+ nb._extract_mesh(S())
+ print(json.dumps({"raised": None}))
+except ValueError as e:
+ print(json.dumps({"raised": str(e)}))
+`);
+ expect(r.raised).toMatch(/expects exactly one mesh, got 2/);
+ });
+ });
+});