Ship shared projects and CAD reliability updates

This commit is contained in:
Formsmith
2026-07-19 15:58:52 +03:00
parent 3a7db063e7
commit c5ce5a80f0
23 changed files with 999 additions and 83 deletions
+7
View File
@@ -4,6 +4,13 @@ export const CAD_MODIFIER_MAX_SHARP_ANGLE = 90;
export type CadModifierRequestPhase = "prepare" | "preview";
export function isCadModifierWasmMemoryFault(message: string, errorName = "") {
return (
/memory access out of bounds|out of bounds memory access|\bwasm\b|\babort(?:ed)?\b/i.test(message) ||
/^(?:WebAssembly\.)?RuntimeError$/i.test(errorName)
);
}
export function edgeModifierSelectionStatus(prepared: boolean, selectedCount: number, availableCount: number) {
return prepared ? `${selectedCount} of ${availableCount} sharp edges selected` : "Preparing edges\u2026";
}
+115
View File
@@ -0,0 +1,115 @@
export type SketchOutlinePoint = Readonly<{ x: number; y: number }>;
export type SketchOutlineIntersection = {
outlineA: number;
edgeA: number;
outlineB: number;
edgeB: number;
};
function distanceSquared(a: SketchOutlinePoint, b: SketchOutlinePoint) {
const dx = a.x - b.x;
const dy = a.y - b.y;
return dx * dx + dy * dy;
}
function normalizedOutline(points: readonly SketchOutlinePoint[], epsilon: number) {
const epsilonSquared = epsilon * epsilon;
const result: SketchOutlinePoint[] = [];
points.forEach((point) => {
if (!Number.isFinite(point.x) || !Number.isFinite(point.y)) return;
if (!result.length || distanceSquared(result[result.length - 1], point) > epsilonSquared) result.push(point);
});
if (result.length > 1 && distanceSquared(result[0], result[result.length - 1]) <= epsilonSquared) result.pop();
return result;
}
function orientation(a: SketchOutlinePoint, b: SketchOutlinePoint, c: SketchOutlinePoint) {
return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);
}
function pointOnSegment(point: SketchOutlinePoint, start: SketchOutlinePoint, end: SketchOutlinePoint, epsilon: number) {
if (Math.abs(orientation(start, end, point)) > epsilon) return false;
return point.x >= Math.min(start.x, end.x) - epsilon
&& point.x <= Math.max(start.x, end.x) + epsilon
&& point.y >= Math.min(start.y, end.y) - epsilon
&& point.y <= Math.max(start.y, end.y) + epsilon;
}
function segmentsIntersect(
a: SketchOutlinePoint,
b: SketchOutlinePoint,
c: SketchOutlinePoint,
d: SketchOutlinePoint,
epsilon: number,
) {
if (Math.max(a.x, b.x) + epsilon < Math.min(c.x, d.x)
|| Math.max(c.x, d.x) + epsilon < Math.min(a.x, b.x)
|| Math.max(a.y, b.y) + epsilon < Math.min(c.y, d.y)
|| Math.max(c.y, d.y) + epsilon < Math.min(a.y, b.y)) {
return false;
}
const abC = orientation(a, b, c);
const abD = orientation(a, b, d);
const cdA = orientation(c, d, a);
const cdB = orientation(c, d, b);
const crossesAB = (abC > epsilon && abD < -epsilon) || (abC < -epsilon && abD > epsilon);
const crossesCD = (cdA > epsilon && cdB < -epsilon) || (cdA < -epsilon && cdB > epsilon);
if (crossesAB && crossesCD) return true;
return (Math.abs(abC) <= epsilon && pointOnSegment(c, a, b, epsilon))
|| (Math.abs(abD) <= epsilon && pointOnSegment(d, a, b, epsilon))
|| (Math.abs(cdA) <= epsilon && pointOnSegment(a, c, d, epsilon))
|| (Math.abs(cdB) <= epsilon && pointOnSegment(b, c, d, epsilon));
}
function outlineEpsilon(outlines: readonly (readonly SketchOutlinePoint[])[]) {
const points = outlines.flatMap((outline) => [...outline]);
if (!points.length) return 1e-8;
const minX = Math.min(...points.map((point) => point.x));
const maxX = Math.max(...points.map((point) => point.x));
const minY = Math.min(...points.map((point) => point.y));
const maxY = Math.max(...points.map((point) => point.y));
return Math.max(1e-8, Math.hypot(maxX - minX, maxY - minY) * 1e-8);
}
function adjacentEdges(first: number, second: number, edgeCount: number) {
return first === second
|| Math.abs(first - second) === 1
|| (first === 0 && second === edgeCount - 1)
|| (second === 0 && first === edgeCount - 1);
}
/**
* Finds crossings that make closed sketch contours unsafe to triangulate.
* Adjacent edges may share their intended endpoint; all other touching,
* crossing, or overlapping edges are rejected.
*/
export function findSketchOutlineIntersection(outlines: readonly (readonly SketchOutlinePoint[])[]): SketchOutlineIntersection | null {
const epsilon = outlineEpsilon(outlines);
const clean = outlines.map((outline) => normalizedOutline(outline, epsilon));
for (let outlineA = 0; outlineA < clean.length; outlineA += 1) {
const a = clean[outlineA];
if (a.length < 3) continue;
for (let edgeA = 0; edgeA < a.length; edgeA += 1) {
const aStart = a[edgeA];
const aEnd = a[(edgeA + 1) % a.length];
for (let outlineB = outlineA; outlineB < clean.length; outlineB += 1) {
const b = clean[outlineB];
if (b.length < 3) continue;
const firstEdgeB = outlineA === outlineB ? edgeA + 1 : 0;
for (let edgeB = firstEdgeB; edgeB < b.length; edgeB += 1) {
if (outlineA === outlineB && adjacentEdges(edgeA, edgeB, a.length)) continue;
const bStart = b[edgeB];
const bEnd = b[(edgeB + 1) % b.length];
if (segmentsIntersect(aStart, aEnd, bStart, bEnd, epsilon)) {
return { outlineA, edgeA, outlineB, edgeB };
}
}
}
}
}
return null;
}
+44 -15
View File
@@ -152,6 +152,13 @@ export type SkfRestoredProject = {
migratedFromVersion?: number;
};
export type SkfProjectPackageSummary = {
projectName: string;
createdAt: number;
modifiedAt: number;
formatVersion: number;
};
export type SkfSourceImporter = (asset: ProjectAsset) => Promise<NonNullable<WorkplaneShape["importedMesh"]>>;
export type ImportSkfOptions = {
@@ -1102,9 +1109,44 @@ function validateLegacyRuntimeShape(shape: WorkplaneShape, label: string) {
if (cadBrep !== undefined && typeof cadBrep !== "string") throw new Error(`${label}.cadBrep is invalid`);
}
export async function importSkfProject(input: ArrayBuffer | Uint8Array, options: ImportSkfOptions = {}): Promise<SkfRestoredProject> {
function skfInputBytes(input: ArrayBuffer | Uint8Array) {
const bytes = input instanceof Uint8Array ? new Uint8Array(input) : new Uint8Array(input.slice(0));
if (!bytes.byteLength) throw new Error(".skf file is empty");
return bytes;
}
async function readPackagedSkf(bytes: Uint8Array) {
inspectZipBeforeExpansion(bytes);
let files: ArchiveFiles;
try {
files = await unzipAsync(bytes);
} catch (error) {
throw new Error(`Could not expand .skf package: ${error instanceof Error ? error.message : "corrupt ZIP data"}`);
}
let raw: unknown;
try {
raw = JSON.parse(strFromU8(files["project.json"]));
} catch {
throw new Error("project.json is malformed");
}
return { files, validated: await validateDocumentAndAssets(raw, files) };
}
export async function inspectSkfProjectPackage(input: ArrayBuffer | Uint8Array): Promise<SkfProjectPackageSummary> {
const bytes = skfInputBytes(input);
const prefix = strFromU8(bytes.subarray(0, Math.min(bytes.length, 64))).trimStart();
if (prefix.startsWith("{")) throw new Error("Shared storage accepts packaged .skf files, not legacy JSON projects");
const { validated } = await readPackagedSkf(bytes);
return {
projectName: validated.document.metadata.projectName,
createdAt: Date.parse(validated.document.metadata.createdAt),
modifiedAt: Date.parse(validated.document.metadata.modifiedAt),
formatVersion: validated.document.formatVersion,
};
}
export async function importSkfProject(input: ArrayBuffer | Uint8Array, options: ImportSkfOptions = {}): Promise<SkfRestoredProject> {
const bytes = skfInputBytes(input);
const prefix = strFromU8(bytes.subarray(0, Math.min(bytes.length, 64))).trimStart();
if (prefix.startsWith("{")) {
if (bytes.byteLength > SKF_LIMITS.projectJsonBytes) throw new Error("Legacy .skf JSON exceeds the supported size limit");
@@ -1123,19 +1165,6 @@ export async function importSkfProject(input: ArrayBuffer | Uint8Array, options:
throw new Error("This legacy .skf version is not supported");
}
inspectZipBeforeExpansion(bytes);
let files: ArchiveFiles;
try {
files = await unzipAsync(bytes);
} catch (error) {
throw new Error(`Could not expand .skf package: ${error instanceof Error ? error.message : "corrupt ZIP data"}`);
}
let raw: unknown;
try {
raw = JSON.parse(strFromU8(files["project.json"]));
} catch {
throw new Error("project.json is malformed");
}
const validated = await validateDocumentAndAssets(raw, files);
const { files, validated } = await readPackagedSkf(bytes);
return restoreV1(validated.document, validated.assetById, validated.stateById, files, options);
}
+17
View File
@@ -29,6 +29,23 @@ export function shapeDepth(shape: WorkplaneShape) {
return shape.depth ?? shape.size;
}
export function meshYawDegrees(shape: WorkplaneShape) {
const isRoundPrimitive = !shape.importedMesh && (shape.kind === "cylinder" || shape.kind === "cone");
const isCircular = Math.abs(shapeWidth(shape) - shapeDepth(shape)) < 0.0005;
if (!isRoundPrimitive || !isCircular) {
return shape.rotation;
}
// A tessellated circular primitive is only invariant by one whole side step.
// Preserve the remaining yaw so low-sided cylinders (for example a triangular
// prism) are baked and used in booleans at the same angle shown in the viewport.
const sides = Math.max(3, Math.round(shape.sides ?? 96));
const sideStep = 360 / sides;
const normalized = normalizeDegrees(shape.rotation);
const equivalentYaw = normalized - Math.round(normalized / sideStep) * sideStep;
return Math.abs(equivalentYaw) < 1e-9 ? 0 : equivalentYaw;
}
function edgeTreatmentPreserveZone(shape: WorkplaneShape): number {
const own = Math.max(...(shape.edgeTreatments ?? []).map((feature) => feature.amount), 0);
const child = Math.max(...(shape.groupedShapes ?? []).map(edgeTreatmentPreserveZone), 0);