Add OBJ/STL to GLB conversion
Implements client-side import support for OBJ and STL files with automatic conversion to GLB using OBJLoader/STLLoader and GLTFExporter. Updates include a converter utility, integration in index page to handle conversion, and UI/UX adjustments for streamlined import workflow. X-Lovable-Edit-ID: edt-befcd392-2925-4291-bb13-0224e3ebfb0c
This commit is contained in:
@@ -0,0 +1,67 @@
|
|||||||
|
import * as THREE from 'three';
|
||||||
|
import { STLLoader } from 'three/examples/jsm/loaders/STLLoader.js';
|
||||||
|
import { OBJLoader } from 'three/examples/jsm/loaders/OBJLoader.js';
|
||||||
|
import { GLTFExporter } from 'three/examples/jsm/exporters/GLTFExporter.js';
|
||||||
|
|
||||||
|
type SupportedExt = 'glb' | 'obj' | 'stl';
|
||||||
|
|
||||||
|
export function getSupportedExtension(fileName: string): SupportedExt | null {
|
||||||
|
const ext = fileName.split('.').pop()?.toLowerCase();
|
||||||
|
if (ext === 'glb' || ext === 'obj' || ext === 'stl') return ext;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const ACCEPTED_EXTENSIONS = '.glb,.obj,.stl';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert an OBJ or STL file (ArrayBuffer) into a GLB Blob.
|
||||||
|
* GLB files are returned as-is from their original blob.
|
||||||
|
*/
|
||||||
|
export async function convertToGLB(
|
||||||
|
buffer: ArrayBuffer,
|
||||||
|
ext: 'obj' | 'stl',
|
||||||
|
fileName: string
|
||||||
|
): Promise<{ blob: Blob; fileName: string; fileSize: number }> {
|
||||||
|
const scene = new THREE.Scene();
|
||||||
|
|
||||||
|
const material = new THREE.MeshStandardMaterial({
|
||||||
|
color: 0x8899aa,
|
||||||
|
metalness: 0.85,
|
||||||
|
roughness: 0.35,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (ext === 'stl') {
|
||||||
|
const loader = new STLLoader();
|
||||||
|
const geometry = loader.parse(buffer);
|
||||||
|
geometry.computeVertexNormals();
|
||||||
|
const mesh = new THREE.Mesh(geometry, material);
|
||||||
|
mesh.name = fileName.replace(/\.stl$/i, '');
|
||||||
|
scene.add(mesh);
|
||||||
|
} else {
|
||||||
|
const loader = new OBJLoader();
|
||||||
|
const text = new TextDecoder().decode(buffer);
|
||||||
|
const obj = loader.parse(text);
|
||||||
|
obj.traverse((child) => {
|
||||||
|
if (child instanceof THREE.Mesh) {
|
||||||
|
child.material = material;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
obj.name = fileName.replace(/\.obj$/i, '');
|
||||||
|
scene.add(obj);
|
||||||
|
}
|
||||||
|
|
||||||
|
const exporter = new GLTFExporter();
|
||||||
|
const glb = await new Promise<ArrayBuffer>((resolve, reject) => {
|
||||||
|
exporter.parse(
|
||||||
|
scene,
|
||||||
|
(result) => resolve(result as ArrayBuffer),
|
||||||
|
(error) => reject(error),
|
||||||
|
{ binary: true }
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
const glbFileName = fileName.replace(/\.(obj|stl)$/i, '.glb');
|
||||||
|
const blob = new Blob([glb], { type: 'model/gltf-binary' });
|
||||||
|
|
||||||
|
return { blob, fileName: glbFileName, fileSize: blob.size };
|
||||||
|
}
|
||||||
+32
-8
@@ -5,11 +5,13 @@ import { Button } from '@/components/ui/button';
|
|||||||
import { useModelStore } from '@/stores/useModelStore';
|
import { useModelStore } from '@/stores/useModelStore';
|
||||||
import { toast } from 'sonner';
|
import { toast } from 'sonner';
|
||||||
import { generateDemoBeamGLB } from '@/lib/generateDemoBeam';
|
import { generateDemoBeamGLB } from '@/lib/generateDemoBeam';
|
||||||
|
import { getSupportedExtension, convertToGLB, ACCEPTED_EXTENSIONS } from '@/lib/convertToGLB';
|
||||||
|
|
||||||
const Index = () => {
|
const Index = () => {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||||
const [loadingDemo, setLoadingDemo] = useState(false);
|
const [loadingDemo, setLoadingDemo] = useState(false);
|
||||||
|
const [converting, setConverting] = useState(false);
|
||||||
const { model, setModel, xrSupported, setXrSupported } = useModelStore();
|
const { model, setModel, xrSupported, setXrSupported } = useModelStore();
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -20,16 +22,37 @@ const Index = () => {
|
|||||||
}
|
}
|
||||||
}, [setXrSupported]);
|
}, [setXrSupported]);
|
||||||
|
|
||||||
const handleFileUpload = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
|
const handleFileUpload = useCallback(async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
const file = e.target.files?.[0];
|
const file = e.target.files?.[0];
|
||||||
if (!file) return;
|
if (!file) return;
|
||||||
if (!file.name.toLowerCase().endsWith('.glb')) {
|
|
||||||
toast.error('Formato inválido. Por favor, selecione um arquivo .GLB');
|
const ext = getSupportedExtension(file.name);
|
||||||
|
if (!ext) {
|
||||||
|
toast.error('Formato inválido. Selecione um arquivo .GLB, .OBJ ou .STL');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (ext === 'glb') {
|
||||||
const url = URL.createObjectURL(file);
|
const url = URL.createObjectURL(file);
|
||||||
setModel({ fileName: file.name, fileSize: file.size, url });
|
setModel({ fileName: file.name, fileSize: file.size, url });
|
||||||
toast.success(`Modelo "${file.name}" carregado com sucesso!`);
|
toast.success(`Modelo "${file.name}" carregado com sucesso!`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convert OBJ/STL to GLB
|
||||||
|
setConverting(true);
|
||||||
|
try {
|
||||||
|
const buffer = await file.arrayBuffer();
|
||||||
|
const { blob, fileName, fileSize } = await convertToGLB(buffer, ext, file.name);
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
setModel({ fileName, fileSize, url });
|
||||||
|
toast.success(`"${file.name}" convertido para GLB e carregado!`);
|
||||||
|
} catch (err) {
|
||||||
|
console.error(err);
|
||||||
|
toast.error(`Falha ao converter "${file.name}"`);
|
||||||
|
} finally {
|
||||||
|
setConverting(false);
|
||||||
|
}
|
||||||
}, [setModel]);
|
}, [setModel]);
|
||||||
|
|
||||||
const handleLoadDemo = useCallback(async () => {
|
const handleLoadDemo = useCallback(async () => {
|
||||||
@@ -60,7 +83,7 @@ const Index = () => {
|
|||||||
<input
|
<input
|
||||||
ref={fileInputRef}
|
ref={fileInputRef}
|
||||||
type="file"
|
type="file"
|
||||||
accept=".glb"
|
accept={ACCEPTED_EXTENSIONS}
|
||||||
className="hidden"
|
className="hidden"
|
||||||
onChange={handleFileUpload} />
|
onChange={handleFileUpload} />
|
||||||
|
|
||||||
@@ -84,12 +107,13 @@ const Index = () => {
|
|||||||
<Button
|
<Button
|
||||||
variant="outline"
|
variant="outline"
|
||||||
className="h-28 w-full flex-col gap-3 border-dashed border-2 text-muted-foreground hover:border-primary hover:text-primary transition-all"
|
className="h-28 w-full flex-col gap-3 border-dashed border-2 text-muted-foreground hover:border-primary hover:text-primary transition-all"
|
||||||
onClick={() => fileInputRef.current?.click()}>
|
onClick={() => fileInputRef.current?.click()}
|
||||||
|
disabled={converting}>
|
||||||
|
|
||||||
<Upload className="h-8 w-8" />
|
{converting ? <Loader2 className="h-8 w-8 animate-spin" /> : <Upload className="h-8 w-8" />}
|
||||||
<div className="text-center">
|
<div className="text-center">
|
||||||
<p className="text-sm font-semibold">Importar Modelo GLB</p>
|
<p className="text-sm font-semibold">{converting ? 'Convertendo modelo…' : 'Importar Modelo 3D'}</p>
|
||||||
<p className="text-xs text-muted-foreground">Escala 1:1 — Unidades em mm</p>
|
<p className="text-xs text-muted-foreground">GLB · OBJ · STL — Escala 1:1</p>
|
||||||
</div>
|
</div>
|
||||||
</Button>
|
</Button>
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user