From bce1ce567ac1fa98ac203fea71dcedd08378ca8e Mon Sep 17 00:00:00 2001 From: superGeometry Date: Sun, 8 Nov 2026 13:31:40 +0200 Subject: [PATCH] Sketch: Align moves only the first thing picked onto the second's axis - the target and everything else hold still when the constraints are solved again (only the ones the move breaks go); a line already selected is the one that moves, and a selected shape (or a rectangle's side) moves as a whole, turned the short way. Rotate About says what it does: "a point you tap", a Turn around field, and a dotted arc showing the path the selection's centre takes round that point. A linear pattern (sketch or bodies) starts with its first copy just clear of the original: its size along the pattern plus a fifth Co-Authored-By: Claude Opus 5.5 --- src/geom.ts | 9 ++++ src/sketch/edit.ts | 56 +++++++++++++++++++- src/tools/ops.ts | 27 ++++++++-- src/tools/select.ts | 3 +- src/tools/sketch.ts | 105 +++++++++++++++++++++++++++++++------- src/ui/help.ts | 2 +- tests/alignmove.test.ts | 77 ++++++++++++++++++++++++++++ tests/offsetspike.test.ts | 9 ++++ 8 files changed, 263 insertions(+), 25 deletions(-) create mode 100644 tests/alignmove.test.ts diff --git a/src/geom.ts b/src/geom.ts index 5775190..560581a 100644 --- a/src/geom.ts +++ b/src/geom.ts @@ -66,6 +66,15 @@ export function roundSig(v: number, sig = 2): number { return Math.round(v / p) * p; } +/** + * A linear pattern's spacing to start with: the copy clear of the original + * (its size along the pattern plus a fifth), not a fixed 10 / 20 that piled + * copies on top of a big part. `fallback` when there's no size to go by. + */ +export function patternSpacing(extent: number, fallback = 10): number { + return extent > 1e-9 ? roundSig(extent * 1.2) : fallback; +} + export function niceStep(raw: number): number { const p = Math.pow(10, Math.floor(Math.log10(raw))); const m = raw / p; diff --git a/src/sketch/edit.ts b/src/sketch/edit.ts index 8c508dc..dd6c8c0 100644 --- a/src/sketch/edit.ts +++ b/src/sketch/edit.ts @@ -3,7 +3,7 @@ import type { PlaneDef, SketchConstraint, SketchEntity, Vec2, Vec3 } from "../doc/types"; import { roundSig, toPlane } from "../geom"; -import { constraintError, pointOf, pointsOf, refsOf } from "./constraints"; +import { constraintError, pointOf, pointsOf, refsOf, solve } from "./constraints"; import { arcFrom3, closestOnPrim, entityCorners, entityPrims, evalPrim, isClosedPrim, primSegments, samplePrim, type Prim } from "./curves"; export function uid(): string { @@ -1279,6 +1279,60 @@ export function alignLine(entities: SketchEntity[], id: string, target: SketchEn return entities.map((e) => (e.id === id ? { ...ln, a: ends.a, b: ends.b } : moved.get(e.id) ?? e)); } +/** + * Align, as the tool does it: line `id` moves onto `target`'s axis (lines + * joined to it slide along), and only it - the target and the rest stay put + * when the sketch's constraints are solved again. Constraints the move breaks + * (an old angle, a size) go; joins stay. + */ +export function alignOne(entities: SketchEntity[], constraints: SketchConstraint[], id: string, target: LineE): { entities: SketchEntity[]; constraints: SketchConstraint[] } | null { + const next = alignLine(entities, id, target); + if (!next) return null; + return settleMoved(next, constraints, new Set(next.filter((x, i) => x !== entities[i]).map((x) => x.id)), target.id); +} + +/** + * Align a whole shape: turned (the short way) and slid so its `edge` lies on + * `target`'s axis; it moves as one, nothing else does. + */ +export function alignShape(entities: SketchEntity[], constraints: SketchConstraint[], shape: Set, edge: LineE, target: LineE): { entities: SketchEntity[]; constraints: SketchConstraint[] } | null { + const de: Vec2 = [edge.b[0] - edge.a[0], edge.b[1] - edge.a[1]]; + const dt: Vec2 = [target.b[0] - target.a[0], target.b[1] - target.a[1]]; + const le = Math.hypot(...de); + const lt = Math.hypot(...dt); + if (le < 1e-12 || lt < 1e-12 || shape.has(target.id)) return null; + let ang = Math.atan2(dt[1], dt[0]) - Math.atan2(de[1], de[0]); + // The short way round: a line has no direction. + while (ang > Math.PI / 2) ang -= Math.PI; + while (ang <= -Math.PI / 2) ang += Math.PI; + const mid: Vec2 = [(edge.a[0] + edge.b[0]) / 2, (edge.a[1] + edge.b[1]) / 2]; + const turn = rotateXf(mid, ang); + const on = projectOnLine(mid, target.a, target.b); + const xf: Xf = (p) => { + const q = turn(p); + return [q[0] + on[0] - mid[0], q[1] + on[1] - mid[1]]; + }; + const next = entities.map((e) => (shape.has(e.id) ? transformEntity(e, xf) : e)); + return settleMoved(next, constraints, shape, target.id); +} + +/** + * After an align: keep the constraints still met (and joins, which the solve + * restores), drop the rest, and solve with the target held still. + */ +function settleMoved(next: SketchEntity[], constraints: SketchConstraint[], moved: Set, target: string): { entities: SketchEntity[]; constraints: SketchConstraint[] } { + let size = 1; + for (const e of next) for (const q of pointsOf(e)) size = Math.max(size, Math.abs(q.at[0]), Math.abs(q.at[1])); + // What the move broke (a join to something that stayed, an old angle) would + // pull it back: only the constraints still met stay. + const kept = constraints.filter((c) => !refsOf(c).some((r) => moved.has(r)) || constraintError(next, [c]) < size * 1e-7); + const r = solve(next, kept, { fixed: new Set([target]) }); + if (r.ok) return { entities: r.entities, constraints: kept }; + // Couldn't settle: the constraints on what moved go (it stays where it was put). + const rest = kept.filter((c) => !refsOf(c).some((x) => moved.has(x))); + return { entities: next, constraints: rest }; +} + /** * Join: line `id` and a line on the same axis that shares one of its ends * become a single line. Returns the new entities and the id that was merged away. diff --git a/src/tools/ops.ts b/src/tools/ops.ts index 2f216b2..826d0bb 100644 --- a/src/tools/ops.ts +++ b/src/tools/ops.ts @@ -4,7 +4,7 @@ import type { ThreadFeature } from "../doc/types"; import { defaultPitch, threadLabel } from "../kernel/threads"; import type { AxisFeature, AxisRef, EdgeFeature, EdgeRef, ExtrudeFeature, ExtrudeSource, FaceRef, FillToPlaneFeature, ImageFeature, LoftFeature, MoveFaceFeature, PathRef, PlaneDef, PlaneFeature, ReplaceFaceFeature, RevolveFeature, ScaleFaceFeature, ShellFeature, SketchFeature, SplitFeature, SweepFeature, TransformFeature, Vec3 } from "../doc/types"; -import { FRONT, GROUND, RIGHT, add, cross, dot, len, norm, niceStep, scale, sub, xDirFor } from "../geom"; +import { FRONT, GROUND, RIGHT, add, cross, dot, len, norm, niceStep, patternSpacing, scale, sub, xDirFor } from "../geom"; import type { PanelItem } from "../ui/ui"; import { evaluate, fmtLen } from "../units"; import type { ToolPointer } from "../view/input"; @@ -847,7 +847,7 @@ export class TransformOp extends FeatureOp { : kind === "mirror" ? { kind: "mirror", plane: { origin: [0, 0, 0], xDir: [0, 1, 0], normal: [1, 0, 0] } } : kind === "linear" - ? { kind: "linear", dir: [1, 0, 0], spacing: 20, count: 3 } + ? { kind: "linear", dir: [1, 0, 0], spacing: patternSpacing(bodyExtent(app, bodies, [1, 0, 0]), 20), count: 3 } : kind === "circular" ? { kind: "circular", axis: { origin: [0, 0, 0], dir: [0, 0, 1] }, count: 6, angle: 360 } : { kind: "move", translate: [0, 0, 0], rotate: { origin: center, axis: [0, 0, 1], angle: 0 } }; @@ -936,7 +936,12 @@ export class TransformOp extends FeatureOp { private applyDir(): void { const o = this.feature.op; - if (o.kind === "linear" && this.dir) o.dir = this.dir; + if (o.kind === "linear" && this.dir) { + // A new pattern's spacing (not typed yet) follows the direction: the copies just clear of the bodies. + const was = patternSpacing(bodyExtent(this.app, this.feature.bodies, o.dir), 20); + if (!this.existing && Math.abs(o.spacing - was) < 1e-9) o.spacing = patternSpacing(bodyExtent(this.app, this.feature.bodies, this.dir), 20); + o.dir = this.dir; + } if (this.kind === "translate" && o.kind === "move" && this.dir) o.translate = scale(this.dir, this.distance); } @@ -1627,6 +1632,22 @@ function axisName(a?: Vec3): string { return ["X", "Y", "Z"][a ? Math.max(0, axisIndex(a)) : 2]; } +/** How far the bodies reach along a direction (their size that way). */ +export function bodyExtent(app: AppContext, bodies: string[], dir: Vec3): number { + let lo = Infinity; + let hi = -Infinity; + for (const id of bodies) { + const p = app.view.body(id)?.positions; + if (!p) continue; + for (let i = 0; i < p.length; i += 3) { + const t = p[i] * dir[0] + p[i + 1] * dir[1] + p[i + 2] * dir[2]; + if (t < lo) lo = t; + if (t > hi) hi = t; + } + } + return hi > lo ? hi - lo : 0; +} + export function bodyCenter(app: AppContext, bodies: string[]): Vec3 { const pts = bodies.flatMap((id) => app.view.body(id)?.faces.map((f) => f.center) ?? []); if (!pts.length) return [0, 0, 0]; diff --git a/src/tools/select.ts b/src/tools/select.ts index 3676d84..996625a 100644 --- a/src/tools/select.ts +++ b/src/tools/select.ts @@ -438,7 +438,8 @@ export class SelectTool implements Tool { { id: "axis", label: "Axis – Perp. to Face", icon: "axis", run: () => frame && app.setTool(new AxisOp(app, frame.base, frame.normal)) }, { id: "plane", label: "Plane – Offset", icon: "plane", run: () => plane && app.setTool(new PlaneOp(app, plane, undefined)) }, { id: "text", label: "Text", icon: "text", run: inSketch("text") }, - { id: "rotate", label: "Rotate Around Axis", icon: "rotateAxis", run: inSketch("rotate") }, + // In the sketch: the shape turns about a point you tap (not a 3D axis). + { id: "rotate", label: "Rotate About", icon: "rotateAxis", sub: "a point you tap", run: inSketch("rotate") }, { id: "mirror", label: "Mirror", icon: "mirror", run: inSketch("mirror") }, { id: "loft", label: "Loft", icon: "loft", run: () => app.setTool(new LoftOp(app, sourcesOf(app, sel).flatMap(splitRegions), sel)) }, { id: "split", label: "Split Body", icon: "split", disabled: !app.view.bodyList.length || !plane, why: "Needs a body", run: () => this.splitWith(plane!) }, diff --git a/src/tools/sketch.ts b/src/tools/sketch.ts index 034be87..3f2680e 100644 --- a/src/tools/sketch.ts +++ b/src/tools/sketch.ts @@ -2,7 +2,7 @@ import { isTouchDevice } from "../device"; import { simplifyStroke } from "../sketch/freehand"; import { BufferGeometry, Line, LineBasicMaterial, LineDashedMaterial, Points, PointsMaterial, Vector3 } from "three"; import type { FaceRef, PlaneDef, PointRef, SketchConstraint, SketchEntity, SketchFeature, Vec2, Vec3 } from "../doc/types"; -import { add as add3, dot, GROUND, niceStep as niceStepOf, originOnPlane, planeY, roundSig, scale as scale3, sub as sub3, toPlane } from "../geom"; +import { add as add3, dot, GROUND, niceStep as niceStepOf, originOnPlane, patternSpacing, planeY, roundSig, scale as scale3, sub as sub3, toPlane } from "../geom"; import { addForUser, addStrict, constraintError, constraintName, pointOf, pointsOf, refsOf, setValueStrict, sizeOf as sizeOfFn, solve } from "../sketch/constraints"; import { isExpression } from "../ui/ui"; import { nearestSnap } from "../sketch/snapPick"; @@ -17,7 +17,8 @@ import { connectedChain, angleLines, explode, - alignLine, + alignOne, + alignShape, endNear, joinCollinear, extend, @@ -100,7 +101,7 @@ const HINTS: Record = { scale: "Tap curves to select, then set the factor and Apply.", patternLinear: "Tap curves to select, then set count and spacing.", patternCircular: "Tap curves to select (double-tap for a whole shape), then tap the centre to turn them around.", - rotate: "Tap curves to select, set the pivot and angle.", + rotate: "Tap curves to select (double-tap: a whole shape), then tap the point to turn them around - an end, a midpoint or another shape's centre. The whole selection turns about that point, rigidly, by the angle: its own centre swings round it.", mirror: "Tap a shape to select it (Shift+tap: single curves), then tap the line to mirror it across - any line, even one of its own edges.", trim: "Tap the part of a curve to cut away (between crossings), or swipe across several. Join mode: tap a line to merge it with the line on the same axis it touches.", align: "Tap the line to move, then the line it should line up with (the first one moves onto the second one's axis).", @@ -873,7 +874,7 @@ export class SketchTool implements Tool { t("move", "Move/Rotate", "move", "M"), // Turned about a point tapped (a tie rod a quarter way round the axis // centre): the code had it, the menu didn't. - t("rotate", "Rotate About", "rotateAxis"), + t("rotate", "Rotate About", "rotateAxis", undefined, { sub: "a point you tap" }), t("scale", "Scale", "scale", "S"), { ...t(memory.pattern, "Pattern", memory.pattern), @@ -958,19 +959,29 @@ export class SketchTool implements Tool { // Move starts from nothing (it shared ΔX with the linear pattern's spacing: // an ellipse only meant to be turned 20° also moved 10 across). if (kind === "move") ((this.edit.dx = 0), (this.edit.dy = 0), (this.edit.moveRot = 0)); - if (kind === "patternLinear" && Math.hypot(this.edit.dx, this.edit.dy) < 1e-12) this.edit.dx = 10; + // A linear pattern starts with its first copy just clear of the selection. + if (kind === "patternLinear") this.autoPatternSpacing(); this.finishFillet(); this.clearPreviewJoin(); this.edit.mirrorLine = undefined; // Editing tools keep the selection; drawing tools start clean. - if (!["move", "scale", "patternLinear", "patternCircular", "rotate", "mirror", "select", "delete"].includes(kind)) this.selected.clear(); + if (!["move", "scale", "patternLinear", "patternCircular", "rotate", "mirror", "select", "delete", "align"].includes(kind)) this.selected.clear(); + // Align with a line already selected: that's the one that moves - next, what to align it with. + // (A whole shape selected: tap its edge to align, then the line.) + let alignHint: string | undefined; + if (kind === "align" && this.selected.size === 1 && this.entities.find((e) => e.id === [...this.selected][0])?.kind === "line") { + this.edit.alignFrom = [...this.selected][0]; + this.selected.clear(); + alignHint = "Now tap the line to align it with (it moves onto that line's axis)."; + } else if (kind === "align" && this.selected.size > 1) alignHint = "Tap the edge of the selected shape to line up, then the line to align it with (the whole shape moves)."; this.clearOverlays(); this.hideLineDim(); this.refreshDistanceDim(); this.showSelection(); this.updateMenu(); this.updatePanel(); - this.setHint(); + this.setHint(alignHint); + if (kind === "align" && this.edit.alignFrom) this.app.setSelection([{ kind: "curve", sketch: this.sketchId ?? "", entity: this.edit.alignFrom }]); } private setHint(extra?: string): void { @@ -1165,7 +1176,7 @@ export class SketchTool implements Tool { case "patternCircular": case "rotate": items.push( - { type: "slot", label: "Center", value: this.edit.pivot ? `${trimNum(this.edit.pivot[0])}, ${trimNum(this.edit.pivot[1])}` : k === "patternCircular" ? "Tap the centre" : "Origin (tap to set)", active: this.edit.picking === "pivot", filled: !!this.edit.pivot, onClick: () => ((this.edit.picking = "pivot"), this.updatePanel()) }, + { type: "slot", label: k === "rotate" ? "Turn around" : "Center", value: this.edit.pivot ? `${trimNum(this.edit.pivot[0])}, ${trimNum(this.edit.pivot[1])}` : k === "patternCircular" ? "Tap the centre" : "Tap a point", active: this.edit.picking === "pivot", filled: !!this.edit.pivot, onClick: () => ((this.edit.picking = "pivot"), this.updatePanel()) }, ...(k === "patternCircular" ? [{ type: "number", label: "Count", value: this.edit.count, kind: "int", min: 2, onInput: (v: number) => ((this.edit.count = v), this.refreshPreview()) } as PanelItem] : []), k === "patternCircular" ? { type: "number", label: "Angle", value: this.edit.patAngle, kind: "angle", onInput: (v) => ((this.edit.patAngle = v), this.refreshPreview()) } @@ -2004,7 +2015,7 @@ export class SketchTool implements Tool { if (memory.trim === "join") return this.tapCurve(p, (id, uv) => this.tapJoin(id, uv)); return this.tapCurve(p, (id, uv) => this.commitEdit(this.trimHere(this.entities, id, uv))); case "align": - return this.tapCurve(p, (id) => this.tapAlign(id)); + return this.tapCurve(p, (id, uv) => this.tapAlign(id, uv)); case "extend": return this.tapCurve(p, (id, uv) => this.tapExtend(id, uv)); case "split": @@ -3057,6 +3068,23 @@ export class SketchTool implements Tool { } if (this.kind === "offset" && this.edit.offsetOf) ghosts.push(...this.offsetResult()); if (this.isSelectionTool() && this.selected.size) ghosts.push(...this.transformed(true)); + // Rotate About: the point it turns around, and the path the selection's centre takes round it. + if ((this.kind === "rotate" || this.kind === "patternCircular") && this.edit.pivot && this.selected.size) { + const pv = this.edit.pivot; + this.drawCentreMark(pv); + const c = centroidOf(this.entities.filter((e) => this.selected.has(e.id))); + const r = Math.hypot(c[0] - pv[0], c[1] - pv[1]); + const sweep = ((this.kind === "rotate" ? this.edit.angle : this.edit.patAngle) * Math.PI) / 180; + if (r > 1e-9 && Math.abs(sweep) > 1e-9) { + const a0 = Math.atan2(c[1] - pv[1], c[0] - pv[0]); + const at = (t: number): Vec2 => [pv[0] + r * Math.cos(a0 + sweep * t), pv[1] + r * Math.sin(a0 + sweep * t)]; + const n = Math.max(8, Math.ceil(Math.abs(sweep) / 0.1)); + this.drawGhosts([ + { id: "rot-radius", kind: "line", a: pv, b: c }, + { id: "rot-path", kind: "polyline", points: Array.from({ length: n + 1 }, (_, i) => at(i / n)), closed: false }, + ], 0x9fb4d6, true); + } + } this.drawGhosts(ghosts); // Mirror: the axis (picked, or the line under the pointer) with a mirror mark on it. if (this.kind === "mirror" && this.selected.size) { @@ -3358,26 +3386,40 @@ export class SketchTool implements Tool { * Extend in two taps: the half of the first curve, then the half of the * second - both picked ends run along their own line/circle until they meet. */ - private tapAlign(id: string): void { + /** Align's first pick, as a line: the line, or the side of a shape that was tapped. */ + private alignEdge: Extract | null = null; + + private tapAlign(id: string, uv: Vec2): void { const all = [...this.entities, ...this.boundary]; const e = all.find((x) => x.id === id); - if (e?.kind !== "line") return this.app.ui.toast("Align works on lines"); + // A line, or the side of a rectangle / polygon / outline that was tapped. + const side = sideNear(e, uv); + if (!side) return this.app.ui.toast("Align works on lines and the sides of shapes"); const first = this.edit.alignFrom; if (!first) { if (id.startsWith("bnd-")) return this.app.ui.toast("Pick a line of this sketch to move (face edges stay)"); this.edit.alignFrom = id; + this.alignEdge = side; + // A shape (not a lone line): it moves as a whole - with the rest of the selection it's part of. + if (e?.kind !== "line") this.selected.add(id); + else if (!this.selected.has(id)) this.selected.clear(); + this.showSelection(); this.app.setSelection([{ kind: "curve", sketch: this.sketchId ?? "", entity: id }]); - return this.setHint("Now tap the line it should line up with."); + return this.setHint("Now tap the line to align it with (the first one moves)."); } + const edge = this.alignEdge ?? (all.find((x) => x.id === first) as Extract | undefined); this.edit.alignFrom = undefined; + this.alignEdge = null; this.app.setSelection([]); this.setHint(); - if (first === id) return; - const next = alignLine(this.entities, first, e); - if (!next) return this.app.ui.toast("Those lines can't be aligned"); - // Constraints that held the old position would pull it back: keep the rest. - const moved = new Set(next.filter((x, i) => x !== this.entities[i]).map((x) => x.id)); - this.commit(next, this.constraints.filter((c) => c.type === "coincident" || c.type === "horizontal" || c.type === "vertical" || !refsOf(c).some((r) => moved.has(r)))); + if (first === id || !edge || edge.kind !== "line") return; + // A whole shape (several curves selected, or a rectangle / polygon): it moves as one. + const shape = (this.selected.size > 1 && this.selected.has(first)) || all.find((x) => x.id === first)?.kind !== "line" ? new Set([...this.selected, first]) : null; + this.selected.clear(); + this.showSelection(); + const res = shape ? alignShape(this.entities, this.constraints, shape, edge, side) : alignOne(this.entities, this.constraints, first, side); + if (!res) return this.app.ui.toast("Those lines can't be aligned"); + this.commit(res.entities, res.constraints); } /** Trim's Join mode: a line and the line on its axis it touches become one. */ @@ -3665,7 +3707,32 @@ export class SketchTool implements Tool { return op.down(p); } + /** The spacing a linear pattern was given on its own (null once typed / dragged). */ + private patAuto: number | null = null; + + /** Spacing = the selection's size along the pattern's direction, plus a fifth (copies don't overlap it). */ + private autoPatternSpacing(): void { + const L = Math.hypot(this.edit.dx, this.edit.dy); + const dir: Vec2 = L > 1e-12 ? [this.edit.dx / L, this.edit.dy / L] : [Math.cos(this.patAng), Math.sin(this.patAng)]; + let lo = Infinity; + let hi = -Infinity; + for (const e of this.entities) + if (this.selected.has(e.id)) + for (const poly of entityPolylines(e)) + for (const q of poly) { + const t = q[0] * dir[0] + q[1] * dir[1]; + lo = Math.min(lo, t); + hi = Math.max(hi, t); + } + const s = patternSpacing(hi > lo ? hi - lo : 0, L > 1e-12 ? L : 10); + this.edit.dx = dir[0] * s; + this.edit.dy = dir[1] * s; + this.patAuto = s; + } + private selectionChanged(): void { + // A pattern's spacing that wasn't set by hand follows what's selected. + if (this.kind === "patternLinear" && this.patAuto !== null && Math.abs(Math.hypot(this.edit.dx, this.edit.dy) - this.patAuto) < 1e-9) this.autoPatternSpacing(); if (this.regionArrow && (this.selected.size || this.selPts.length)) this.hideRegionArrow(); this.updateMenu(); this.refreshDistanceDim(); @@ -4238,7 +4305,7 @@ function phoneScreen(): boolean { } function titleOf(k: string): string { - const t: Record = { patternLinear: "Pattern – Linear", patternCircular: "Pattern – Circular", rotate: "Rotate Around Axis", rect: "Rectangle", offset: "Offset Edge", polyline: "Outline" }; + const t: Record = { patternLinear: "Pattern – Linear", patternCircular: "Pattern – Circular", rotate: "Rotate About", rect: "Rectangle", offset: "Offset Edge", polyline: "Outline" }; return t[k] ?? k[0].toUpperCase() + k.slice(1); } diff --git a/src/ui/help.ts b/src/ui/help.ts index 06741ac..5d5d739 100644 --- a/src/ui/help.ts +++ b/src/ui/help.ts @@ -75,7 +75,7 @@ const SECTIONS: { title: string; intro?: string; items: Entry[] }[] = [ { icon: "offset", name: "Offset Edge", text: "A parallel copy of a curve (or a whole outline) at a distance. Tap empty space to finish." }, { icon: "sketchFillet", name: "Fillet / Chamfer", text: "Round or bevel a corner where lines or arcs meet; tap the next corner to go on." }, { icon: "trim", name: "Trim / Join", text: "Cut away the piece of a curve between crossings (tap, or swipe across several) - or join two lines on the same axis." }, - { icon: "mirror", name: "Mirror, Move/Rotate, Pattern", text: "Mirror the selected shapes across a line or an axis; Move/Rotate with its gimbal (Rotate About a tapped centre); Pattern in a row or round a centre." }, + { icon: "mirror", name: "Mirror, Move/Rotate, Pattern", text: "Mirror the selected shapes across a line or an axis; Move/Rotate with its gimbal (turns about the selection's own centre); Rotate About turns the whole selection rigidly about a point you tap - an end, a midpoint or another shape's centre - so its own centre swings round that point (the dotted arc shows the path); Pattern in a row or round a centre." }, { icon: "alignLine", name: "Align", text: "Move a line onto another line's axis; lines joined to it stretch along." }, { icon: "extend", name: "Extend", text: "Carry a line or arc on until it meets another curve." }, { icon: "constraints", name: "Constraints", text: "Rules that keep the drawing in shape: horizontal, parallel, equal, a fixed distance… shown as small faint marks, a colour per kind. A new rule replaces the ones in its way (an old angle or parallel), and says which; locked points stay put. Dragging a point onto another joins them." }, diff --git a/tests/alignmove.test.ts b/tests/alignmove.test.ts new file mode 100644 index 0000000..75f2a80 --- /dev/null +++ b/tests/alignmove.test.ts @@ -0,0 +1,77 @@ +// Run: npx tsx tests/alignmove.test.ts +// Align: the first thing picked moves onto the second's axis - never the other +// way round, even when constraints tie them (and nothing is locked). +import assert from "node:assert/strict"; +import type { SketchConstraint, SketchEntity, Vec2 } from "../src/doc/types"; +import { alignOne, alignShape } from "../src/sketch/edit"; +import { constraintError, solve } from "../src/sketch/constraints"; + +type Ln = Extract; +const L = (id: string, a: Vec2, b: Vec2): Ln => ({ id, kind: "line", a, b }); +const coin = (a: string, pa: string, b: string, pb: string): SketchConstraint => ({ id: `c${a}${pa}${b}${pb}`, type: "coincident", pts: [{ e: a, p: pa }, { e: b, p: pb }] }); +const get = (es: SketchEntity[], id: string) => es.find((e) => e.id === id) as Ln; +const near = (p: Vec2, q: Vec2) => Math.hypot(p[0] - q[0], p[1] - q[1]) < 1e-6; + +// A constrained (not locked) box: lines joined, sides horizontal / vertical, a width. +const box = () => { + const es: SketchEntity[] = [L("b", [0, 0], [40, 0]), L("r", [40, 0], [40, 20]), L("t", [40, 20], [0, 20]), L("l", [0, 20], [0, 0])]; + const cs: SketchConstraint[] = [coin("b", "b", "r", "a"), coin("r", "b", "t", "a"), coin("t", "b", "l", "a"), coin("l", "b", "b", "a"), + { id: "hb", type: "horizontal", curves: ["b"] }, { id: "ht", type: "horizontal", curves: ["t"] }, { id: "vr", type: "vertical", curves: ["r"] }, { id: "vl", type: "vertical", curves: ["l"] }, + { id: "w", type: "dim", curves: ["b"], prop: "length", value: 40 }]; + return { es, cs }; +}; + +const checks: [string, () => void][] = [ + ["a box's right side moves out to a line; the line stays", () => { + const { es, cs } = box(); + const target = L("x", [70, -10], [70, 50]); + const all = [...es, target]; + const res = alignOne(all, cs, "r", target)!; + assert.ok(res); + const r = get(res.entities, "r"); + assert.ok(Math.abs(r.a[0] - 70) < 1e-6 && Math.abs(r.b[0] - 70) < 1e-6, `right side at ${r.a[0]}`); + assert.deepEqual(get(res.entities, "x"), target, "the target didn't move"); + // Solved again as the app will: still there (the width that held it was dropped, not the line pulled back). + const again = solve(res.entities, res.constraints); + assert.ok(Math.abs(get(again.entities, "r").a[0] - 70) < 1e-6); + assert.ok(near(get(again.entities, "x").a, target.a)); + assert.ok(constraintError(res.entities, res.constraints) < 1e-6); + }], + ["aligning to a line of another constrained shape moves only the first", () => { + const a = box(); + const bEs = a.es.map((e) => ({ ...(e as Ln), id: "B" + e.id, a: [(e as Ln).a[0] + 100, (e as Ln).a[1] + 7] as Vec2, b: [(e as Ln).b[0] + 100, (e as Ln).b[1] + 7] as Vec2 })); + const bCs = a.cs.map((c) => ({ ...c, id: "B" + c.id, curves: c.curves?.map((x) => "B" + x), pts: c.pts?.map((q) => ({ ...q, e: "B" + q.e })) })); + const all = [...a.es, ...bEs]; + const res = alignOne(all, [...a.cs, ...bCs], "t", get(all, "Bt"))!; + assert.ok(Math.abs(get(res.entities, "t").a[1] - 27) < 1e-6); + for (const e of bEs) assert.deepEqual(get(res.entities, e.id), e, `${e.id} moved`); + }], + ["a whole shape turns and slides so its edge lies on the line", () => { + const { es, cs } = box(); + // A slanted target line: y = x - 100. + const target = L("x", [100, 0], [200, 100]); + const res = alignShape([...es, target], cs, new Set(["b", "r", "t", "l"]), get(es, "b"), target)!; + const b = get(res.entities, "b"); + const onT = (p: Vec2) => Math.abs(p[1] - (p[0] - 100)) < 1e-6; + assert.ok(onT(b.a) && onT(b.b), "edge on the target's axis"); + assert.ok(Math.abs(Math.hypot(b.b[0] - b.a[0], b.b[1] - b.a[1]) - 40) < 1e-6, "size kept"); + assert.deepEqual(get(res.entities, "x"), target); + // Still a box: corners joined, sides at right angles. + assert.ok(near(get(res.entities, "b").b, get(res.entities, "r").a) && near(get(res.entities, "t").b, get(res.entities, "l").a)); + // Its H/V constraints no longer hold (it's turned): they went. + assert.ok(!res.constraints.some((c) => c.id === "hb" || c.id === "vr")); + }], +]; + +let failed = 0; +for (const [name, f] of checks) { + try { + f(); + console.log(`ok ${name}`); + } catch (e) { + failed++; + console.log(`FAIL ${name}\n ${(e as Error).message}`); + } +} +if (failed) process.exit(1); +console.log("all align-move checks passed"); diff --git a/tests/offsetspike.test.ts b/tests/offsetspike.test.ts index eee4066..df1bccc 100644 --- a/tests/offsetspike.test.ts +++ b/tests/offsetspike.test.ts @@ -5,6 +5,7 @@ import assert from "node:assert/strict"; import type { SketchEntity, Vec2 } from "../src/doc/types"; import { defaultOffset, offsetChain } from "../src/sketch/edit"; import { closestOnPrim, entityPrims } from "../src/sketch/curves"; +import { patternSpacing, roundSig } from "../src/geom"; const L = (id: string, a: Vec2, b: Vec2): SketchEntity => ({ id, kind: "line", a, b }); // Sketch 11's outline (closed, clockwise as drawn). @@ -53,6 +54,14 @@ const checks: [string, () => void][] = [ // Sketch 11's first side (2470 long): 250, not 2. assert.equal(defaultOffset(L("s", P[0], P[1])), 250); }], + ["pattern spacing starts just clear of the shape", () => { + assert.equal(patternSpacing(100), 120); + assert.equal(patternSpacing(2350), 2800); + assert.equal(patternSpacing(0), 10); + assert.equal(patternSpacing(0, 20), 20); + assert.ok(patternSpacing(37) > 37); + assert.equal(roundSig(0.0347), 0.035); + }], ["Sketch 11 outline offset inward 840 doesn't cross it", () => checkOffset(loop(P), -840, "in 840")], ["Sketch 11 outline at many distances, both ways", () => { for (const d of [50, 200, 400, 600, 840, 1000, 1300]) {