diff --git a/src/bim/drawing.ts b/src/bim/drawing.ts index 35a0493..ceeabe9 100644 --- a/src/bim/drawing.ts +++ b/src/bim/drawing.ts @@ -16,7 +16,7 @@ import { measureBodies } from "./bimTool"; import { SheetCamera } from "./sheetCamera"; import { sheetToDXF } from "../io/sheetDxf"; import { zip } from "../io/threemf"; -import { partsList, type PartRow } from "./sheet"; +import { partsList, printPage, type PartRow } from "./sheet"; import { arrangeDims, drawingsOf, @@ -1995,11 +1995,7 @@ export async function openDrawing(app: AppContext, which?: string): Promise { const a = document.createElement("a"); @@ -2059,11 +2055,7 @@ export async function openDrawing(app: AppContext, which?: string): Promise { const sheets = await allSheets("Print"); diff --git a/src/bim/sheet.ts b/src/bim/sheet.ts index 01f4be5..6a56415 100644 --- a/src/bim/sheet.ts +++ b/src/bim/sheet.ts @@ -54,6 +54,42 @@ export function partsList(app: AppContext, props: Map): PartR const len = (mm: number) => trim(mm / UNIT_MM[units()], 2); +let afterPrint: (() => void) | null = null; +/** + * The print window, with `cls` on the page while it is up (the styles for printing go by it) and `extra` (a style, + * the sheets to print) in the page that long. Put right when printing is over, not when print() returns: on a phone + * print() returns at once, before the preview has drawn the page - what it then drew was the page put back already + * (a blank sheet, or the app itself). + */ +export function printPage(cls: string, ...extra: HTMLElement[]): void { + afterPrint?.(); + let over = false; + const tidy = () => { + if (over) return; + over = true; + afterPrint = null; + removeEventListener("afterprint", tidy); + removeEventListener("focus", late); + document.body.classList.remove(cls); + for (const e of extra) e.remove(); + }; + // (A browser that never says printing is over: tidied when the app is come back to, a moment after.) + const late = () => setTimeout(() => !matchMedia("print").matches && tidy(), 1500); + afterPrint = tidy; + document.body.classList.add(cls); + addEventListener("afterprint", tidy); + const t0 = performance.now(); + try { + window.print(); + } catch { + tidy(); + return; + } + // (print() that waited for the window to close - a computer's browser: over now, whether or not it said so.) + if (performance.now() - t0 > 400) tidy(); + else addEventListener("focus", late); +} + export async function openSheet(app: AppContext): Promise { document.querySelector(".bim-sheet")?.remove(); const back = el("div", "bim-sheet"); @@ -75,11 +111,7 @@ export async function openSheet(app: AppContext): Promise { }; window.addEventListener("keydown", onKey, true); close.addEventListener("click", shut); - print.addEventListener("click", () => { - document.body.classList.add("printing-sheet"); - window.print(); - document.body.classList.remove("printing-sheet"); - }); + print.addEventListener("click", () => printPage("printing-sheet")); let rows: PartRow[] = []; try { diff --git a/src/kernel/engine.ts b/src/kernel/engine.ts index ac0ccdf..e6aafc7 100644 --- a/src/kernel/engine.ts +++ b/src/kernel/engine.ts @@ -2736,12 +2736,16 @@ function threadTarget(body: Shape3D, f: Extract): 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, like?: { t0: number; t1: number; phase?: number; shallow?: number }, used?: { phase?: number }): Shape3D { +export function threadFace(body: Shape3D, face: Face, pitch: number, left = false, like?: { t0: number; t1: number; anchor?: number; phase?: number; shallow?: number; c?: Vec3; a?: Vec3 }, 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".) if (pitch < 0.2 - 1e-9) throw new Error("That pitch is too fine - the finest is 0.2 mm"); - const cy = cylinderOf(face); + const cy0 = cylinderOf(face); + // (`like.c`, `like.a`: measured from the same point along the same axis as another thread. A face's own centre + // and the way its axis points are the kernel's choice, and differ from one body to the same body grown - the + // turns then started somewhere else, and ran into the first thread's.) + const cy = cy0 && like?.c && like.a ? { ...cy0, c: like.c, a: like.a } : cy0; if (!cy) throw new Error("Threads go on round faces (a shank or a hole)"); const inside = cy.s < 0; // (`like.shallow`: a groove that much less deep, and so that much narrower - the thread of a body grown by a @@ -2788,7 +2792,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, like?.phase, used); + const res = threadCut(body, face, cy, a, pitch, left, inside, depth, tip, mouth, hm, t0, t1, like?.phase, used, like?.anchor); 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; @@ -2842,6 +2846,7 @@ function threadCut( t1: number, only?: number, used?: { phase?: number }, + anchor?: number, ): Shape3D | null { const lo = t0 + 0.05 * pitch; const hi = t1 - 0.05 * pitch; @@ -2876,7 +2881,8 @@ function threadCut( // trips on one start (a groove lining up with the face's seams), another // is tried. for (const phase of only !== undefined ? [only] : [0, 0.37, 0.71]) { - const start = lo - pitch * (1 + phase); + // (`anchor`: where another thread's stretch began - the turns start from there, whatever stretch this one has.) + const start = (anchor !== undefined ? anchor + 0.05 * pitch : 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 // drift over many turns and the sweep fails), through the groove's middle. @@ -3259,12 +3265,15 @@ function grownThreaded(s: Shape3D, by: number, bodyId: string): Shape3D[] | null let plain = s; const v0 = Math.abs(measureVolume(s)); for (const t of cut) { + // The whole band the thread is in - from under its roots to its round face - taken out and put back as one + // clean ring. (A cylinder simply added over the grooves left their edges in the body: grown, that body broke + // the engine.) 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); + const h = t.t1 - t.t0; + const [inner, outer] = t.inside ? [t.r, t.r + depth] : [Math.max(t.r - depth, t.r * 0.05), t.r]; + const ring = (makeCylinder(outer, h, from, t.a) as Shape3D).cut(makeCylinder(inner, h, from, t.a) as Shape3D) as Shape3D; + plain = unify((plain.cut(ring.clone()) as Shape3D).fuse(ring) 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; @@ -3284,7 +3293,14 @@ function grownThreaded(s: Shape3D, by: number, bodyId: string): Shape3D[] | null 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 }); + // Along the first thread's own stretch - but not into what has grown towards it: an end that stops at a + // shoulder (under a bolt's head) stops the clearance short of where it did, the shoulder having come that + // much nearer. (Run on to the old end, the groove cut into the grown head, and the hole had a ridge there.) + const along: number[] = []; + for (const e of face.edges) for (const k of [0, 0.25, 0.5, 0.75, 1]) along.push(dot(sub(e.pointAt(k).toTuple() as Vec3, t.c), t.a)); + const g0 = Math.min(...along); + const g1 = Math.max(...along); + out = threadFace(out, face, t.pitch, t.left, { t0: Math.max(t.t0, g0), t1: Math.min(t.t1, g1), anchor: t.t0, phase: t.phase, shallow: by, c: t.c, a: t.a }); } return Math.abs(measureVolume(out)) > 0 ? [out] : null; } catch (err) { diff --git a/src/sketch/edit.ts b/src/sketch/edit.ts index 5d5bdc0..ee4e3b4 100644 --- a/src/sketch/edit.ts +++ b/src/sketch/edit.ts @@ -6,7 +6,7 @@ import { roundSig, toPlane, toWorld } from "../geom"; import type { Arrangement, Region } from "./regions"; import { constraintError, pointOf, pointsOf, refsOf, solve } from "./constraints"; import { fitSpline } from "./freehand"; -import { arcFrom3, closestOnPrim, entityCorners, entityPrims, evalPrim, isClosedPrim, primSegments, samplePrim, type Prim } from "./curves"; +import { arcFrom3, closestOnPrim, entityCorners, entityPrims, evalPrim, isClosedPrim, primSegments, samplePrim, splineHeights, splineHeightSamples, type Prim } from "./curves"; export function uid(): string { return Math.random().toString(36).slice(2, 10); @@ -454,6 +454,7 @@ function moveEnd(e: SketchEntity, end: "a" | "b", to: Vec2): SketchEntity { // The end fit point moves there. const pts = [...e.points]; pts[end === "a" ? 0 : pts.length - 1] = to; + // (Its heights stay with its points: the spread above keeps them.) return { ...e, points: pts }; } if (e.kind !== "arc") return e; @@ -671,15 +672,21 @@ export function splitAny(entities: SketchEntity[], id: string, at: Vec2, step: n const T = closestOnPrim(prim, P).t; const spans = closed ? pts.length : pts.length - 1; const s = Math.max(0, Math.min(spans - 1, Math.floor(T * spans + 1e-9))); + // A spline with points off the plane: each piece keeps its points' heights, and the new end is as high as the + // curve is there. (The pieces came out flat on the plane.) + const z = splineHeights(e); + const high = z ? splineHeightSamples(e) : null; + const zP = high ? (high[Math.max(0, Math.min(high.length - 1, Math.round(T * (high.length - 1))))] ?? 0) : 0; + const up = (list: number[]) => (z ? { z: list } : {}); if (closed) { // A closed loop opens up at that point (one piece, both ends there). const ring = [...pts.slice(s + 1), ...pts.slice(0, s + 1)]; - const open: SketchEntity = { id, kind: "spline", points: [P, ...ring, P], closed: false, mode, construction: e.construction }; + const open: SketchEntity = { id, kind: "spline", points: [P, ...ring, P], closed: false, mode, construction: e.construction, ...up(z ? [zP, ...z.slice(s + 1), ...z.slice(0, s + 1), zP] : []) }; return { entities: entities.map((x) => (x.id === id ? open : x)), parts: [id], exploded: true }; } const n = newId(); - const first: SketchEntity = { id, kind: "spline", points: [...pts.slice(0, s + 1), P], closed: false, mode, construction: e.construction }; - const second: SketchEntity = { id: n, kind: "spline", points: [P, ...pts.slice(s + 1)], closed: false, mode, construction: e.construction }; + const first: SketchEntity = { id, kind: "spline", points: [...pts.slice(0, s + 1), P], closed: false, mode, construction: e.construction, ...up(z ? [...z.slice(0, s + 1), zP] : []) }; + const second: SketchEntity = { id: n, kind: "spline", points: [P, ...pts.slice(s + 1)], closed: false, mode, construction: e.construction, ...up(z ? [zP, ...z.slice(s + 1)] : []) }; return { entities: entities.flatMap((x) => (x.id === id ? [first, second] : [x])), parts: [id, n], exploded: false }; } return null; diff --git a/tests/spline3d.test.ts b/tests/spline3d.test.ts index 43f4d6e..3501c1a 100644 --- a/tests/spline3d.test.ts +++ b/tests/spline3d.test.ts @@ -5,7 +5,7 @@ import type { Shape3D } from "replicad"; import { after, bodies, check, circle, done, health, near, profile, sketch, volume, XY, YZ } from "./kit"; import type { Feature, SketchEntity } from "../src/doc/types"; import { entityPolylines, entityWorldPolylines, splineHeightSamples, splineHeights } from "../src/sketch/curves"; -import { transformEntity } from "../src/sketch/edit"; +import { splitAny, transformEntity } from "../src/sketch/edit"; import { solve } from "../src/sketch/constraints"; const flat: SketchEntity = { id: "p", kind: "spline", points: [[0, 0], [40, 0], [80, 0], [120, 0]], closed: false, mode: "fit" }; @@ -97,4 +97,37 @@ check("as long as the curve through space", run > 125 && near(vHigh, Math.PI * 9 const good = volume(t.body); check("a profile on the curve, square to it: a rod as thick all the way, nothing to say", !t.err && !!t.body && health(t.body!).healthy && near(good, Math.PI * 9 * run2, Math.PI * 9 * run2 * 0.004) && !t.r.notes.length, `${good.toFixed(0)} / ${(Math.PI * 9 * run2).toFixed(0)} (${run2.toFixed(2)} long) ${t.err ?? ""} ${t.r.notes.map((n) => n.message).join(" ")}`); } + +// Split in two: each piece keeps its points' heights, and where they part the two are as high as the curve was. +{ + const whole: SketchEntity = { id: "w", kind: "spline", points: [[0, 0], [40, 0], [80, 0], [120, 0]], closed: false, mode: "fit", z: [0, 30, 30, 0] } as SketchEntity; + let n = 0; + const out = splitAny([whole], "w", [60, 0], 1, true, () => `n${++n}`)!; + const [a, b] = out.entities as any[]; + const at = (e: any, i: number) => [e.points[i][0], e.z?.[i]]; + check("split: two pieces, both with heights for each of their points", out.entities.length === 2 && a.z?.length === a.points.length && b.z?.length === b.points.length, JSON.stringify(out.entities.map((e: any) => [e.points.length, e.z]))); + const hA = splineHeightSamples(a)!; + const hB = splineHeightSamples(b)!; + check("split: they meet at the same height, the curve's own there (30 at its top)", near(hA[hA.length - 1], hB[0], 1e-9) && hA[hA.length - 1] > 29 && hA[hA.length - 1] < 34, `${hA[hA.length - 1]} / ${hB[0]}`); + check("split: the far ends are as they were (on the plane)", near(at(a, 0)[1], 0) && near(at(b, b.points.length - 1)[1], 0)); + // A flat one split stays flat (no heights made up). + const flat2 = splitAny([{ ...whole, z: undefined } as SketchEntity], "w", [60, 0], 1, true, () => `m${++n}`)!; + check("split of a flat spline: flat pieces", (flat2.entities as any[]).every((e) => e.z === undefined)); +} + +// A loft's guide through space: a small circle to a bigger one 30 up, along a curve that bows 12 out of its plane. +{ + const lo = sketch("a", XY(), [circle("ca", 0, 0, 3)]); + const hi = sketch("b", XY(30), [circle("cb", 0, 0, 3)]); + const sec = (s: Feature, id: string) => ({ kind: "profile", sketch: s.id, regions: (profile(s.id, [circle(id, 0, 0, 3)]) as any).regions }); + const guide = (z?: number[]): Feature => ({ id: "g", name: "g", type: "sketch", plane: { origin: [0, 0, 0], xDir: [1, 0, 0], normal: [0, -1, 0] }, entities: [{ id: "s", kind: "spline", points: [[0, 0], [0, 10], [0, 20], [0, 30]], closed: false, mode: "fit", ...(z ? { z } : {}) }] }) as unknown as Feature; + const loft = { id: "L", name: "Loft", type: "loft", sections: [sec(lo, "ca"), sec(hi, "cb")], ruled: false, mode: "new", guide: { kind: "sketch", sketch: "g", entities: ["s"] } } as unknown as Feature; + let r = await after([lo, hi, guide(), loft], "L"); + const straight = r.body ? r.body.boundingBox.bounds : null; + check("a loft along a flat guide: a straight rod", !r.err && !!straight && near(straight[0][1], -3, 0.05) && near(straight[1][1], 3, 0.05), r.err ?? JSON.stringify(straight)); + r = await after([lo, hi, guide([0, 12, 12, 0]), loft], "L"); + const bowed = r.body ? r.body.boundingBox.bounds : null; + // (The plane's normal is -Y: 12 off it is 12 towards -Y.) + check("along the same guide bowed 12 off its plane: the rod bows out with it, and is sound", !r.err && !!bowed && bowed[0][1] < -12 && bowed[0][1] > -17 && near(bowed[1][1], 3, 0.6) && health(r.body!).healthy, r.err ?? JSON.stringify(bowed)); +} done(); diff --git a/tests/stepimport.test.ts b/tests/stepimport.test.ts new file mode 100644 index 0000000..3ae21de --- /dev/null +++ b/tests/stepimport.test.ts @@ -0,0 +1,97 @@ +// Run: npx tsx tests/stepimport.test.ts +// STEP files of several solids put in, written the ways other programs write them: in metres, in inches, bodies +// that touch, many bodies, CRLF line ends, a file cut short. Each solid has to come in as a body of its own, the +// right size in millimetres, sound - and each has to be usable afterwards (moved, cut, deleted by itself). +import { after, block, bodies, check, cylinder, done, health, near, volume } from "./kit"; +import { exportBodies } from "../src/kernel/engine"; +import type { Feature } from "../src/doc/types"; +import type { Shape3D } from "replicad"; + +const text = async (fs: Feature[]) => new TextDecoder().decode(new Uint8Array(await (await exportBodies(fs, "step")).arrayBuffer())); +const put = (t: string, id = "In"): Feature => ({ id, name: "Imported", type: "import", format: "step", fileName: "x.step", data: Buffer.from(t, "utf8").toString("base64"), apart: true }) as Feature; +const vols = () => [...bodies().values()].map((b) => volume(b as Shape3D)).sort((a, b) => a - b); +const sound = () => [...bodies().values()].every((b) => health(b as Shape3D).healthy); + +// A block (1000), a cylinder (pi * 16 * 8) sunk 2 into it, a block apart, a block touching the first. +const parts = [...block("A", 20, 10, 5), ...cylinder("C", 4, 8, 10, 5, 3), ...block("B", 4, 4, 4, [100, 0, 0]), ...block("T", 6, 10, 5, [13, 0, 0])]; +const V = [64, 300, Math.PI * 128, 1000].sort((a, b) => a - b); +const mm = await text(parts); +const MILLI = /SI_UNIT\(\s*\.MILLI\.\s*,\s*\.METRE\.\s*\)/g; +// (Each solid of the file has its own units: all of them changed.) +check("the file: four solids, in millimetres", (mm.match(MILLI) ?? []).length >= 1 && (mm.match(/MANIFOLD_SOLID_BREP/g) ?? []).length === 4, `${mm.length} characters`); + +{ + const r = await after([put(mm)]); + const got = vols(); + check("four solids (two touching, one standing on another): four bodies, each its own size, sound", !r.errors.length && got.length === 4 && got.every((v, i) => near(v, V[i], 1e-3)) && sound(), `${got.map((v) => v.toFixed(2))} ${r.errors.join("; ")}`); + check(" named In, In:1, In:2, In:3", [...bodies().keys()].join() === "In,In:1,In:2,In:3", [...bodies().keys()].join()); +} + +// ---- in metres: every length a thousand times as long +{ + const m = mm.replace(MILLI, "SI_UNIT($,.METRE.)"); + const r = await after([put(m)]); + const got = vols(); + check("the same file in metres: four bodies, a thousand times the size each way", !r.errors.length && got.length === 4 && got.every((v, i) => near(v / 1e9, V[i], 1e-3)), `${got.map((v) => (v / 1e9).toFixed(2))} ${r.errors.join("; ")}`); +} + +// ---- in inches (a unit made from another, as most programs write it) +{ + let top = Math.max(...[...mm.matchAll(/#(\d+)\s*=/g)].map((x) => Number(x[1]))); + const unit = /\(\s*LENGTH_UNIT\(\)\s*NAMED_UNIT\(\*\)\s*SI_UNIT\(\s*\.MILLI\.\s*,\s*\.METRE\.\s*\)\s*\)\s*;/g; + const inch = mm.replace(unit, () => { + const [a, b, c] = [++top, ++top, ++top]; + return `( CONVERSION_BASED_UNIT('INCH',#${a}) LENGTH_UNIT() NAMED_UNIT(#${c}) ); +#${a} = LENGTH_MEASURE_WITH_UNIT(LENGTH_MEASURE(25.4),#${b}); +#${b} = ( LENGTH_UNIT() NAMED_UNIT(*) SI_UNIT(.MILLI.,.METRE.) ); +#${c} = DIMENSIONAL_EXPONENTS(1.,0.,0.,0.,0.,0.,0.);`; + }); + const r = await after([put(inch)]); + const got = vols(); + const k = 25.4 ** 3; + check("the same file in inches: four bodies, 25.4 times the size each way", inch !== mm && !r.errors.length && got.length === 4 && got.every((v, i) => near(v / k, V[i], 1e-3)), `${got.map((v) => (v / k).toFixed(2))} ${r.errors.join("; ")}`); +} + +// ---- CRLF line ends, as a file saved on Windows +{ + const r = await after([put(mm.replace(/\r?\n/g, "\r\n"))]); + check("with Windows line ends: the same four", !r.errors.length && vols().length === 4, r.errors.join("; ")); +} + +// ---- each body used by itself afterwards +{ + await after([put(mm)]); + const id = (v: number) => [...bodies().entries()].find(([, b]) => near(volume(b as Shape3D), v, 1e-2))![0]; + const [A, C, B, T] = [id(1000), id(Math.PI * 128), id(64), id(300)]; + const move: Feature = { id: "mv", name: "Move", type: "transform", bodies: [B], copy: false, op: { kind: "move", translate: [0, 0, 50] } } as unknown as Feature; + const cut: Feature = { id: "bo", name: "Subtract", type: "boolean", op: "subtract", target: A, tools: [C] } as unknown as Feature; + const del: Feature = { id: "de", name: "Delete", type: "delete", bodies: [T] } as unknown as Feature; + const r = await after([put(mm), move, cut, del]); + const got = vols(); + check("then one moved, one cut by another (its 2 mm in it), one deleted: two bodies left, the cut one 1000 - 32 pi, sound", !r.errors.length && sound() && got.length === 2 && near(got[0], 64, 1e-3) && near(got[1], 1000 - Math.PI * 32, 1e-2), `${[...bodies().keys()].join()} ${got.map((v) => v.toFixed(2))} ${r.errors.join("; ")}`); +} + +// ---- two files put in: their bodies kept apart by name +{ + const two = await text([...block("P", 2, 2, 2), ...block("Q", 3, 3, 3, [10, 0, 0])]); + const r = await after([put(mm, "In"), put(two, "In2")]); + check("two files: six bodies, none over another's name", !r.errors.length && bodies().size === 6 && new Set(bodies().keys()).size === 6, [...bodies().keys()].join()); +} + +// ---- many bodies +{ + const many: Feature[] = []; + for (let i = 0; i < 40; i++) many.push(...block(`M${i}`, 2 + (i % 5), 3, 1 + (i % 3), [(i % 8) * 12, Math.floor(i / 8) * 12, 0])); + const t = await text(many); + const t0 = performance.now(); + const r = await after([put(t)]); + const want = many.length ? Array.from({ length: 40 }, (_, i) => (2 + (i % 5)) * 3 * (1 + (i % 3))).reduce((s, v) => s + v, 0) : 0; + check("forty solids: forty bodies, their sizes kept", !r.errors.length && bodies().size === 40 && near(vols().reduce((s, v) => s + v, 0), want, 1e-2), `${bodies().size} bodies, ${Math.round(performance.now() - t0)} ms`); +} + +// ---- a file cut short, and one that is not STEP at all: said in plain words +for (const [name, t] of [["cut short", mm.slice(0, Math.floor(mm.length * 0.6))], ["not a STEP file", "hello, this is a text file\n"], ["empty", ""]] as const) { + const r = await after([put(t)]); + check(`a file ${name}: said in plain words, or what could be read is sound`, r.errors.length ? r.errors.every((e) => /STEP|solid|file/i.test(e) && !/null|undefined|memory|exception|\bat \w+\./i.test(e)) : sound(), `${bodies().size} bodies ${r.errors.join("; ")}`); +} +done(); diff --git a/tests/threadclearance.test.ts b/tests/threadclearance.test.ts index 3acc2ab..c1074c4 100644 --- a/tests/threadclearance.test.ts +++ b/tests/threadclearance.test.ts @@ -42,7 +42,47 @@ for (const c of [0.1, 0.2, 0.4]) { 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("; ")); +// A bolt with a head: the thread is on its shank only; the block is cut round shank and head alike. +{ + const head = cylinder("head", 9, 6, 15, 15, 18); + const join: Feature = { id: "j", name: "Union", type: "boolean", op: "union", target: "bolt", tools: ["head"] } as Feature; + const tall = block("blk", 30, 30, 22); + const base = [...tall, ...bolt, ...head, join]; + const r0 = await after(base); + const shank = r0.r.bodies.find((b) => b.id === "bolt")!.faces.find((f) => f.type === "CYLINDRE" && Math.abs((f.round?.r ?? 0) - 5) < 1e-6)!; + const th: Feature = { id: "thr", name: "Thread", type: "thread", face: { body: "bolt", center: shank.center, normal: shank.normal, area: shank.area }, pitch: 1.5 } as Feature; + const rr = await after([...base, th, cut({ clearance: 0.2 })]); + const okk = !rr.errors.length && !!B("blk"); + check("a headed bolt, clearance 0.2: cut, sound, 0.2 off at its nearest", okk && health(B("blk")).healthy && near(gap(B("blk"), B("bolt")), 0.2, 0.01), `${rr.errors.join("; ")} gap ${okk ? gap(B("blk"), B("bolt")).toFixed(4) : "-"}`); + // Something done to the bolt after its thread (a chamfer on the head): it is no longer the thread's own result + // in every part, yet its thread is still there - cut the same way. + const top = rr.r.bodies.find((b) => b.id === "bolt")!; + const rim = top.edges.find((e) => e.type === "CIRCLE" && Math.abs(e.start[2] - 24) < 1e-6 && Math.abs(Math.hypot(e.start[0] - 15, e.start[1] - 15) - 9) < 1e-6)!; + const cham: Feature = { id: "ch", name: "Chamfer", type: "chamfer", edges: [{ body: "bolt", mid: rim.mid, dir: [0, 0, 1], length: rim.length }], radius: 1 } as unknown as Feature; + const r2 = await after([...base, th, cham, cut({ clearance: 0.2 })]); + const ok2 = !r2.errors.length && !!B("blk"); + check("the same with the head chamfered after the thread: cut, or said why in plain words", ok2 ? health(B("blk")).healthy && gap(B("blk"), B("bolt")) > 0.15 : /clear|smaller/i.test(r2.errors.join()), `${r2.errors.join("; ")} gap ${ok2 ? gap(B("blk"), B("bolt")).toFixed(4) : "-"}`); +} + +// A nut (a thread in a hole) used as the cutter of a rod standing in it: the rod gets the outside thread, 0.2 smaller. +{ + const nut = block("nut", 24, 24, 8, [3, 3, 2]); + const hole = cylinder("pin", 4.25, 8, 15, 15, 2); + const bore: Feature = { id: "bore", name: "Subtract", type: "boolean", op: "subtract", target: "nut", tools: ["pin"] } as Feature; + const rod = cylinder("rod", 5, 14, 15, 15, -1); + const r0 = await after([...nut, ...hole, bore]); + const inner = r0.r.bodies.find((b) => b.id === "nut")!.faces.find((f) => f.type === "CYLINDRE")!; + const th: Feature = { id: "nt", name: "Thread", type: "thread", face: { body: "nut", center: inner.center, normal: inner.normal, area: inner.area }, pitch: 1.5 } as Feature; + const c: Feature = { id: "cut", name: "Subtract", type: "boolean", op: "subtract", target: "rod", tools: ["nut"], keepTools: true, clearance: 0.2 } as Feature; + const rr = await after([...nut, ...hole, bore, th, ...rod, c]); + const okk = !rr.errors.length && !!B("rod"); + check("a rod cut by a threaded nut, clearance 0.2: made, sound, 0.2 off the nut at its nearest", okk && health(B("rod")).healthy && near(gap(B("rod"), B("nut")), 0.2, 0.01), `${rr.errors.join("; ")} gap ${okk ? gap(B("rod"), B("nut")).toFixed(4) : "-"}`); +} + +// The clearance taken from the bolt instead of the block ("The others"), and shared between them ("All"). +for (const from of ["tools", "all"] as const) { + r = await after([...blockF, ...bolt, thread, cut({ clearance: 0.2, cutFrom: from })]); + const okk = !r.errors.length && !!B("blk") && !!B("bolt"); + check(`clearance 0.2 taken from ${from === "tools" ? "the bolt" : "both"}: made and 0.2 apart, or said why in plain words`, okk ? gap(B("blk"), B("bolt")) > 0.15 && gap(B("blk"), B("bolt")) < 0.25 : /clear|smaller|thread/i.test(r.errors.join()), `${r.errors.join("; ")} gap ${okk ? gap(B("blk"), B("bolt")).toFixed(4) : "-"}`); +} done();