diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..288bf1a --- /dev/null +++ b/.gitattributes @@ -0,0 +1,11 @@ +# Default: let Git normalize text files, auto-detecting on commit. +* text=auto + +# Shell scripts MUST use LF — CRLF breaks the shebang on Linux/macOS +# ("bad interpreter: /usr/bin/env bash^M"). core.autocrlf=true would otherwise +# convert them on checkout. +*.sh text eol=lf + +# Windows batch files need CRLF. +*.bat text eol=crlf +*.cmd text eol=crlf diff --git a/.github/workflows/desktop-build.yml b/.github/workflows/desktop-build.yml index 4eaad9e..de12135 100644 --- a/.github/workflows/desktop-build.yml +++ b/.github/workflows/desktop-build.yml @@ -32,7 +32,7 @@ jobs: - name: Set up Node uses: actions/setup-node@v5 with: - node-version: 22 + node-version: 24 cache: npm - name: Install dependencies diff --git a/.gitignore b/.gitignore index 548dfbf..75e1c49 100644 --- a/.gitignore +++ b/.gitignore @@ -27,4 +27,17 @@ Thumbs.db dev.log python-server.log -.claude/ \ No newline at end of file +.claude/ + +# Python +__pycache__/ +.venv/ + +# SkinTokens rigging service — generated / downloaded artifacts (never commit) +thirdparty/skintokens/.venv/ +thirdparty/skintokens/rig-server.log +thirdparty/skintokens/experiments/ +thirdparty/skintokens/models/ +thirdparty/skintokens/tmp_ckpt/ +thirdparty/skintokens/tmp_gradio/ +thirdparty/skintokens/results/ \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 4ffaa98..5be485b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "app", - "version": "0.0.0", + "version": "1.3.3", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "app", - "version": "0.0.0", + "version": "1.3.3", "dependencies": { "@react-three/drei": "^10.7.7", "@react-three/fiber": "^9.5.0", @@ -31,7 +31,8 @@ "tencentcloud-sdk-nodejs-intl-en": "^3.0.1352", "three": "^0.183.2", "three-bvh-csg": "^0.0.18", - "three-mesh-bvh": "^0.9.9" + "three-mesh-bvh": "^0.9.9", + "ws": "^8.21.0" }, "devDependencies": { "@eslint/js": "^9.39.4", @@ -11638,6 +11639,27 @@ "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", "license": "ISC" }, + "node_modules/ws": { + "version": "8.21.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz", + "integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, "node_modules/xmlbuilder": { "version": "15.1.1", "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-15.1.1.tgz", diff --git a/package.json b/package.json index fb4793f..447654f 100644 --- a/package.json +++ b/package.json @@ -49,19 +49,20 @@ "tencentcloud-sdk-nodejs-intl-en": "^3.0.1352", "three": "^0.183.2", "three-bvh-csg": "^0.0.18", - "three-mesh-bvh": "^0.9.9" + "three-mesh-bvh": "^0.9.9", + "ws": "^8.21.0" }, "devDependencies": { "@eslint/js": "^9.39.4", "@types/react": "^19.2.14", "@types/react-dom": "^19.2.3", "@vitejs/plugin-react": "^6.0.1", + "electron": "^33.2.0", + "electron-builder": "^25.1.8", "eslint": "^9.39.4", "eslint-plugin-react-hooks": "^7.0.1", "eslint-plugin-react-refresh": "^0.5.2", "globals": "^17.4.0", - "vite": "^8.0.4", - "electron": "^33.2.0", - "electron-builder": "^25.1.8" + "vite": "^8.0.4" } } diff --git a/python-server/.python-version b/python-server/.python-version new file mode 100644 index 0000000..24ee5b1 --- /dev/null +++ b/python-server/.python-version @@ -0,0 +1 @@ +3.13 diff --git a/python-server/run.bat b/python-server/run.bat index 3d5eeaa..12d5141 100644 --- a/python-server/run.bat +++ b/python-server/run.bat @@ -1,10 +1,17 @@ @echo off :: Start the 3D Gen Studio Python mesh-processing service. -:: On first run: creates a local virtual environment, installs the base (CPU) -:: requirements, then auto-detects an NVIDIA GPU and installs matching GPU +:: On first run: uses `uv` to provision a pinned standalone Python (see +:: .python-version), create a local virtual environment, install the base (CPU) +:: requirements, then auto-detect an NVIDIA GPU and install matching GPU :: acceleration (Warp + the correct cupy-cudaXXx wheel for your CUDA version). +:: +:: uv gives every machine the SAME Python without depending on a system install +:: (mirrors thirdparty/skintokens). It is auto-downloaded if not already present. setlocal enabledelayedexpansion cd /d "%~dp0" +set "PYVER=3.13" + +call :ensure_uv || goto :error if not exist ".venv\Scripts\python.exe" ( call :setup || goto :error @@ -17,15 +24,29 @@ python main.py goto :eof +:ensure_uv +set "UV=" +where uv >nul 2>nul && set "UV=uv" +if not defined UV if exist "%USERPROFILE%\.local\bin\uv.exe" set "UV=%USERPROFILE%\.local\bin\uv.exe" +if not defined UV ( + echo Installing uv ^(Python toolchain manager^)... + powershell -NoProfile -ExecutionPolicy Bypass -Command "irm https://astral.sh/uv/install.ps1 | iex" || exit /b 1 + set "UV=%USERPROFILE%\.local\bin\uv.exe" +) +exit /b 0 + + :setup -echo Creating virtual environment... -python -m venv .venv || exit /b 1 +echo Provisioning Python %PYVER% via uv... +"%UV%" python install %PYVER% || exit /b 1 + +echo Creating virtual environment ^(Python %PYVER%^)... +"%UV%" venv .venv --python %PYVER% || exit /b 1 call ".venv\Scripts\activate.bat" -python -m pip install --upgrade pip echo. echo Installing base (CPU) requirements... -pip install -r requirements.txt || exit /b 1 +"%UV%" pip install -r requirements.txt || exit /b 1 :: --- Optional NVIDIA GPU acceleration ------------------------------------- :: detect_cuda.py prints the matching CuPy wheel (e.g. cupy-cuda13x) when an @@ -43,8 +64,8 @@ for /f "usebackq delims=" %%p in (`python detect_cuda.py`) do set "CUPY_PKG=%%p" if defined CUPY_PKG ( echo NVIDIA GPU detected -- installing GPU acceleration: !CUPY_PKG! + Warp - pip install -r requirements-nvidia.txt || exit /b 1 - pip install "!CUPY_PKG!" || exit /b 1 + "%UV%" pip install -r requirements-nvidia.txt || exit /b 1 + "%UV%" pip install "!CUPY_PKG!" || exit /b 1 echo GPU acceleration installed. ) else ( echo No NVIDIA GPU detected -- CPU-only install. Auto Retopo will run on the CPU. diff --git a/python-server/run.sh b/python-server/run.sh new file mode 100644 index 0000000..09a08c1 --- /dev/null +++ b/python-server/run.sh @@ -0,0 +1,60 @@ +#!/usr/bin/env bash +# Start the 3D Gen Studio Python mesh-processing service (Linux / macOS). +# +# On first run: uses `uv` to provision a pinned standalone Python (see +# .python-version), create a local virtual environment, install the base (CPU) +# requirements, then auto-detect an NVIDIA GPU and install matching GPU +# acceleration (Warp + the correct cupy-cudaXXx wheel). macOS has no NVIDIA GPU, +# so it always does a CPU-only install. +# +# uv is auto-downloaded if not already present. Override host/port via env +# (e.g. MESHTOOLS_PORT=8200). +set -euo pipefail +cd "$(dirname "$0")" +PYVER=3.13 + +# --- Ensure uv is available ------------------------------------------------- +if command -v uv >/dev/null 2>&1; then + UV="uv" +elif [ -x "$HOME/.local/bin/uv" ]; then + UV="$HOME/.local/bin/uv" +else + echo "Installing uv (Python toolchain manager)..." + curl -LsSf https://astral.sh/uv/install.sh | sh + UV="$HOME/.local/bin/uv" +fi + +if [ ! -x ".venv/bin/python" ]; then + echo "Provisioning Python $PYVER via uv..." + "$UV" python install "$PYVER" + echo "Creating virtual environment (Python $PYVER)..." + "$UV" venv .venv --python "$PYVER" + # shellcheck disable=SC1091 + source .venv/bin/activate + + echo + echo "Installing base (CPU) requirements..." + "$UV" pip install -r requirements.txt + + # --- Optional NVIDIA GPU acceleration ------------------------------------- + echo + if [ -n "${MESHTOOLS_SKIP_GPU:-}" ]; then + echo "MESHTOOLS_SKIP_GPU set -- skipping GPU acceleration (CPU-only install)." + else + echo "Detecting NVIDIA GPU / CUDA version..." + CUPY_PKG="$(python detect_cuda.py || true)" + if [ -n "$CUPY_PKG" ]; then + echo "NVIDIA GPU detected -- installing GPU acceleration: $CUPY_PKG + Warp" + "$UV" pip install -r requirements-nvidia.txt + "$UV" pip install "$CUPY_PKG" + echo "GPU acceleration installed." + else + echo "No NVIDIA GPU detected -- CPU-only install. Auto Retopo will run on the CPU." + fi + fi +else + # shellcheck disable=SC1091 + source .venv/bin/activate +fi + +python main.py diff --git a/run.bat b/run.bat index 10e523b..2e6ba72 100644 --- a/run.bat +++ b/run.bat @@ -10,6 +10,12 @@ start "3DGenStudio Dev" /min cmd /c "npm run dev > dev.log 2>&1" :: first run can take a few minutes; output goes to python-server\python-server.log. start "3DGenStudio Python" /min cmd /c "cd /d "%~dp0python-server" && run.bat > python-server.log 2>&1" +:: Start the SkinTokens rigging service (Auto Rig, port 8300) the same way. Its +:: run_server.bat builds a venv + installs torch/flash-attn/model on first launch, +:: so the FIRST run can take a long while (multi-GB download); output goes to +:: thirdparty\skintokens\rig-server.log. Needs an NVIDIA GPU (>=14 GB). +start "3DGenStudio Rigging" /min cmd /c "cd /d "%~dp0thirdparty\skintokens" && run_server.bat > rig-server.log 2>&1" + :: Wait a few seconds to let Vite + the backend spin up timeout /t 3 /nobreak >nul diff --git a/run.sh b/run.sh new file mode 100644 index 0000000..e3eb245 --- /dev/null +++ b/run.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env bash +# Launch 3D Gen Studio on Linux / macOS (the cross-platform counterpart of +# run.bat). Starts the Vite dev server + Node backend, the Python mesh-tools +# service, and the SkinTokens rigging service (Linux only — it self-skips on +# macOS), each logging to its own file, then opens the app in the browser. +# +# First launch is slow: the Python services build their uv virtual environments +# and download dependencies + model checkpoints in the background. +set -u +cd "$(dirname "$0")" + +echo "Starting dev server (npm run dev) -> dev.log" +npm run dev > dev.log 2>&1 & + +echo "Starting Python mesh-tools service -> python-server/python-server.log" +( cd python-server && bash run.sh > python-server.log 2>&1 ) & + +echo "Starting SkinTokens rigging service -> thirdparty/skintokens/rig-server.log" +( cd thirdparty/skintokens && bash run_server.sh > rig-server.log 2>&1 ) & + +# Give Vite + the backend a moment to come up. +sleep 3 + +URL="http://localhost:5173" +if command -v xdg-open >/dev/null 2>&1; then + xdg-open "$URL" >/dev/null 2>&1 & +elif command -v open >/dev/null 2>&1; then + open "$URL" >/dev/null 2>&1 & +else + echo "Open $URL in your browser." +fi + +echo +echo "3D Gen Studio is starting. Logs: dev.log, python-server/python-server.log, thirdparty/skintokens/rig-server.log" +echo "Press Ctrl+C to stop the dev server (background services keep running; close their windows/processes to stop them)." +wait diff --git a/server.js b/server.js index a09ace3..b883bc0 100644 --- a/server.js +++ b/server.js @@ -13,7 +13,12 @@ import process from 'node:process'; import os from 'node:os'; import { fileURLToPath } from 'node:url'; import si from 'systeminformation'; +import { WebSocket as WsWebSocket } from 'ws'; import tencentcloudSdk from 'tencentcloud-sdk-nodejs-intl-en'; + +// Node 20 (bundled by Electron 33) has no global WebSocket, so fall back to the +// `ws` package. Newer Node runtimes (dev) expose a global WebSocket we can reuse. +const WebSocketImpl = globalThis.WebSocket ?? WsWebSocket; import { ASSETS_DIR, DATA_DIR, @@ -896,6 +901,24 @@ function buildMeshToolsBaseUrl(settings = {}) { return parsedUrl.toString().replace(/\/$/, ''); } +// Base URL of the dedicated rigging micro-service (thirdparty/skintokens/rig_server.py). +// It lives on its own host/port because it needs a heavy GPU/ML environment that +// must not mix with the mesh-tools service. Mirrors buildMeshToolsBaseUrl. +function buildRigToolsBaseUrl(settings = {}) { + const rigSettings = settings?.apis?.rigtools || {}; + const rawUrl = String(rigSettings.url || 'http://127.0.0.1').trim(); + const normalizedUrl = /^https?:\/\//i.test(rawUrl) ? rawUrl : `http://${rawUrl}`; + const parsedUrl = new URL(normalizedUrl); + const port = String(rigSettings.port || parsedUrl.port || '8300').trim(); + + parsedUrl.port = port; + parsedUrl.pathname = ''; + parsedUrl.search = ''; + parsedUrl.hash = ''; + + return parsedUrl.toString().replace(/\/$/, ''); +} + function buildComfyUiWebSocketUrl(baseUrl, clientId) { const parsedUrl = new URL(baseUrl); const currentPath = parsedUrl.pathname && parsedUrl.pathname !== '/' ? parsedUrl.pathname.replace(/\/$/, '') : ''; @@ -1104,7 +1127,7 @@ function createComfyExecutionMonitor(baseUrl, { clientId, promptId, workflowJson }; const ready = new Promise((resolve, reject) => { - socket = new WebSocket(wsUrl); + socket = new WebSocketImpl(wsUrl); if (Number.isFinite(timeout) && timeout > 0) { timer = setTimeout(() => { @@ -1306,7 +1329,7 @@ function createComfyExecutionMonitor(baseUrl, { clientId, promptId, workflowJson close: () => { isSettled = true; clearTimeout(timer); - if (socket && socket.readyState < WebSocket.CLOSING) { + if (socket && socket.readyState < WebSocketImpl.CLOSING) { socket.close(); } } @@ -5731,14 +5754,14 @@ const meshToolsUpload = multer({ limits: { fileSize: 512 * 1024 * 1024 }, }); -async function proxyMeshTool(operationPath, req, res) { +async function proxyMeshTool(operationPath, req, res, { baseUrlBuilder = buildMeshToolsBaseUrl } = {}) { const meshFile = req.file; if (!meshFile?.buffer?.length) { return res.status(400).json({ error: 'meshFile is required' }); } const settings = await getSettings(); - const baseUrl = buildMeshToolsBaseUrl(settings); + const baseUrl = baseUrlBuilder(settings); const form = new FormData(); form.append( @@ -5834,6 +5857,18 @@ app.post('/api/meshes/repair', meshToolsUpload.single('meshFile'), async (req, r } }); +// 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. +app.post('/api/meshes/rig', meshToolsUpload.single('meshFile'), async (req, res) => { + try { + await proxyMeshTool('/meshes/rig', req, res, { baseUrlBuilder: buildRigToolsBaseUrl }); + } catch (err) { + console.error('Auto Rig proxy failed:', err); + if (!res.headersSent) res.status(500).json({ error: err.message || 'Auto Rig failed' }); + } +}); + // --- Mesh optimize (meshoptimizer / gltfpack binary) ------------------------ // Unlike Auto UV / Auto Retopo (which proxy to the Python service), this runs // the bundled `gltfpack` binary locally. The browser uploads a GLB; we write it diff --git a/src/components/SettingsModal.jsx b/src/components/SettingsModal.jsx index 8ce50fa..fb6444e 100644 --- a/src/components/SettingsModal.jsx +++ b/src/components/SettingsModal.jsx @@ -488,6 +488,61 @@ export default function SettingsModal({ onClose }) { python-server/run.bat. Can run on another machine or port.

