Add SVG import extrusion

This commit is contained in:
Francisco Rivero
2026-07-07 23:59:36 +09:00
parent 4d2d59cb94
commit fd76c5bd96
6 changed files with 57 additions and 22 deletions
+1
View File
@@ -32,6 +32,7 @@ playwright-report/
# Local workspace state # Local workspace state
.codex/ .codex/
.codex-run/
.codex-remote-attachments/ .codex-remote-attachments/
# OS/editor noise # OS/editor noise
+18 -15
View File
@@ -2,7 +2,7 @@
import { Clock3, EllipsisVertical, FileUp, Grid3X3, HomeIcon, List, Pencil, Plus, Search, Settings, SlidersHorizontal, Trash2, X } from "lucide-react"; import { Clock3, EllipsisVertical, FileUp, Grid3X3, HomeIcon, List, Pencil, Plus, Search, Settings, SlidersHorizontal, Trash2, X } from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { SketchForgeEditor, importedShapeFromStl } from "@/components/SketchForgeEditor"; import { SketchForgeEditor, importedShapeFromStl, importedShapeFromSvg } from "@/components/SketchForgeEditor";
import { createLocalId } from "@/lib/localIds"; import { createLocalId } from "@/lib/localIds";
import { importExtensionSupported } from "@/lib/stlImport"; import { importExtensionSupported } from "@/lib/stlImport";
import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings } from "@/lib/workplaneSettings"; import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings } from "@/lib/workplaneSettings";
@@ -236,7 +236,7 @@ function newProject(name: string, index: number, shapeCount = 0): DashboardProje
} }
function projectNameFromFileName(fileName: string) { function projectNameFromFileName(fileName: string) {
return fileName.replace(/\.[^.]+$/, "").trim() || "Imported STL design"; return fileName.replace(/\.[^.]+$/, "").trim() || "Imported design";
} }
export default function Home() { export default function Home() {
@@ -255,7 +255,7 @@ export default function Home() {
const [dashboardNotice, setDashboardNotice] = useState(""); const [dashboardNotice, setDashboardNotice] = useState("");
const [projectShapesById, setProjectShapesById] = useState<Record<string, ProjectShapeCacheEntry>>({}); const [projectShapesById, setProjectShapesById] = useState<Record<string, ProjectShapeCacheEntry>>({});
const projectsJsonRef = useRef(""); const projectsJsonRef = useRef("");
const dashboardStlInputRef = useRef<HTMLInputElement | null>(null); const dashboardImportInputRef = useRef<HTMLInputElement | null>(null);
const nextProjectRevisionRef = useRef(0); const nextProjectRevisionRef = useRef(0);
const projectShapeSaveQueuesRef = useRef<Record<string, Promise<void>>>({}); const projectShapeSaveQueuesRef = useRef<Record<string, Promise<void>>>({});
@@ -513,15 +513,18 @@ export default function Home() {
openEditor(project.id, { allowMissingFromStorage: true }); openEditor(project.id, { allowMissingFromStorage: true });
}; };
const importStlFileFromDashboard = useCallback( const importFileFromDashboard = useCallback(
async (file: File) => { async (file: File) => {
if (!importExtensionSupported(file.name)) { const isSvg = /\.svg$/i.test(file.name) || file.type === "image/svg+xml";
setDashboardNotice("Unsupported file type. Use STL."); if (!isSvg && !importExtensionSupported(file.name)) {
setDashboardNotice("Unsupported file type. Use STL or SVG.");
return; return;
} }
try { try {
const shape = importedShapeFromStl(file.name, await file.arrayBuffer()); const shape = isSvg
? importedShapeFromSvg(file.name, await file.text())
: importedShapeFromStl(file.name, await file.arrayBuffer());
const project = newProject(projectNameFromFileName(file.name), projects.length, 1); const project = newProject(projectNameFromFileName(file.name), projects.length, 1);
const revision = project.revision ?? project.updatedAt; const revision = project.revision ?? project.updatedAt;
await saveProjectShapes(project.id, [shape], revision); await saveProjectShapes(project.id, [shape], revision);
@@ -608,14 +611,14 @@ export default function Home() {
{JSON.stringify(projectDebugSummary)} {JSON.stringify(projectDebugSummary)}
</pre> </pre>
<input <input
ref={dashboardStlInputRef} ref={dashboardImportInputRef}
className="hidden-file-input" className="hidden-file-input"
type="file" type="file"
accept=".stl" accept=".stl,.svg,image/svg+xml"
onChange={(event) => { onChange={(event) => {
const file = event.currentTarget.files?.[0]; const file = event.currentTarget.files?.[0];
if (file) { if (file) {
void importStlFileFromDashboard(file); void importFileFromDashboard(file);
} }
event.currentTarget.value = ""; event.currentTarget.value = "";
}} }}
@@ -637,7 +640,7 @@ export default function Home() {
onDeleteProject={deleteProject} onDeleteProject={deleteProject}
onDownloadFolderChange={setDownloadFolder} onDownloadFolderChange={setDownloadFolder}
onDownloadModeChange={setDownloadMode} onDownloadModeChange={setDownloadMode}
onImportStl={() => dashboardStlInputRef.current?.click()} onImportFile={() => dashboardImportInputRef.current?.click()}
onChallenges={() => { onChallenges={() => {
setDashboardSection("challenges"); setDashboardSection("challenges");
setDashboardNotice(""); setDashboardNotice("");
@@ -688,7 +691,7 @@ function Dashboard({
onDeleteProject, onDeleteProject,
onDownloadFolderChange, onDownloadFolderChange,
onDownloadModeChange, onDownloadModeChange,
onImportStl, onImportFile,
onChallenges, onChallenges,
onDashboardHome, onDashboardHome,
onOpenProject, onOpenProject,
@@ -714,7 +717,7 @@ function Dashboard({
onDeleteProject: (projectId: string) => void; onDeleteProject: (projectId: string) => void;
onDownloadFolderChange: (value: string) => void; onDownloadFolderChange: (value: string) => void;
onDownloadModeChange: (value: DownloadMode) => void; onDownloadModeChange: (value: DownloadMode) => void;
onImportStl: () => void; onImportFile: () => void;
onChallenges: () => void; onChallenges: () => void;
onDashboardHome: () => void; onDashboardHome: () => void;
onOpenProject: (projectId: string) => void; onOpenProject: (projectId: string) => void;
@@ -810,11 +813,11 @@ function Dashboard({
</span> </span>
<span>Create new 3D design</span> <span>Create new 3D design</span>
</button> </button>
<button className="dashboard-action-tile" type="button" onClick={onImportStl}> <button className="dashboard-action-tile" type="button" onClick={onImportFile}>
<span className="dashboard-action-icon"> <span className="dashboard-action-icon">
<FileUp size={24} strokeWidth={2.4} /> <FileUp size={24} strokeWidth={2.4} />
</span> </span>
<span>Import STL</span> <span>Import STL/SVG</span>
</button> </button>
<button className="dashboard-action-tile" type="button" onClick={onWorkspace}> <button className="dashboard-action-tile" type="button" onClick={onWorkspace}>
<span className="dashboard-action-icon"> <span className="dashboard-action-icon">
+21 -5
View File
@@ -79,7 +79,7 @@ import {
import type { CadModifierComponentMesh, CadModifierDisplayEdge, CadModifierEdge, CadModifierKind, CadModifierMeshPart, CadModifierPrimitivePart, CadModifierQuality, CadModifierWorkerRequest, CadModifierWorkerResponse } from "@/lib/cadModifierTypes"; import type { CadModifierComponentMesh, CadModifierDisplayEdge, CadModifierEdge, CadModifierKind, CadModifierMeshPart, CadModifierPrimitivePart, CadModifierQuality, CadModifierWorkerRequest, CadModifierWorkerResponse } from "@/lib/cadModifierTypes";
import type { AlignAxis, AlignHandleStatus, AlignTarget, GridSize, ShapeAsset, SketchImage, SketchPoint, SketchProfile, SketchSegment, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge"; import type { AlignAxis, AlignHandleStatus, AlignTarget, GridSize, ShapeAsset, SketchImage, SketchPoint, SketchProfile, SketchSegment, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
export { importedShapeFromStl }; export { importedShapeFromStl, importedShapeFromSvg };
type TopPanel = "import" | "export" | "tips" | "profile" | "settings" | null; type TopPanel = "import" | "export" | "tips" | "profile" | "settings" | null;
type ExportFormat = "stl" | "obj"; type ExportFormat = "stl" | "obj";
@@ -2102,6 +2102,7 @@ function bakeShapeTransformIntoMesh(shape: WorkplaneShape): WorkplaneShape {
function importedShapeFromSvg(fileName: string, source: string): WorkplaneShape { function importedShapeFromSvg(fileName: string, source: string): WorkplaneShape {
const parsed = svgLoader.parse(source); const parsed = svgLoader.parse(source);
const rawPositions: number[] = []; const rawPositions: number[] = [];
const rawNormals: number[] = [];
parsed.paths.forEach((path) => { parsed.paths.forEach((path) => {
SVGLoader.createShapes(path).forEach((svgShape) => { SVGLoader.createShapes(path).forEach((svgShape) => {
@@ -2113,10 +2114,17 @@ function importedShapeFromSvg(fileName: string, source: string): WorkplaneShape
}); });
rawGeometry.rotateX(-Math.PI / 2); rawGeometry.rotateX(-Math.PI / 2);
const geometry = rawGeometry.index ? rawGeometry.toNonIndexed() : rawGeometry; const geometry = rawGeometry.index ? rawGeometry.toNonIndexed() : rawGeometry;
geometry.computeVertexNormals();
const position = geometry.getAttribute("position"); const position = geometry.getAttribute("position");
const normal = geometry.getAttribute("normal");
for (let i = 0; i < position.count; i += 1) { for (let i = 0; i < position.count; i += 1) {
rawPositions.push(position.getX(i), position.getY(i), position.getZ(i)); rawPositions.push(position.getX(i), position.getY(i), position.getZ(i));
if (normal) {
rawNormals.push(normal.getX(i), normal.getY(i), normal.getZ(i));
}
} }
if (geometry !== rawGeometry) geometry.dispose();
rawGeometry.dispose();
}); });
}); });
@@ -2146,9 +2154,13 @@ function importedShapeFromSvg(fileName: string, source: string): WorkplaneShape
const height = Math.max(1, maxY - minY); const height = Math.max(1, maxY - minY);
const depth = Math.max(1, maxZ - minZ); const depth = Math.max(1, maxZ - minZ);
const positions: number[] = []; const positions: number[] = [];
const normals: number[] = [];
for (let i = 0; i < rawPositions.length; i += 3) { for (let i = 0; i < rawPositions.length; i += 3) {
positions.push(rawPositions[i] - centerX, rawPositions[i + 1] - minY, rawPositions[i + 2] - centerZ); positions.push(rawPositions[i] - centerX, rawPositions[i + 1] - minY, rawPositions[i + 2] - centerZ);
if (rawNormals.length === rawPositions.length) {
normals.push(rawNormals[i], rawNormals[i + 1], rawNormals[i + 2]);
}
} }
return { return {
@@ -2167,6 +2179,7 @@ function importedShapeFromSvg(fileName: string, source: string): WorkplaneShape
rotationZ: 0, rotationZ: 0,
importedMesh: { importedMesh: {
positions, positions,
normals: normals.length ? normals : undefined,
baseWidth: width, baseWidth: width,
baseDepth: depth, baseDepth: depth,
baseHeight: height, baseHeight: height,
@@ -7552,8 +7565,9 @@ export function SketchForgeEditor({
const selectFile = useCallback(async (file: File) => { const selectFile = useCallback(async (file: File) => {
const isStep = /\.(step|stp)$/i.test(file.name); const isStep = /\.(step|stp)$/i.test(file.name);
if (!isStep && !importExtensionSupported(file.name)) { const isSvg = /\.svg$/i.test(file.name) || file.type === "image/svg+xml";
setNotice("Unsupported file type. Use STL or STEP."); if (!isStep && !isSvg && !importExtensionSupported(file.name)) {
setNotice("Unsupported file type. Use STL, STEP, or SVG.");
return; return;
} }
@@ -7563,6 +7577,8 @@ export function SketchForgeEditor({
setNotice("Reading STEP… first import loads the OpenCascade kernel (~22 MB), one time per session"); setNotice("Reading STEP… first import loads the OpenCascade kernel (~22 MB), one time per session");
const { importedShapeFromStep } = await import("@/lib/stepImport"); const { importedShapeFromStep } = await import("@/lib/stepImport");
nextShape = await importedShapeFromStep(file.name, await file.arrayBuffer()); nextShape = await importedShapeFromStep(file.name, await file.arrayBuffer());
} else if (isSvg) {
nextShape = importedShapeFromSvg(file.name, await file.text());
} else { } else {
nextShape = importedShapeFromStl(file.name, await file.arrayBuffer()); nextShape = importedShapeFromStl(file.name, await file.arrayBuffer());
} }
@@ -8044,7 +8060,7 @@ export function SketchForgeEditor({
ref={fileInputRef} ref={fileInputRef}
className="hidden-file-input" className="hidden-file-input"
type="file" type="file"
accept=".stl,.step,.stp" accept=".stl,.step,.stp,.svg,image/svg+xml"
onChange={(event) => { onChange={(event) => {
if (event.currentTarget.files) { if (event.currentTarget.files) {
selectFiles(event.currentTarget.files); selectFiles(event.currentTarget.files);
@@ -8565,7 +8581,7 @@ function TopActionPanel({
}} }}
> >
<ToolbarImportIcon /> <ToolbarImportIcon />
<strong>Drop STL or STEP files</strong> <strong>Drop STL, STEP, or SVG files</strong>
<span>or click to choose from your computer</span> <span>or click to choose from your computer</span>
</button> </button>
</div> </div>
@@ -4437,7 +4437,7 @@ function createShapeObject(shape: WorkplaneShape, showEdges = false, onTextureRe
opacity: shape.hole ? (shape.importedMesh ? 0.34 : 0.52) : 1, opacity: shape.hole ? (shape.importedMesh ? 0.34 : 0.52) : 1,
roughness: shape.hole ? 0.88 : 0.57, roughness: shape.hole ? 0.88 : 0.57,
metalness: 0.02, metalness: 0.02,
side: shape.importedMesh?.sourceFormat === "json" || mirroredAxisCount(shape) % 2 === 1 ? THREE.DoubleSide : THREE.FrontSide, side: shape.importedMesh?.sourceFormat === "json" || shape.importedMesh?.sourceFormat === "svg" || mirroredAxisCount(shape) % 2 === 1 ? THREE.DoubleSide : THREE.FrontSide,
}); });
const width = shapeWidth(shape); const width = shapeWidth(shape);
+1 -1
View File
@@ -4,7 +4,7 @@ import { createLocalId } from "@/lib/localIds";
import type { WorkplaneShape } from "@/types/sketchforge"; import type { WorkplaneShape } from "@/types/sketchforge";
const stlLoader = new STLLoader(); const stlLoader = new STLLoader();
const SUPPORTED_IMPORT_EXTENSIONS = new Set(["stl"]); const SUPPORTED_IMPORT_EXTENSIONS = new Set(["stl", "svg"]);
function fileExtension(fileName: string) { function fileExtension(fileName: string) {
return fileName.split(".").pop()?.toLowerCase() ?? ""; return fileName.split(".").pop()?.toLowerCase() ?? "";
+15
View File
@@ -0,0 +1,15 @@
import { describe, expect, it } from "vitest";
import { importExtensionSupported } from "@/lib/stlImport";
describe("importExtensionSupported", () => {
it("accepts STL and SVG imports", () => {
expect(importExtensionSupported("part.stl")).toBe(true);
expect(importExtensionSupported("logo.svg")).toBe(true);
expect(importExtensionSupported("profile.SVG")).toBe(true);
});
it("rejects unsupported dashboard import extensions", () => {
expect(importExtensionSupported("drawing.png")).toBe(false);
expect(importExtensionSupported("assembly.step")).toBe(false);
});
});