release: add sketch revolve and configurable gears

This commit is contained in:
Formsmith
2026-07-24 11:55:44 +03:00
parent 5dde9faceb
commit fe161f8d75
32 changed files with 1913 additions and 115 deletions
+240
View File
@@ -0,0 +1,240 @@
import * as THREE from "three";
import { toCreasedNormals } from "three/examples/jsm/utils/BufferGeometryUtils.js";
import type { GearType, WorkplaneShape } from "@/types/sketchforge";
export const DEFAULT_GEAR_TEETH = 12;
export const DEFAULT_GEAR_TOOTH_SIZE = 2.5;
export const DEFAULT_GEAR_CENTER_HOLE_SIZE = 6;
export const DEFAULT_GEAR_TYPE: GearType = "spur";
export const DEFAULT_GEAR_HELIX_ANGLE = 22.5;
export const DEFAULT_GEAR_HELIX_QUALITY = 16;
export const MIN_GEAR_TEETH = 6;
export const MAX_GEAR_TEETH = 64;
export const MIN_GEAR_HELIX_ANGLE = -45;
export const MAX_GEAR_HELIX_ANGLE = 45;
export const MIN_GEAR_HELIX_QUALITY = 4;
export const MAX_GEAR_HELIX_QUALITY = 32;
function clamp(value: number, min: number, max: number) {
return Math.min(max, Math.max(min, value));
}
export function normalizeGearTeeth(value?: number) {
return clamp(Math.round(Number.isFinite(value) ? value as number : DEFAULT_GEAR_TEETH), MIN_GEAR_TEETH, MAX_GEAR_TEETH);
}
export function normalizeGearType(value?: string): GearType {
return value === "helical" || value === "bevel" ? value : DEFAULT_GEAR_TYPE;
}
export function normalizeGearToothSize(value: number | undefined, width: number, depth: number) {
const maximum = Math.max(0.2, Math.min(width, depth) * 0.22);
return clamp(Number.isFinite(value) ? value as number : DEFAULT_GEAR_TOOTH_SIZE, 0.2, maximum);
}
export function gearToothPitch(width: number, depth: number, teeth?: number) {
return Math.PI * Math.max(0.01, Math.min(width, depth)) / normalizeGearTeeth(teeth);
}
export function normalizeGearToothWidth(value: number | undefined, width: number, depth: number, teeth?: number) {
const pitch = gearToothPitch(width, depth, teeth);
return clamp(Number.isFinite(value) ? value as number : pitch * 0.54, pitch * 0.12, pitch * 0.82);
}
export function gearCenterHoleLimits(width: number, depth: number, toothSize?: number) {
const outerRadius = Math.max(0.005, Math.min(width, depth) / 2);
const normalizedToothSize = normalizeGearToothSize(toothSize, width, depth);
const rootRadius = Math.max(outerRadius * 0.34, outerRadius - normalizedToothSize);
const max = Math.max(0.01, rootRadius * 1.5);
return { min: 0, max };
}
export function normalizeGearCenterHoleSize(value: number | undefined, width: number, depth: number, toothSize?: number) {
const limits = gearCenterHoleLimits(width, depth, toothSize);
const outerRadius = Math.max(0.005, Math.min(width, depth) / 2);
const normalizedToothSize = normalizeGearToothSize(toothSize, width, depth);
const rootRadius = Math.max(outerRadius * 0.34, outerRadius - normalizedToothSize);
const defaultSize = Math.min(outerRadius * 0.4, rootRadius * 1.1);
return clamp(Number.isFinite(value) ? value as number : defaultSize, limits.min, limits.max);
}
export function normalizeGearHelixAngle(value?: number) {
return clamp(
Number.isFinite(value) ? value as number : DEFAULT_GEAR_HELIX_ANGLE,
MIN_GEAR_HELIX_ANGLE,
MAX_GEAR_HELIX_ANGLE,
);
}
export function normalizeGearHelixQuality(value?: number) {
return clamp(
Math.round(Number.isFinite(value) ? value as number : DEFAULT_GEAR_HELIX_QUALITY),
MIN_GEAR_HELIX_QUALITY,
MAX_GEAR_HELIX_QUALITY,
);
}
export function gearSettings(shape: Pick<WorkplaneShape, "width" | "depth" | "teeth" | "toothSize" | "toothWidth" | "centerHoleSize" | "gearType" | "helixAngle" | "helixQuality">) {
return {
teeth: normalizeGearTeeth(shape.teeth),
toothSize: normalizeGearToothSize(shape.toothSize, shape.width, shape.depth),
toothWidth: normalizeGearToothWidth(shape.toothWidth, shape.width, shape.depth, shape.teeth),
centerHoleSize: normalizeGearCenterHoleSize(shape.centerHoleSize, shape.width, shape.depth, shape.toothSize),
gearType: normalizeGearType(shape.gearType),
helixAngle: normalizeGearHelixAngle(shape.helixAngle),
helixQuality: normalizeGearHelixQuality(shape.helixQuality),
};
}
type GearGeometryOptions = {
width: number;
depth: number;
height: number;
teeth?: number;
toothSize?: number;
toothWidth?: number;
centerHoleSize?: number;
gearType?: GearType;
helixAngle?: number;
helixQuality?: number;
};
export function createGearGeometry({
width,
depth,
height,
teeth: requestedTeeth,
toothSize: requestedToothSize,
toothWidth: requestedToothWidth,
centerHoleSize: requestedCenterHoleSize,
gearType: requestedType,
helixAngle: requestedHelixAngle,
helixQuality: requestedHelixQuality,
}: GearGeometryOptions) {
const safeWidth = Math.max(0.01, width);
const safeDepth = Math.max(0.01, depth);
const safeHeight = Math.max(0.01, height);
const teeth = normalizeGearTeeth(requestedTeeth);
const toothSize = normalizeGearToothSize(requestedToothSize, safeWidth, safeDepth);
const toothPitch = gearToothPitch(safeWidth, safeDepth, teeth);
const toothWidth = normalizeGearToothWidth(requestedToothWidth, safeWidth, safeDepth, teeth);
const toothFraction = toothWidth / toothPitch;
const centerHoleSize = normalizeGearCenterHoleSize(requestedCenterHoleSize, safeWidth, safeDepth, toothSize);
const hasCenterHole = centerHoleSize > 0;
const gearType = normalizeGearType(requestedType);
const helixAngle = normalizeGearHelixAngle(requestedHelixAngle);
const helixQuality = normalizeGearHelixQuality(requestedHelixQuality);
const outlineCount = teeth * 4;
const ringCount = gearType === "helical" ? helixQuality : 2;
const twist = gearType === "helical" ? THREE.MathUtils.degToRad(helixAngle) : 0;
const topScale = gearType === "bevel" ? 0.68 : 1;
const outerX = safeWidth / 2;
const outerZ = safeDepth / 2;
const rootX = Math.max(outerX * 0.34, outerX - toothSize);
const rootZ = Math.max(outerZ * 0.34, outerZ - toothSize);
const boreX = centerHoleSize / 2;
const boreZ = centerHoleSize / 2;
const toothPhases = [0.05, (1 - toothFraction) / 2, (1 + toothFraction) / 2, 0.95] as const;
const positions: number[] = [];
const indices: number[] = [];
const outerIndex = (ring: number, point: number) => ring * outlineCount * 2 + point;
const innerIndex = (ring: number, point: number) => ring * outlineCount * 2 + outlineCount + point;
for (let ring = 0; ring < ringCount; ring += 1) {
const progress = ring / (ringCount - 1);
const y = progress * safeHeight;
const ringTwist = progress * twist;
const scale = 1 + (topScale - 1) * progress;
for (let tooth = 0; tooth < teeth; tooth += 1) {
for (let phaseIndex = 0; phaseIndex < toothPhases.length; phaseIndex += 1) {
const phase = toothPhases[phaseIndex];
const angle = ((tooth + phase) / teeth) * Math.PI * 2 + ringTwist;
const isOuter = phaseIndex === 1 || phaseIndex === 2;
const radiusX = (isOuter ? outerX : rootX) * scale;
const radiusZ = (isOuter ? outerZ : rootZ) * scale;
positions.push(Math.cos(angle) * radiusX, y, Math.sin(angle) * radiusZ);
}
}
for (let point = 0; point < outlineCount; point += 1) {
const angle = (point / outlineCount) * Math.PI * 2;
positions.push(Math.cos(angle) * boreX, y, Math.sin(angle) * boreZ);
}
}
let outlineMinX = Number.POSITIVE_INFINITY;
let outlineMaxX = Number.NEGATIVE_INFINITY;
let outlineMinZ = Number.POSITIVE_INFINITY;
let outlineMaxZ = Number.NEGATIVE_INFINITY;
for (let ring = 0; ring < ringCount; ring += 1) {
for (let point = 0; point < outlineCount; point += 1) {
const offset = outerIndex(ring, point) * 3;
outlineMinX = Math.min(outlineMinX, positions[offset]);
outlineMaxX = Math.max(outlineMaxX, positions[offset]);
outlineMinZ = Math.min(outlineMinZ, positions[offset + 2]);
outlineMaxZ = Math.max(outlineMaxZ, positions[offset + 2]);
}
}
const outlineScaleX = safeWidth / Math.max(Number.EPSILON, outlineMaxX - outlineMinX);
const outlineScaleZ = safeDepth / Math.max(Number.EPSILON, outlineMaxZ - outlineMinZ);
for (let ring = 0; ring < ringCount; ring += 1) {
for (let point = 0; point < outlineCount; point += 1) {
const offset = outerIndex(ring, point) * 3;
positions[offset] *= outlineScaleX;
positions[offset + 2] *= outlineScaleZ;
}
}
for (let ring = 0; ring < ringCount - 1; ring += 1) {
for (let point = 0; point < outlineCount; point += 1) {
const next = (point + 1) % outlineCount;
const outerBottom = outerIndex(ring, point);
const outerNextBottom = outerIndex(ring, next);
const outerTop = outerIndex(ring + 1, point);
const outerNextTop = outerIndex(ring + 1, next);
indices.push(outerBottom, outerTop, outerNextTop, outerBottom, outerNextTop, outerNextBottom);
if (hasCenterHole) {
const innerBottom = innerIndex(ring, point);
const innerNextBottom = innerIndex(ring, next);
const innerTop = innerIndex(ring + 1, point);
const innerNextTop = innerIndex(ring + 1, next);
indices.push(innerBottom, innerNextBottom, innerNextTop, innerBottom, innerNextTop, innerTop);
}
}
}
const topRing = ringCount - 1;
for (let point = 0; point < outlineCount; point += 1) {
const next = (point + 1) % outlineCount;
const bottomOuter = outerIndex(0, point);
const bottomOuterNext = outerIndex(0, next);
const bottomInner = innerIndex(0, point);
const bottomInnerNext = innerIndex(0, next);
if (hasCenterHole) {
indices.push(bottomOuter, bottomOuterNext, bottomInnerNext, bottomOuter, bottomInnerNext, bottomInner);
} else {
indices.push(bottomOuter, bottomOuterNext, innerIndex(0, 0));
}
const topOuter = outerIndex(topRing, point);
const topOuterNext = outerIndex(topRing, next);
const topInner = innerIndex(topRing, point);
const topInnerNext = innerIndex(topRing, next);
if (hasCenterHole) {
indices.push(topOuter, topInner, topInnerNext, topOuter, topInnerNext, topOuterNext);
} else {
indices.push(topOuter, innerIndex(topRing, 0), topOuterNext);
}
}
const indexed = new THREE.BufferGeometry();
indexed.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3));
indexed.setIndex(indices);
const geometry = toCreasedNormals(indexed, THREE.MathUtils.degToRad(12));
indexed.dispose();
geometry.computeBoundingBox();
return geometry;
}
+20
View File
@@ -75,6 +75,26 @@ export function displayStepFromMillimeters(step: number, workspace: Pick<Workpla
return step / lengthDisplayUnit(workspace).millimetersPerUnit;
}
export function parseMeasurementInput(value: string | number) {
if (typeof value === "number") return Number.isFinite(value) ? value : Number.NaN;
const compact = value.trim().replace(/[\s\u00a0]/g, "");
if (!compact) return Number.NaN;
const commaIndex = compact.lastIndexOf(",");
const dotIndex = compact.lastIndexOf(".");
let normalized = compact;
if (commaIndex >= 0 && dotIndex >= 0) {
normalized = commaIndex > dotIndex
? compact.replace(/\./g, "").replace(",", ".")
: compact.replace(/,/g, "");
} else if (commaIndex >= 0) {
normalized = compact.replace(",", ".");
}
const parsed = Number(normalized);
return Number.isFinite(parsed) ? parsed : Number.NaN;
}
export function formatMeasurementNumber(value: number, accuracy: MeasurementAccuracy, _step?: number) {
let decimals = accuracy;
while (decimals < 6 && value !== 0 && Math.abs(value) < 0.5 * 10 ** -decimals) {
+21 -3
View File
@@ -1,5 +1,6 @@
import { canonicalizeShape } from "@/lib/workplaneShapes";
import { createLocalId } from "@/lib/localIds";
import { DEFAULT_GEAR_CENTER_HOLE_SIZE, DEFAULT_GEAR_HELIX_ANGLE, DEFAULT_GEAR_HELIX_QUALITY, DEFAULT_GEAR_TEETH, DEFAULT_GEAR_TOOTH_SIZE, DEFAULT_GEAR_TYPE } from "@/lib/gearGeometry";
import type { ShapeAsset, WorkplaneShape } from "@/types/sketchforge";
export type ToolbarShapeAsset = ShapeAsset & { menuIcon: string };
@@ -16,6 +17,7 @@ export const toolbarShapeAssets: ToolbarShapeAsset[] = [
{ id: "half-sphere", name: "Half Sphere", src: "assets/sketchforge/shape-icons-gray/half-sphere.png", menuIcon: "assets/sketchforge/shape-icons-gray/half-sphere.png", kind: "halfSphere", color: "#c9009a" },
{ id: "torus", name: "Torus", src: "assets/sketchforge/shape-icons-gray/torus.png", menuIcon: "assets/sketchforge/shape-icons-gray/torus.png", kind: "torus", color: "#0098c7" },
{ id: "tube", name: "Tube", src: "assets/sketchforge/shape-icons-gray/tube.png", menuIcon: "assets/sketchforge/shape-icons-gray/tube.png", kind: "tube", color: "#ce7013" },
{ id: "gear", name: "Gear", src: "assets/sketchforge/gear-types/spur.png", menuIcon: "assets/sketchforge/gear-types/spur.png", kind: "gear", color: "#6f7f8d" },
];
export function sceneShape(shape: Partial<WorkplaneShape> & Pick<WorkplaneShape, "name" | "kind" | "color">): WorkplaneShape {
@@ -45,10 +47,20 @@ export function sceneShape(shape: Partial<WorkplaneShape> & Pick<WorkplaneShape,
segments: shape.segments,
topRadius: shape.topRadius,
baseRadius: shape.baseRadius,
teeth: shape.teeth,
toothSize: shape.toothSize,
toothWidth: shape.toothWidth,
centerHoleSize: shape.centerHoleSize,
gearType: shape.gearType,
helixAngle: shape.helixAngle,
helixQuality: shape.helixQuality,
text: shape.text,
font: shape.font,
importedMesh: shape.importedMesh,
imagePlate: shape.imagePlate,
sketchProfile: shape.sketchProfile,
sketchOperation: shape.sketchOperation,
sketchRevolve: shape.sketchRevolve,
groupedShapes: shape.groupedShapes,
groupedBaseWidth: shape.groupedBaseWidth,
groupedBaseDepth: shape.groupedBaseDepth,
@@ -61,9 +73,9 @@ export function sceneShape(shape: Partial<WorkplaneShape> & Pick<WorkplaneShape,
export function makeShapeFromAsset(asset: ShapeAsset, point?: { x: number; z: number; elevation?: number }): WorkplaneShape {
const roundProfile = asset.kind === "sphere" || asset.kind === "torus" || asset.kind === "ring" || asset.kind === "halfSphere";
const flatProfile = asset.kind === "torus" || asset.kind === "ring" || asset.kind === "text";
const size = roundProfile ? 22 : 20;
const height = asset.kind === "text" ? 10 : asset.kind === "roundRoof" ? 10 : asset.kind === "halfSphere" ? 11 : flatProfile ? 5 : 20;
const flatProfile = asset.kind === "torus" || asset.kind === "ring" || asset.kind === "text" || asset.kind === "gear";
const size = asset.kind === "gear" ? 30 : roundProfile ? 22 : 20;
const height = asset.kind === "gear" ? 6 : asset.kind === "text" ? 10 : asset.kind === "roundRoof" ? 10 : asset.kind === "halfSphere" ? 11 : flatProfile ? 5 : 20;
const width = asset.kind === "text" ? 86 : size;
const depth = asset.kind === "text" ? 28 : size;
@@ -92,6 +104,12 @@ export function makeShapeFromAsset(asset: ShapeAsset, point?: { x: number; z: nu
segments: asset.kind === "cylinder" ? 1 : undefined,
topRadius: asset.kind === "cone" ? 0 : undefined,
baseRadius: asset.kind === "cone" ? size / 2 : undefined,
teeth: asset.kind === "gear" ? DEFAULT_GEAR_TEETH : undefined,
toothSize: asset.kind === "gear" ? DEFAULT_GEAR_TOOTH_SIZE : undefined,
centerHoleSize: asset.kind === "gear" ? DEFAULT_GEAR_CENTER_HOLE_SIZE : undefined,
gearType: asset.kind === "gear" ? DEFAULT_GEAR_TYPE : undefined,
helixAngle: asset.kind === "gear" ? DEFAULT_GEAR_HELIX_ANGLE : undefined,
helixQuality: asset.kind === "gear" ? DEFAULT_GEAR_HELIX_QUALITY : undefined,
locked: false,
hidden: false,
};
+320
View File
@@ -0,0 +1,320 @@
import type { ManifoldToplevel } from "manifold-3d";
import type { SketchPoint, SketchProfile, SketchRevolveSettings, SketchSegment } from "@/types/sketchforge";
export const DEFAULT_SKETCH_REVOLVE_SETTINGS: SketchRevolveSettings = {
startAngle: 0,
sweepAngle: 360,
sides: 64,
quality: 6,
thickness: 1,
};
type OrderedStep = { segment: SketchSegment; from: SketchPoint; to: SketchPoint };
type OrderedPath = { steps: OrderedStep[]; closed: boolean };
type Point2 = [number, number];
type SampledPoint = { x: number; z: number };
export type SketchRevolveMesh = {
positions: number[];
width: number;
depth: number;
height: number;
triangleCount: number;
};
function clamp(value: number, min: number, max: number) {
return Math.min(max, Math.max(min, value));
}
function finiteOr(value: number | undefined, fallback: number) {
return typeof value === "number" && Number.isFinite(value) ? value : fallback;
}
export function normalizeSketchRevolveSettings(settings?: Partial<SketchRevolveSettings>): SketchRevolveSettings {
const rawSweep = clamp(finiteOr(settings?.sweepAngle, DEFAULT_SKETCH_REVOLVE_SETTINGS.sweepAngle), -360, 360);
const sweepAngle = Math.abs(rawSweep) < 1 ? (rawSweep < 0 ? -1 : 1) : rawSweep;
return {
startAngle: ((finiteOr(settings?.startAngle, DEFAULT_SKETCH_REVOLVE_SETTINGS.startAngle) % 360) + 360) % 360,
sweepAngle,
sides: Math.round(clamp(finiteOr(settings?.sides, DEFAULT_SKETCH_REVOLVE_SETTINGS.sides), 3, 128)),
quality: Math.round(clamp(finiteOr(settings?.quality, DEFAULT_SKETCH_REVOLVE_SETTINGS.quality), 1, 10)),
thickness: clamp(finiteOr(settings?.thickness, DEFAULT_SKETCH_REVOLVE_SETTINGS.thickness), 0.1, 20),
};
}
function orderedPaths(profile: SketchProfile): OrderedPath[] {
const pointById = new Map(profile.points.map((point) => [point.id, point]));
const adjacency = new Map<string, Array<{ pointId: string; segment: SketchSegment }>>();
profile.points.forEach((point) => adjacency.set(point.id, []));
const validSegments = profile.segments.filter((segment) => {
if (!pointById.has(segment.startId) || !pointById.has(segment.endId)) return false;
adjacency.get(segment.startId)?.push({ pointId: segment.endId, segment });
adjacency.get(segment.endId)?.push({ pointId: segment.startId, segment });
return true;
});
const unvisited = new Set(validSegments.map((segment) => segment.id));
const paths: OrderedPath[] = [];
while (unvisited.size > 0) {
const seed = validSegments.find((segment) => unvisited.has(segment.id));
if (!seed) break;
const componentIds = new Set<string>();
const queue = [seed.startId, seed.endId];
while (queue.length > 0) {
const id = queue.pop();
if (!id || componentIds.has(id)) continue;
componentIds.add(id);
adjacency.get(id)?.forEach((entry) => queue.push(entry.pointId));
}
const startId = [...componentIds].find((id) => (adjacency.get(id)?.filter((entry) => unvisited.has(entry.segment.id)).length ?? 0) === 1) ?? seed.startId;
const steps: OrderedStep[] = [];
let currentId = startId;
for (let guard = 0; guard <= validSegments.length; guard += 1) {
const edge = adjacency.get(currentId)?.find((entry) => unvisited.has(entry.segment.id));
if (!edge) break;
const from = pointById.get(currentId);
const to = pointById.get(edge.pointId);
if (!from || !to) break;
unvisited.delete(edge.segment.id);
steps.push({ segment: edge.segment, from, to });
currentId = to.id;
if (currentId === startId) break;
}
if (steps.length > 0) paths.push({ steps, closed: currentId === startId && steps.length >= 3 });
}
return paths;
}
function cubicPoint(start: SketchPoint, first: { x: number; z: number }, second: { x: number; z: number }, end: SketchPoint, amount: number) {
const inverse = 1 - amount;
return {
x: inverse ** 3 * start.x + 3 * inverse ** 2 * amount * first.x + 3 * inverse * amount ** 2 * second.x + amount ** 3 * end.x,
z: inverse ** 3 * start.z + 3 * inverse ** 2 * amount * first.z + 3 * inverse * amount ** 2 * second.z + amount ** 3 * end.z,
};
}
function samplePath(path: OrderedPath, quality: number) {
const first = path.steps[0]?.from;
if (!first) return [];
const sampled = [{ x: first.x, z: first.z }];
const curveSamples = 4 + quality * 6;
path.steps.forEach(({ segment, from, to }) => {
const forward = segment.startId === from.id;
const firstControl = forward ? from.handleOut : from.handleIn;
const secondControl = forward ? to.handleIn : to.handleOut;
if (segment.kind !== "line" && firstControl && secondControl) {
for (let index = 1; index <= curveSamples; index += 1) {
sampled.push(cubicPoint(from, firstControl, secondControl, to, index / curveSamples));
}
} else {
sampled.push({ x: to.x, z: to.z });
}
});
if (path.closed && sampled.length > 1) sampled.pop();
return sampled;
}
function compactSampledPath(points: SampledPoint[]) {
const compact: SampledPoint[] = [];
points.forEach((point) => {
const previous = compact[compact.length - 1];
if (!previous || Math.hypot(point.x - previous.x, point.z - previous.z) > 1e-7) compact.push(point);
});
if (compact.length > 2) {
const first = compact[0];
const last = compact[compact.length - 1];
if (Math.hypot(first.x - last.x, first.z - last.z) <= 1e-7) compact.pop();
}
return compact;
}
function axisIntersection(from: SampledPoint, to: SampledPoint): SampledPoint {
const deltaX = to.x - from.x;
const amount = Math.abs(deltaX) <= 1e-12 ? 0 : clamp(-from.x / deltaX, 0, 1);
return { x: 0, z: from.z + (to.z - from.z) * amount };
}
function clipClosedPathToRevolveSide(points: SampledPoint[]) {
if (points.length < 3) return [];
const clipped: SampledPoint[] = [];
for (let index = 0; index < points.length; index += 1) {
const from = points[index];
const to = points[(index + 1) % points.length];
const fromInside = from.x <= 0;
const toInside = to.x <= 0;
if (fromInside && toInside) {
clipped.push(to);
} else if (fromInside) {
clipped.push(axisIntersection(from, to));
} else if (toInside) {
clipped.push(axisIntersection(from, to), to);
}
}
return compactSampledPath(clipped);
}
function clipOpenPathToRevolveSide(points: SampledPoint[]) {
const paths: SampledPoint[][] = [];
let current: SampledPoint[] = [];
const finishCurrent = () => {
const compact = compactSampledPath(current);
if (compact.length >= 2) paths.push(compact);
current = [];
};
for (let index = 0; index < points.length - 1; index += 1) {
const from = points[index];
const to = points[index + 1];
const fromInside = from.x <= 0;
const toInside = to.x <= 0;
if (fromInside && toInside) {
if (current.length === 0) current.push(from);
current.push(to);
} else if (fromInside) {
if (current.length === 0) current.push(from);
current.push(axisIntersection(from, to));
finishCurrent();
} else if (toInside) {
current = [axisIntersection(from, to), to];
}
}
finishCurrent();
return paths;
}
function distance(a: Point2, b: Point2) {
return Math.hypot(b[0] - a[0], b[1] - a[1]);
}
function compactPolygon(points: Point2[]) {
const compact: Point2[] = [];
points.forEach((point) => {
if (!compact.length || distance(compact[compact.length - 1], point) > 1e-7) compact.push(point);
});
if (compact.length > 2 && distance(compact[0], compact[compact.length - 1]) <= 1e-7) compact.pop();
return compact;
}
function strokeOpenPath(points: Point2[], thickness: number) {
if (points.length < 2) return [];
const half = thickness / 2;
const normals: Point2[] = [];
for (let index = 0; index < points.length - 1; index += 1) {
const dx = points[index + 1][0] - points[index][0];
const dy = points[index + 1][1] - points[index][1];
const length = Math.hypot(dx, dy);
normals.push(length > 1e-8 ? [-dy / length, dx / length] : [0, 0]);
}
const offsetAt = (index: number): Point2 => {
const previous = normals[Math.max(0, index - 1)];
const next = normals[Math.min(normals.length - 1, index)];
const sumX = previous[0] + next[0];
const sumY = previous[1] + next[1];
const sumLength = Math.hypot(sumX, sumY);
if (sumLength <= 1e-8) return [next[0] * half, next[1] * half];
const unit: Point2 = [sumX / sumLength, sumY / sumLength];
const projection = Math.abs(unit[0] * next[0] + unit[1] * next[1]);
const miter = Math.min(half * 4, half / Math.max(0.25, projection));
return [unit[0] * miter, unit[1] * miter];
};
const left: Point2[] = [];
const right: Point2[] = [];
points.forEach((point, index) => {
const offset = offsetAt(index);
left.push([point[0] + offset[0], point[1] + offset[1]]);
right.push([point[0] - offset[0], point[1] - offset[1]]);
});
return compactPolygon([...left, ...right.reverse()]);
}
export function sketchProfileToRevolvePolygons(profile: SketchProfile, settings?: Partial<SketchRevolveSettings>) {
const normalized = normalizeSketchRevolveSettings(settings);
const paths = orderedPaths(profile).flatMap((path) => {
const sampled = samplePath(path, normalized.quality);
if (path.closed) {
const clipped = clipClosedPathToRevolveSide(sampled);
return clipped.length >= 3 ? [{ closed: true, points: clipped }] : [];
}
return clipOpenPathToRevolveSide(sampled).map((points) => ({ closed: false, points }));
});
if (paths.length === 0) return [];
const maxZ = Math.max(...paths.flatMap((entry) => entry.points.map((point) => point.z)));
const toSectionPoint = (point: SampledPoint): Point2 => [-point.x, maxZ - point.z];
return paths.flatMap(({ closed, points }) => {
const sectionPoints = compactPolygon(points.map(toSectionPoint));
const polygon = closed ? sectionPoints : strokeOpenPath(sectionPoints, normalized.thickness).map((point) => [Math.max(0, point[0]), point[1]] as Point2);
return polygon.length >= 3 ? [compactPolygon(polygon)] : [];
});
}
function manifoldMeshPositions(mesh: InstanceType<ManifoldToplevel["Mesh"]>) {
const positions: number[] = [];
for (let index = 0; index < mesh.triVerts.length; index += 1) {
const offset = mesh.triVerts[index] * mesh.numProp;
positions.push(mesh.vertProperties[offset], mesh.vertProperties[offset + 1], mesh.vertProperties[offset + 2]);
}
return positions;
}
function dispose(value: unknown) {
(value as { delete?: () => void } | null)?.delete?.();
}
export function buildSketchRevolveMesh(runtime: ManifoldToplevel, profile: SketchProfile, requestedSettings?: Partial<SketchRevolveSettings>): SketchRevolveMesh {
const settings = normalizeSketchRevolveSettings(requestedSettings);
const polygons = sketchProfileToRevolvePolygons(profile, settings);
if (polygons.length === 0) throw new Error("Draw at least one connected profile on the left side of the revolve axis");
const disposable: unknown[] = [];
try {
const section = new runtime.CrossSection(polygons, "EvenOdd");
disposable.push(section);
const scale = polygons.reduce((largest, polygon) => polygon.reduce((current, point) => Math.max(current, Math.abs(point[0]), Math.abs(point[1])), largest), 1);
const simplified = section.simplify(Math.max(1e-7, scale * 1e-8));
disposable.push(simplified);
if (simplified.toPolygons().length === 0) throw new Error("The revolve profile has no filled area");
const sweep = Math.abs(settings.sweepAngle);
const solid = simplified.revolve(settings.sides, sweep);
disposable.push(solid);
const rotation = settings.sweepAngle < 0 ? settings.startAngle + settings.sweepAngle : settings.startAngle;
const revolved = Math.abs(rotation) > 1e-8 ? solid.rotate([0, 0, rotation]) : solid;
if (revolved !== solid) disposable.push(revolved);
if (revolved.status() !== "NoError" || revolved.numTri() < 1) throw new Error("The profile could not be revolved into a valid solid");
const manifoldPositions = manifoldMeshPositions(revolved.getMesh());
const positions = new Array<number>(manifoldPositions.length);
let minX = Number.POSITIVE_INFINITY;
let minY = Number.POSITIVE_INFINITY;
let minZ = Number.POSITIVE_INFINITY;
let maxX = Number.NEGATIVE_INFINITY;
let maxY = Number.NEGATIVE_INFINITY;
let maxZ = Number.NEGATIVE_INFINITY;
for (let index = 0; index + 2 < manifoldPositions.length; index += 3) {
const x = manifoldPositions[index];
const y = manifoldPositions[index + 2];
const z = -manifoldPositions[index + 1];
positions[index] = x;
positions[index + 1] = y;
positions[index + 2] = z;
minX = Math.min(minX, x);
minY = Math.min(minY, y);
minZ = Math.min(minZ, z);
maxX = Math.max(maxX, x);
maxY = Math.max(maxY, y);
maxZ = Math.max(maxZ, z);
}
const centerX = (minX + maxX) / 2;
const centerZ = (minZ + maxZ) / 2;
for (let index = 0; index + 2 < positions.length; index += 3) {
positions[index] -= centerX;
positions[index + 1] -= minY;
positions[index + 2] -= centerZ;
}
return {
positions,
width: Math.max(0.01, maxX - minX),
depth: Math.max(0.01, maxZ - minZ),
height: Math.max(0.01, maxY - minY),
triangleCount: Math.floor(positions.length / 9),
};
} finally {
[...new Set(disposable)].reverse().forEach(dispose);
}
}
+55 -10
View File
@@ -5,12 +5,12 @@ import { canonicalizeShape } from "@/lib/workplaneShapes";
import { importedShapeFromStl } from "@/lib/stlImport";
import { importedShapeFromSvg } from "@/lib/svgImport";
import { normalizeSnapGrid, normalizeWorkspaceSettings } from "@/lib/workplaneSettings";
import type { GridSize, ProjectAsset, ProjectAssetSourceFormat, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
import type { GridSize, ProjectAsset, ProjectAssetSourceFormat, SketchOperation, SketchRevolveSettings, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
export const SKF_SCHEMA_ID = "com.sketchforge.project";
export const SKF_FORMAT_VERSION = 1;
export const SKF_MINIMUM_READER_VERSION = 1;
export const SKF_CREATED_WITH_VERSION = "0.6.0";
export const SKF_CREATED_WITH_VERSION = "0.7.0";
export const SKF_MEDIA_TYPE = "application/vnd.sketchforge.project+zip";
export const SKF_LIMITS = {
@@ -27,11 +27,11 @@ export const SKF_LIMITS = {
const SHAPE_KINDS = new Set([
"box", "cylinder", "sphere", "sketch", "scribble", "cone", "pyramid", "roof", "text", "roundRoof",
"halfSphere", "torus", "tube", "ring", "wedge", "polygon", "icosahedron", "mesh",
"halfSphere", "torus", "tube", "gear", "ring", "wedge", "polygon", "icosahedron", "mesh",
]);
const FEATURE_TYPES = new Set([
"group", "boolean-subtraction", "boolean-intersection", "mirror", "sketch-extrusion", "fillet", "chamfer",
"group", "boolean-subtraction", "boolean-intersection", "mirror", "sketch-extrusion", "sketch-revolve", "fillet", "chamfer",
]);
type SkfAssetKind = "source" | "derived-mesh" | "brep" | "image";
@@ -110,7 +110,7 @@ export type SkfProjectDocumentV1 = {
entries: Array<{ stateId: string; selectedObjectIds: string[] }>;
index: number;
};
sketches: Array<{ id: string; nodeId: string; objectId: string; extrusionDepth: number }>;
sketches: Array<{ id: string; nodeId: string; objectId: string; operation?: SketchOperation; extrusionDepth: number; revolve?: SketchRevolveSettings }>;
features: SkfFeatureV1[];
groups: Array<{ id: string; nodeId: string; objectId: string; memberNodeIds: string[]; operation: string }>;
workplanes: Array<{ id: string; kind: "base" | "offset"; elevation: number }>;
@@ -451,6 +451,8 @@ async function serializeShapeNode(
const objectType = groupedShapeNodeIds.length
? "group"
: sketchProfile
? "sketch"
: importedReference
? "imported"
: shape.kind === "sketch"
@@ -511,17 +513,28 @@ function activeProjectIndexes(state: SkfStateV1) {
if (!node) return;
(node.groupedShapeNodeIds ?? []).forEach(visit);
let previous: string | undefined;
if (node.definition.sketchProfile && node.definition.kind === "sketch") {
const featureId = `feature/${safeNodeToken(node.nodeId)}/sketch-extrusion`;
if (node.definition.sketchProfile) {
const operation = node.definition.sketchOperation === "revolve" ? "revolve" : "extrude";
const featureType = operation === "revolve" ? "sketch-revolve" : "sketch-extrusion";
const featureId = `feature/${safeNodeToken(node.nodeId)}/${featureType}`;
features.push({
id: featureId,
type: "sketch-extrusion",
type: featureType,
outputObjectId: node.objectId,
inputObjectIds: [],
dependsOnFeatureIds: [],
parameters: { depth: node.definition.height, direction: "positive-y", mode: "create" },
parameters: operation === "revolve"
? { ...(node.definition.sketchRevolve as Record<string, unknown> | undefined), axis: "vertical-sketch-axis", mode: "create" }
: { depth: node.definition.height, direction: "positive-y", mode: "create" },
});
sketches.push({
id: `sketch/${safeNodeToken(node.objectId)}`,
nodeId: node.nodeId,
objectId: node.objectId,
operation,
extrusionDepth: operation === "extrude" ? Number(node.definition.height) : 0,
...(operation === "revolve" && node.definition.sketchRevolve ? { revolve: node.definition.sketchRevolve as SketchRevolveSettings } : {}),
});
sketches.push({ id: `sketch/${safeNodeToken(node.objectId)}`, nodeId: node.nodeId, objectId: node.objectId, extrusionDepth: Number(node.definition.height) });
previous = featureId;
}
if (node.groupedShapeNodeIds?.length) {
@@ -776,6 +789,38 @@ function validateShapeDefinition(definition: Record<string, unknown>, label: str
throw new Error(`${label} contains inline package-only geometry fields`);
}
if (definition.sketchProfile) validateSketchProfile(definition.sketchProfile, `${label}.sketchProfile`);
if (definition.sketchOperation !== undefined && definition.sketchOperation !== "extrude" && definition.sketchOperation !== "revolve") {
throw new Error(`${label}.sketchOperation is invalid`);
}
if (definition.sketchRevolve !== undefined) {
const settings = objectRecord(definition.sketchRevolve, `${label}.sketchRevolve`);
["startAngle", "sweepAngle", "sides", "quality", "thickness"].forEach((field) => finiteNumber(settings[field], `${label}.sketchRevolve.${field}`));
}
if (kind === "gear") {
const teeth = finiteNumber(definition.teeth, `${label}.teeth`);
if (!Number.isInteger(teeth) || teeth < 6 || teeth > 64) throw new Error(`${label}.teeth is outside the supported range`);
const toothSize = finiteNumber(definition.toothSize, `${label}.toothSize`);
if (toothSize <= 0) throw new Error(`${label}.toothSize must be positive`);
if (definition.toothWidth !== undefined) {
const toothWidth = finiteNumber(definition.toothWidth, `${label}.toothWidth`);
if (toothWidth <= 0) throw new Error(`${label}.toothWidth must be positive`);
}
if (definition.centerHoleSize !== undefined) {
const centerHoleSize = finiteNumber(definition.centerHoleSize, `${label}.centerHoleSize`);
if (centerHoleSize < 0) throw new Error(`${label}.centerHoleSize cannot be negative`);
}
if (!["spur", "helical", "bevel"].includes(definition.gearType as string)) throw new Error(`${label}.gearType is invalid`);
if (definition.helixAngle !== undefined) {
const helixAngle = finiteNumber(definition.helixAngle, `${label}.helixAngle`);
if (helixAngle < -45 || helixAngle > 45) throw new Error(`${label}.helixAngle is outside the supported range`);
}
if (definition.helixQuality !== undefined) {
const helixQuality = finiteNumber(definition.helixQuality, `${label}.helixQuality`);
if (!Number.isInteger(helixQuality) || helixQuality < 4 || helixQuality > 32) {
throw new Error(`${label}.helixQuality is outside the supported range`);
}
}
}
return id;
}
+1
View File
@@ -1,6 +1,7 @@
const WORKPLANE_BOUNDARY_EPSILON = 0.0001;
export const WORKPLANE_LINE_ELEVATION = 0;
export const WORKPLANE_MAJOR_GRID_INTERVAL = 5;
export type WorkplaneGridCoordinate = {
coordinate: number;
+11
View File
@@ -114,10 +114,12 @@ export function proportionalResizeScale(startWidth: number, startDepth: number,
}
export function fallbackSolidColor(shape: WorkplaneShape) {
if (shape.sketchOperation === "revolve") return "#78b96b";
if (shape.kind === "cylinder") return "#d97813";
if (shape.kind === "sphere") return "#0098c7";
if (shape.kind === "cone") return "#6e2786";
if (shape.kind === "pyramid") return "#f2cf10";
if (shape.kind === "gear") return "#6f7f8d";
return "#d41721";
}
@@ -188,11 +190,20 @@ export function workplaneShapesEqual(a: WorkplaneShape, b: WorkplaneShape) {
a.segments === b.segments &&
a.topRadius === b.topRadius &&
a.baseRadius === b.baseRadius &&
a.teeth === b.teeth &&
a.toothSize === b.toothSize &&
a.toothWidth === b.toothWidth &&
a.centerHoleSize === b.centerHoleSize &&
a.gearType === b.gearType &&
a.helixAngle === b.helixAngle &&
a.helixQuality === b.helixQuality &&
a.text === b.text &&
a.font === b.font &&
a.importedMesh === b.importedMesh &&
a.imagePlate === b.imagePlate &&
a.sketchProfile === b.sketchProfile &&
a.sketchOperation === b.sketchOperation &&
a.sketchRevolve === b.sketchRevolve &&
a.edgeTreatments === b.edgeTreatments &&
a.edgeTreatmentHistory === b.edgeTreatmentHistory &&
a.cadDisplayEdges === b.cadDisplayEdges &&