Mesh Previewer: Can export to Blender, Unity, Unreal Engine in FBX

This commit is contained in:
Bruno Fargnoli 2026-07-15 17:28:08 +02:00
parent 8355e6b319
commit 3398851f8d
15 changed files with 707 additions and 38 deletions

View file

@ -18,6 +18,7 @@ const fs = require('node:fs');
const { spawn } = require('node:child_process');
const {
isReady,
MESHTOOLS_REQS_TAG,
ensureUv,
setupPythonServer,
setupSkintokens,
@ -125,7 +126,9 @@ function waitForBackend(timeoutMs = 60000, intervalMs = 400) {
function serviceRegistry() {
return {
meshtools: {
label: 'Mesh Tools', venv: PY_VENV, port: PYTHON_PORT,
// reqsTag: a requirements.txt bump flips this service back to
// "not installed" until setup re-runs (incrementally) and re-tags it.
label: 'Mesh Tools', venv: PY_VENV, port: PYTHON_PORT, reqsTag: MESHTOOLS_REQS_TAG,
start: () => startPythonServer({
serviceDir: PYTHON_DIR, venvDir: PY_VENV, port: PYTHON_PORT,
logStream: openLogStream('python.log'), log,
@ -183,7 +186,7 @@ function stopService(name) {
function ensureService(name) {
const svc = SERVICES[name];
if (!svc) return Promise.reject(new Error(`Unknown service: ${name}`));
if (!isReady(svc.venv)) {
if (!isReady(svc.venv, svc.reqsTag)) {
return Promise.reject(new Error(`${svc.label} is not installed yet. Install it in Settings.`));
}
if (starting[name]) return starting[name];
@ -207,7 +210,7 @@ function serviceStatus() {
for (const [name, svc] of Object.entries(SERVICES)) {
out[name] = {
label: svc.label,
installed: isReady(svc.venv),
installed: isReady(svc.venv, svc.reqsTag),
running: !!handles[name],
starting: !!starting[name],
};
@ -238,7 +241,7 @@ async function doSetup(rigging, send) {
const uv = await ensureUv({ appRoot: APP_ROOT, onLine: (t) => send({ service: 'meshtools', kind: 'log', text: t }) });
if (!uv) throw new Error('Could not find or install uv (the Python toolchain manager).');
if (!isReady(PY_VENV)) {
if (!isReady(PY_VENV, MESHTOOLS_REQS_TAG)) {
await setupPythonServer({
uv, serviceDir: PYTHON_DIR, venvDir: PY_VENV,
onProgress: (e) => send({ service: 'meshtools', ...e }),
@ -261,7 +264,7 @@ async function doSetup(rigging, send) {
function registerSetupIpc() {
ipcMain.handle('setup:status', () => ({
desktop: true,
meshtools: isReady(PY_VENV),
meshtools: isReady(PY_VENV, MESHTOOLS_REQS_TAG),
rigging: isReady(RIG_VENV),
}));
@ -272,7 +275,7 @@ function registerSetupIpc() {
// Provisioned only — services are started on demand (or from Settings),
// not here, so installing doesn't spin up a process the user isn't using.
log('Setup run complete.');
return { ok: true, status: { meshtools: isReady(PY_VENV), rigging: isReady(RIG_VENV) } };
return { ok: true, status: { meshtools: isReady(PY_VENV, MESHTOOLS_REQS_TAG), rigging: isReady(RIG_VENV) } };
} catch (err) {
log(`Setup run failed: ${err.message}`);
send({ kind: 'error', text: err.message });
@ -341,7 +344,7 @@ async function boot() {
// progress (isReady probes the venv, so a legacy venv whose system Python was
// removed is detected and rebuilt). Otherwise → fast path (splash).
let splash = null;
if (!isReady(PY_VENV)) {
if (!isReady(PY_VENV, MESHTOOLS_REQS_TAG)) {
await runFirstRunSetup();
} else {
splash = loadingWindow();

View file

@ -24,6 +24,12 @@ const IS_WIN = process.platform === 'win32';
const PYVER = '3.13';
const UV_EXE = IS_WIN ? 'uv.exe' : 'uv';
// Bump whenever python-server/requirements.txt changes so EXISTING installs
// re-run the (incremental) mesh-tools setup and pick up the new deps — the
// marker alone only proves that SOME requirements set was installed once.
// History: 2 = added bpy (GLB->FBX engine export, v1.5.0).
const MESHTOOLS_REQS_TAG = 'meshtools-reqs-2';
function venvPython(venvDir) {
return IS_WIN
? path.join(venvDir, 'Scripts', 'python.exe')
@ -52,8 +58,19 @@ function venvUsable(venvDir) {
}
}
function isReady(venvDir) {
return fs.existsSync(depsMarker(venvDir)) && venvUsable(venvDir);
// `requiredTag` (optional) additionally requires the marker to start with that
// tag — pass MESHTOOLS_REQS_TAG for the mesh-tools venv so a requirements bump
// re-triggers its setup. Rigging keeps the tag-less check (its marker must not
// be invalidated by mesh-tools changes: re-setup means multi-GB torch/model
// downloads).
function isReady(venvDir, requiredTag) {
if (!fs.existsSync(depsMarker(venvDir)) || !venvUsable(venvDir)) return false;
if (!requiredTag) return true;
try {
return fs.readFileSync(depsMarker(venvDir), 'utf8').startsWith(requiredTag);
} catch {
return false;
}
}
// Create the venv with uv, rebuilding from scratch if the existing one is broken
@ -165,7 +182,7 @@ async function setupPythonServer({ uv, serviceDir, venvDir, onProgress }) {
run: (log) => runStream(uv, ['pip', 'install', '--python', vp, '-r', 'requirements.txt'], { cwd: serviceDir, env, onLine: log }).then((r) => r.code),
},
], onProgress);
fs.writeFileSync(depsMarker(venvDir), new Date().toISOString());
fs.writeFileSync(depsMarker(venvDir), `${MESHTOOLS_REQS_TAG} ${new Date().toISOString()}`);
onProgress({ kind: 'done' });
}
@ -315,6 +332,7 @@ function startService({ name, serviceDir, venvDir, script, env, logStream, log }
module.exports = {
PYVER,
MESHTOOLS_REQS_TAG,
venvPython,
isReady,
ensureUv,

View file

@ -71,7 +71,7 @@
<div class="svc__head">
<span class="dot"></span>
<span class="svc__name">Mesh Tools</span>
<span class="svc__tag">required · Auto UV / Retopo</span>
<span class="svc__tag">required · Auto UV / Retopo / FBX export (~1 GB)</span>
</div>
<div class="svc__phase">Waiting to start…</div>
<div class="bar"><i></i></div>

View file

@ -39,6 +39,10 @@ ALLOWED_ORIGINS: list[str] = [
# Upload guard rails.
MAX_UPLOAD_BYTES: int = _env_int("MESHTOOLS_MAX_UPLOAD_BYTES", 512 * 1024 * 1024)
# GLB -> FBX conversion (headless Blender subprocess). Generous default: bpy
# import alone takes seconds and heavy scenes bake many animation takes.
CONVERT_TIMEOUT_S: int = _env_int("MESHTOOLS_CONVERT_TIMEOUT", 600)
# Scratch space for temp files when a tool needs real paths on disk
# (many mesh CLIs/libraries only accept file paths, not in-memory buffers).
WORK_DIR: Path = Path(

View file

@ -1,6 +1,6 @@
"""Mesh-processing endpoints: Auto UV and Auto Retopo.
"""Mesh-processing endpoints: Auto UV, Auto Retopo, Repair and FBX Convert.
Contract (shared by both routes):
Contract (shared by all routes):
Request : multipart/form-data
- meshFile : the mesh to process (GLB/OBJ/PLY/STL)
- options : JSON string of the operation options (optional)
@ -29,9 +29,10 @@ from pydantic import ValidationError
from ..config import MAX_UPLOAD_BYTES
from ..meshio import export_mesh, load_mesh, mesh_stats
from ..schemas import AutoRetopoOptions, AutoUvOptions, RepairOptions
from ..schemas import AutoRetopoOptions, AutoUvOptions, ConvertOptions, RepairOptions
from ..services.auto_retopo import run_auto_retopo
from ..services.auto_uv import run_auto_uv
from ..services.convert_fbx import run_convert_fbx
from ..services.repair import run_repair
router = APIRouter(prefix="/meshes", tags=["meshes"])
@ -86,11 +87,13 @@ def _sse(obj: dict) -> str:
return f"data: {json.dumps(obj, separators=(',', ':'))}\n\n"
def _stream_tool(run_callable, fmt: str, label: str) -> StreamingResponse:
def _stream_payload(run_callable, label: str) -> StreamingResponse:
"""Run `run_callable(emit)` in a worker thread and stream SSE progress events.
`run_callable(emit)` must return (mesh, tool_stats, preview_png) and may call
emit(stage, frac, message) to report progress.
`run_callable(emit)` must return the terminal `done` payload dict and may
call emit(stage, frac, message) to report progress. Use this directly for
tools that build their own envelope (e.g. FBX conversion, which must never
round-trip through trimesh); use `_stream_tool` for trimesh-based tools.
"""
events: "queue.Queue" = queue.Queue()
holder: dict = {}
@ -100,8 +103,7 @@ def _stream_tool(run_callable, fmt: str, label: str) -> StreamingResponse:
def worker():
try:
mesh, tool_stats, preview = run_callable(emit)
holder["payload"] = _envelope(mesh, fmt, tool_stats, preview)
holder["payload"] = run_callable(emit)
except Exception as exc: # noqa: BLE001 — surfaced to the client as an error event
holder["error"] = f"{label} failed: {exc}"
finally:
@ -132,6 +134,17 @@ def _stream_tool(run_callable, fmt: str, label: str) -> StreamingResponse:
return StreamingResponse(generate(), media_type="text/event-stream", headers=_SSE_HEADERS)
def _stream_tool(run_callable, fmt: str, label: str) -> StreamingResponse:
"""`_stream_payload` for trimesh-based tools: `run_callable(emit)` returns
(mesh, tool_stats, preview_png) and the envelope is built here.
"""
def run(emit):
mesh, tool_stats, preview = run_callable(emit)
return _envelope(mesh, fmt, tool_stats, preview)
return _stream_payload(run, label)
@router.post("/auto-uv")
async def auto_uv(
meshFile: UploadFile = File(...),
@ -166,3 +179,38 @@ async def repair(
data = await _read_upload(meshFile)
mesh = load_mesh(data, meshFile.filename or "mesh.glb")
return _stream_tool(lambda emit: run_repair(mesh, opts, progress=emit), format, "Repair")
@router.post("/convert")
async def convert(
meshFile: UploadFile = File(...),
options: str | None = Form(None),
format: str = Form("fbx"),
) -> StreamingResponse:
"""GLB -> FBX engine export (headless Blender subprocess).
Deliberately bypasses trimesh (`load_mesh`/`_envelope`): trimesh cannot
write FBX and flattens skinned meshes, and this endpoint's whole point is
preserving the skeleton + animation takes. The GLB bytes go to the worker
untouched.
"""
opts = _parse_options(options, ConvertOptions)
data = await _read_upload(meshFile)
if (format or "fbx").lstrip(".").lower() != "fbx":
raise HTTPException(status_code=400, detail="Only 'fbx' output is supported by /meshes/convert.")
def run(emit):
fbx_bytes, tool_stats = run_convert_fbx(data, opts, progress=emit)
return {
"format": "fbx",
"mesh_b64": base64.b64encode(fbx_bytes).decode("ascii"),
"stats": {
"vertex_count": tool_stats.get("vertices"),
"face_count": None,
"has_uv": bool(tool_stats.get("has_uv")),
"tool": tool_stats,
},
"preview_b64": None,
}
return _stream_payload(run, "Convert to FBX")

View file

@ -132,6 +132,28 @@ class RepairOptions(BaseModel):
description="Weld coincident vertices by position before repairing (matches the editor's check).")
class ConvertOptions(BaseModel):
"""Options for the GLB -> FBX engine-export endpoint (headless Blender).
Presets tune the FBX for the target engine's import pipeline; see
app/tools/fbx_worker.py for the exact exporter settings each one maps to.
"""
preset: Literal["unity", "unreal", "generic"] = Field(
default="generic",
description="Target engine. 'unity'/'generic' write a meters file with "
"scale-1 transforms; 'unreal' bakes the scene to centimeters.")
unreal_scale_mode: Literal["bake", "units"] = Field(
default="bake",
description="Unreal only. 'bake' rescales mesh/armature/animation data "
"x100 to native centimeters; 'units' keeps meters and relies "
"on UE's 'Convert Scene Unit' import option.")
bake_fps: int = Field(default=30, ge=1, le=120,
description="Frame rate animation takes are baked at.")
anim_simplify: float = Field(default=1.0, ge=0.0, le=10.0,
description="Baked curve simplification (0 = lossless, larger = smaller files).")
class MeshStats(BaseModel):
"""Reported back to the caller (also surfaced via response headers)."""

View file

@ -0,0 +1,116 @@
"""GLB -> FBX conversion — subprocess driver for app/tools/fbx_worker.py.
The worker owns the actual Blender (bpy) work; this module only provisions a
job directory, spawns the worker with the venv's own interpreter, relays its
sentinel-prefixed progress lines, and returns the FBX bytes + stats.
bpy stays OUT of this process on purpose: it is not thread-safe, keeps ~1GB RSS
once imported, and a Blender crash must not take the API down. Conversions are
serialized with a semaphore for the same reason (each subprocess peaks 1-2GB).
"""
from __future__ import annotations
import json
import os
import shutil
import subprocess
import sys
import threading
from pathlib import Path
from uuid import uuid4
from ..config import CONVERT_TIMEOUT_S, WORK_DIR
from ..schemas import ConvertOptions
SENTINEL = "GENSTUDIO_EVT " # keep in sync with app/tools/fbx_worker.py
_WORKER = Path(__file__).resolve().parents[1] / "tools" / "fbx_worker.py"
_convert_lock = threading.Semaphore(1)
def run_convert_fbx(glb_bytes: bytes, opts: ConvertOptions, progress) -> tuple[bytes, dict]:
"""Convert a GLB to FBX. Returns (fbx_bytes, worker_stats); raises on failure.
`progress(stage, frac, message)` is called for each worker progress event.
"""
job_dir = WORK_DIR / f"convert-{uuid4().hex}"
job_dir.mkdir(parents=True)
try:
in_path = job_dir / "input.glb"
in_path.write_bytes(glb_bytes)
out_path = job_dir / "output.fbx"
opt_path = job_dir / "options.json"
opt_path.write_text(opts.model_dump_json(), encoding="utf-8")
with _convert_lock:
result = _run_worker(in_path, out_path, opt_path, progress)
if not result.get("ok"):
raise RuntimeError(result.get("error") or "FBX conversion failed.")
if not out_path.exists():
raise RuntimeError("FBX worker reported success but produced no output file.")
return out_path.read_bytes(), result.get("stats") or {}
finally:
shutil.rmtree(job_dir, ignore_errors=True)
def _run_worker(in_path: Path, out_path: Path, opt_path: Path, progress) -> dict:
proc = subprocess.Popen(
[
sys.executable,
str(_WORKER),
"--input", str(in_path),
"--output", str(out_path),
"--options", str(opt_path),
],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
encoding="utf-8",
errors="replace",
env={**os.environ, "PYTHONIOENCODING": "utf-8", "PYTHONUNBUFFERED": "1"},
)
# Watchdog instead of a read timeout: the stdout iteration below ends when
# the process dies, so killing it on expiry unblocks the loop too.
timed_out = threading.Event()
def _expire():
timed_out.set()
proc.kill()
watchdog = threading.Timer(CONVERT_TIMEOUT_S, _expire)
watchdog.daemon = True
watchdog.start()
result: dict | None = None
tail: list[str] = [] # last non-protocol lines, for error context
try:
for line in proc.stdout:
if not line.startswith(SENTINEL):
stripped = line.strip()
if stripped:
tail.append(stripped)
del tail[:-8]
continue
try:
event = json.loads(line[len(SENTINEL):])
except json.JSONDecodeError:
continue
if event.get("type") == "progress":
progress(event.get("stage", "convert"), event.get("frac", 0.0), event.get("message", ""))
elif event.get("type") == "result":
result = event
code = proc.wait()
finally:
watchdog.cancel()
if proc.poll() is None:
proc.kill()
if timed_out.is_set():
raise RuntimeError(f"FBX conversion timed out after {CONVERT_TIMEOUT_S}s.")
if result is None:
detail = f" Last output: {' | '.join(tail)}" if tail else ""
raise RuntimeError(f"FBX worker exited (code {code}) without a result.{detail}")
return result

View file

@ -0,0 +1,5 @@
"""Standalone worker scripts run as subprocesses by app/services wrappers.
Nothing in here should be imported by the FastAPI process — workers may pull in
heavy/unsafe-in-process dependencies (bpy is not thread-safe and never unloads).
"""

View file

@ -0,0 +1,293 @@
"""GLB -> FBX conversion worker (headless Blender).
Runs `bpy` in ISOLATION: invoked as a subprocess by app/services/convert_fbx.py
(`python fbx_worker.py --input in.glb --output out.fbx --options opts.json`).
Never import this module from the service — bpy is not thread-safe, holds ~1GB
RSS once imported, and a crash inside Blender must not take the API down.
Presets tailor the FBX for the target engine:
- unity : file declared in meters with clean scale-1 transforms
(FBX_SCALE_UNITS -> Unity "File Scale" = 1).
- unreal : the scene is baked to centimeters (x100 on mesh/armature data and
every location F-curve) and written with FBX_SCALE_NONE, so UE
imports at the right size with unit bone scales — no reliance on
the "Convert Scene Unit" import option.
- generic : same neutral meters export as unity (most interoperable).
Every glTF animation arrives as an NLA track (that is how Blender's importer
stashes clips); the exporter turns each NLA strip into a separate FBX take, so
engines see one clip per animation.
Protocol: progress/result JSON lines on stdout prefixed with GENSTUDIO_EVT
(bpy prints its own "Info:" noise, the parent ignores non-matching lines).
Exit codes: 0 ok, 2 conversion error, 3 validation failed, 4 bpy missing.
"""
from __future__ import annotations
import argparse
import json
import sys
SENTINEL = "GENSTUDIO_EVT " # keep in sync with app/services/convert_fbx.py
# Shared exporter settings. Axis conversion stays on the export matrix
# (use_space_transform) instead of being baked into vertices:
# bake_space_transform=True is unsafe with skinned meshes — it transforms mesh
# data but not armature/bone animation consistently. The compensating root
# rotation it avoids is absorbed by Unity/Unreal importers anyway.
COMMON_FBX = dict(
check_existing=False,
use_selection=False,
object_types={"ARMATURE", "MESH"},
use_mesh_modifiers=True,
mesh_smooth_type="FACE",
use_tspace=False, # tangent export fails on generated/disconnected UVs
add_leaf_bones=False, # leaf bones pollute Unity/UE skeletons
primary_bone_axis="Y",
secondary_bone_axis="X",
use_armature_deform_only=True,
armature_nodetype="NULL",
bake_anim=True,
bake_anim_use_all_bones=True,
bake_anim_use_nla_strips=True, # one take per clip (NLA-stashed by the importer)
bake_anim_use_all_actions=False, # True would cross-product junk takes
bake_anim_force_startend_keying=True,
bake_anim_step=1.0,
path_mode="COPY",
embed_textures=True,
axis_forward="-Z",
axis_up="Y",
use_space_transform=True,
bake_space_transform=False,
)
METER_SCALE_FBX = dict( # unity + generic
apply_unit_scale=True,
apply_scale_options="FBX_SCALE_UNITS",
global_scale=1.0,
)
CM_BAKED_FBX = dict( # unreal, after the x100 bake
apply_unit_scale=False,
apply_scale_options="FBX_SCALE_NONE",
global_scale=1.0,
)
def emit(obj: dict) -> None:
sys.stdout.write(SENTINEL + json.dumps(obj, separators=(",", ":")) + "\n")
sys.stdout.flush()
def progress(stage: str, frac: float, message: str = "") -> None:
emit({"type": "progress", "stage": stage, "frac": round(float(frac), 4), "message": message})
def fail(error: str, code: int) -> None:
emit({"type": "result", "ok": False, "error": error})
sys.exit(code)
def normalize_nla(objects) -> list[str]:
"""Make the exporter's take collection deterministic.
The FBX exporter only bakes UNMUTED NLA strips, and depending on the
Blender version the glTF importer may leave the last clip as a dangling
active action instead of a stashed track. Unmute everything, stash any
dangling active action as its own track, and clear active actions so no
clip layers on top of the strip bakes. Returns the clip (strip) names.
"""
clip_names: list[str] = []
for obj in objects:
ad = obj.animation_data
if not ad:
continue
for track in ad.nla_tracks:
track.mute = False
clip_names.extend(strip.name for strip in track.strips)
action = ad.action
if action is not None:
in_nla = any(
strip.action == action
for track in ad.nla_tracks
for strip in track.strips
)
if not in_nla:
track = ad.nla_tracks.new()
track.name = action.name
track.strips.new(action.name, int(action.frame_range[0]), action)
clip_names.append(action.name)
ad.action = None
# A clip animating several objects appears once per object — dedupe, keep order.
return list(dict.fromkeys(clip_names))
def collect_stats(objects, clip_names) -> dict:
import bpy
armatures = [o for o in objects if o.type == "ARMATURE"]
meshes = [o for o in objects if o.type == "MESH"]
seen_mesh_data = {m.data for m in meshes}
return {
"armature_count": len(armatures),
"bones": sum(len(a.data.bones) for a in armatures),
"meshes": len(meshes),
"vertices": sum(len(d.vertices) for d in seen_mesh_data),
"materials": len([m for m in bpy.data.materials if m.users]),
"has_uv": any(d.uv_layers for d in seen_mesh_data),
"clips": clip_names,
}
def bake_unreal_scale(objects, factor: float = 100.0) -> None:
"""Bake the scene from meters to centimeters at the DATA level.
Data-level transforms (Mesh.transform / Armature.transform) avoid the
operator selection/context dance that transform_apply needs headless, and
sidestep its child parent-inverse compensation (which would leave mesh data
small behind a scale-100 node — exactly the transform FBX must not carry).
Skinning stays consistent because in Blender the armature rest pose IS the
bind pose: scaling mesh and rest bones by the same factor preserves it.
"""
import bpy
from mathutils import Matrix
scale = Matrix.Scale(factor, 4)
seen_data = set()
for obj in objects:
if obj.type in {"MESH", "ARMATURE"} and obj.data not in seen_data:
seen_data.add(obj.data)
obj.data.transform(scale)
obj.location = [component * factor for component in obj.location]
parent_inverse = obj.matrix_parent_inverse.copy()
parent_inverse.translation *= factor
obj.matrix_parent_inverse = parent_inverse
# Object/data transforms do not touch animation: location F-curves (object
# and pose-bone hip/root-motion translation) are in now-x100 local units.
for action in bpy.data.actions:
for fcurve in _action_fcurves(action):
if fcurve.data_path == "location" or fcurve.data_path.endswith(".location"):
for key in fcurve.keyframe_points:
key.co.y *= factor
key.handle_left.y *= factor
key.handle_right.y *= factor
def _action_fcurves(action):
"""All F-curves of an action across bpy versions: Blender 5.x replaced the
flat Action.fcurves with slotted actions (layers > strips > channelbags)."""
fcurves = getattr(action, "fcurves", None)
if fcurves is not None:
return list(fcurves)
return [
fcurve
for layer in action.layers
for strip in layer.strips
if strip.type == "KEYFRAME"
for channelbag in strip.channelbags
for fcurve in channelbag.fcurves
]
def validate_reimport(path: str, in_stats: dict, clip_names: list[str]) -> dict:
"""Re-import the exported FBX into a fresh scene and assert nothing was lost."""
import bpy
bpy.ops.wm.read_factory_settings(use_empty=True)
bpy.ops.import_scene.fbx(filepath=path, ignore_leaf_bones=True)
objects = list(bpy.context.scene.objects)
armatures = [o for o in objects if o.type == "ARMATURE"]
meshes = [o for o in objects if o.type == "MESH"]
actions = list(bpy.data.actions) # FBX importer: one action per take
if in_stats["armature_count"] and not armatures:
raise ValidationError("exported FBX contains no armature")
if clip_names and len(actions) < len(clip_names):
raise ValidationError(
f"expected {len(clip_names)} animation take(s), re-import found {len(actions)}"
)
if in_stats["meshes"] and not meshes:
raise ValidationError("exported FBX contains no mesh")
return {
"armatures": len(armatures),
"meshes": len(meshes),
"actions": sorted(action.name for action in actions),
}
class ValidationError(RuntimeError):
pass
def convert(input_path: str, output_path: str, opts: dict) -> dict:
import bpy
bpy.ops.wm.read_factory_settings(use_empty=True)
scene = bpy.context.scene
# Set fps BEFORE import: the glTF importer converts clip times to frames
# with the scene fps, and the exporter bakes one key per frame.
scene.render.fps = int(opts.get("bake_fps", 30))
scene.render.fps_base = 1.0
progress("import", 0.1, "Importing GLB…")
bpy.ops.import_scene.gltf(filepath=input_path)
objects = list(scene.objects)
clip_names = normalize_nla(objects)
stats = collect_stats(objects, clip_names)
progress(
"import", 0.3,
f"Imported {stats['armature_count']} armature(s) ({stats['bones']} bones), "
f"{stats['meshes']} mesh(es), {len(clip_names)} clip(s)",
)
preset = opts.get("preset", "generic")
kwargs = dict(COMMON_FBX)
kwargs["bake_anim_simplify_factor"] = float(opts.get("anim_simplify", 1.0))
if preset == "unreal" and opts.get("unreal_scale_mode", "bake") == "bake":
progress("transform", 0.45, "Baking centimeter scale for Unreal…")
bake_unreal_scale(objects)
kwargs.update(CM_BAKED_FBX)
else:
kwargs.update(METER_SCALE_FBX)
progress("export", 0.55, f"Baking {len(clip_names)} animation take(s) to FBX…")
bpy.ops.export_scene.fbx(filepath=output_path, **kwargs)
progress("validate", 0.8, "Re-importing FBX to validate…")
stats["validation"] = validate_reimport(output_path, stats, clip_names)
stats["preset"] = preset
return stats
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--input", required=True, help="Source .glb path")
parser.add_argument("--output", required=True, help="Destination .fbx path")
parser.add_argument("--options", required=True, help="Path to an options JSON file")
args = parser.parse_args()
with open(args.options, encoding="utf-8") as handle:
opts = json.load(handle)
try:
import bpy # noqa: F401 — probe only; used inside convert()
except ImportError as exc:
fail(f"bpy is not installed in this environment: {exc}", 4)
try:
stats = convert(args.input, args.output, opts)
except ValidationError as exc:
fail(f"Validation failed: {exc}", 3)
except Exception as exc: # noqa: BLE001 — everything must surface to the parent
import traceback
traceback.print_exc()
fail(f"{type(exc).__name__}: {exc}", 2)
else:
emit({"type": "result", "ok": True, "stats": stats})
if __name__ == "__main__":
main()

View file

@ -16,6 +16,12 @@ pymeshlab>=2023.12 # isotropic remesh / decimation / quad conversion
matplotlib>=3.8 # only needed for the CLI's UV-layout / compare PNGs
rtree
# Engine export (GLB -> FBX via headless Blender). cp313 wheel (~340MB download,
# ~1GB installed); each bpy release supports exactly one Python version — keep in
# sync with .python-version (3.13). Imported ONLY by app/tools/fbx_worker.py,
# which runs as a subprocess (never import bpy in the FastAPI process).
bpy>=5.0,<6
# --- Optional GPU acceleration (Auto Retopo) ---------------------------------
# GPU packages live in requirements-nvidia.txt and are NOT installed from this
# file. run.bat auto-detects an NVIDIA GPU on first setup and installs them

View file

@ -5864,6 +5864,18 @@ app.post('/api/meshes/repair', meshToolsUpload.single('meshFile'), async (req, r
}
});
// GLB -> FBX engine-preset conversion (headless Blender in the mesh-tools
// service). Used by the Unity/Unreal/FBX export presets; preserves the
// skeleton and one animation take per clip.
app.post('/api/meshes/convert', meshToolsUpload.single('meshFile'), async (req, res) => {
try {
await proxyMeshTool('/meshes/convert', req, res);
} catch (err) {
console.error('Mesh convert proxy failed:', err);
if (!res.headersSent) res.status(500).json({ error: err.message || 'Mesh convert failed' });
}
});
// Auto Rig proxies to the dedicated rigging micro-service (SkinTokens/TokenRig),
// which runs on its own host/port (settings.apis.rigtools) with a GPU/ML stack.
// Same SSE contract as the mesh-tools routes above.

View file

@ -145,6 +145,32 @@
color: var(--on-surface-variant);
}
.export-mesh__progress {
display: flex;
flex-direction: column;
gap: 0.35rem;
}
.export-mesh__progress-track {
height: 6px;
border-radius: 999px;
background: rgba(71, 72, 74, 0.28);
overflow: hidden;
}
.export-mesh__progress-bar {
height: 100%;
border-radius: 999px;
background: var(--primary);
transition: width 0.25s ease;
}
.export-mesh__progress-message {
font-size: 0.74rem;
line-height: 1.4;
color: var(--on-surface-variant);
}
.export-mesh__message {
padding: 0.65rem 0.8rem;
border-radius: var(--radius-md);

View file

@ -3,25 +3,53 @@ import FolderBrowserDialog from './FolderBrowserDialog'
import {
EXPORT_FORMATS,
exportObject3D,
isGlbUrl,
loadObject3DFromUrl,
sanitizeBaseName,
writeExportedFiles
} from '../utils/meshExport'
import { convertMesh, ensureDesktopService } from '../utils/meshTools'
import './ExportMeshDialog.css'
// Reusable export popup. Provide either `getObject3D` (an async function that
// returns the in-memory THREE.Object3D to export) or `meshUrl` (a mesh URL the
// dialog loads itself). `defaultName` seeds the output file name.
//
// Engine presets (Blender/Unity/Unreal/FBX) are only offered in `meshUrl` mode:
// they exist to carry the rig + animation clips of saved assets, while
// `getObject3D` callers (the mesh editor) hand over rig-free geometry.
export default function ExportMeshDialog({ getObject3D, meshUrl, defaultName = 'mesh', onClose }) {
const [format, setFormat] = useState('glb')
const [fileName, setFileName] = useState(sanitizeBaseName(defaultName))
const [outputFolder, setOutputFolder] = useState('')
const [showFolderBrowser, setShowFolderBrowser] = useState(false)
const [exporting, setExporting] = useState(false)
const [progress, setProgress] = useState(null)
const [error, setError] = useState('')
const [success, setSuccess] = useState('')
const selectedFormat = EXPORT_FORMATS.find(entry => entry.value === format) || EXPORT_FORMATS[0]
const formats = getObject3D ? EXPORT_FORMATS.filter(entry => entry.kind === 'local') : EXPORT_FORMATS
const selectedFormat = formats.find(entry => entry.value === format) || formats[0]
// Source GLB for the preset paths. When the asset is already a .glb, use its
// original bytes (perfect fidelity — skin weights, clips and textures
// untouched); otherwise serialize through three.js, which now carries the
// loaded animations onto the exported GLB.
const getSourceGlbBlob = async base => {
if (!getObject3D && meshUrl && isGlbUrl(meshUrl)) {
const response = await fetch(meshUrl)
if (!response.ok) {
throw new Error('Could not fetch the source mesh.')
}
return await response.blob()
}
const object = getObject3D ? await getObject3D() : await loadObject3DFromUrl(meshUrl)
if (!object) {
throw new Error('No mesh is available to export.')
}
const files = await exportObject3D(object, { format: 'glb', baseName: base })
return files[0].blob
}
const handleExport = async () => {
const folder = outputFolder.trim()
@ -35,21 +63,51 @@ export default function ExportMeshDialog({ getObject3D, meshUrl, defaultName = '
setExporting(true)
setError('')
setSuccess('')
setProgress(null)
try {
const object = getObject3D ? await getObject3D() : await loadObject3DFromUrl(meshUrl)
if (!object) {
throw new Error('No mesh is available to export.')
let files
let convertNote = ''
if (selectedFormat.kind !== 'preset') {
const object = getObject3D ? await getObject3D() : await loadObject3DFromUrl(meshUrl)
if (!object) {
throw new Error('No mesh is available to export.')
}
files = await exportObject3D(object, { format: selectedFormat.value, baseName: base })
} else if (selectedFormat.value === 'blender') {
setProgress({ frac: 0.2, message: 'Preparing GLB…' })
files = [{ filename: `${base}.glb`, blob: await getSourceGlbBlob(base) }]
} else {
setProgress({ frac: 0.05, message: 'Preparing source GLB…' })
const glbBlob = await getSourceGlbBlob(base)
setProgress({ frac: 0.1, message: 'Starting the Mesh Tools service…' })
await ensureDesktopService('meshtools')
const { blob, stats } = await convertMesh(glbBlob, {
options: { preset: selectedFormat.preset },
fileName: `${base}.glb`,
onProgress: evt => setProgress({
frac: 0.1 + 0.85 * (evt.frac ?? 0),
message: evt.message || 'Converting to FBX…'
})
})
files = [{ filename: `${base}.fbx`, blob }]
const tool = stats?.tool
if (tool) {
const clipCount = Array.isArray(tool.clips) ? tool.clips.length : 0
convertNote = ` — ${tool.bones || 0} bones, ${clipCount} animation clip${clipCount === 1 ? '' : 's'}`
}
}
const files = await exportObject3D(object, { format, baseName: base })
setProgress({ frac: 0.97, message: 'Writing files…' })
const result = await writeExportedFiles(folder, files)
const writtenNames = (result?.written || files.map(file => file.filename)).join(', ')
setSuccess(`Exported ${files.length} file${files.length === 1 ? '' : 's'}: ${writtenNames}`)
setSuccess(`Exported ${files.length} file${files.length === 1 ? '' : 's'}: ${writtenNames}${convertNote}`)
} catch (err) {
setError(err.message || 'Failed to export the mesh.')
} finally {
setExporting(false)
setProgress(null)
}
}
@ -77,7 +135,7 @@ export default function ExportMeshDialog({ getObject3D, meshUrl, defaultName = '
value={format}
onChange={event => { setFormat(event.target.value); setSuccess('') }}
>
{EXPORT_FORMATS.map(entry => (
{formats.map(entry => (
<option key={entry.value} value={entry.value}>{entry.label}</option>
))}
</select>
@ -117,11 +175,20 @@ export default function ExportMeshDialog({ getObject3D, meshUrl, defaultName = '
</div>
</label>
{selectedFormat.multiFile && (
<p className="export-mesh__hint">
OBJ saves geometry, materials and textures as separate files named after the mesh
(e.g. {sanitizeBaseName(fileName)}.obj, {sanitizeBaseName(fileName)}.mtl, {sanitizeBaseName(fileName)}_albedo.png).
</p>
{selectedFormat.hint && (
<p className="export-mesh__hint">{selectedFormat.hint}</p>
)}
{progress && (
<div className="export-mesh__progress" role="status">
<div className="export-mesh__progress-track">
<div
className="export-mesh__progress-bar"
style={{ width: `${Math.round(Math.min(1, Math.max(0, progress.frac)) * 100)}%` }}
/>
</div>
<span className="export-mesh__progress-message">{progress.message}</span>
</div>
)}
{error && <div className="export-mesh__message export-mesh__message--error">{error}</div>}

View file

@ -10,13 +10,40 @@ import { PLYExporter } from 'three/examples/jsm/exporters/PLYExporter.js'
import { STLExporter } from 'three/examples/jsm/exporters/STLExporter.js'
import { API_BASE } from '../config'
// Formats we can reliably serialize with three.js. FBX has no official
// exporter, so it is intentionally excluded.
// kind 'local' — serialized in the browser with three.js exporters.
// kind 'preset' — engine-targeted exports (Blender/Unity/Unreal). FBX has no
// three.js exporter, so those go through the mesh-tools service, which runs
// headless Blender to convert a GLB into an engine-tuned FBX (skeleton + one
// animation take per clip). Presets are only offered when exporting from a
// mesh URL (asset library preview) — the mesh editor exports raw geometry.
export const EXPORT_FORMATS = [
{ value: 'glb', label: 'GLB — single file, textures embedded', extension: 'glb', multiFile: false },
{ value: 'obj', label: 'OBJ — geometry + .mtl + textures', extension: 'obj', multiFile: true },
{ value: 'ply', label: 'PLY — geometry only', extension: 'ply', multiFile: false },
{ value: 'stl', label: 'STL — geometry only', extension: 'stl', multiFile: false }
{ value: 'glb', label: 'GLB — single file, textures embedded', extension: 'glb', multiFile: false, kind: 'local' },
{
value: 'blender', label: 'Blender — GLB (rig + animations)', extension: 'glb', multiFile: false,
kind: 'preset', preset: 'blender', requiresService: false,
hint: 'Blender imports GLB natively (File > Import > glTF 2.0) with the skeleton and every animation clip. GLB source assets are copied byte-for-byte for perfect fidelity.'
},
{
value: 'unity', label: 'Unity — FBX (rig + animation takes)', extension: 'fbx', multiFile: false,
kind: 'preset', preset: 'unity', requiresService: true,
hint: 'Drop the .fbx into Assets. Textures are embedded — use Materials > Extract Textures. Pick the rig type under Rig (Humanoid may need Enforce T-Pose); each clip appears as a separate take.'
},
{
value: 'unreal', label: 'Unreal Engine — FBX (cm, rig + takes)', extension: 'fbx', multiFile: false,
kind: 'preset', preset: 'unreal', requiresService: true,
hint: 'Import as Skeletal Mesh with "Import Animations" enabled. The file is exported in centimeters at scale 1 — no unit conversion needed.'
},
{
value: 'fbx', label: 'FBX — generic (rig + animation takes)', extension: 'fbx', multiFile: false,
kind: 'preset', preset: 'generic', requiresService: true,
hint: 'Neutral FBX (meters, Y-up) with the skeleton and one take per animation clip. Suitable for Godot, Maya, 3ds Max and other DCC tools.'
},
{
value: 'obj', label: 'OBJ — geometry + .mtl + textures', extension: 'obj', multiFile: true, kind: 'local',
hint: 'OBJ saves geometry, materials and textures as separate files named after the mesh (e.g. mesh.obj, mesh.mtl, mesh_albedo.png).'
},
{ value: 'ply', label: 'PLY — geometry only', extension: 'ply', multiFile: false, kind: 'local' },
{ value: 'stl', label: 'STL — geometry only', extension: 'stl', multiFile: false, kind: 'local' }
]
function defaultMaterial() {
@ -29,6 +56,13 @@ function getExtensionFromUrl(url) {
return dot >= 0 ? clean.slice(dot).toLowerCase() : ''
}
// True when the URL points at a binary glTF — those sources can be exported
// byte-for-byte (or fed to the FBX converter) without a lossy three.js
// round-trip.
export function isGlbUrl(url) {
return getExtensionFromUrl(url) === '.glb'
}
function loadWithLoader(loader, url) {
return new Promise((resolve, reject) => {
loader.load(url, resolve, undefined, reject)
@ -54,6 +88,10 @@ export async function loadObject3DFromUrl(url) {
if (!scene) {
throw new Error('The glTF file did not contain a scene to export.')
}
// Carry the clips on the object (FBXLoader's convention) so exportGlb can
// hand them to GLTFExporter — otherwise animated assets re-export silently
// stripped of their animations.
scene.animations = Array.isArray(gltf.animations) ? gltf.animations : []
return scene
}
@ -125,7 +163,10 @@ function exportGlb(object, base) {
resolve([{ filename: `${base}.glb`, blob: new Blob([result], { type: 'model/gltf-binary' }) }])
},
error => reject(error instanceof Error ? error : new Error('Failed to export the mesh as GLB.')),
{ binary: true, onlyVisible: false }
// Loader-produced clips are already node-name-addressed, so they need no
// track renaming here — the `.bones[...]` rewrite in animationLibrary.js
// exists only for the retargeter's mixer-bound clips.
{ binary: true, onlyVisible: false, animations: object.animations || [] }
)
})
}

View file

@ -127,6 +127,14 @@ export function repairMesh(meshBlob, opts = {}) {
return callMeshTool('/meshes/repair', meshBlob, opts)
}
// GLB -> FBX engine-preset conversion (headless Blender in the mesh-tools
// service). options: { preset: 'unity'|'unreal'|'generic', ... } — see the
// service's ConvertOptions. Same SSE contract; the returned blob is the FBX and
// stats.tool carries { bones, meshes, clips, preset, validation }.
export function convertMesh(meshBlob, opts = {}) {
return callMeshTool('/meshes/convert', meshBlob, { ...opts, format: 'fbx' })
}
// Auto Rig (SkinTokens/TokenRig). Proxies to the dedicated rigging service; the
// returned blob is a SKINNED GLB (mesh + skeleton + skin weights) — unlike the
// tools above it must NOT be flattened into editable geometry. Same SSE contract;