diff --git a/public/3dgenstudio.ico b/public/3dgenstudio.ico new file mode 100644 index 0000000..0b9c164 Binary files /dev/null and b/public/3dgenstudio.ico differ diff --git a/server.js b/server.js index 95135ea..49e4e81 100644 --- a/server.js +++ b/server.js @@ -5061,6 +5061,98 @@ app.post('/api/meshes/auto-retopo', meshToolsUpload.single('meshFile'), async (r } }); +// --- 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 +// to a temp file, run gltfpack to simplify it (-si ), then return the +// simplified GLB as base64. `-noq` disables quantization so the output stays +// plain-float and loads cleanly into the editable geometry pipeline. +const MESHOPTIMIZER_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), 'tools', 'meshoptimizer'); + +function resolveGltfpackPath() { + const platform = process.platform; + if (platform === 'win32') { + return path.join(MESHOPTIMIZER_DIR, 'win', 'gltfpack.exe'); + } + if (platform === 'linux') { + return path.join(MESHOPTIMIZER_DIR, 'linux', 'gltfpack'); + } + if (platform === 'darwin') { + const arch = process.arch === 'arm64' ? 'arm' : 'intel'; + return path.join(MESHOPTIMIZER_DIR, 'macos', arch, 'gltfpack'); + } + throw new Error(`Unsupported platform for gltfpack: ${platform}`); +} + +app.post('/api/meshes/optimize', meshToolsUpload.single('meshFile'), async (req, res) => { + const tmpFiles = []; + try { + const meshFile = req.file; + if (!meshFile?.buffer?.length) { + return res.status(400).json({ error: 'meshFile is required' }); + } + + let options = {}; + if (typeof req.body?.options === 'string' && req.body.options.length) { + try { options = JSON.parse(req.body.options); } catch { options = {}; } + } + let ratio = Number(options.simplify_ratio); + if (!Number.isFinite(ratio)) ratio = 1; + ratio = Math.min(1, Math.max(0.001, ratio)); + + const binaryPath = resolveGltfpackPath(); + if (!existsSync(binaryPath)) { + return res.status(500).json({ error: `gltfpack binary not found at ${binaryPath}` }); + } + // git-checked-out unix binaries may lack the execute bit. + if (process.platform !== 'win32') { + try { await fs.chmod(binaryPath, 0o755); } catch { /* best effort */ } + } + + const id = randomUUID(); + const inputPath = path.join(os.tmpdir(), `meshopt-${id}-in.glb`); + const outputPath = path.join(os.tmpdir(), `meshopt-${id}-out.glb`); + tmpFiles.push(inputPath, outputPath); + await fs.writeFile(inputPath, meshFile.buffer); + + // -kv keeps source vertex attributes (UVs, normals) even when they look + // "unused" — the editor exports meshes with an untextured placeholder + // material, so without -kv gltfpack strips TEXCOORD_0 and the reloaded mesh + // loses its UVs (disabling the texture/paint/projection modes). + const args = ['-i', inputPath, '-o', outputPath, '-si', String(ratio), '-noq', '-kv']; + const stderr = await new Promise((resolve, reject) => { + const proc = spawn(binaryPath, args, { windowsHide: true }); + let err = ''; + proc.stderr.on('data', chunk => { err += chunk.toString(); }); + proc.stdout.on('data', chunk => { err += chunk.toString(); }); + proc.on('error', reject); + proc.on('close', code => { + if (code === 0) resolve(err); + else reject(new Error(err.trim() || `gltfpack exited with code ${code}`)); + }); + }); + + const outBuffer = await fs.readFile(outputPath); + + // Best-effort: pull the output triangle count from gltfpack's report. + let triangles = null; + const triMatch = [...stderr.matchAll(/([\d,]+)\s+triangles/gi)]; + if (triMatch.length) { + triangles = Number(triMatch[triMatch.length - 1][1].replace(/,/g, '')); + } + + res.json({ + mesh_b64: outBuffer.toString('base64'), + stats: { simplify_ratio: ratio, triangles: Number.isFinite(triangles) ? triangles : null }, + }); + } catch (err) { + console.error('Mesh optimize failed:', err); + if (!res.headersSent) res.status(500).json({ error: err.message || 'Mesh optimize failed' }); + } finally { + await Promise.all(tmpFiles.map(f => fs.rm(f, { force: true }).catch(() => {}))); + } +}); + app.post('/api/export/mesh', multer({ storage: multer.memoryStorage(), limits: { fileSize: 512 * 1024 * 1024 } }).array('files'), async (req, res) => { try { const folder = typeof req.body?.folder === 'string' ? req.body.folder.trim() : ''; diff --git a/src/components/meshEditor/OptimizeToolsPanel.jsx b/src/components/meshEditor/OptimizeToolsPanel.jsx new file mode 100644 index 0000000..5fa8fe0 --- /dev/null +++ b/src/components/meshEditor/OptimizeToolsPanel.jsx @@ -0,0 +1,63 @@ +// Optimize mode left panel. Runs the bundled gltfpack (meshoptimizer) binary +// server-side to simplify the mesh, and offers Keep/Revert on the result. +// Presentational: option state + handlers come from MeshEditorPage. +import { RangeField } from './MeshToolField' +import MeshToolResult from './MeshToolResult' +import MeshToolProgress from './MeshToolProgress' + +export default function OptimizeToolsPanel({ + options, + setOption, + running, + result, + progress, + onRun, + onKeepResult, + onRevertResult, + disabled, +}) { + const o = options + const fieldsDisabled = disabled || running + + return ( + <>{/* OPTIMIZE */} +
+ Optimize + + + {running && } + + {result && ( + + )} +
+ +
+ Simplify + setOption('simplify_ratio', v)} disabled={fieldsDisabled} + hint="Target triangle count as a fraction of the original (1 = no simplification)" /> +
+ +
+ Optimize runs the bundled gltfpack (meshoptimizer) binary. + The result replaces the mesh; use Keep or Revert to decide. +
+ + ) +} diff --git a/src/pages/MeshEditorPage.jsx b/src/pages/MeshEditorPage.jsx index be78840..af20726 100644 --- a/src/pages/MeshEditorPage.jsx +++ b/src/pages/MeshEditorPage.jsx @@ -146,7 +146,8 @@ import { saveWorkflowDefaults } from '../utils/workflowDefaults' import PaintingToolsPanel from '../components/meshEditor/PaintingToolsPanel' import AutoUvToolsPanel from '../components/meshEditor/AutoUvToolsPanel' import AutoRetopoToolsPanel from '../components/meshEditor/AutoRetopoToolsPanel' -import { autoUv as runAutoUvService, autoRetopo as runAutoRetopoService } from '../utils/meshTools' +import OptimizeToolsPanel from '../components/meshEditor/OptimizeToolsPanel' +import { autoUv as runAutoUvService, autoRetopo as runAutoRetopoService, optimizeMesh as runOptimizeService } 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 @@ -190,6 +191,10 @@ const DEFAULT_AUTO_RETOPO_OPTIONS = { seed: 0, } +const DEFAULT_OPTIMIZE_OPTIONS = { + simplify_ratio: 0.5, +} + // ── Projection per-layer mask helpers ─────────────────────────────────────── // A projection layer can carry a user-drawn UV-space mask so the layer's view is // applied ONLY where the mask is painted. The mask lives in a canvas the same size @@ -403,6 +408,10 @@ export default function MeshEditorPage() { const [autoRetopoResult, setAutoRetopoResult] = useState(null) const [autoUvProgress, setAutoUvProgress] = useState(null) const [autoRetopoProgress, setAutoRetopoProgress] = useState(null) + const [optimizeOptions, setOptimizeOptions] = useState(DEFAULT_OPTIMIZE_OPTIONS) + const [optimizeRunning, setOptimizeRunning] = useState(false) + const [optimizeResult, setOptimizeResult] = useState(null) + const [optimizeProgress, setOptimizeProgress] = useState(null) const [booleanOperation, setBooleanOperation] = useState('out') const [booleanPlaceMode, setBooleanPlaceMode] = useState(false) const [booleanBrushSource, setBooleanBrushSource] = useState('asset') @@ -1765,7 +1774,21 @@ export default function MeshEditorPage() { } targetMesh.geometry = geometry - targetMesh.updateMatrixWorld(true) + // The editable `geometry` already has the mesh's full world transform baked + // in (loadEditableGeometryFromObject applies child.matrixWorld). If the + // source node carries its own transform we must NOT apply it again — e.g. + // gltfpack / KHR_mesh_quantization stores the real scale in the node + // transform, so leaving it in place double-applies it and collapses the mesh + // to an invisible speck in the texture/paint/projection views (modeling mode + // renders the geometry directly, which is why it stayed visible there). Pin + // this node's world matrix to identity so the textured display and its + // raycasting match the editable geometry. + targetMesh.position.set(0, 0, 0) + targetMesh.quaternion.identity() + targetMesh.scale.set(1, 1, 1) + targetMesh.matrix.identity() + targetMesh.matrixWorldAutoUpdate = false + targetMesh.matrixWorld.identity() root.updateMatrixWorld(true) }, [geometry, geometryRevision, texturableMesh]) @@ -3757,8 +3780,8 @@ export default function MeshEditorPage() { // pre-op mesh onto the modeling undo stack, so "Revert" is just an undo. // After applying, the texturable-mesh state is rebuilt so the new UVs (Auto // UV) immediately enable painting/texturing/projection. - const runMeshTool = useCallback(async (service, options, { setRunning, setResult, setProgress, buildRows, label }) => { - if (!geometry || autoUvRunning || autoRetopoRunning) { + const runMeshTool = useCallback(async (service, options, { setRunning, setResult, setProgress, buildRows, label, preserveTexture = false }) => { + if (!geometry || autoUvRunning || autoRetopoRunning || optimizeRunning) { return } setRunning(true) @@ -3778,13 +3801,36 @@ export default function MeshEditorPage() { const nextGeometry = await loadEditableGeometryFromGlbBuffer(resultBuffer) applyGeometryUpdate(nextGeometry, [], { pushUndo: true }) // Resync texture editing to the new topology/UVs (enables the texture - // modes when the result carries UVs, disables them otherwise). - const nextTexturable = await buildTexturableFromGeometry(nextGeometry, blankTextureSize) + // modes when the result carries UVs, disables them otherwise). When the + // operation preserves the existing UV layout (Optimize/simplify only + // reduces triangles), carry the current texture over onto the new geometry + // instead of resetting to a blank canvas. + let nextTexturable + if (preserveTexture && texturableMesh?.textureCanvas) { + const preservedTexture = createCanvasTexture(texturableMesh.textureCanvas, texturableMesh.textureConfig) + const preservedRoot = new THREE.Mesh( + nextGeometry.clone(), + new THREE.MeshStandardMaterial({ map: preservedTexture, metalness: 0.08, roughness: 0.62 }) + ) + preservedRoot.name = 'MeshEditorResult' + const loaded = await loadTexturableMeshFromRoot(preservedRoot, { url: modelUrl, blankTextureSize }) + nextTexturable = loaded?.textureCanvas + ? { + ...loaded, + maskCanvas: Object.assign(document.createElement('canvas'), { + width: loaded.textureCanvas.width, + height: loaded.textureCanvas.height, + }), + } + : loaded + } else { + nextTexturable = await buildTexturableFromGeometry(nextGeometry, blankTextureSize) + } setTexturableMesh(nextTexturable) setTextureRevision(0) setPaintLayers([]) setSelectedLayerId(null) - setResult({ rows: buildRows(stats), previewUrl }) + setResult({ rows: buildRows(stats, nextGeometry), previewUrl }) setFeedback(`${label} complete.`) } catch (err) { console.error(`${label} failed:`, err) @@ -3793,7 +3839,7 @@ export default function MeshEditorPage() { setRunning(false) setProgress(null) } - }, [geometry, autoUvRunning, autoRetopoRunning, applyGeometryUpdate, buildTexturableFromGeometry, blankTextureSize]) + }, [geometry, autoUvRunning, autoRetopoRunning, optimizeRunning, applyGeometryUpdate, buildTexturableFromGeometry, blankTextureSize, texturableMesh, modelUrl]) const handleRunAutoUv = useCallback(() => { runMeshTool(runAutoUvService, autoUvOptions, { @@ -3835,12 +3881,31 @@ export default function MeshEditorPage() { }) }, [runMeshTool, autoRetopoOptions]) + const handleRunOptimize = useCallback(() => { + runMeshTool(runOptimizeService, optimizeOptions, { + setRunning: setOptimizeRunning, + setResult: setOptimizeResult, + setProgress: setOptimizeProgress, + label: 'Optimize', + preserveTexture: true, + buildRows: (stats, geo) => { + const rows = [{ label: 'Simplify ratio', value: optimizeOptions.simplify_ratio }] + if (geo?.index) rows.push({ label: 'Faces', value: geo.index.count / 3 }) + if (geo?.attributes?.position) rows.push({ label: 'Vertices', value: geo.attributes.position.count }) + return rows + }, + }) + }, [runMeshTool, optimizeOptions]) + const setAutoUvOption = useCallback((key, value) => { setAutoUvOptions(prev => ({ ...prev, [key]: value })) }, []) const setAutoRetopoOption = useCallback((key, value) => { setAutoRetopoOptions(prev => ({ ...prev, [key]: value })) }, []) + const setOptimizeOption = useCallback((key, value) => { + setOptimizeOptions(prev => ({ ...prev, [key]: value })) + }, []) const handleRevertMeshTool = useCallback((clearResult) => { handleModelingUndo() @@ -5862,6 +5927,15 @@ export default function MeshEditorPage() { grid_4x4 Auto Retopo + {texturableMesh?.isBlank && ( @@ -5952,6 +6026,15 @@ export default function MeshEditorPage() { onRevertResult: () => handleRevertMeshTool(setAutoRetopoResult), disabled: !geometry }} /> + ) : activeMenu === 'optimize' ? ( + setOptimizeResult(null), + onRevertResult: () => handleRevertMeshTool(setOptimizeResult), + disabled: !geometry + }} /> ) : activeMenu === 'sculpting' ? ( <>{/* SCULPTING */} { + const attribute = geometry.attributes[name] + if (!attribute) { + return + } + if (attribute.isInterleavedBufferAttribute || attribute.normalized || !(attribute.array instanceof Float32Array)) { + geometry.setAttribute(name, toFloat32Attribute(attribute)) + } + }) + return geometry +} + function createMergedGeometryFromObject(object) { const root = object?.scene || object @@ -239,6 +276,7 @@ function createMergedGeometryFromObject(object) { } const geometry = child.geometry.clone() + dequantizeGeometryAttributes(geometry) geometry.applyMatrix4(child.matrixWorld) geometries.push(geometry.index ? geometry.toNonIndexed() : geometry) }) diff --git a/src/utils/meshTools.js b/src/utils/meshTools.js index de7d41f..a1da8e4 100644 --- a/src/utils/meshTools.js +++ b/src/utils/meshTools.js @@ -107,3 +107,31 @@ export function autoUv(meshBlob, opts = {}) { export function autoRetopo(meshBlob, opts = {}) { return callMeshTool('/meshes/auto-retopo', meshBlob, opts) } + +// Runs the bundled gltfpack binary server-side (not the Python service). Unlike +// the SSE-based tools above, this returns a single JSON envelope with the +// simplified GLB as base64. Same { blob, stats, previewUrl } contract so it +// plugs into runMeshTool alongside Auto UV / Auto Retopo. +export async function optimizeMesh(meshBlob, { options = {}, fileName = 'mesh.glb', onProgress = null } = {}) { + const form = new FormData() + form.append('meshFile', meshBlob, fileName) + form.append('options', JSON.stringify(options)) + + onProgress?.({ type: 'progress', stage: 'run', frac: 0.3, message: 'Optimizing…' }) + + const response = await fetch(`${API_BASE}/meshes/optimize`, { method: 'POST', body: form }) + if (!response.ok) { + let message = `Request failed (${response.status})` + try { + const payload = await response.json() + message = payload.error || message + } catch { + // non-JSON error body — keep the status message + } + throw new Error(message) + } + + const data = await response.json() + const blob = base64ToBlob(data.mesh_b64, 'model/gltf-binary') + return { blob, stats: data.stats || null, previewUrl: null } +} diff --git a/tools/meshoptimizer/linux/gltfpack b/tools/meshoptimizer/linux/gltfpack new file mode 100644 index 0000000..f216eec Binary files /dev/null and b/tools/meshoptimizer/linux/gltfpack differ diff --git a/tools/meshoptimizer/macos/arm/gltfpack b/tools/meshoptimizer/macos/arm/gltfpack new file mode 100644 index 0000000..d25d9dd Binary files /dev/null and b/tools/meshoptimizer/macos/arm/gltfpack differ diff --git a/tools/meshoptimizer/macos/intel/gltfpack b/tools/meshoptimizer/macos/intel/gltfpack new file mode 100644 index 0000000..47f56ff Binary files /dev/null and b/tools/meshoptimizer/macos/intel/gltfpack differ diff --git a/tools/meshoptimizer/win/gltfpack.exe b/tools/meshoptimizer/win/gltfpack.exe new file mode 100644 index 0000000..b4544c1 Binary files /dev/null and b/tools/meshoptimizer/win/gltfpack.exe differ