* inspect.clearance: pairs whose bodies did not change are not measured again Each clearance check measured every close pair again, though between two checks usually only a few bodies change or move. Results are now kept per pair, keyed by both bodies' geometry and placement and the check's settings; a pair whose two bodies are unchanged is taken from that cache. With 40 overlapping parts, a check after moving one of them took 0.8 s instead of 23 s (741 of 780 pairs reused). Pairs that could not be worked out are tried again each time. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * inspect.clearance: boxes and placed keys exactly as before the reuse The pair boxes are taken over the mesh's triangles with finite corners, as a distance shape's are, so pruning is unchanged. A placed body's identity now includes its model body's own frame, so two placements are never mistaken for one another. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * inspect.clearance: a large body is meshed once for all its pairs Each pair that touches cuts the larger body down to the pair's region with a kernel boolean, and that boolean meshed the whole body twice: once for its checks and once inside the intersection. A sheet with 600 faces paid about 2.5 s per pair for meshes that were the same every time. A body can now keep its meshes for reuse (Body::keeping_meshes); its booleans take the meshes from there, and the intersection takes its shell meshes from there too (truck-shapeops: and_with_history_meshed). Clearance uses such copies for one check. Results are unchanged to the bit. On a 3 x 2 m sheet with bends and 300 holes, the clip took 0.23 s per pair instead of 2.6 s, and 24 rivets took 5.6 s instead of 16.5 s. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * inspect.clearance: pins on one cylinder with their hole are answered or reported in seconds A pin seated line to line in its hole, on its axis, and with a blend running into its wall (a fillet under a head) sent the boolean through minutes of retries that ended unchecked; a pin a hair off its hole's axis was passed as clear. Clearance now asks first whether the pair holds such a pin (from the faces' surfaces alone). On its axis the boolean gets a few tries, which answer plain pins at once; a hair off, or when those tries fail, the shared volume is worked out apart by coaxial_overlap, which now also takes the zero-offset, equal-radius case, moves the hole's wall when a blend keeps the pin's from moving, and checks its band more tightly. What neither answers is reported as unchecked, naming the pin. The kernel gains with_attempt_budget: the booleans run inside it get a number of tries of the kernel's own intersection between them, the same on every machine. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * inspect.clearance: the pin tests sit beside the other measured pairs, not at the file's end Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * inspect.clearance: the bodies left whole meet their booleans with their meshes kept A body that meets several others at one size (a bracket with balls pressed into it) was meshed again for each pair's intersect: only the clipping used the copies that keep their meshes. The intersect, the pin work and the union check now take those copies too. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * Near-coaxial overlap: ten tries per intersection, enough for a flush head pulled back #1984's headed pin made before its plate needs more than eight. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Aac7mP9rthK3WsPpPRvCsF --------- Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Co-authored-by: bherbruck <brennen.herbruck@gmail.com>
687 lines
32 KiB
Rust
687 lines
32 KiB
Rust
//! The shared volume of a pin in a hole of (nearly) its own size whose axis is a hair off the
|
|
//! hole's (parts placed from rounded coordinates), or on it: a pin seated line to line.
|
|
//!
|
|
//! The pin's wall and the hole's wall then meet along two lines where they are all but tangent,
|
|
//! or lie on one another, which the boolean cannot intersect, and the facets of the two walls pass through each other
|
|
//! by less than the boolean's sampled shortcuts can see. So the overlap is worked out in two
|
|
//! parts instead. The pin's wall is moved off the hole's by a clear step (`offset_body`; where a
|
|
//! blend running into the pin's wall keeps it from moving, the hole's wall is moved instead) and the
|
|
//! bodies are intersected as they then are, which the boolean can do: narrowed, that gives the
|
|
//! overlap away from the walls (the core). In the band the move swept, what the two walls
|
|
//! share is a crescent in every section, whose area follows from the two circles alone. The
|
|
//! band is assumed to hold nothing but the two walls; that is checked by intersecting with the
|
|
//! pin widened by half the step and by the whole step, whose volumes must come out as the core
|
|
//! plus the crescents those wider circles give. Where they don't (a cross hole through the
|
|
//! band, a hole that is not round all the way, a pin end inside the hole), the overlap is not
|
|
//! answered here and the caller takes the general boolean.
|
|
|
|
use solidcraft_geom::{Aabb3, UnitVec3, Vec3};
|
|
|
|
use crate::body::Body;
|
|
use crate::{BoolOp, FaceSurface};
|
|
|
|
/// The overlap of two bodies with a pin of one in a hole of the other, worked out as above.
|
|
#[derive(Clone, Debug)]
|
|
pub struct CoaxialOverlap {
|
|
pub volume: f64,
|
|
/// Approximate: the core's area plus the crescents' walls and ends.
|
|
pub area: f64,
|
|
pub centroid: Vec3,
|
|
pub bbox: Aabb3,
|
|
/// The largest offset between a pin's axis and its hole's, and the length they share.
|
|
pub offset: f64,
|
|
pub length: f64,
|
|
}
|
|
|
|
/// Largest axis offset plus radius difference handled, as a share of the radius.
|
|
const NEAR: f64 = 0.01;
|
|
/// The step the pin's wall is moved by, as a share of its radius.
|
|
const STEP: f64 = 0.1;
|
|
/// The tries each intersection here gets: with a wall moved clear it takes one or two, and a
|
|
/// few more where a flush face is pulled back or the tool is nudged by a hair; one that needs
|
|
/// more than that meets something this work does not cover.
|
|
const ATTEMPTS: usize = 10;
|
|
|
|
/// The faces of one body on one cylinder, the side its material is on and their extent along
|
|
/// the axis.
|
|
#[derive(Clone, Debug)]
|
|
struct Wall {
|
|
faces: Vec<usize>,
|
|
origin: Vec3,
|
|
axis: UnitVec3,
|
|
radius: f64,
|
|
/// Material inside the cylinder (a pin), not outside it (a hole).
|
|
boss: bool,
|
|
/// Intervals along `axis` from `origin`, one per face.
|
|
spans: Vec<(f64, f64)>,
|
|
}
|
|
|
|
/// A pin of one body (`pin_in_a`) in a hole of the other, and the length they share.
|
|
#[derive(Clone, Debug)]
|
|
struct Pair {
|
|
pin: Wall,
|
|
pin_in_a: bool,
|
|
hole: Wall,
|
|
/// The hole's axis seen from the pin's, across it, and how far.
|
|
toward: Vec3,
|
|
offset: f64,
|
|
/// Where they share length along the pin's axis.
|
|
shared: Vec<(f64, f64)>,
|
|
step: f64,
|
|
}
|
|
|
|
/// The overlap of `a` and `b` when a pin of one sits in a hole of the other on nearly the same
|
|
/// cylinder (axes parallel, offset plus radius difference within 1 % of the radius, none for a
|
|
/// pin seated line to line), worked out as the module says. `None` when there is no such pin, or the
|
|
/// bodies hold more than the pin and the hole where the work assumes they don't: the caller
|
|
/// then takes the general boolean.
|
|
pub fn coaxial_overlap(a: &Body, b: &Body) -> Option<CoaxialOverlap> {
|
|
if a.is_mesh() || b.is_mesh() {
|
|
return None;
|
|
}
|
|
// The boolean that takes the core can fail in one order of the bodies and not the other.
|
|
crate::guard("near-coaxial overlap", || Ok(overlap(a, b).or_else(|| overlap(b, a)))).ok().flatten()
|
|
}
|
|
|
|
/// Whether a cylinder of `a` and one of `b` are on one cylinder or nearly (what
|
|
/// [`coaxial_overlap`] asks first, from the faces' surfaces alone): a cheap test for whether
|
|
/// it is worth preparing the bodies for it. `Some(true)` when every such pair is on one cylinder
|
|
/// within the kernel's same-surface tolerance, which the boolean takes as one wall; `Some(false)`
|
|
/// when one is a hair off, which it cannot intersect and may even pass as clear.
|
|
pub fn coaxial_candidate(a: &Body, b: &Body) -> Option<bool> {
|
|
if a.is_mesh() || b.is_mesh() {
|
|
return None;
|
|
}
|
|
crate::guard("near-coaxial candidate", || {
|
|
let same = same_surface(a.size().max(b.size()));
|
|
let (ca, cb) = (cylinders(a), cylinders(b));
|
|
let mut found = None;
|
|
for x in &ca {
|
|
for y in &cb {
|
|
if x.axis.dot(y.axis).abs() <= 1.0 - 1e-9 {
|
|
continue;
|
|
}
|
|
if let Some((_, offset)) = near(x, y) {
|
|
let one = offset + (x.radius - y.radius).abs() <= same;
|
|
found = Some(found.unwrap_or(true) && one);
|
|
}
|
|
}
|
|
}
|
|
Ok(found)
|
|
})
|
|
.ok()
|
|
.flatten()
|
|
}
|
|
|
|
/// The distance within which the kernel takes two surfaces as one, for bodies of `size`.
|
|
fn same_surface(size: f64) -> f64 {
|
|
(size * 1e-7).max(1e-9) * 10.0
|
|
}
|
|
|
|
fn overlap(a: &Body, b: &Body) -> Option<CoaxialOverlap> {
|
|
let size = a.size().max(b.size());
|
|
if !(size.is_finite() && size > 0.0) {
|
|
return None;
|
|
}
|
|
// The same surface as the kernel takes it elsewhere: walls that close are one wall.
|
|
let same = same_surface(size);
|
|
// Meshed only when two cylinders are close enough to be asked about.
|
|
let (ca, cb) = (cylinders(a), cylinders(b));
|
|
let close = |x: &Wall, y: &Wall| x.axis.dot(y.axis).abs() > 1.0 - 1e-9 && near(x, y).is_some();
|
|
if !ca.iter().any(|x| cb.iter().any(|y| close(x, y))) {
|
|
return None;
|
|
}
|
|
// A wall that runs once round along a seam edge (as STEP files have them) is cut in two
|
|
// first: the boolean cannot always intersect it whole.
|
|
let (sa, sb) = (crate::step_in::split::split_seams(a), crate::step_in::split::split_seams(b));
|
|
let (ca, cb) = match (&sa, &sb) {
|
|
(None, None) => (ca, cb),
|
|
_ => (sa.as_ref().map_or(ca, cylinders), sb.as_ref().map_or(cb, cylinders)),
|
|
};
|
|
let (a, b) = (sa.as_ref().unwrap_or(a), sb.as_ref().unwrap_or(b));
|
|
let (wa, wb) = (walls(a, ca, same)?, walls(b, cb, same)?);
|
|
let mut pairs = Vec::new();
|
|
for x in &wa {
|
|
for y in &wb {
|
|
if x.axis.dot(y.axis).abs() <= 1.0 - 1e-9 {
|
|
continue;
|
|
}
|
|
let (pin, hole, pin_in_a) = match (x.boss, y.boss) {
|
|
(true, false) => (x, y, true),
|
|
(false, true) => (y, x, false),
|
|
// Two pins or two holes on nearly one cylinder, side by side along it: not this
|
|
// case. Apart along the axis (a screw's head beside a bush of its radius), they
|
|
// don't meet.
|
|
_ if near(x, y).is_some() && total(&intersect(&union(&x.spans), &union(&project(y, x)))) > same => return None,
|
|
_ => continue,
|
|
};
|
|
let Some((toward, offset)) = near(pin, hole) else { continue };
|
|
let shared = intersect(&union(&pin.spans), &union(&project(hole, pin)));
|
|
if total(&shared) <= same {
|
|
continue;
|
|
}
|
|
let step = (pin.radius * STEP).min(size * 0.02);
|
|
// Within the kernel's same-surface tolerance the two walls are one: no crescent.
|
|
let mut hole = hole.clone();
|
|
let offset = if offset + (pin.radius - hole.radius).abs() <= same {
|
|
hole.radius = pin.radius;
|
|
0.0
|
|
} else {
|
|
offset
|
|
};
|
|
pairs.push(Pair { pin: pin.clone(), pin_in_a, hole, toward, offset, shared, step });
|
|
}
|
|
}
|
|
if pairs.is_empty() {
|
|
return None;
|
|
}
|
|
// A pin's face flush against the other body (a rivet's head on the sheet) touches it over
|
|
// an area, which the boolean cannot always take: it is pulled back off it by a little.
|
|
// Only material outside the other body goes, so the overlap is the same.
|
|
let back = pairs.iter().map(|p| p.step).fold(f64::INFINITY, f64::min) * 0.05;
|
|
let flat = (flush(a, b, same, back), flush(b, a, same, back), back);
|
|
// The pin's wall is moved where its neighbours let it; where they don't (a blend running
|
|
// into it), the hole's wall is moved away from the pin instead.
|
|
let stuck = std::cell::Cell::new(false);
|
|
answer(a, b, &pairs, size, &flat, false, &stuck).or_else(|| if stuck.get() { answer(a, b, &pairs, size, &flat, true, &stuck) } else { None })
|
|
}
|
|
|
|
/// The overlap of the `pairs` worked out with each pin's wall moved by steps, or each hole's
|
|
/// (`move_hole`); `stuck` set when a body could not be moved. `flat` holds the faces of `a`
|
|
/// and of `b` that touch the other flat, and how far they are pulled back off it.
|
|
fn answer(
|
|
a: &Body,
|
|
b: &Body,
|
|
pairs: &[Pair],
|
|
size: f64,
|
|
flat: &(Vec<usize>, Vec<usize>, f64),
|
|
move_hole: bool,
|
|
stuck: &std::cell::Cell<bool>,
|
|
) -> Option<CoaxialOverlap> {
|
|
let (fa, fb, back) = (&flat.0, &flat.1, flat.2);
|
|
// The pin's and the hole's radius with the moved wall `k` steps toward the other.
|
|
let radii = |p: &Pair, k: f64| if move_hole { (p.pin.radius, p.hole.radius - p.step * k) } else { (p.pin.radius + p.step * k, p.hole.radius) };
|
|
// A wall's faces move together: one step for each of them (a wall does not repeat across
|
|
// pairs unless one pin is near two holes, which the check below then answers).
|
|
let shared_at = |k: f64| -> Option<(f64, Option<Body>)> {
|
|
let moved = |body: &Body, in_a: bool| -> Option<Body> {
|
|
let mine: Vec<(&Wall, f64)> = pairs
|
|
.iter()
|
|
.filter_map(|p| match (move_hole, p.pin_in_a == in_a) {
|
|
(false, true) => Some((&p.pin, p.step)),
|
|
(true, false) => Some((&p.hole, p.step)),
|
|
_ => None,
|
|
})
|
|
.collect();
|
|
if mine.is_empty() {
|
|
return Some(body.clone());
|
|
}
|
|
let flush = if in_a { fa } else { fb };
|
|
let shift = |i: usize, _| match mine.iter().find(|(w, _)| w.faces.contains(&i)) {
|
|
Some((_, step)) => step * k,
|
|
None if flush.contains(&i) => -back,
|
|
None => 0.0,
|
|
};
|
|
let m = crate::offset::offset_body(body, shift).ok().filter(|m| m.validity().is_empty());
|
|
if m.is_none() {
|
|
stuck.set(true);
|
|
}
|
|
m
|
|
};
|
|
let (ma, mb) = (moved(a, true)?, moved(b, false)?);
|
|
let (r, report) =
|
|
crate::capture_boolean_diagnostics(|| crate::ops::with_attempt_budget(ATTEMPTS, || crate::ops::boolean(&ma, &mb, BoolOp::Intersect)));
|
|
// The core is the answer and must be exact. The wider pins only check the band, to
|
|
// 2 % of what it gains: a tool nudged by a hair of the step there is as good.
|
|
let nudge = if k > 0.0 { pairs.iter().map(|p| p.step).fold(f64::INFINITY, f64::min) * 1e-2 } else { 0.0 };
|
|
if report.unverified().is_some() || !altered_by_at_most(&report, nudge, size) {
|
|
return None;
|
|
}
|
|
match r.ok()? {
|
|
None => Some((0.0, None)),
|
|
Some(body) => Some((crate::measure(&body).ok()?.volume, Some(body))),
|
|
}
|
|
};
|
|
// The crescents' area along each pair with the moved walls `k` steps toward each other.
|
|
let crescent_at = |p: &Pair, k: f64| {
|
|
let (r, h) = radii(p, k);
|
|
crescent(r, h, p.offset).area
|
|
};
|
|
let crescents = |k: f64| -> f64 { pairs.iter().map(|p| total(&p.shared) * crescent_at(p, k)).sum() };
|
|
let (core, core_body) = shared_at(-1.0)?;
|
|
for k in [0.5, 1.0] {
|
|
let (v, _) = shared_at(k)?;
|
|
let gain = crescents(k) - crescents(-1.0);
|
|
if !((v - core - gain).abs() <= 0.002 * gain + 1e-4 * v.abs() + 1e-12 * size.powi(3)) {
|
|
return None;
|
|
}
|
|
}
|
|
// The band held the two walls only: the overlap is the core plus the crescents.
|
|
let mut volume = core;
|
|
let mut moment = Vec3::ZERO;
|
|
let mut area = 0.0;
|
|
let mut bbox = Aabb3::EMPTY;
|
|
if let Some(body) = &core_body
|
|
&& let Ok(m) = crate::measure(body)
|
|
{
|
|
moment = m.centroid * m.volume;
|
|
area = m.area;
|
|
bbox = m.bbox;
|
|
volume = m.volume;
|
|
}
|
|
for p in pairs {
|
|
let c = crescent(p.pin.radius, p.hole.radius, p.offset);
|
|
let length = total(&p.shared);
|
|
// Less what the moved walls already shared (nothing, unless the hole is the smaller).
|
|
let v = length * (c.area - crescent_at(p, -1.0));
|
|
let mid = p.shared.iter().map(|(s, t)| (s + t) * 0.5 * (t - s)).sum::<f64>() / length;
|
|
let side = p.toward.cross(p.pin.axis);
|
|
moment += (p.pin.origin + p.pin.axis * mid + p.toward * c.centroid) * v;
|
|
volume += v;
|
|
area += p.shared.len() as f64 * 2.0 * c.area + length * c.perimeter;
|
|
for (s, t) in &p.shared {
|
|
for q in crescent_outline(p.pin.radius, p.hole.radius, p.offset) {
|
|
let at = p.pin.origin + p.toward * q.0 + side * q.1;
|
|
bbox.add(at + p.pin.axis * *s);
|
|
bbox.add(at + p.pin.axis * *t);
|
|
}
|
|
}
|
|
}
|
|
let centroid = if volume > 0.0 { moment / volume } else { bbox.center() };
|
|
let offset = pairs.iter().map(|p| p.offset).fold(0.0, f64::max);
|
|
let length = pairs.iter().map(|p| total(&p.shared)).sum();
|
|
Some(CoaxialOverlap { volume: volume.max(0.0), area, centroid, bbox, offset, length })
|
|
}
|
|
|
|
/// Whether every retry of a boolean that can change its result moved the tool by at most
|
|
/// `limit` (a rotation counted at the bodies' `size` from its pivot): none for a `limit` of 0.
|
|
fn altered_by_at_most(report: &crate::BooleanDiagnostics, limit: f64, size: f64) -> bool {
|
|
!report.truncated
|
|
&& report
|
|
.events
|
|
.iter()
|
|
.filter(|e| e.strategy.alters_result())
|
|
.all(|e| e.strategy == crate::BooleanStrategy::ToolNudge && limit > 0.0 && e.translation_mm + e.rotation_rad * size <= limit)
|
|
}
|
|
|
|
/// The pin's offset to the hole, when the two are on one cylinder or nearly: the unit direction
|
|
/// from the pin's axis to the hole's (any, for one axis) and the distance.
|
|
fn near(pin: &Wall, hole: &Wall) -> Option<(Vec3, f64)> {
|
|
let d = hole.origin - pin.origin;
|
|
let across = d - pin.axis * d.dot(pin.axis);
|
|
let offset = across.len();
|
|
let gap = (pin.radius - hole.radius).abs();
|
|
if !(offset + gap <= NEAR * pin.radius.min(hole.radius)) {
|
|
return None;
|
|
}
|
|
let toward = across.normalized().unwrap_or_else(|| pin.axis.any_perp());
|
|
Some((toward, offset))
|
|
}
|
|
|
|
/// The planar faces of `x` that lie on a face of `y`'s facing the other way, where the two touch
|
|
/// flat: on a plane of `y`'s, with `y` just beyond the face and not just behind it (within
|
|
/// `depth`, at every sampled facet of it). A face on such a plane elsewhere (a collar's
|
|
/// underside inside the other body, level with a pocket's floor) is not one.
|
|
fn flush(x: &Body, y: &Body, same: f64, depth: f64) -> Vec<usize> {
|
|
let planes = |b: &Body| -> Vec<(usize, Vec3, Vec3)> {
|
|
(0..b.face_count())
|
|
.filter_map(|i| match crate::face_surface(b, i)? {
|
|
FaceSurface::Plane { normal, point } => Some((i, normal.vec(), point)),
|
|
_ => None,
|
|
})
|
|
.collect()
|
|
};
|
|
let theirs = planes(y);
|
|
let level: Vec<(usize, Vec3)> = planes(x)
|
|
.into_iter()
|
|
.filter(|(_, n, p)| theirs.iter().any(|(_, m, q)| n.dot(*m) < -1.0 + 1e-9 && (*q - *p).dot(*n).abs() <= same))
|
|
.map(|(i, n, _)| (i, n))
|
|
.collect();
|
|
if level.is_empty() || !(depth.is_finite() && depth > 0.0) {
|
|
return Vec::new();
|
|
}
|
|
let tol = (x.size().max(y.size()) * 2e-3).max(1e-4);
|
|
let (Ok(mx), Ok(my)) = (x.tessellate(tol), y.tessellate(tol)) else { return Vec::new() };
|
|
// At most this many facets of a face are sampled.
|
|
const SAMPLES: usize = 64;
|
|
level
|
|
.into_iter()
|
|
.filter(|&(i, n)| {
|
|
let centres: Vec<Vec3> = mx
|
|
.triangles
|
|
.iter()
|
|
.zip(&mx.tri_face)
|
|
.filter(|(_, f)| **f as usize == i)
|
|
.filter_map(|(t, _)| mx.tri(t))
|
|
.filter(|[a, b, c]| (*b - *a).cross(*c - *a).len() > 0.0)
|
|
.map(|[a, b, c]| (a + b + c) / 3.0)
|
|
.collect();
|
|
let stride = centres.len().div_ceil(SAMPLES).max(1);
|
|
!centres.is_empty() && centres.iter().step_by(stride).all(|c| my.contains(*c + n * depth) && !my.contains(*c - n * depth))
|
|
})
|
|
.map(|(i, _)| i)
|
|
.collect()
|
|
}
|
|
|
|
/// The body's cylindrical faces, each as a wall of its own with no side or extent yet.
|
|
fn cylinders(b: &Body) -> Vec<Wall> {
|
|
(0..b.face_count())
|
|
.filter_map(|i| match crate::face_surface(b, i)? {
|
|
FaceSurface::Cylinder { origin, axis, radius } if origin.is_finite() && radius.is_finite() && radius > 0.0 => {
|
|
Some(Wall { faces: vec![i], origin, axis, radius, boss: false, spans: Vec::new() })
|
|
}
|
|
_ => None,
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
/// The cylindrical walls of a body from its `cylinders`: its faces on each cylinder, which side
|
|
/// its material is on and where they run along the axis. `None` when the body can't be meshed.
|
|
fn walls(b: &Body, cylinders: Vec<Wall>, same: f64) -> Option<Vec<Wall>> {
|
|
let mut out: Vec<Wall> = Vec::new();
|
|
let mesh = b.tessellate_with((b.size() * 1e-3).max(1e-4), true).ok()?;
|
|
for Wall { faces, origin, axis, radius, .. } in cylinders {
|
|
let Some(&face) = faces.first() else { continue };
|
|
// Which way the face looks: out of the axis for a pin, toward it for a hole.
|
|
let (mut facing, mut lo, mut hi) = (0.0, f64::INFINITY, f64::NEG_INFINITY);
|
|
for (t, f) in mesh.triangles.iter().zip(&mesh.tri_face) {
|
|
if *f as usize != face {
|
|
continue;
|
|
}
|
|
let Some([p, q, r]) = mesh.tri(t) else { continue };
|
|
let c = (p + q + r) / 3.0;
|
|
let radial = (c - origin) - axis * (c - origin).dot(axis);
|
|
facing += (q - p).cross(r - p).dot(radial);
|
|
for x in [p, q, r] {
|
|
let s = (x - origin).dot(axis);
|
|
lo = lo.min(s);
|
|
hi = hi.max(s);
|
|
}
|
|
}
|
|
if !(lo < hi) || facing == 0.0 {
|
|
continue;
|
|
}
|
|
let boss = facing > 0.0;
|
|
let wall = Wall { faces: vec![face], origin, axis, radius, boss, spans: vec![(lo, hi)] };
|
|
match out.iter_mut().find(|w| w.boss == boss && on_one_cylinder(w, &wall, same)) {
|
|
Some(w) => {
|
|
// Where the face's origin lies along the wall's axis; a face whose axis runs the
|
|
// other way measures its span backwards from there.
|
|
let s = (origin - w.origin).dot(w.axis);
|
|
let (a, b) = if axis.dot(w.axis) < 0.0 { (-hi, -lo) } else { (lo, hi) };
|
|
w.faces.push(face);
|
|
w.spans.push((a + s, b + s));
|
|
}
|
|
None => out.push(wall),
|
|
}
|
|
}
|
|
Some(out)
|
|
}
|
|
|
|
fn on_one_cylinder(x: &Wall, y: &Wall, same: f64) -> bool {
|
|
let d = y.origin - x.origin;
|
|
x.axis.dot(y.axis).abs() > 1.0 - 1e-9 && (x.radius - y.radius).abs() < same && (d - x.axis * d.dot(x.axis)).len() < same
|
|
}
|
|
|
|
/// `wall`'s spans along `onto`'s axis.
|
|
fn project(wall: &Wall, onto: &Wall) -> Vec<(f64, f64)> {
|
|
let flip = wall.axis.dot(onto.axis) < 0.0;
|
|
let s = (wall.origin - onto.origin).dot(onto.axis);
|
|
wall.spans.iter().map(|&(lo, hi)| if flip { (s - hi, s - lo) } else { (s + lo, s + hi) }).collect()
|
|
}
|
|
|
|
/// Sorted, disjoint intervals covering `spans`.
|
|
fn union(spans: &[(f64, f64)]) -> Vec<(f64, f64)> {
|
|
let mut v: Vec<(f64, f64)> = spans.iter().copied().filter(|(a, b)| a < b).collect();
|
|
v.sort_by(|x, y| x.0.total_cmp(&y.0));
|
|
let mut out: Vec<(f64, f64)> = Vec::with_capacity(v.len());
|
|
for (a, b) in v {
|
|
match out.last_mut() {
|
|
Some(last) if a <= last.1 => last.1 = last.1.max(b),
|
|
_ => out.push((a, b)),
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
fn intersect(x: &[(f64, f64)], y: &[(f64, f64)]) -> Vec<(f64, f64)> {
|
|
let mut out = Vec::new();
|
|
for &(a, b) in x {
|
|
for &(c, d) in y {
|
|
let (lo, hi) = (a.max(c), b.min(d));
|
|
if lo < hi {
|
|
out.push((lo, hi));
|
|
}
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
fn total(spans: &[(f64, f64)]) -> f64 {
|
|
spans.iter().map(|(a, b)| b - a).sum()
|
|
}
|
|
|
|
/// The part of a disc of radius `pin` outside a disc of radius `hole` whose centre is `offset`
|
|
/// away along +x: its area, its centroid's x (y is 0) and its perimeter.
|
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
|
pub(crate) struct Crescent {
|
|
pub(crate) area: f64,
|
|
pub(crate) centroid: f64,
|
|
pub(crate) perimeter: f64,
|
|
}
|
|
|
|
pub(crate) fn crescent(pin: f64, hole: f64, offset: f64) -> Crescent {
|
|
use std::f64::consts::PI;
|
|
let (r, q, e) = (pin.max(0.0), hole.max(0.0), offset.abs());
|
|
let disc = PI * r * r;
|
|
if e >= r + q {
|
|
return Crescent { area: disc, centroid: 0.0, perimeter: 2.0 * PI * r };
|
|
}
|
|
if e <= (r - q).abs() {
|
|
return if q >= r {
|
|
Crescent { area: 0.0, centroid: 0.0, perimeter: 0.0 }
|
|
} else {
|
|
let area = disc - PI * q * q;
|
|
Crescent { area, centroid: -PI * q * q * e / area, perimeter: 2.0 * PI * (r + q) }
|
|
};
|
|
}
|
|
// Half-angles of the lens's two segments, seen from each centre.
|
|
let alpha = ((e * e + r * r - q * q) / (2.0 * e * r)).clamp(-1.0, 1.0).acos();
|
|
let beta = ((e * e + q * q - r * r) / (2.0 * e * q)).clamp(-1.0, 1.0).acos();
|
|
let segment = |radius: f64, half: f64| {
|
|
let area = radius * radius * (half - half.sin() * half.cos());
|
|
let w = 2.0 * half - (2.0 * half).sin();
|
|
let from_centre = if w > 1e-12 { 4.0 * radius * half.sin().powi(3) / (3.0 * w) } else { radius };
|
|
(area, from_centre)
|
|
};
|
|
let (sa, da) = segment(r, alpha);
|
|
let (sb, db) = segment(q, beta);
|
|
let lens = sa + sb;
|
|
let area = (disc - lens).max(0.0);
|
|
let moment = -(sa * da + sb * (e - db));
|
|
let centroid = if area > 0.0 { moment / area } else { 0.0 };
|
|
Crescent { area, centroid, perimeter: r * (2.0 * PI - 2.0 * alpha) + q * 2.0 * beta }
|
|
}
|
|
|
|
/// Points around the crescent's outline (x toward the hole's centre, y across), for its box.
|
|
fn crescent_outline(pin: f64, hole: f64, offset: f64) -> Vec<(f64, f64)> {
|
|
let (r, q, e) = (pin, hole, offset);
|
|
let alpha = if e > 0.0 { ((e * e + r * r - q * q) / (2.0 * e * r)).clamp(-1.0, 1.0).acos() } else { 0.0 };
|
|
let n = 32;
|
|
(0..=n)
|
|
.map(|i| {
|
|
let t = alpha + (2.0 * std::f64::consts::PI - 2.0 * alpha) * f64::from(i) / f64::from(n);
|
|
(r * t.cos(), r * t.sin())
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
/// The crescent against the textbook lens of two equal circles, and its limits.
|
|
#[test]
|
|
fn crescent_matches_the_lens_formula() {
|
|
let (r, e) = (3.0f64, 0.01f64);
|
|
let lens = 2.0 * r * r * (e / (2.0 * r)).acos() - e / 2.0 * (4.0 * r * r - e * e).sqrt();
|
|
let c = crescent(r, r, e);
|
|
assert!((c.area - (std::f64::consts::PI * r * r - lens)).abs() < 1e-12, "{c:?}");
|
|
// Thin: twice the radius times the offset, its centroid π/4 of the radius away from
|
|
// the hole's centre, its outline nearly two half circles.
|
|
assert!((c.area - 2.0 * r * e).abs() < 1e-6, "{c:?}");
|
|
assert!((c.centroid + std::f64::consts::FRAC_PI_4 * r).abs() < 1e-2, "{c:?}");
|
|
assert!((c.perimeter - 2.0 * std::f64::consts::PI * r).abs() < 1e-3, "{c:?}");
|
|
assert_eq!(crescent(r, r, 0.0).area, 0.0);
|
|
// A pin with clearance in its hole shares nothing; a pin wider than its hole a ring.
|
|
assert_eq!(crescent(2.99, 3.0, 0.005).area, 0.0);
|
|
let ring = crescent(3.01, 3.0, 0.0);
|
|
assert!((ring.area - std::f64::consts::PI * (3.01f64.powi(2) - 9.0)).abs() < 1e-12, "{ring:?}");
|
|
}
|
|
|
|
/// A 20 x 20 x 5 plate with a hole of radius 3 through it, and a pin of radius `pin` through
|
|
/// the hole, `offset` off its axis along X.
|
|
fn plate_and_pin(pin: f64, offset: f64) -> (Body, Body) {
|
|
let block = crate::box_solid(Vec3::new(-10.0, -10.0, 0.0), Vec3::new(10.0, 10.0, 5.0)).unwrap();
|
|
let drill = crate::cylinder(Vec3::new(0.0, 0.0, -2.0), Vec3::Z, 3.0, 9.0).unwrap();
|
|
let plate = crate::boolean(&block, &drill, BoolOp::Cut).unwrap().unwrap();
|
|
(plate, crate::cylinder(Vec3::new(offset, 0.0, -2.0), Vec3::Z, pin, 9.0).unwrap())
|
|
}
|
|
|
|
/// The pin shares a crescent with the plate over the plate's thickness, in either order.
|
|
#[test]
|
|
fn a_pin_off_its_hole_shares_a_crescent() {
|
|
let (plate, pin) = plate_and_pin(3.0, 0.01);
|
|
let want = 5.0 * crescent(3.0, 3.0, 0.01).area;
|
|
for (x, y) in [(&plate, &pin), (&pin, &plate)] {
|
|
let o = coaxial_overlap(x, y).unwrap();
|
|
assert!((o.volume - want).abs() < 1e-6 * want, "{o:?} {want}");
|
|
assert!((o.offset - 0.01).abs() < 1e-9 && (o.length - 5.0).abs() < 1e-9, "{o:?}");
|
|
// The crescent is on the pin's side away from the hole's axis (+X).
|
|
assert!(o.centroid.x > 2.0 && o.bbox.min.z > -1e-9 && o.bbox.max.z < 5.0 + 1e-9, "{o:?}");
|
|
}
|
|
}
|
|
|
|
/// A pin with clearance all round, though off the axis, shares nothing.
|
|
#[test]
|
|
fn a_pin_with_clearance_shares_nothing() {
|
|
let (plate, pin) = plate_and_pin(2.995, 0.003);
|
|
let o = coaxial_overlap(&plate, &pin).unwrap();
|
|
assert!(o.volume < 1e-9, "{o:?}");
|
|
}
|
|
|
|
/// A slot through the hole's wall where the crescent would be: the band holds more than the
|
|
/// two walls, the widened pin says so, and the pair is left to the boolean.
|
|
#[test]
|
|
fn a_slot_through_the_band_is_left_to_the_boolean() {
|
|
let (plate, pin) = plate_and_pin(3.0, 0.01);
|
|
let slot = crate::box_solid(Vec3::new(2.5, -1.0, -1.0), Vec3::new(4.0, 1.0, 6.0)).unwrap();
|
|
let slotted = crate::boolean(&plate, &slot, BoolOp::Cut).unwrap().unwrap();
|
|
assert!(coaxial_overlap(&slotted, &pin).is_none());
|
|
// So it is for a pin on the very axis; one far off it isn't asked about.
|
|
assert!(coaxial_overlap(&slotted, &plate_and_pin(3.0, 0.0).1).is_none());
|
|
assert!(coaxial_overlap(&plate, &plate_and_pin(3.0, 0.5).1).is_none());
|
|
}
|
|
|
|
/// A pin seated line to line, on the hole's very axis: the walls share nothing, and a head
|
|
/// sunk 0.2 into the plate's face shares the ring under it.
|
|
#[test]
|
|
fn a_pin_seated_line_to_line_shares_only_what_its_head_sinks() {
|
|
let (plate, pin) = plate_and_pin(3.0, 0.0);
|
|
for (x, y) in [(&plate, &pin), (&pin, &plate)] {
|
|
let o = coaxial_overlap(x, y).unwrap();
|
|
assert!(o.volume < 1e-9 && o.offset < 1e-9 && (o.length - 5.0).abs() < 1e-9, "{o:?}");
|
|
}
|
|
let head = crate::cylinder(Vec3::new(0.0, 0.0, 4.8), Vec3::Z, 5.0, 2.0).unwrap();
|
|
let headed = crate::boolean(&pin, &head, BoolOp::Union).unwrap().unwrap();
|
|
let want = std::f64::consts::PI * (5.0f64.powi(2) - 3.0f64.powi(2)) * 0.2;
|
|
let o = coaxial_overlap(&plate, &headed).unwrap();
|
|
// Measured off the core's mesh, as a boolean's result is.
|
|
assert!((o.volume - want).abs() < 1e-4 * want, "{o:?} {want}");
|
|
assert!((o.centroid.z - 4.9).abs() < 1e-6, "{o:?}");
|
|
}
|
|
|
|
/// A bush and a headed screw whose shank ends inside the bore, both written to STEP and
|
|
/// read back: their cylinders come back as one face each that runs once round along a seam
|
|
/// edge, which the boolean cannot intersect where the shank's end meets the bore. The
|
|
/// walls are cut in two first and the answer is the one of the bodies as built.
|
|
#[test]
|
|
fn a_screw_in_a_bush_after_a_step_round_trip() {
|
|
let e = 0.01;
|
|
let outer = crate::cylinder(Vec3::ZERO, Vec3::Z, 5.0, 10.0).unwrap();
|
|
let bore = crate::cylinder(Vec3::new(0.0, 0.0, -1.0), Vec3::Z, 3.0, 12.0).unwrap();
|
|
let bush = crate::boolean(&outer, &bore, BoolOp::Cut).unwrap().unwrap();
|
|
let shank = crate::cylinder(Vec3::new(e, 0.0, -2.0), Vec3::Z, 3.0, 8.0).unwrap();
|
|
let head = crate::cylinder(Vec3::new(e, 0.0, -5.0), Vec3::Z, 5.25, 3.0).unwrap();
|
|
let screw = crate::boolean(&shank, &head, BoolOp::Union).unwrap().unwrap();
|
|
let back = |b: &Body| crate::step_import(&crate::step_export(&[b], "round trip").unwrap()).unwrap().bodies.remove(0).body;
|
|
let (bush, screw) = (back(&bush), back(&screw));
|
|
// The shank shares a crescent with the bush over the 6 mm it reaches into the bore.
|
|
let want = 6.0 * crescent(3.0, 3.0, e).area;
|
|
for (x, y) in [(&bush, &screw), (&screw, &bush)] {
|
|
let o = coaxial_overlap(x, y).unwrap();
|
|
assert!((o.volume - want).abs() < 1e-6 * want, "{o:?} {want}");
|
|
assert!((o.length - 6.0).abs() < 1e-6, "{o:?}");
|
|
}
|
|
// Cut in two, each wall is a face more and the body keeps its volume.
|
|
let split = crate::step_in::split::split_seams(&bush).unwrap();
|
|
assert_eq!(split.face_count(), bush.face_count() + 2);
|
|
let (v0, v1) = (crate::measure(&bush).unwrap().volume, crate::measure(&split).unwrap().volume);
|
|
assert!((v0 - v1).abs() < 1e-6 * v0, "{v0} {v1}");
|
|
assert!(crate::step_in::split::split_seams(&outer).is_none());
|
|
}
|
|
|
|
/// A pin with a Ø7 collar embedded in a block (the collar's underside at z = 0, inside the
|
|
/// block's material), a hair off its hole, and a pocket elsewhere in the block whose floor
|
|
/// is at z = 0 too, facing the collar's underside: the two are level but don't touch, so the
|
|
/// collar is not pulled back, and all of it inside the block counts.
|
|
#[test]
|
|
fn a_collar_level_with_a_pocket_floor_elsewhere_is_not_pulled_back() {
|
|
let e = 0.01;
|
|
let mut block = crate::box_solid(Vec3::new(-10.0, -10.0, -5.0), Vec3::new(20.0, 10.0, 3.0)).unwrap();
|
|
let hole = crate::cylinder(Vec3::new(0.0, 0.0, -6.0), Vec3::Z, 2.0, 10.0).unwrap();
|
|
let pocket = crate::box_solid(Vec3::new(10.0, -3.0, 0.0), Vec3::new(14.0, 3.0, 4.0)).unwrap();
|
|
for cut in [&hole, &pocket] {
|
|
block = crate::boolean(&block, cut, BoolOp::Cut).unwrap().unwrap();
|
|
}
|
|
let shank = crate::cylinder(Vec3::new(e, 0.0, -7.0), Vec3::Z, 2.0, 8.0).unwrap();
|
|
let collar = crate::cylinder(Vec3::new(e, 0.0, 0.0), Vec3::Z, 3.5, 1.0).unwrap();
|
|
let pin = crate::boolean(&shank, &collar, BoolOp::Union).unwrap().unwrap();
|
|
// The collar less the hole, plus the shank's crescent over the 5 mm below the collar.
|
|
let want = std::f64::consts::PI * (3.5 * 3.5 - 2.0 * 2.0) + 5.0 * crescent(2.0, 2.0, e).area;
|
|
for (x, y) in [(&block, &pin), (&pin, &block)] {
|
|
let o = coaxial_overlap(x, y).unwrap();
|
|
assert!((o.volume - want).abs() < 1e-4 * want, "{o:?} {want}");
|
|
}
|
|
}
|
|
|
|
/// Two rivets with their heads flush on both faces of a sheet, each a hair off its hole,
|
|
/// read back from STEP: the heads touch the sheet flat, which the boolean cannot always
|
|
/// take, so they are pulled back off it first. Each rivet shares its own crescent.
|
|
#[test]
|
|
fn two_rivets_flush_on_a_sheet_after_a_step_round_trip() {
|
|
let rivet = |x: f64| {
|
|
let shank = crate::cylinder(Vec3::new(x, 0.0, -1.0), Vec3::Z, 2.0, 3.5).unwrap();
|
|
let under = crate::cylinder(Vec3::new(x, 0.0, -1.0), Vec3::Z, 3.5, 1.0).unwrap();
|
|
let over = crate::cylinder(Vec3::new(x, 0.0, 1.5), Vec3::Z, 3.5, 1.0).unwrap();
|
|
let r = crate::boolean(&shank, &under, BoolOp::Union).unwrap().unwrap();
|
|
crate::boolean(&r, &over, BoolOp::Union).unwrap().unwrap()
|
|
};
|
|
let mut sheet = crate::box_solid(Vec3::new(-20.0, -10.0, 0.0), Vec3::new(20.0, 10.0, 1.5)).unwrap();
|
|
for x in [-4.0, 4.0] {
|
|
let drill = crate::cylinder(Vec3::new(x, 0.0, -1.0), Vec3::Z, 2.0, 4.0).unwrap();
|
|
sheet = crate::boolean(&sheet, &drill, BoolOp::Cut).unwrap().unwrap();
|
|
}
|
|
let back = |b: &Body| crate::step_import(&crate::step_export(&[b], "round trip").unwrap()).unwrap().bodies.remove(0).body;
|
|
let sheet = back(&sheet);
|
|
for (x, e) in [(-4.0, 0.004), (4.0, 0.006)] {
|
|
let r = back(&rivet(x + e));
|
|
let want = 1.5 * crescent(2.0, 2.0, e).area;
|
|
for (p, q) in [(&sheet, &r), (&r, &sheet)] {
|
|
let o = coaxial_overlap(p, q).unwrap();
|
|
assert!((o.volume - want).abs() < 1e-6 * want, "{o:?} {want}");
|
|
}
|
|
}
|
|
}
|
|
}
|