Added meshoptimizer tool used in Mesh Editor
This commit is contained in:
parent
6579a39f5d
commit
21faf57531
10 changed files with 312 additions and 8 deletions
BIN
public/3dgenstudio.ico
Normal file
BIN
public/3dgenstudio.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 209 KiB |
92
server.js
92
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 <ratio>), 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) => {
|
app.post('/api/export/mesh', multer({ storage: multer.memoryStorage(), limits: { fileSize: 512 * 1024 * 1024 } }).array('files'), async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const folder = typeof req.body?.folder === 'string' ? req.body.folder.trim() : '';
|
const folder = typeof req.body?.folder === 'string' ? req.body.folder.trim() : '';
|
||||||
|
|
|
||||||
63
src/components/meshEditor/OptimizeToolsPanel.jsx
Normal file
63
src/components/meshEditor/OptimizeToolsPanel.jsx
Normal file
|
|
@ -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 */}
|
||||||
|
<div className="mesh-editor-panel__section">
|
||||||
|
<span className="mesh-editor-panel__section-title">Optimize</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="mesh-editor-btn mesh-editor-btn--primary"
|
||||||
|
onClick={onRun}
|
||||||
|
disabled={disabled || running}
|
||||||
|
title="Simplify the mesh with gltfpack (meshoptimizer)"
|
||||||
|
>
|
||||||
|
<span className="material-symbols-outlined">{running ? 'progress_activity' : 'compress'}</span>
|
||||||
|
<span>{running ? 'Optimizing…' : 'Run Optimize'}</span>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{running && <MeshToolProgress progress={progress} />}
|
||||||
|
|
||||||
|
{result && (
|
||||||
|
<MeshToolResult
|
||||||
|
title="Optimization applied"
|
||||||
|
rows={result.rows}
|
||||||
|
onKeep={onKeepResult}
|
||||||
|
onRevert={onRevertResult}
|
||||||
|
disabled={running}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mesh-editor-panel__section">
|
||||||
|
<span className="mesh-editor-panel__section-title">Simplify</span>
|
||||||
|
<RangeField label="Simplify ratio" min={0.001} max={1} step={0.001} decimals={3}
|
||||||
|
value={o.simplify_ratio} onChange={v => setOption('simplify_ratio', v)} disabled={fieldsDisabled}
|
||||||
|
hint="Target triangle count as a fraction of the original (1 = no simplification)" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mesh-editor-panel__notes">
|
||||||
|
<span className="mesh-editor-panel__hint">Optimize runs the bundled gltfpack (meshoptimizer) binary.</span>
|
||||||
|
<span className="mesh-editor-panel__hint">The result replaces the mesh; use Keep or Revert to decide.</span>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
@ -146,7 +146,8 @@ import { saveWorkflowDefaults } from '../utils/workflowDefaults'
|
||||||
import PaintingToolsPanel from '../components/meshEditor/PaintingToolsPanel'
|
import PaintingToolsPanel from '../components/meshEditor/PaintingToolsPanel'
|
||||||
import AutoUvToolsPanel from '../components/meshEditor/AutoUvToolsPanel'
|
import AutoUvToolsPanel from '../components/meshEditor/AutoUvToolsPanel'
|
||||||
import AutoRetopoToolsPanel from '../components/meshEditor/AutoRetopoToolsPanel'
|
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
|
// Default option sets for the Python mesh-tools panels. These mirror the
|
||||||
// defaults of autouv.unwrap() and autoretopo.RetopoConfig 1:1 (see
|
// defaults of autouv.unwrap() and autoretopo.RetopoConfig 1:1 (see
|
||||||
|
|
@ -190,6 +191,10 @@ const DEFAULT_AUTO_RETOPO_OPTIONS = {
|
||||||
seed: 0,
|
seed: 0,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const DEFAULT_OPTIMIZE_OPTIONS = {
|
||||||
|
simplify_ratio: 0.5,
|
||||||
|
}
|
||||||
|
|
||||||
// ── Projection per-layer mask helpers ───────────────────────────────────────
|
// ── Projection per-layer mask helpers ───────────────────────────────────────
|
||||||
// A projection layer can carry a user-drawn UV-space mask so the layer's view is
|
// 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
|
// 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 [autoRetopoResult, setAutoRetopoResult] = useState(null)
|
||||||
const [autoUvProgress, setAutoUvProgress] = useState(null)
|
const [autoUvProgress, setAutoUvProgress] = useState(null)
|
||||||
const [autoRetopoProgress, setAutoRetopoProgress] = 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 [booleanOperation, setBooleanOperation] = useState('out')
|
||||||
const [booleanPlaceMode, setBooleanPlaceMode] = useState(false)
|
const [booleanPlaceMode, setBooleanPlaceMode] = useState(false)
|
||||||
const [booleanBrushSource, setBooleanBrushSource] = useState('asset')
|
const [booleanBrushSource, setBooleanBrushSource] = useState('asset')
|
||||||
|
|
@ -1765,7 +1774,21 @@ export default function MeshEditorPage() {
|
||||||
}
|
}
|
||||||
|
|
||||||
targetMesh.geometry = geometry
|
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)
|
root.updateMatrixWorld(true)
|
||||||
}, [geometry, geometryRevision, texturableMesh])
|
}, [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.
|
// 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
|
// After applying, the texturable-mesh state is rebuilt so the new UVs (Auto
|
||||||
// UV) immediately enable painting/texturing/projection.
|
// UV) immediately enable painting/texturing/projection.
|
||||||
const runMeshTool = useCallback(async (service, options, { setRunning, setResult, setProgress, buildRows, label }) => {
|
const runMeshTool = useCallback(async (service, options, { setRunning, setResult, setProgress, buildRows, label, preserveTexture = false }) => {
|
||||||
if (!geometry || autoUvRunning || autoRetopoRunning) {
|
if (!geometry || autoUvRunning || autoRetopoRunning || optimizeRunning) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
setRunning(true)
|
setRunning(true)
|
||||||
|
|
@ -3778,13 +3801,36 @@ export default function MeshEditorPage() {
|
||||||
const nextGeometry = await loadEditableGeometryFromGlbBuffer(resultBuffer)
|
const nextGeometry = await loadEditableGeometryFromGlbBuffer(resultBuffer)
|
||||||
applyGeometryUpdate(nextGeometry, [], { pushUndo: true })
|
applyGeometryUpdate(nextGeometry, [], { pushUndo: true })
|
||||||
// Resync texture editing to the new topology/UVs (enables the texture
|
// Resync texture editing to the new topology/UVs (enables the texture
|
||||||
// modes when the result carries UVs, disables them otherwise).
|
// modes when the result carries UVs, disables them otherwise). When the
|
||||||
const nextTexturable = await buildTexturableFromGeometry(nextGeometry, blankTextureSize)
|
// 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)
|
setTexturableMesh(nextTexturable)
|
||||||
setTextureRevision(0)
|
setTextureRevision(0)
|
||||||
setPaintLayers([])
|
setPaintLayers([])
|
||||||
setSelectedLayerId(null)
|
setSelectedLayerId(null)
|
||||||
setResult({ rows: buildRows(stats), previewUrl })
|
setResult({ rows: buildRows(stats, nextGeometry), previewUrl })
|
||||||
setFeedback(`${label} complete.`)
|
setFeedback(`${label} complete.`)
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(`${label} failed:`, err)
|
console.error(`${label} failed:`, err)
|
||||||
|
|
@ -3793,7 +3839,7 @@ export default function MeshEditorPage() {
|
||||||
setRunning(false)
|
setRunning(false)
|
||||||
setProgress(null)
|
setProgress(null)
|
||||||
}
|
}
|
||||||
}, [geometry, autoUvRunning, autoRetopoRunning, applyGeometryUpdate, buildTexturableFromGeometry, blankTextureSize])
|
}, [geometry, autoUvRunning, autoRetopoRunning, optimizeRunning, applyGeometryUpdate, buildTexturableFromGeometry, blankTextureSize, texturableMesh, modelUrl])
|
||||||
|
|
||||||
const handleRunAutoUv = useCallback(() => {
|
const handleRunAutoUv = useCallback(() => {
|
||||||
runMeshTool(runAutoUvService, autoUvOptions, {
|
runMeshTool(runAutoUvService, autoUvOptions, {
|
||||||
|
|
@ -3835,12 +3881,31 @@ export default function MeshEditorPage() {
|
||||||
})
|
})
|
||||||
}, [runMeshTool, autoRetopoOptions])
|
}, [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) => {
|
const setAutoUvOption = useCallback((key, value) => {
|
||||||
setAutoUvOptions(prev => ({ ...prev, [key]: value }))
|
setAutoUvOptions(prev => ({ ...prev, [key]: value }))
|
||||||
}, [])
|
}, [])
|
||||||
const setAutoRetopoOption = useCallback((key, value) => {
|
const setAutoRetopoOption = useCallback((key, value) => {
|
||||||
setAutoRetopoOptions(prev => ({ ...prev, [key]: value }))
|
setAutoRetopoOptions(prev => ({ ...prev, [key]: value }))
|
||||||
}, [])
|
}, [])
|
||||||
|
const setOptimizeOption = useCallback((key, value) => {
|
||||||
|
setOptimizeOptions(prev => ({ ...prev, [key]: value }))
|
||||||
|
}, [])
|
||||||
|
|
||||||
const handleRevertMeshTool = useCallback((clearResult) => {
|
const handleRevertMeshTool = useCallback((clearResult) => {
|
||||||
handleModelingUndo()
|
handleModelingUndo()
|
||||||
|
|
@ -5862,6 +5927,15 @@ export default function MeshEditorPage() {
|
||||||
<span className="material-symbols-outlined">grid_4x4</span>
|
<span className="material-symbols-outlined">grid_4x4</span>
|
||||||
<span>Auto Retopo</span>
|
<span>Auto Retopo</span>
|
||||||
</button>
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={`mesh-editor-mode-btn ${activeMenu === 'optimize' ? 'mesh-editor-mode-btn--active' : ''}`}
|
||||||
|
onClick={() => setActiveMenu('optimize')}
|
||||||
|
title="Simplify the mesh with gltfpack (meshoptimizer)"
|
||||||
|
>
|
||||||
|
<span className="material-symbols-outlined">compress</span>
|
||||||
|
<span>Optimize</span>
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{texturableMesh?.isBlank && (
|
{texturableMesh?.isBlank && (
|
||||||
|
|
@ -5952,6 +6026,15 @@ export default function MeshEditorPage() {
|
||||||
onRevertResult: () => handleRevertMeshTool(setAutoRetopoResult),
|
onRevertResult: () => handleRevertMeshTool(setAutoRetopoResult),
|
||||||
disabled: !geometry
|
disabled: !geometry
|
||||||
}} />
|
}} />
|
||||||
|
) : activeMenu === 'optimize' ? (
|
||||||
|
<OptimizeToolsPanel {...{
|
||||||
|
options: optimizeOptions, setOption: setOptimizeOption,
|
||||||
|
running: optimizeRunning, result: optimizeResult, progress: optimizeProgress,
|
||||||
|
onRun: handleRunOptimize,
|
||||||
|
onKeepResult: () => setOptimizeResult(null),
|
||||||
|
onRevertResult: () => handleRevertMeshTool(setOptimizeResult),
|
||||||
|
disabled: !geometry
|
||||||
|
}} />
|
||||||
) : activeMenu === 'sculpting' ? (
|
) : activeMenu === 'sculpting' ? (
|
||||||
<>{/* SCULPTING */}
|
<>{/* SCULPTING */}
|
||||||
<SculptToolsPanel
|
<SculptToolsPanel
|
||||||
|
|
|
||||||
|
|
@ -223,6 +223,43 @@ function loadWithLoader(loader, url) {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Rebuild an attribute as a plain, de-interleaved, non-normalized Float32 array.
|
||||||
|
// Reading via getX/…/getW denormalizes normalized integer attributes and resolves
|
||||||
|
// interleaved buffers, so the resulting attribute holds real float values.
|
||||||
|
function toFloat32Attribute(attribute) {
|
||||||
|
const { itemSize, count } = attribute
|
||||||
|
const array = new Float32Array(count * itemSize)
|
||||||
|
const getters = ['getX', 'getY', 'getZ', 'getW']
|
||||||
|
for (let i = 0; i < count; i += 1) {
|
||||||
|
for (let component = 0; component < itemSize; component += 1) {
|
||||||
|
array[i * itemSize + component] = attribute[getters[component]](i)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return new THREE.BufferAttribute(array, itemSize)
|
||||||
|
}
|
||||||
|
|
||||||
|
// gltfpack (and other exporters) store vertex data with KHR_mesh_quantization:
|
||||||
|
// attributes become normalized integers whose real scale lives in the node
|
||||||
|
// transform, and are often interleaved. THREE renders these correctly, but
|
||||||
|
// reading the raw typed array or calling applyMatrix4 on a still-`normalized`
|
||||||
|
// integer attribute corrupts the geometry — applyMatrix4 writes float world
|
||||||
|
// coordinates back into the int array while the normalized flag stays set,
|
||||||
|
// collapsing the whole mesh to a speck (it then loads without error but is
|
||||||
|
// invisible in the editor). Convert everything we read to plain Float32 first.
|
||||||
|
function dequantizeGeometryAttributes(geometry) {
|
||||||
|
const names = ['position', 'normal', 'tangent', 'uv', 'uv1', 'uv2', 'color']
|
||||||
|
names.forEach(name => {
|
||||||
|
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) {
|
function createMergedGeometryFromObject(object) {
|
||||||
const root = object?.scene || object
|
const root = object?.scene || object
|
||||||
|
|
||||||
|
|
@ -239,6 +276,7 @@ function createMergedGeometryFromObject(object) {
|
||||||
}
|
}
|
||||||
|
|
||||||
const geometry = child.geometry.clone()
|
const geometry = child.geometry.clone()
|
||||||
|
dequantizeGeometryAttributes(geometry)
|
||||||
geometry.applyMatrix4(child.matrixWorld)
|
geometry.applyMatrix4(child.matrixWorld)
|
||||||
geometries.push(geometry.index ? geometry.toNonIndexed() : geometry)
|
geometries.push(geometry.index ? geometry.toNonIndexed() : geometry)
|
||||||
})
|
})
|
||||||
|
|
|
||||||
|
|
@ -107,3 +107,31 @@ export function autoUv(meshBlob, opts = {}) {
|
||||||
export function autoRetopo(meshBlob, opts = {}) {
|
export function autoRetopo(meshBlob, opts = {}) {
|
||||||
return callMeshTool('/meshes/auto-retopo', 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 }
|
||||||
|
}
|
||||||
|
|
|
||||||
BIN
tools/meshoptimizer/linux/gltfpack
Normal file
BIN
tools/meshoptimizer/linux/gltfpack
Normal file
Binary file not shown.
BIN
tools/meshoptimizer/macos/arm/gltfpack
Normal file
BIN
tools/meshoptimizer/macos/arm/gltfpack
Normal file
Binary file not shown.
BIN
tools/meshoptimizer/macos/intel/gltfpack
Normal file
BIN
tools/meshoptimizer/macos/intel/gltfpack
Normal file
Binary file not shown.
BIN
tools/meshoptimizer/win/gltfpack.exe
Normal file
BIN
tools/meshoptimizer/win/gltfpack.exe
Normal file
Binary file not shown.
Loading…
Add table
Reference in a new issue