Undo inside a tool; a thread cut with clearance; the phone's sketch line in two rows; undo / redo the bar's height; a sketch's steps in History pick what they made (asked for, six points: "when I want to subtract a thread and I put clearance, it always fails ... on mobile, when I hit sketch ... I have to scroll right in a box that is only a button wide. Maybe you can make that option window 2 buttons tall? ... in sketch, if I close a shape, it should automatically exit the line type ... the undo and redo buttons should be the same as the ones on the bottom bar. Same bar height ... in history, if I make changes in a sketch, I want those changes to be selectable from that history action so I can edit them ... when I ... select a vertex and I move it around, and I hit undo, that undo should change the last modification, not go back to the extruding action ... I want full history control").

- Undo. With a tool open (Move Vertex, Move Edge or Face, Extrude, Fillet, Move/Rotate, any of them), Undo closed the tool - all of what was done in it gone - and then took back the step before it as well. Each change made in an open tool is a step of its own now (a drag of its handle, a value typed, an option, something more picked): Undo takes the last one back, Redo puts it back, and the handles go with them. With nothing left to take back in the tool, Undo closes it; the next is the project's.
- Thread and clearance. The kernel cannot grow a thread's helical faces, so Subtract with a clearance round a threaded body failed every time. Such a body is grown another way: its grooves filled back in (what it was before its thread), that grown, and the same thread cut on it again - over the same stretch, from the same start, its V that much less deep so its sides stand the clearance off the first thread's sides (out by the clearance alone they stood half of it). tests/threadclearance.test.ts, 9 checks: an M10 bolt through a block, clearances 0.1, 0.2 and 0.4 - cut, sound, the bolt untouched, and the hole exactly that far from the bolt at its nearest (0.0999, 0.1998, 0.3996).
- A phone held upright, in a sketch with a tool's own parts on the line (Line on, a point placed): two rows of buttons, a picture over its name each, all in view. It was one row to slide, a button and a half wide.
- Undo and redo are the bar's height on every screen (49 to 61; they were 52, 48 on a phone), and sit on its line.
- History: each step listed under a sketch remembers the curves it made or changed. Tapped, the sketch opens with them picked, their sizes on the line to change.
- Closing a shape: looked at, and already so - the drawing tool is put down and the sketch stays open (line, rectangle, circle, polygon, ellipse, by touch).
In the app: a corner dragged three times with its gimbal, then Undo, Undo, Redo, Undo, Undo (each step back in turn, the gimbal with it), Undo again (the tool closes), Done after another drag and Undo (that step only); a rectangle and two circles drawn, their steps tapped in History (two circles picked; the rectangle picked and its width typed); the sketch line at 390 wide in two rows; undo against the line at four sizes.
Tests: threadclearance 9, clearance 32, thread 15, sketchtools, constraints, projectlean, exports as before.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
superGeometry
2026-11-21 16:14:55 +02:00
parent a305c3c859
commit 4f93cfbf83
9 changed files with 6054 additions and 5722 deletions
+12 -4
View File
@@ -882,7 +882,7 @@ export class App implements AppContext {
// The rows are rebuilt: a hover on an old row is over.
this.view.setStepHover(null);
this.ui.renderHistory(this.store.doc.features, this.result?.errors ?? [], this.tool.editingId ?? this.tool.activeSketch ?? null, {
edit: (id) => this.editFeature(id),
edit: (id, pick) => this.editFeature(id, pick),
hover: (id) => this.view.setStepHover(id ? this.stepTargets(id) : null),
toggle: (id) => {
const f = this.store.find(id);
@@ -1030,7 +1030,7 @@ export class App implements AppContext {
this.editFeature(id);
}
private editFeature(id: string): void {
private editFeature(id: string, pick?: string[]): void {
const f = this.store.find(id);
if (!f) return;
this.setSelection([]);
@@ -1045,8 +1045,16 @@ export class App implements AppContext {
// Subtract / Intersect open their tool (picks, Keep options); Union has nothing to set.
if (f.op !== "union") return this.setTool(new BooleanOp(this, f.op, f.target, f.tools, f));
break;
case "sketch":
return this.setTool(new SketchTool(this, { sketchId: f.id }));
case "sketch": {
// (From one of its steps in History: open with what that step made picked, ready to change.)
const tool = new SketchTool(this, { sketchId: f.id });
this.setTool(tool);
if (pick?.length) {
tool.stopDrawing();
tool.preselect(pick);
}
return;
}
case "extrude":
return this.setTool(new ExtrudeOp(this, f.source, f as ExtrudeFeature));
case "fillet":
+1 -1
View File
@@ -181,7 +181,7 @@ export interface SketchFeature extends FeatureBase {
links?: EdgeLink[];
/** What was done in the sketch, in order (shown under it in History); repeats are counted. */
log?: { op: string; n: number }[];
log?: { op: string; n: number; ids?: string[] }[];
}
export interface ExtrudeFeature extends FeatureBase {
+91 -9
View File
@@ -803,6 +803,7 @@ export function debugBodies(): Map<string, Shape3D> {
}
async function run(features: Feature[], saved = false) {
stepsNow = new Set(features.map((f) => f.id));
useSafeBooleans();
useReleases();
// Steps after the History's breakpoint: off, like suppressed ones.
@@ -1529,7 +1530,8 @@ async function apply(f: Feature, ctx: Ctx): Promise<void> {
if (!(by > 0)) return [s.clone()];
let g = grown.get(s)?.get(by);
if (!g) {
g = grownBy(s, by) ?? undefined;
// (A threaded body: the same thread cut on the body grown. The kernel can't grow a thread's own faces.)
g = grownThreaded(s, by, toolIds[tools.indexOf(s)] ?? (s === target ? f.target : "")) ?? grownBy(s, by) ?? undefined;
if (!g) throw new Error(`Couldn't keep ${+by.toFixed(4)} mm clear round one of the bodies - try a smaller clearance`);
grown.set(s, (grown.get(s) ?? new Map()).set(by, g));
}
@@ -1803,7 +1805,21 @@ async function apply(f: Feature, ctx: Ctx): Promise<void> {
case "thread": {
const body = need(bodies, f.face.body);
bodies.set(f.face.body, threadFace(body, threadTarget(body, f), f.pitch, !!f.left));
const face = threadTarget(body, f);
const cy = cylinderOf(face);
// (How it was cut is kept by its step: a clearance round the body is the same thread cut on the body grown -
// see grownThreaded.)
if (cy) {
const a = norm(cy.a);
const ts: number[] = [];
for (const e of face.edges) for (const k of [0, 0.25, 0.5, 0.75, 1]) ts.push(dot(sub(e.pointAt(k).toTuple() as Vec3, cy.c), a));
const used: { phase?: number } = {};
const made = threadFace(body, face, f.pitch, !!f.left, undefined, used);
threadsCut.set(f.id, { body: f.face.body, c: cy.c, a, r: cy.r, inside: cy.s < 0, pitch: f.pitch, left: !!f.left, t0: Math.min(...ts), t1: Math.max(...ts), phase: used.phase });
bodies.set(f.face.body, made);
return;
}
bodies.set(f.face.body, threadFace(body, face, f.pitch, !!f.left));
return;
}
@@ -2720,7 +2736,7 @@ function threadTarget(body: Shape3D, f: Extract<Feature, { type: "thread" }>): F
* a ridge) is the reliable way: a ridge only just overlapping its core can
* come out of OpenCascade wrong without a word.
*/
export function threadFace(body: Shape3D, face: Face, pitch: number, left = false): Shape3D {
export function threadFace(body: Shape3D, face: Face, pitch: number, left = false, like?: { t0: number; t1: number; phase?: number; shallow?: number }, used?: { phase?: number }): Shape3D {
if (face.geomType !== "CYLINDRE") throw new Error("Threads go on round faces (a shank or a hole)");
if (!(pitch > 0)) throw new Error("The pitch must be more than 0");
// (Finer than any standard thread: it failed with "try a slightly different pitch".)
@@ -2728,14 +2744,20 @@ export function threadFace(body: Shape3D, face: Face, pitch: number, left = fals
const cy = cylinderOf(face);
if (!cy) throw new Error("Threads go on round faces (a shank or a hole)");
const inside = cy.s < 0;
const depth = threadDepth(pitch, inside);
// (`like.shallow`: a groove that much less deep, and so that much narrower - the thread of a body grown by a
// clearance. Its round face is already out by the clearance; with the V out by it once more, its sides stand
// that clearance off the first thread's sides, not half of it.)
const depth = threadDepth(pitch, inside) - (like?.shallow ?? 0);
if (!(depth > 0)) throw new Error("That clearance is more than the thread is deep");
if (!inside && depth >= cy.r * 0.9) throw new Error("That pitch is too coarse for this diameter");
const a = norm(cy.a);
// The face's length along its axis.
const ts: number[] = [];
for (const e of face.edges) for (const k of [0, 0.25, 0.5, 0.75, 1]) ts.push(dot(sub(e.pointAt(k).toTuple() as Vec3, cy.c), a));
const t0 = Math.min(...ts);
const t1 = Math.max(...ts);
// (`like`: along the same stretch and from the same start as another thread - one cut again on the body grown,
// so its turns lie over the first one's.)
const t0 = like ? like.t0 : Math.min(...ts);
const t1 = like ? like.t1 : Math.max(...ts);
if (t1 - t0 < pitch) throw new Error("This face is shorter than one turn of the thread");
// The groove's section in a plane through the axis: a 60° V from its tip
// (the thread's depth) opening past the face.
@@ -2766,7 +2788,7 @@ export function threadFace(body: Shape3D, face: Face, pitch: number, left = fals
return false;
}
};
const res = threadCut(body, face, cy, a, pitch, left, inside, depth, tip, mouth, hm, t0, t1);
const res = threadCut(body, face, cy, a, pitch, left, inside, depth, tip, mouth, hm, t0, t1, like?.phase, used);
if (res) {
let r = res;
for (const [t, way] of [[t0, -1], [t1, 1]] as const) if (freeAt(t, way)) r = threadEndChamfer(r, cy.c, a, side, cy.r, tip, out, t, way, pitch) ?? r;
@@ -2818,6 +2840,8 @@ function threadCut(
hm: number,
t0: number,
t1: number,
only?: number,
used?: { phase?: number },
): Shape3D | null {
const lo = t0 + 0.05 * pitch;
const hi = t1 - 0.05 * pitch;
@@ -2851,7 +2875,7 @@ function threadCut(
// Where the thread starts round the face doesn't matter: if OpenCascade
// trips on one start (a groove lining up with the face's seams), another
// is tried.
for (const phase of [0, 0.37, 0.71]) {
for (const phase of only !== undefined ? [only] : [0, 0.37, 0.71]) {
const start = lo - pitch * (1 + phase);
const turns = Math.ceil((hi - start) / pitch) + 1;
// An exact helix (a line wound on a cylinder, not a fitted spline: those
@@ -2893,7 +2917,10 @@ function threadCut(
for (const fuzzy of [true, false]) {
try {
const res = fuzzy ? fuzzyBoolean("cut", body, cut) : body.cut(cut);
if (ok(res, cut)) return res;
if (ok(res, cut)) {
if (used) used.phase = phase;
return res;
}
} catch {
// the other way, or the next start
}
@@ -3211,6 +3238,61 @@ function grownBy(s: Shape3D, by: number): Shape3D[] | null {
}
}
/** The threads cut in this project, by their step: on which body, the round face's axis, size and reach, the pitch. */
const threadsCut = new Map<string, { body: string; c: Vec3; a: Vec3; r: number; inside: boolean; pitch: number; left: boolean; t0: number; t1: number; phase?: number }>();
/** The steps of the project being built (a thread's record is only good while its step is there). */
let stepsNow = new Set<string>();
/**
* A threaded body grown by `by` (the clearance a Subtract keeps round it). The kernel's own offset of a thread's
* helical faces fails every time (asked: "when I want to subtract a thread and I put clearance, it always fails").
* So: its grooves filled back in (a cylinder over the thread's reach - what it was before the thread), that
* grown, and the same thread cut on its round face - a thread that much bigger all round (in a hole: that much
* smaller), which is what a nut cut with it needs to turn on the bolt with that gap.
* Null when the body has no thread of its own any more, or it doesn't work out (the plain way is tried then).
*/
function grownThreaded(s: Shape3D, by: number, bodyId: string): Shape3D[] | null {
const cut = [...threadsCut].filter(([step, t]) => t.body === bodyId && stepsNow.has(step)).map(([, t]) => t);
if (!cut.length) return null;
try {
// Its grooves filled in.
let plain = s;
const v0 = Math.abs(measureVolume(s));
for (const t of cut) {
const depth = threadDepth(t.pitch, t.inside) * 1.05 + 0.25 * t.pitch;
const from = add(t.c, scale(t.a, t.t0));
const fill = t.inside
? ((makeCylinder(t.r + depth, t.t1 - t.t0, from, t.a) as Shape3D).cut(makeCylinder(t.r, t.t1 - t.t0, from, t.a) as Shape3D) as Shape3D)
: (makeCylinder(t.r, t.t1 - t.t0, from, t.a) as Shape3D);
plain = unify(plain.fuse(fill) as Shape3D);
}
// (Nothing filled: there is no thread on it now - something else was done to it since.)
if (!(Math.abs(measureVolume(plain)) > v0 * (1 + 1e-9))) return null;
const grown = grownBy(plain, by);
if (!grown || grown.length !== 1) return null;
let out = grown[0];
for (const t of cut) {
const want = t.r + (t.inside ? -by : by);
if (!(want > 0)) return null;
const face = out.faces.find((g) => {
if (g.geomType !== "CYLINDRE") return false;
const cy = cylinderOf(g);
if (!cy || cy.s < 0 !== t.inside || Math.abs(cy.r - want) > 1e-4 * Math.max(1, want)) return false;
if (Math.abs(dot(norm(cy.a), t.a)) < 0.9999) return false;
// (The same axis: its centre is on the thread's axis line.)
const d = sub(cy.c, t.c);
return len(sub(d, scale(t.a, dot(d, t.a)))) < 1e-4 * Math.max(1, want);
});
if (!face) return null;
out = threadFace(out, face, t.pitch, t.left, { t0: t.t0, t1: t.t1, phase: t.phase, shallow: by });
}
return Math.abs(measureVolume(out)) > 0 ? [out] : null;
} catch (err) {
if (isFault(err)) throw err;
return null;
}
}
/** A body brought in by `by` all round (one shape), or null when that doesn't work. */
function broughtIn(s: Shape3D, by: number): Shape3D | null {
const g = grownBy(s, -by);
+83
View File
@@ -7138,3 +7138,86 @@ body.history-open.history-clear-col #right-col {
bottom: auto !important;
transform: translateY(-50%) !important;
}
/* A phone held upright, in a sketch with a tool's own parts on the line: two rows of buttons, a picture over its
name each, four across - nothing to slide to (sentence.ts, sn-two). */
.sn-line.sn-two .sn-row {
flex-wrap: wrap;
align-content: flex-start;
gap: 0;
row-gap: 2px;
padding: 3px;
overflow: hidden;
-webkit-mask-image: none;
mask-image: none;
}
.sn-line.sn-two .sn-row::after {
display: none;
}
.sn-line.sn-two .sn-row .sn-word {
flex: 1 1 25%;
max-width: 50%;
min-width: 0;
align-items: center;
justify-content: center;
padding: 4px 1px 3px;
min-height: 46px;
background: none;
}
.sn-line.sn-two .sn-row .sn-word.on:not(.sn-subject):not(.sn-slot) {
background: var(--accent-soft);
}
.sn-line.sn-two .sn-row .sn-body {
flex-direction: column;
gap: 2px;
max-width: 100%;
}
.sn-line.sn-two .sn-row .sn-icon,
.sn-line.sn-two .sn-row .sn-icon svg {
width: 20px;
height: 20px;
}
.sn-line.sn-two .sn-row .sn-text {
font-size: 10.5px;
max-width: 100%;
overflow: hidden;
text-overflow: clip;
}
.sn-line.sn-two .sn-row .sn-more,
.sn-line.sn-two .sn-row .sn-kbd {
display: none;
}
.sn-line.sn-two .sn-end {
align-self: flex-end;
padding: 4px 4px 4px 0;
}
.sn-line.sn-two .sn-end-btn.sn-all,
.sn-line.sn-two .sn-end-btn.sn-exit {
flex-direction: column;
gap: 2px;
height: 46px;
min-width: 44px;
padding: 3px 4px 2px;
background: none;
}
.sn-line.sn-two .sn-end-btn .sn-end-name {
font-size: 10.5px;
}
/* Undo and redo are a piece of the bottom bar: its height, whatever that is on this screen (asked for: "the undo and
redo buttons should be the same as the ones on the bottom bar. Same bar height"). They were a fixed 52 (48 on a
phone) beside a line of 49 to 61. Not taller than one row where the line has two. */
body.sentence-ui #undo-dock {
box-sizing: border-box;
height: min(var(--sn-bar, 52px), 64px);
align-items: stretch;
}
body.sentence-ui #undo-dock .dock-btn {
height: auto;
}
@media (orientation: landscape) {
html[data-screen="phone"] body.sentence-ui #undo-dock {
bottom: calc(8px + var(--safe-b));
}
}
+90
View File
@@ -90,9 +90,98 @@ export abstract class FeatureOp<F extends Feature> implements Tool {
this.render();
this.update();
this.app.ui.focusPanel();
this.steps = [JSON.stringify(this.feature)];
this.redos = [];
window.addEventListener("pointerdown", this.onDown, true);
window.addEventListener("pointerup", this.onUp, true);
window.addEventListener("pointercancel", this.onUp, true);
}
// ---- Undo inside the tool
// Each change made while the tool is open - a drag of its handle, a value typed, an option chosen, something more
// picked - is a step of its own that Undo takes back, one at a time, and Redo puts back (asked for: "when I ...
// select a vertex and I move it around, and I hit undo, that undo should change the last modification, not go back
// to the extruding action or the one before entirely ... I want full history control"). Undo used to close the tool,
// throwing all of it away, and then take back the step before it as well. With nothing left to take back in the
// tool, Undo closes it (nothing made); the next Undo is the project's.
private steps: string[] = [];
private redos: string[] = [];
private held = false;
private settle = 0;
private restoring = false;
private onDown = (): void => void (this.held = true);
private onUp = (): void => {
this.held = false;
// (After the tool's own handlers for this lift have run.)
window.setTimeout(() => this.record(), 0);
};
/** What the draft is now, as a step - if it differs from the last one. */
private record(): void {
if (this.restoring || !this.steps.length) return;
const now = JSON.stringify(this.feature);
if (now === this.steps[this.steps.length - 1]) return;
this.steps.push(now);
if (this.steps.length > 100) this.steps.shift();
this.redos = [];
(this.app as AppContext & { refreshUndo?(): void }).refreshUndo?.();
}
/** The draft changed: a step once the drag ends, or once typing stops for a moment (digit by digit is one step). */
private noteChange(): void {
if (this.restoring || this.held) return;
clearTimeout(this.settle);
this.settle = window.setTimeout(() => this.record(), 450);
}
/** The draft put back to a step (in place: the window's parts and the handles hold on to it). */
private restore(step: string): void {
this.restoring = true;
try {
const f = this.feature as unknown as Record<string, unknown>;
for (const k of Object.keys(f)) delete f[k];
Object.assign(f, JSON.parse(step));
this.restored();
this.render();
this.update();
} finally {
this.restoring = false;
}
}
/** After Undo / Redo put the draft back: for a tool that keeps something beside the draft in step with it. */
protected restored(): void {}
get canUndo(): boolean {
return true;
}
get canRedo(): boolean {
return this.redos.length > 0;
}
undo(): boolean {
clearTimeout(this.settle);
this.record();
if (this.steps.length < 2) {
this.cancel();
return true;
}
this.redos.push(this.steps.pop()!);
this.restore(this.steps[this.steps.length - 1]);
return true;
}
redo(): boolean {
const next = this.redos.pop();
if (!next) return false;
this.steps.push(next);
this.restore(next);
return true;
}
exit(): void {
clearTimeout(this.settle);
window.removeEventListener("pointerdown", this.onDown, true);
window.removeEventListener("pointerup", this.onUp, true);
window.removeEventListener("pointercancel", this.onUp, true);
this.app.view.setOriginPlanesVisible(false);
this.app.ui.showPanel(null);
this.app.ui.setHint(null);
@@ -286,6 +375,7 @@ export abstract class FeatureOp<F extends Feature> implements Tool {
/** Re-run the preview with the current draft. */
protected update(): void {
this.onDraftChanged();
this.noteChange();
const ready = this.ready();
const base = this.app.store.features;
// (The steps that aren't the project's own: the draft, or what a tool puts in its place.)
+5714 -5705
View File
File diff suppressed because it is too large Load Diff
+10
View File
@@ -681,6 +681,12 @@ export class Sentence {
// (A tool's sentence is read whole: it runs on to the next line, as writing does. What a pick offers is one line to slide along.)
// (Not on a screen too low for it - a phone on its side: there it is one line to slide along too.)
this.row.classList.toggle("sn-wrap", b.about.startsWith("tool:") && innerHeight > 480);
// A phone held upright, in a sketch with a tool's own parts on the line (Line on, a point placed: Stop, Values,
// Draw, Modify, Transform, Delete): two rows of buttons, each a picture over its name, all in view (asked for:
// "it's so small and I have to scroll right in a box that is only a button wide. Maybe you can make that option
// window 2 buttons tall?"). It was one row to slide, a button and a half wide beside More and Exit.
const upright = document.documentElement.dataset.screen === "phone" && matchMedia("(max-width: 720px) and (orientation: portrait)").matches;
this.line.classList.toggle("sn-two", upright && b.about.startsWith("sketch:") && !b.grouped);
if (fresh) this.row.scrollLeft = 0;
// The end of the line: everything for this pick, the eraser, the tick.
this.end.replaceChildren();
@@ -730,11 +736,15 @@ export class Sentence {
document.body.style.setProperty("--sn-sheet", h);
}
private barTall = "";
private measure(): void {
// (A phone held upright has the tag at the line's far end, beside undo: only the line's own height counts there.)
const beside = document.documentElement.dataset.screen === "phone" && matchMedia("(max-width: 720px) and (orientation: portrait)").matches;
const tag = this.tag.hidden || beside ? 0 : this.tag.offsetHeight;
const h = `${this.line.offsetHeight + (tag ? tag + 6 : 0)}px`;
// (The line's own height, for undo / redo beside it: the same bar, the same height.)
const bar = `${this.line.offsetHeight}px`;
if (bar !== this.barTall) document.body.style.setProperty("--sn-bar", (this.barTall = bar));
if (h === this.tall) return;
this.tall = h;
document.body.style.setProperty("--sn-line", h);
+5 -3
View File
@@ -139,7 +139,7 @@ export interface ValuePanel {
}
export interface HistoryHandlers {
edit(id: string): void;
edit(id: string, pick?: string[]): void;
/** Pointer over a step (null: left it): show what it works on. */
hover?(id: string | null): void;
toggle(id: string): void;
@@ -1755,9 +1755,11 @@ export class UI {
const sub = el("li", "history-steps");
if (steps.length > shownSteps.length) sub.append(el("div", "history-step more", `… ${steps.length - shownSteps.length} earlier`));
for (const s of shownSteps) {
// (What the step made or changed that is still in the sketch: picked when its line is tapped.)
const still = (s.ids ?? []).filter((id) => f.entities.some((e) => e.id === id));
const row = el("button", "history-step", `${s.op}${s.n > 1 ? ` ×${s.n}` : ""}`);
row.title = "Open the sketch";
row.addEventListener("click", () => h.edit(f.id));
row.title = still.length ? `Open the sketch with ${still.length === 1 ? "this curve" : `these ${still.length} curves`} picked, to change ${still.length === 1 ? "it" : "them"}` : "Open the sketch";
row.addEventListener("click", () => h.edit(f.id, still));
sub.append(row);
}
this.historyList.append(sub);
+48
View File
@@ -0,0 +1,48 @@
// Run: npx tsx tests/threadclearance.test.ts
// A threaded bolt subtracted from a block with a clearance: a threaded hole a little bigger than the bolt all
// round, so the printed bolt turns in it. (It failed every time: "Couldn't keep 0.2 mm clear ...".)
import { after, bodies, block, check, cylinder, done, health, near, volume } from "./kit";
import { getOC, type Shape3D } from "replicad";
import type { Feature } from "../src/doc/types";
const oc = getOC();
const gap = (a: Shape3D, b: Shape3D) => {
const d = new oc.BRepExtrema_DistShapeShape(a.wrapped, b.wrapped);
try {
return d.IsDone() ? d.Value() : -1;
} finally {
d.delete();
}
};
// A block 30 x 30 x 12 and an M10 bolt shank (r 5, 24 long) standing through its middle.
const blockF = block("blk", 30, 30, 12);
const bolt = cylinder("bolt", 5, 24, 15, 15, -6);
const first = await after([...blockF, ...bolt]);
const side = first.r.bodies.find((b) => b.id === "bolt")!.faces.find((f) => f.type === "CYLINDRE")!;
const thread: Feature = { id: "thr", name: "Thread", type: "thread", face: { body: "bolt", center: side.center, normal: side.normal, area: side.area }, pitch: 1.5 } as Feature;
const cut = (extra: object): Feature => ({ id: "cut", name: "Subtract", type: "boolean", op: "subtract", target: "blk", tools: ["bolt"], keepTools: true, ...extra }) as Feature;
const B = (id: string) => bodies().get(id) as Shape3D;
let r = await after([...blockF, ...bolt, thread]);
const vBolt = volume(B("bolt"));
check("the bolt is threaded", !r.errors.length && health(B("bolt")).healthy && vBolt < Math.PI * 25 * 24, `${vBolt.toFixed(1)} ${r.errors.join("; ")}`);
r = await after([...blockF, ...bolt, thread, cut({})]);
const vTight = volume(B("blk"));
check("no clearance: a threaded hole the bolt's own size", !r.errors.length && health(B("blk")).healthy && near(gap(B("blk"), B("bolt")), 0, 1e-3), `${r.errors.join("; ")} gap ${gap(B("blk"), B("bolt")).toFixed(4)}`);
for (const c of [0.1, 0.2, 0.4]) {
const t0 = performance.now();
r = await after([...blockF, ...bolt, thread, cut({ clearance: c })]);
const ok = !r.errors.length && !!B("blk");
const g = ok ? gap(B("blk"), B("bolt")) : -1;
const v = ok ? volume(B("blk")) : 0;
// The hole is the thread that much bigger all round: nowhere nearer the bolt than the clearance (its sides and
// its crests at just that; its roots have more).
check(`clearance ${c}: the cut is made, sound, the bolt kept`, ok && health(B("blk")).healthy && near(volume(B("bolt")), vBolt, 1e-6), `${r.errors.join("; ")} ${Math.round(performance.now() - t0)} ms`);
check(`clearance ${c}: the hole stands ${c} off the bolt at its nearest, and is bigger than the tight one`, ok && g > c * 0.97 && g < c * 1.03 && v < vTight, `gap ${g.toFixed(4)}, block ${v.toFixed(1)} against ${vTight.toFixed(1)}`);
}
// Cut the other way: the bolt gives way to the block.
r = await after([...blockF, ...bolt, thread, cut({ clearance: 0.2, cutFrom: "tools" })]);
check("clearance taken from the bolt instead: made, or said why in plain words", !r.errors.length || /clear|smaller/i.test(r.errors.join()), r.errors.join("; "));
done();