Checkpoint SKF project format and export updates

This commit is contained in:
Formsmith
2026-07-16 12:30:39 +03:00
parent 400c4bf86e
commit 70e45bb966
22 changed files with 3028 additions and 133 deletions
+17 -1
View File
@@ -1,8 +1,9 @@
import type { WorkplaneShape } from "@/types/sketchforge";
import { canonicalizeShape, serializeShapesForSync } from "@/lib/workplaneShapes";
export const MAX_EDITOR_HISTORY_ENTRIES = 100;
export const MAX_EDITOR_HISTORY_ENTRIES = 5000;
export const MAX_EDITOR_HISTORY_BYTES = 64 * 1024 * 1024;
export type EditorHistoryExportLimit = "unlimited" | 100 | 50 | 30;
export type EditorHistoryEntry = {
shapes: WorkplaneShape[];
@@ -105,3 +106,18 @@ export function hydrateEditorHistoryState(
return { entries: [fallback], index: 0 };
}
}
export function editorHistoryForExport(
entries: EditorHistoryEntry[],
requestedIndex: number,
limit: EditorHistoryExportLimit,
): EditorHistoryState {
if (entries.length === 0) return { entries: [], index: 0 };
const index = Math.min(Math.max(0, requestedIndex), entries.length - 1);
if (limit === "unlimited") return { entries, index };
const start = Math.max(0, index - limit);
return {
entries: entries.slice(start, index + 1),
index: index - start,
};
}
+1 -1
View File
@@ -1,4 +1,4 @@
export type ProjectExportFormat = "stl" | "obj" | "step";
export type ProjectExportFormat = "stl" | "obj" | "step" | "svg" | "skf";
export function projectExportFileName(projectName: string, format: ProjectExportFormat) {
const safeProjectName = projectName
+93
View File
@@ -0,0 +1,93 @@
import type { ProjectAsset, ProjectAssetSourceFormat, WorkplaneShape } from "@/types/sketchforge";
function exactArrayBuffer(bytes: Uint8Array) {
return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;
}
export async function sha256Hex(bytes: Uint8Array) {
if (!globalThis.crypto?.subtle) {
throw new Error("Secure hashing is unavailable in this browser");
}
const digest = await globalThis.crypto.subtle.digest("SHA-256", exactArrayBuffer(bytes));
return Array.from(new Uint8Array(digest), (value) => value.toString(16).padStart(2, "0")).join("");
}
export function sourceFormatForFileName(fileName: string): ProjectAssetSourceFormat | null {
const extension = fileName.split(".").pop()?.toLowerCase();
if (extension === "stl" || extension === "obj" || extension === "svg") return extension;
if (extension === "step" || extension === "stp") return "step";
return null;
}
export function defaultMediaTypeForSource(format: ProjectAssetSourceFormat) {
if (format === "svg") return "image/svg+xml";
if (format === "step") return "application/step";
if (format === "obj") return "model/obj";
return "model/stl";
}
export async function projectAssetFromBytes(
name: string,
sourceFormat: ProjectAssetSourceFormat,
bytes: Uint8Array,
mediaType = defaultMediaTypeForSource(sourceFormat),
): Promise<ProjectAsset> {
const stableBytes = new Uint8Array(bytes);
const sha256 = await sha256Hex(stableBytes);
return {
id: `asset-${sha256.slice(0, 32)}`,
name: name.trim() || `Imported ${sourceFormat.toUpperCase()}`,
mediaType: mediaType.trim() || defaultMediaTypeForSource(sourceFormat),
sourceFormat,
bytes: stableBytes,
byteLength: stableBytes.byteLength,
sha256,
};
}
export async function projectAssetFromFile(file: File, sourceFormat = sourceFormatForFileName(file.name)) {
if (!sourceFormat) throw new Error("Unsupported project asset type");
const bytes = new Uint8Array(await file.arrayBuffer());
return projectAssetFromBytes(file.name, sourceFormat, bytes, file.type);
}
export function normalizeProjectAsset(value: ProjectAsset): ProjectAsset {
const candidate = value.bytes as Uint8Array | ArrayBuffer | number[];
const bytes = candidate instanceof Uint8Array
? new Uint8Array(candidate)
: candidate instanceof ArrayBuffer
? new Uint8Array(candidate.slice(0))
: new Uint8Array(Array.isArray(candidate) ? candidate : []);
return { ...value, bytes, byteLength: bytes.byteLength };
}
export function dedupeProjectAssets(assets: ProjectAsset[]) {
const byHash = new Map<string, ProjectAsset>();
assets.forEach((asset) => {
const normalized = normalizeProjectAsset(asset);
if (!byHash.has(normalized.sha256)) byHash.set(normalized.sha256, normalized);
});
return [...byHash.values()].sort((a, b) => a.id.localeCompare(b.id));
}
export function attachProjectAsset(shape: WorkplaneShape, assetId: string): WorkplaneShape {
if (!shape.importedMesh) return shape;
return {
...shape,
importedMesh: {
...shape.importedMesh,
assetId,
},
};
}
export function projectAssetIdsInShapes(shapes: WorkplaneShape[]) {
const ids = new Set<string>();
const visit = (shape: WorkplaneShape) => {
if (shape.importedMesh?.assetId) ids.add(shape.importedMesh.assetId);
shape.groupedShapes?.forEach(visit);
shape.edgeTreatmentHistory?.forEach((entry) => visit(entry.before));
};
shapes.forEach(visit);
return ids;
}
+1
View File
@@ -53,6 +53,7 @@ export function sceneShape(shape: Partial<WorkplaneShape> & Pick<WorkplaneShape,
groupedBaseWidth: shape.groupedBaseWidth,
groupedBaseDepth: shape.groupedBaseDepth,
groupedBaseHeight: shape.groupedBaseHeight,
groupOperation: shape.groupOperation,
locked: shape.locked ?? false,
hidden: shape.hidden ?? false,
});
File diff suppressed because it is too large Load Diff
+67
View File
@@ -0,0 +1,67 @@
export type SvgProjectionPolygon = ReadonlyArray<readonly [number, number]>;
export type SvgProjectionLayer = {
name: string;
color: string;
polygons: ReadonlyArray<SvgProjectionPolygon>;
};
function xmlEscape(value: string) {
return value
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&apos;");
}
function svgNumber(value: number) {
const rounded = Math.abs(value) < 1e-9 ? 0 : Number(value.toFixed(6));
return String(rounded);
}
function safeFillColor(value: string) {
return /^(?:#[0-9a-f]{3,8}|(?:rgb|hsl)a?\([^<>]+\))$/i.test(value.trim()) ? value.trim() : "#0098c7";
}
export function toSvgProjection(layers: ReadonlyArray<SvgProjectionLayer>, title = "SketchForge design") {
const cleanLayers = layers.flatMap((layer) => {
const polygons = layer.polygons.filter(
(polygon) => polygon.length >= 3 && polygon.every(([x, y]) => Number.isFinite(x) && Number.isFinite(y)),
);
return polygons.length ? [{ ...layer, polygons }] : [];
});
let pointCount = 0;
let minX = Number.POSITIVE_INFINITY;
let minY = Number.POSITIVE_INFINITY;
let maxX = Number.NEGATIVE_INFINITY;
let maxY = Number.NEGATIVE_INFINITY;
cleanLayers.forEach((layer) => layer.polygons.forEach((polygon) => polygon.forEach(([x, y]) => {
pointCount += 1;
minX = Math.min(minX, x);
minY = Math.min(minY, y);
maxX = Math.max(maxX, x);
maxY = Math.max(maxY, y);
})));
if (!pointCount) throw new Error("SVG projection contains no readable contours");
const width = maxX - minX;
const height = maxY - minY;
if (width <= 0 || height <= 0) throw new Error("SVG projection does not enclose a visible area");
const body = cleanLayers.map((layer) => {
const pathData = layer.polygons
.map((polygon) => polygon.map(([x, y], index) => `${index === 0 ? "M" : "L"}${svgNumber(x)} ${svgNumber(y)}`).join(" ") + " Z")
.join(" ");
return ` <path data-name="${xmlEscape(layer.name)}" d="${pathData}" fill="${safeFillColor(layer.color)}" fill-rule="evenodd"/>`;
});
return [
'<?xml version="1.0" encoding="UTF-8"?>',
`<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="${svgNumber(width)}mm" height="${svgNumber(height)}mm" viewBox="${svgNumber(minX)} ${svgNumber(minY)} ${svgNumber(width)} ${svgNumber(height)}">`,
` <title>${xmlEscape(title)}</title>`,
" <desc>Top-view vector projection exported by SketchForge</desc>",
...body,
"</svg>",
].join("\n");
}
+83 -10
View File
@@ -18,6 +18,9 @@ type SvgPathStyle = {
fill?: string;
fillOpacity?: number;
opacity?: number;
stroke?: string;
strokeOpacity?: number;
strokeWidth?: number;
visibility?: string;
};
@@ -54,13 +57,34 @@ function attributeValues(source: string, name: string) {
return values;
}
const SVG_DOCUMENT_TYPE_PATTERN = /<!DOCTYPE\b[^>]*>/gi;
const SVG_11_DOCUMENT_TYPE_PATTERN = /^<!DOCTYPE\s+svg(?:\s+PUBLIC\s+(["'])-\/\/W3C\/\/DTD SVG 1\.1\/\/EN\1\s+(["'])https?:\/\/www\.w3\.org\/Graphics\/SVG\/1\.1\/DTD\/svg11\.dtd\2)?\s*>$/i;
function svgDocumentTypes(source: string) {
return source.match(SVG_DOCUMENT_TYPE_PATTERN) ?? [];
}
export function normalizeSvgDocumentType(source: string) {
return source.replace(SVG_DOCUMENT_TYPE_PATTERN, "");
}
export function validateSvgSourcePreflight(source: string) {
if (!source.trim()) throw new Error("SVG file is empty");
if (sourceByteLength(source) > MAX_SVG_BYTES) {
throw new Error(`SVG is too large. The maximum supported size is ${MAX_SVG_BYTES / 1024 / 1024} MB`);
}
if (/<!DOCTYPE|<!ENTITY/i.test(source)) {
throw new Error("SVG document types and entities are not supported");
if (/<!ENTITY/i.test(source)) {
throw new Error("SVG entities are not supported");
}
const documentTypes = svgDocumentTypes(source);
const documentTypeStarts = source.match(/<!DOCTYPE\b/gi)?.length ?? 0;
if (documentTypes.length !== documentTypeStarts || documentTypes.some((declaration) => !SVG_11_DOCUMENT_TYPE_PATTERN.test(declaration))) {
throw new Error("Only the standard SVG 1.1 document type is supported");
}
if (/\b(?:width|height|viewBox|d)\s*=\s*(["'])[^"']*\bNaN\b[^"']*\1/i.test(source)) {
throw new Error("SVG contains invalid NaN geometry. In Tinkercad, make sure the workplane intersects the model before exporting the cross-section");
}
const xmlElementCount = source.match(/<[a-z][^!?/\s>]*/gi)?.length ?? 0;
@@ -122,6 +146,10 @@ function fillAlpha(fill: string | undefined) {
return Number.parseFloat(functional);
}
function strokeAlpha(stroke: string | undefined) {
return stroke ? fillAlpha(stroke) : 0;
}
function elementStyleValue(element: Element, property: string) {
const style = (element as Element & { style?: CSSStyleDeclaration }).style;
const fromStyle = style?.getPropertyValue(property);
@@ -143,15 +171,55 @@ function elementOrAncestorSuppressesRendering(element: Element | null | undefine
return false;
}
function pathIsFilledAndVisible(path: THREE.ShapePath) {
function pathStyleAndNode(path: THREE.ShapePath) {
const userData = (path as THREE.ShapePath & { userData?: { style?: SvgPathStyle; node?: Element } }).userData;
const style = userData?.style ?? {};
return { style: userData?.style ?? {}, node: userData?.node };
}
function pathIsVisible(path: THREE.ShapePath) {
const { style, node } = pathStyleAndNode(path);
const visibility = style.visibility?.trim().toLowerCase();
if (visibility === "hidden" || visibility === "collapse") return false;
if (numericStyleValue(style.opacity) <= MIN_VISIBLE_ALPHA) return false;
return !elementOrAncestorSuppressesRendering(node);
}
function pathHasVisibleFill(path: THREE.ShapePath) {
if (!pathIsVisible(path)) return false;
const { style } = pathStyleAndNode(path);
if (numericStyleValue(style.fillOpacity) <= MIN_VISIBLE_ALPHA) return false;
if (fillAlpha(style.fill) <= MIN_VISIBLE_ALPHA) return false;
return !elementOrAncestorSuppressesRendering(userData?.node);
return fillAlpha(style.fill) > MIN_VISIBLE_ALPHA;
}
function pathHasVisibleStroke(path: THREE.ShapePath) {
if (!pathIsVisible(path)) return false;
const { style } = pathStyleAndNode(path);
if (numericStyleValue(style.strokeOpacity) <= MIN_VISIBLE_ALPHA) return false;
if (numericStyleValue(style.strokeWidth, 0) <= MIN_VISIBLE_ALPHA) return false;
return strokeAlpha(style.stroke) > MIN_VISIBLE_ALPHA;
}
function subPathIsClosed(path: THREE.Path) {
const points = path.getPoints(SVG_CURVE_SEGMENTS);
if (points.length < 3) return false;
if (path.autoClose) return true;
const extent = points.reduce((largest, point) => Math.max(largest, Math.abs(point.x), Math.abs(point.y)), 1);
const tolerance = extent * 1e-9;
return points[0].distanceToSquared(points[points.length - 1]) <= tolerance * tolerance;
}
function extrusionProfileFromPath(path: THREE.ShapePath) {
if (pathHasVisibleFill(path)) return path;
if (!pathHasVisibleStroke(path)) return null;
const closedSubPaths = path.subPaths.filter(subPathIsClosed);
if (!closedSubPaths.length) return null;
const profile = new THREE.ShapePath();
profile.color.copy(path.color);
profile.subPaths.push(...closedSubPaths);
const userData = (path as THREE.ShapePath & { userData?: { style?: SvgPathStyle; node?: Element } }).userData;
(profile as THREE.ShapePath & { userData?: { style?: SvgPathStyle; node?: Element } }).userData = userData;
return profile;
}
function cleanRingPoints(points: THREE.Vector2[]) {
@@ -422,10 +490,15 @@ export function validateClosedSolidTriangleSoup(positions: readonly number[], la
}
export function buildSvgExtrusionFromPaths(paths: readonly THREE.ShapePath[]) {
const visiblePaths = paths.filter(pathIsFilledAndVisible);
if (!visiblePaths.length) throw new Error("SVG has no readable visible filled paths");
const profilePaths = paths.map(extrusionProfileFromPath).filter((path): path is THREE.ShapePath => Boolean(path));
if (!profilePaths.length) {
if (paths.some(pathHasVisibleStroke)) {
throw new Error("SVG contains only open strokes. Close the paths or convert the strokes to filled outlines before importing");
}
throw new Error("SVG has no readable visible filled or closed-stroke paths");
}
const sourceShapes = visiblePaths.flatMap((path) => SVGLoader.createShapes(path));
const sourceShapes = profilePaths.flatMap((path) => SVGLoader.createShapes(path));
const shapes = composeNestedRings(sourceShapes);
const rawPositions: number[] = [];
const acceptedAnalyses: TriangleSoupAnalysis[] = [];
@@ -485,7 +558,7 @@ export function buildSvgExtrusionFromPaths(paths: readonly THREE.ShapePath[]) {
export function importedShapeFromSvg(fileName: string, source: string): WorkplaneShape {
validateSvgSourcePreflight(source);
const parsed = svgLoader.parse(normalizeSvgUseReferences(source));
const parsed = svgLoader.parse(normalizeSvgUseReferences(normalizeSvgDocumentType(source)));
const parsedXml = parsed.xml as unknown as XMLDocument | Element;
const root = "documentElement" in parsedXml ? parsedXml.documentElement : parsedXml;
if (root.localName !== "svg" || root.querySelector("parsererror")) {
+1
View File
@@ -188,6 +188,7 @@ export function workplaneShapesEqual(a: WorkplaneShape, b: WorkplaneShape) {
a.groupedBaseWidth === b.groupedBaseWidth &&
a.groupedBaseDepth === b.groupedBaseDepth &&
a.groupedBaseHeight === b.groupedBaseHeight &&
a.groupOperation === b.groupOperation &&
a.locked === b.locked &&
a.hidden === b.hidden
);