+ +

Rigging (Python) Connection

+
+
+
+ accessibility_new +
+ Auto Rig +
+ +
+
+ + setLocalSettings(prev => ({ + ...prev, + apis: { + ...prev?.apis, + rigtools: { + ...prev?.apis?.rigtools, + url: e.target.value + } + } + }))} + /> +
+ +
+ + setLocalSettings(prev => ({ + ...prev, + apis: { + ...prev?.apis, + rigtools: { + ...prev?.apis?.rigtools, + port: e.target.value + } + } + }))} + /> +
+
+ +

+ The SkinTokens/TokenRig rigging service (Auto Rig). Start it from + thirdparty/skintokens/run_server.bat. Needs an NVIDIA GPU (≥14 GB). +

+
)} diff --git a/src/components/meshEditor/AutoRigToolsPanel.jsx b/src/components/meshEditor/AutoRigToolsPanel.jsx new file mode 100644 index 0000000..02f27b8 --- /dev/null +++ b/src/components/meshEditor/AutoRigToolsPanel.jsx @@ -0,0 +1,157 @@ +// Auto Rig mode left panel. Generates a skeleton + skin weights for the current +// mesh via the SkinTokens/TokenRig rigging service, shows the resulting skeleton +// as an overlay in the viewport, and lets you save the rigged GLB as a new +// version or download it. Presentational: option state + handlers come from +// MeshEditorPage. +// +// Unlike Auto UV / Auto Retopo, the rig result is a SKINNED GLB whose value is +// the skeleton itself, so it is NOT flattened back into the editable mesh — hence +// Save/Download instead of Keep/Revert. +import { RangeField, ToggleField, SelectField } from './MeshToolField' +import MeshToolProgress from './MeshToolProgress' + +export default function AutoRigToolsPanel({ + options, + setOption, + running, + progress, + result, + onRun, + onSaveResult, + onDownloadResult, + onDismissResult, + saving, + hasSkeleton, + showSkeleton, + onToggleSkeleton, + disabled, +}) { + const o = options + const fieldsDisabled = disabled || running + + return ( + <>{/* AUTO RIG */} +
+ Auto Rig + + + {!hasSkeleton && ( + This mesh has no skeleton yet. Run Auto Rig to generate one. + )} + + + + {running && } + + {result && ( +
+ + check_circle + Rig generated + + +
+ {result.rows.map(row => ( + {row.label}: {row.value} + ))} +
+ + + The skeleton is shown in the viewport. Save it as a new version or download the rigged GLB. + + +
+ + +
+ +
+ )} +
+ +
+ Skeleton + setOption('rename_bones', v)} disabled={fieldsDisabled} + options={[ + { value: 'mixamo', label: 'Mixamo' }, + { value: 'ue5', label: 'Unreal Engine 5' }, + { value: 'original', label: 'Keep model names' }, + ]} + hint="Rename the generated bones to a standard humanoid convention for retargeting" /> + setOption('use_transfer', v)} disabled={fieldsDisabled} + hint="Transfer the rig onto your original mesh (keeps its texture and scale). Recommended — leave on." /> + setOption('use_postprocess', v)} disabled={fieldsDisabled} + hint="Clean up skin weights with a voxel pass to reduce bleed across disconnected parts" /> +
+ +
+ Generation (advanced) + setOption('top_k', v)} disabled={fieldsDisabled} + hint="Top-k sampling" /> + setOption('top_p', v)} disabled={fieldsDisabled} + hint="Nucleus (top-p) sampling" /> + setOption('temperature', v)} disabled={fieldsDisabled} /> + setOption('repetition_penalty', v)} disabled={fieldsDisabled} /> + setOption('num_beams', v)} disabled={fieldsDisabled} + hint="Beam-search width" /> +
+ +
+ Auto Rig runs on the SkinTokens rigging service (Settings → Rigging). Needs an NVIDIA GPU. + The result is a skinned mesh; save it as a new version to keep the rig. +
+ + ) +} diff --git a/src/components/meshEditor/SkeletonOverlay.jsx b/src/components/meshEditor/SkeletonOverlay.jsx new file mode 100644 index 0000000..bd8ae64 --- /dev/null +++ b/src/components/meshEditor/SkeletonOverlay.jsx @@ -0,0 +1,64 @@ +// Renders a skeleton as an overlay inside the mesh-editor : orange bone +// segments (parent→child) plus a dot at each joint, drawn on top of the mesh so +// the rig is visible through the surface (like a DCC armature view). Fed by the +// plain data from utils/meshEditor.js `extractSkeletonFromObject`. +import { useEffect, useMemo } from 'react' +import * as THREE from 'three' + +const BONE_COLOR = '#f0913c' +const JOINT_COLOR = '#ffd9a0' + +export default function SkeletonOverlay({ skeleton, visible = true }) { + const lineGeometry = useMemo(() => { + if (!skeleton?.segments?.length) return null + const geo = new THREE.BufferGeometry() + geo.setAttribute('position', new THREE.BufferAttribute(skeleton.segments, 3)) + return geo + }, [skeleton]) + + const jointGeometry = useMemo(() => { + if (!skeleton?.joints?.length) return null + const geo = new THREE.BufferGeometry() + geo.setAttribute('position', new THREE.BufferAttribute(skeleton.joints, 3)) + return geo + }, [skeleton]) + + // Size joint dots relative to the skeleton's extent so they read on any scale. + const jointSize = useMemo(() => Math.max((skeleton?.size || 1) * 0.02, 1e-4), [skeleton]) + + useEffect(() => () => { + lineGeometry?.dispose() + jointGeometry?.dispose() + }, [lineGeometry, jointGeometry]) + + if (!visible || (!lineGeometry && !jointGeometry)) return null + + return ( + + {lineGeometry && ( + + + + )} + {jointGeometry && ( + + + + )} + + ) +} diff --git a/src/pages/MeshEditorPage.jsx b/src/pages/MeshEditorPage.jsx index 7751caa..78c4dc6 100644 --- a/src/pages/MeshEditorPage.jsx +++ b/src/pages/MeshEditorPage.jsx @@ -24,6 +24,8 @@ import { getSelectedHoleLoops, loadEditableGeometryFromObject, loadEditableGeometryFromGlbBuffer, + extractSkeletonFromObject, + extractSkeletonFromGlbBuffer, mergeSelectedVertices, smoothSelectedVertices, subdivideSelectedFaces @@ -148,8 +150,10 @@ import { saveWorkflowDefaults } from '../utils/workflowDefaults' import PaintingToolsPanel from '../components/meshEditor/PaintingToolsPanel' import AutoUvToolsPanel from '../components/meshEditor/AutoUvToolsPanel' import AutoRetopoToolsPanel from '../components/meshEditor/AutoRetopoToolsPanel' +import AutoRigToolsPanel from '../components/meshEditor/AutoRigToolsPanel' +import SkeletonOverlay from '../components/meshEditor/SkeletonOverlay' import OptimizeToolsPanel from '../components/meshEditor/OptimizeToolsPanel' -import { autoUv as runAutoUvService, autoRetopo as runAutoRetopoService, optimizeMesh as runOptimizeService, repairMesh as runRepairService } from '../utils/meshTools' +import { autoUv as runAutoUvService, autoRetopo as runAutoRetopoService, optimizeMesh as runOptimizeService, repairMesh as runRepairService, autoRig as runAutoRigService } from '../utils/meshTools' // Default option sets for the Python mesh-tools panels. These mirror the // defaults of autouv.unwrap() and autoretopo.RetopoConfig 1:1 (see @@ -195,6 +199,17 @@ const DEFAULT_AUTO_RETOPO_OPTIONS = { seed: 0, } +const DEFAULT_AUTO_RIG_OPTIONS = { + use_transfer: true, + use_postprocess: false, + rename_bones: 'mixamo', + top_k: 5, + top_p: 0.95, + temperature: 1.0, + repetition_penalty: 2.0, + num_beams: 10, +} + // Non-manifold / topology repair (see python-server/app/schemas.py RepairOptions). const DEFAULT_REPAIR_OPTIONS = { method: 'remove', @@ -420,6 +435,18 @@ export default function MeshEditorPage() { const [autoRetopoResult, setAutoRetopoResult] = useState(null) const [autoUvProgress, setAutoUvProgress] = useState(null) const [autoRetopoProgress, setAutoRetopoProgress] = useState(null) + // Auto Rig (SkinTokens/TokenRig) — dedicated rigging service. + const [autoRigOptions, setAutoRigOptions] = useState(DEFAULT_AUTO_RIG_OPTIONS) + const [autoRigRunning, setAutoRigRunning] = useState(false) + const [autoRigProgress, setAutoRigProgress] = useState(null) + const [autoRigResult, setAutoRigResult] = useState(null) + const [autoRigSaving, setAutoRigSaving] = useState(false) + // Skeleton overlay: the rig of the currently-loaded mesh (if it arrived rigged) + // or of the freshly-generated rig result. `showSkeleton` toggles its visibility. + const [skeleton, setSkeleton] = useState(null) + const [showSkeleton, setShowSkeleton] = useState(true) + // The rigged GLB blob returned by the service, kept for Save-as-version / download. + const riggedBlobRef = useRef(null) // Watertight check (Auto Retopo panel) — runs on demand via a button. const [watertightChecking, setWatertightChecking] = useState(false) const [watertightResult, setWatertightResult] = useState(null) @@ -1863,6 +1890,16 @@ export default function MeshEditorPage() { setLoading(true) setError('') const loadedRoot = await loadMeshRootFromUrl(modelUrl) + // Capture any existing skeleton BEFORE the editable/texturable pipelines + // consume the graph — an already-rigged mesh (skinned GLB) carries bones + // we can show as an overlay. Bone positions are in the same world space + // the editable geometry is baked into, so they align. + let loadedSkeleton = null + try { + loadedSkeleton = extractSkeletonFromObject(loadedRoot) + } catch (skeletonError) { + console.warn('Skeleton extraction failed:', skeletonError) + } const texturableStartedAt = typeof performance !== 'undefined' && performance.now ? performance.now() : Date.now() const geometryPromise = Promise.resolve().then(() => loadEditableGeometryFromObject(loadedRoot)).then(loadedGeometry => { @@ -1899,6 +1936,11 @@ export default function MeshEditorPage() { setSelectedFaceIndices([]) setSelectedVertexIndices([]) setHoleLoops([]) + // Reset the rig overlay to whatever this mesh arrived with. + setSkeleton(loadedSkeleton) + setShowSkeleton(true) + setAutoRigResult(null) + riggedBlobRef.current = null // Bump the camera framing key so CameraRig re-frames the new mesh. // Topology edits below do NOT bump this so the view stays put. setMeshFrameKey(key => key + 1) @@ -3956,6 +3998,111 @@ export default function MeshEditorPage() { setAutoRetopoOptions(prev => ({ ...prev, [key]: value })) }, []) + const setAutoRigOption = useCallback((key, value) => { + setAutoRigOptions(prev => ({ ...prev, [key]: value })) + }, []) + + // Auto Rig: generate a skeleton + skin weights via the SkinTokens rigging + // service. Unlike the other mesh tools this does NOT replace the editable + // geometry (that would discard the rig) — instead we parse the returned skinned + // GLB for a skeleton overlay and keep the blob so it can be saved as a new + // version or downloaded. We upload the TEXTURED GLB when available so the + // service's rig transfer preserves the texture and scale. + const handleRunAutoRig = useCallback(async () => { + if (!geometry || autoRigRunning) return + setAutoRigRunning(true) + setAutoRigResult(null) + setAutoRigProgress({ stage: 'start', frac: 0, message: 'Auto Rig starting…' }) + setError('') + setFeedback('Auto Rig…') + try { + const canExportTextured = !!( + texturableMesh?.root + && texturableMesh?.textureCanvas + && geometry?.attributes?.uv?.count + ) + const meshBinary = canExportTextured + ? await exportTexturedMeshToGlb({ + root: texturableMesh.root, + textureKey: texturableMesh.textureKey, + textureCanvas: texturableMesh.textureCanvas, + textureConfig: texturableMesh.textureConfig, + }) + : await exportGeometryToGlb(geometry) + const meshBlob = new Blob([meshBinary], { type: 'model/gltf-binary' }) + + const { blob, stats } = await runAutoRigService(meshBlob, { + options: autoRigOptions, + fileName: 'mesh.glb', + onProgress: evt => setAutoRigProgress(evt), + }) + + const resultBuffer = await blob.arrayBuffer() + riggedBlobRef.current = blob + const rigSkeleton = await extractSkeletonFromGlbBuffer(resultBuffer) + setSkeleton(rigSkeleton) + setShowSkeleton(true) + + const t = stats?.tool || {} + const rows = [] + if (rigSkeleton?.jointCount != null) rows.push({ label: 'Bones', value: rigSkeleton.jointCount }) + else if (t.bones != null) rows.push({ label: 'Bones', value: t.bones }) + rows.push({ label: 'Bone names', value: autoRigOptions.rename_bones }) + rows.push({ label: 'Texture preserved', value: autoRigOptions.use_transfer ? 'Yes' : 'No' }) + if (autoRigOptions.use_postprocess) rows.push({ label: 'Postprocess', value: 'Voxel skin' }) + setAutoRigResult({ rows }) + setFeedback('Auto Rig complete.') + } catch (err) { + console.error('Auto Rig failed:', err) + setError(err?.message || 'Auto Rig failed.') + } finally { + setAutoRigRunning(false) + setAutoRigProgress(null) + } + }, [geometry, autoRigRunning, autoRigOptions, texturableMesh]) + + const handleSaveRiggedResult = useCallback(async () => { + const blob = riggedBlobRef.current + if (!blob || autoRigSaving) return + try { + setAutoRigSaving(true) + setError('') + setFeedback('Saving rigged mesh…') + const baseName = (meshName || 'mesh').trim() || 'mesh' + const meshFile = new File([blob], `${baseName}-rigged.glb`, { type: 'model/gltf-binary' }) + await saveMeshEdit({ + assetId: Number.isFinite(numericAssetId) && numericAssetId > 0 ? numericAssetId : null, + filePath, + name: `${baseName} (rigged)`, + saveMode: 'version', + meshFile, + }) + setFeedback('Rigged mesh saved as a new version.') + } catch (err) { + console.error('Failed to save rigged mesh:', err) + setError(err?.message || 'Failed to save the rigged mesh.') + } finally { + setAutoRigSaving(false) + } + }, [autoRigSaving, meshName, numericAssetId, filePath, saveMeshEdit]) + + const handleDownloadRiggedResult = useCallback(() => { + const blob = riggedBlobRef.current + if (!blob) return + const url = URL.createObjectURL(blob) + const anchor = document.createElement('a') + anchor.href = url + anchor.download = `${(meshName || 'mesh').trim() || 'mesh'}-rigged.glb` + document.body.appendChild(anchor) + anchor.click() + anchor.remove() + setTimeout(() => URL.revokeObjectURL(url), 1000) + }, [meshName]) + + const handleDismissRigResult = useCallback(() => { + setAutoRigResult(null) + }, []) + // On-demand watertight check for the Auto Retopo panel. The position-welded // edge scan can take a moment on dense meshes, so it runs behind a button with // a loading state rather than automatically. A double rAF lets the spinner @@ -6049,6 +6196,15 @@ export default function MeshEditorPage() { grid_4x4 Auto Retopo +