Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

Wave 130/509: kernel: planar regions stay one 2D arrangement; prism booleans are SMLib's boolean

jyviko3092bf60b780
diff --git a/crates/kernel/src/prism.rs b/crates/kernel/src/prism.rs
index d1be421f35..95300ae197 100644
--- a/crates/kernel/src/prism.rs
+++ b/crates/kernel/src/prism.rs
@@ -1,26 +1,15 @@
-//! Booleans of prisms in 2D: when the target is a prism (two caps square to one direction,
-//! walls of planes and cylinders along it) and the tool a prism along the same direction
-//! spanning the target's height, the result is the prism over the 2D boolean of their
-//! sections. Plates with holes, slots and patterns of them: exact, and immune to the mesh
-//! intersection's trouble with walls meeting along lines.
-//! Stepped extrusions (case floors and walls) use sections between every cap level, so a
-//! circular boss can meet the rim without shifting either operand off its exact plane.
+//! Booleans of planar regions in 2D (an arrangement of their lines, arcs and free-form
+//! curves), the extrusion of planar material from them, and the test of whether a record
+//! surface is a wall swept along a direction.
use std::borrow::Cow;
+use solidcraft_geom::brep::Surface;
use solidcraft_geom::{Aabb2, Loop2, Plane, Region2, Seg2, Vec2, Vec3};
-use truck_modeling as mt;
-use crate::body::{Body, from_p3};
+use crate::body::Body;
use crate::{BoolOp, KernelError, Result};
-#[path = "prism_lineage.rs"]
-mod lineage;
-
-#[cfg(test)]
-#[path = "prism_spline_tests.rs"]
-mod spline_tests;
-
const MAX_PLANAR_SEGMENTS: usize = 8192;
const MAX_PLANAR_EVENTS: usize = 131_072;
const MAX_PLANAR_PAIRS: usize = 16_000_000;
@@ -195,83 +184,25 @@ pub fn extrude_planar_regions(plane: &Plane, regions: &[Region2], start: f64, en
})
}
-/// A prism: the plane of its bottom cap (normal along the walls), its height and section (its
-/// segments' tags alongside).
-struct Prism {
- lo: f64,
- hi: f64,
- section: Section,
-}
-
-/// What a section's segment was made from, for the history of what is built over it: an
-/// operand's cap edge (`edge`, by its place in the operand's edge order), the wall face beside it
-/// (`wall`), and the operand's vertices (by [`Index`]) the segment starts and ends at (`None`
-/// where it was split off a longer one). Where the wall ends with a slab of a stepped operand, at
-/// a cap whose outline runs along the whole segment, `far` is the operand's edge there (the
-/// segment may have been read off a cap at another level). A segment carried through levels
-/// beside the same wall keeps the vertices it was read at, which may lie at another level: they
-/// say which line two walls meet along, not which edge of it. `None` fields: not known (no
-/// history then).
+/// What a section's segment is, through [`boolean2d_tagged`]: the free-form segment (by
+/// number) the arc it is was fitted to, so the result's pieces of it get the exact curve back.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-pub(crate) struct Tag {
- pub operand: usize,
- pub wall: Option<usize>,
- pub edge: Option<usize>,
- pub far: Option<usize>,
- pub start: Option<usize>,
- pub end: Option<usize>,
- /// Inside [`boolean2d_tagged`] only: the free-form segment (by number) the arc this tags
- /// was fitted to, so the result's pieces of it get the exact curve back.
- pub free: Option<usize>,
-}
-
-/// A segment nothing is known of.
-const BLANK: Tag = Tag { operand: 0, wall: None, edge: None, far: None, start: None, end: None, free: None };
-
-impl Tag {
- /// The segment run the other way.
- fn reversed(self) -> Tag {
- Tag { start: self.end, end: self.start, ..self }
- }
-
- /// Piece `k` of `n` the segment was split into, in its direction.
- fn piece(self, k: usize, n: usize) -> Tag {
- Tag { start: if k == 0 { self.start } else { None }, end: if k + 1 == n { self.end } else { None }, ..self }
- }
-
- /// The segment beside `wall` instead (`None`: not known). Its edge and vertices were read
- /// beside the wall it leaves, so they are dropped with it.
- fn beside(self, wall: Option<usize>) -> Tag {
- if wall == self.wall { self } else { Tag { operand: self.operand, wall, ..BLANK } }
- }
-}
-
-/// An operand's [`Index`], built when first needed (only bodies that are prisms are read).
-pub(crate) struct LazyIndex<'a> {
- body: &'a Body,
- operand: usize,
- index: std::cell::OnceCell<Index>,
+struct Tag {
+ free: Option<usize>,
}
-impl<'a> LazyIndex<'a> {
- fn new(body: &'a Body, operand: usize) -> LazyIndex<'a> {
- LazyIndex { body, operand, index: std::cell::OnceCell::new() }
- }
-
- fn get(&self) -> &Index {
- self.index.get_or_init(|| Index::new(self.body, self.operand))
- }
-}
+/// A segment that is no fitted arc.
+const BLANK: Tag = Tag { free: None };
/// Regions with a tag for each segment: per region, per loop (outer, then holes), per segment.
#[derive(Clone, Debug, Default, PartialEq)]
-pub(crate) struct Section {
- pub regions: Vec<Region2>,
- pub tags: Vec<Vec<Vec<Tag>>>,
+struct Section {
+ regions: Vec<Region2>,
+ tags: Vec<Vec<Vec<Tag>>>,
}
impl Section {
- /// Regions whose segments nothing is known of.
+ /// Regions none of whose segments is a fitted arc.
fn untagged(regions: &[Region2]) -> Section {
let tags = regions.iter().map(|r| std::iter::once(&r.outer).chain(&r.holes).map(|l| vec![BLANK; l.segs.len()]).collect()).collect();
Section { regions: regions.to_vec(), tags }
@@ -296,19 +227,6 @@ impl Section {
.unwrap_or_default()
}
- /// One region from its loops (each segment tagged): the loop with the largest area is the
- /// outer one.
- fn from_loops(loops: Vec<(Loop2, Vec<Tag>)>) -> Option<Section> {
- let ((outer, outer_tags), holes) = split_outer(loops)?;
- let (holes, hole_tags): (Vec<Loop2>, Vec<Vec<Tag>>) = holes.into_iter().unzip();
- Some(Section { regions: vec![Region2 { outer, holes }], tags: vec![std::iter::once(outer_tags).chain(hole_tags).collect()] })
- }
-
- /// Region `r` alone.
- fn region(&self, r: usize) -> Section {
- Section { regions: self.regions.get(r).cloned().into_iter().collect(), tags: vec![self.region_tags(r)] }
- }
-
/// Every segment in order (regions, then loops) with its tag.
fn segments(&self) -> (Vec<Seg2>, Vec<Tag>) {
let mut out = (Vec::new(), Vec::new());
@@ -323,83 +241,11 @@ impl Section {
out
}
- /// Each segment's tag mapped by `f`.
- fn retag(&mut self, f: impl Fn(Tag) -> Tag) {
- for t in self.tags.iter_mut().flatten().flatten() {
- *t = f(*t);
- }
- }
-
- /// Mark each segment of a slab with its `far` edge: the operand's edge where its wall meets
- /// one of `caps` (the outlines of the operand's caps ending the slab).
- ///
- /// The operand's topology settles it where `top` gives the wall's edge (the wall ends at the
- /// caps in that one edge, [`Stations::top_edge`]): that edge is over every segment beside it.
- ///
- /// Otherwise, for a wall meeting the caps in several edges (its top split at vertices an
- /// earlier operation left, or beside a wall across it there) or carrying on past the caps
- /// elsewhere, which edge is over a segment depends on where the segment lies along the wall,
- /// and nothing in the topology says that. Only there is position compared: the segment takes
- /// the edge of the cap segment beside the same wall it runs along end to end. A segment
- /// along none, or along segments of different edges, stays unmarked; so do those past
- /// `budget` (segment pairs compared).
- fn mark_far(&mut self, caps: &[&Section], top: impl Fn(usize) -> Option<usize>, tol: f64, budget: &mut usize) {
- let mut tops: std::collections::HashMap<usize, Option<usize>> = std::collections::HashMap::new();
- // The caps' segments by wall, gathered only once a wall needs position.
- let mut by_wall: Option<std::collections::HashMap<usize, Vec<(Seg2, Option<usize>)>>> = None;
- for (reg, tags) in self.regions.iter().zip(&mut self.tags) {
- for (lp, tags) in std::iter::once(&reg.outer).chain(&reg.holes).zip(tags) {
- for (seg, tag) in lp.segs.iter().zip(tags) {
- let Some(w) = tag.wall else { continue };
- if let Some(e) = *tops.entry(w).or_insert_with(|| top(w)) {
- tag.far = Some(e);
- continue;
- }
- let by_wall = by_wall.get_or_insert_with(|| {
- let mut by_wall: std::collections::HashMap<usize, Vec<(Seg2, Option<usize>)>> = std::collections::HashMap::new();
- for (segs, tags) in caps.iter().map(|c| c.segments()) {
- for (seg, tag) in segs.into_iter().zip(tags) {
- if let Some(w) = tag.wall {
- by_wall.entry(w).or_default().push((seg, tag.edge));
- }
- }
- }
- by_wall
- });
- let Some(beside) = by_wall.get(&w) else { continue };
- let Some(left) = budget.checked_sub(beside.len()) else { continue };
- *budget = left;
- // The one edge it runs along (`Some(None)`: along none, or not one edge).
- let mut along: Option<Option<usize>> = None;
- for (_, edge) in beside.iter().filter(|(t, _)| runs_along(seg, t, tol)) {
- along = match along {
- None => Some(*edge),
- Some(e) if e == *edge => Some(e),
- Some(_) => Some(None),
- };
- }
- if let Some(Some(e)) = along {
- tag.far = Some(e);
- }
- }
- }
- }
- }
-
- /// Segments beside a wall another crosses between levels `lo` and `hi` are not beside it
- /// all the way: their walls are not known.
- fn drop_crossed(&mut self, stations: &Stations, lo: f64, hi: f64, tol: f64) {
- self.retag(|t| match t.wall {
- Some(w) if stations.across(w, lo, hi, tol) => t.beside(None),
- _ => t,
- });
- }
-
/// Loops oriented: outers counter-clockwise, holes clockwise; the tags following their
/// segments.
fn oriented(&self) -> Section {
let turn = |lp: &Loop2, tags: Vec<Tag>, reverse: bool| -> (Loop2, Vec<Tag>) {
- if reverse { (lp.reversed(), tags.into_iter().rev().map(Tag::reversed).collect()) } else { (lp.clone(), tags) }
+ if reverse { (lp.reversed(), tags.into_iter().rev().collect()) } else { (lp.clone(), tags) }
};
let mut out = Section::default();
for (r, reg) in self.regions.iter().enumerate() {
@@ -419,266 +265,40 @@ impl Section {
}
}
-/// An operand's faces, edges and vertices by identity, to tag the section segments read off its
-/// caps ([`Tag`]).
-pub(crate) struct Index {
- operand: usize,
- /// Each edge's place in the edge order.
- edges: std::collections::HashMap<mt::EdgeID, usize>,
- /// Per edge (edge order): the faces it bounds, and its ends (by vertex number).
- bounds: Vec<(Vec<usize>, Option<usize>, Option<usize>)>,
- /// The edges between each pair of faces (lesser first; a face twice for a seam).
- between: std::collections::HashMap<(usize, usize), Vec<usize>>,
- /// Each vertex's number (first seen along the edge order).
- vertices: std::collections::HashMap<mt::VertexID, usize>,
- /// Each vertex's point, by number.
- points: Vec<Vec3>,
- /// Per edge (edge order): whether it is a line.
- lines: Vec<bool>,
- /// Per edge (edge order) that is not a line: the points its curve lies within (see
- /// [`control_hull`]); `None` where they are not known.
- hulls: Vec<Option<Vec<Vec3>>>,
-}
-
-impl Index {
- fn new(b: &Body, operand: usize) -> Index {
- let (edges, bounds) = crate::body::edge_order(b.solid.face_iter());
- let mut vertices = std::collections::HashMap::new();
- let mut points = Vec::new();
- for e in &edges {
- for v in [e.absolute_front(), e.absolute_back()] {
- if let std::collections::hash_map::Entry::Vacant(slot) = vertices.entry(v.id()) {
- slot.insert(points.len());
- points.push(from_p3(v.point()));
- }
- }
- }
- let lines = edges.iter().map(|e| matches!(e.curve(), mt::Curve::Line(_))).collect();
- let hulls = edges.iter().map(|e| control_hull(&e.curve())).collect();
- let mut between: std::collections::HashMap<(usize, usize), Vec<usize>> = std::collections::HashMap::new();
- for (i, fs) in bounds.iter().enumerate() {
- match fs.as_slice() {
- [f] => between.entry((*f, *f)).or_default().push(i),
- [f, g] => between.entry((*f.min(g), *f.max(g))).or_default().push(i),
- _ => {}
- }
- }
- let bounds = edges
- .iter()
- .zip(bounds)
- .map(|(e, fs)| (fs, vertices.get(&e.absolute_front().id()).copied(), vertices.get(&e.absolute_back().id()).copied()))
- .collect();
- Index { operand, edges: crate::record::edge_index(&b.solid), bounds, between, vertices, points, lines, hulls }
- }
-
- /// The tag of the segments read off edge `e` (as it runs in a wire) of cap face `cap`.
- fn tag(&self, e: &mt::Edge, cap: usize) -> Tag {
- let edge = self.edges.get(&e.id()).copied();
- let wall = edge.and_then(|i| self.bounds.get(i)).and_then(|(fs, _, _)| match fs.as_slice() {
- [x, y] if *x == cap => Some(*y),
- [x, y] if *y == cap => Some(*x),
- _ => None,
- });
- Tag {
- operand: self.operand,
- wall,
- edge,
- far: None,
- start: self.vertices.get(&e.front().id()).copied(),
- end: self.vertices.get(&e.back().id()).copied(),
- free: None,
- }
- }
-
- /// The loops of cap face `f` (number `cap`) as segments, each with its tag; `None` where an
- /// edge isn't a line or an arc in the plane.
- fn loops(&self, f: &mt::Face, cap: usize, plane: &Plane, tol: f64, work: &mut usize, segments: &mut usize) -> Option<Vec<(Loop2, Vec<Tag>)>> {
- let mut loops = Vec::new();
- for w in f.boundaries() {
- let (mut segs, mut tags) = (Vec::new(), Vec::new());
- for e in w.edge_iter() {
- let pieces = if FREE_FORM.with(|c| c.get()) {
- crate::prism_curve::segment_fitted(e, plane, tol, PLANAR_FIT_TOL, work)?
- } else {
- crate::prism_curve::segment(e, plane, tol, work)?
- };
- *segments = segments.checked_sub(pieces.len())?;
- let tag = self.tag(e, cap);
- tags.extend((0..pieces.len()).map(|k| tag.piece(k, pieces.len())));
- segs.extend(pieces);
- }
- loops.push((Loop2 { segs }, tags));
- }
- Some(loops)
- }
-}
-
-/// Where an operand's walls along a direction end other than at its caps: at edges between two
-/// walls that do not run along the direction (between pieces of one surface an earlier operation
-/// left apart). A section segment carried through a level keeps the wall it was read beside
-/// only where these say so, as its operand's prism or slab is read.
-struct Stations {
- /// Each wall's highest level.
- tops: std::collections::HashMap<usize, f64>,
- /// Per wall, the edges across it: the other wall and the edge's lowest and highest levels.
- /// A curve other than a line spans every level, unless it lies at one level.
- cross: std::collections::HashMap<usize, Vec<(usize, f64, f64)>>,
-}
-
-impl Stations {
- /// From the operand's walls (by face number, with their highest levels).
- fn new(index: &Index, tops: std::collections::HashMap<usize, f64>, d: Vec3, plane: &Plane, tol: f64) -> Stations {
- let mut cross: std::collections::HashMap<usize, Vec<(usize, f64, f64)>> = std::collections::HashMap::new();
- for (i, (fs, front, back)) in index.bounds.iter().enumerate() {
- let [f, g] = fs[..] else { continue };
- if f == g || !tops.contains_key(&f) || !tops.contains_key(&g) {
- continue;
+/// Certify that a curved wall is swept along `d` (unit) from its surface record: a cylinder or
+/// a revolved line about an axis along `d`, or a spline net whose rows run along `d` (either
+/// parameter) with weights that separate into one factor per parameter. Seam vertices alone
+/// cannot establish this: a half-cylinder's seam normals can both be perpendicular to a
+/// transverse direction, silently filling its hole. A plane is no curved wall.
+pub(crate) fn wall_along(surface: &Surface, d: Vec3, tol: f64, remaining: &mut usize) -> bool {
+ let v3 = |p: [f64; 3]| Vec3::new(p[0], p[1], p[2]);
+ let along = |a: Vec3| a.normalized().is_some_and(|a| a.cross(d).len() < 1e-9);
+ let points: Vec<Vec<(Vec3, f64)>> = match surface {
+ Surface::Cylinder { frame, .. } => return along(v3(frame.x_axis).cross(v3(frame.y_axis))),
+ Surface::PlacedRevolution { profile, axis, matrix, .. } => {
+ let solidcraft_geom::brep::Curve::Line { start, end } = &**profile else { return false };
+ let (Some(a), Some(m)) = (v3(*axis).normalized(), (v3(*end) - v3(*start)).normalized()) else { return false };
+ if a.cross(m).len() > 1e-9 {
+ return false; // A conical meridian is not a cylindrical wall.
}
- let ends = front.and_then(|v| index.points.get(v)).zip(back.and_then(|v| index.points.get(v)));
- let (lo, hi) = match ends {
- Some((p, q)) if index.lines.get(i) == Some(&true) => {
- let run = *q - *p;
- if (run - d * run.dot(d)).len() < tol {
- continue; // Along the direction: between walls over two segments.
- }
- let (h, k) = (plane.height(*p), plane.height(*q));
- (h.min(k), h.max(k))
- }
- // A curve at one level (where a piece of a wall's surface stacked on another
- // meets it: a boss's cylinder over the arc of the plate it stands on) crosses
- // the walls there only. Any other spans every level.
- _ => match index.hulls.get(i).and_then(Option::as_deref).map(|hull| level_span(hull, plane)) {
- Some((lo, hi)) if hi - lo < tol => (lo, hi),
- _ => (f64::NEG_INFINITY, f64::INFINITY),
- },
- };
- cross.entry(f).or_default().push((g, lo, hi));
- cross.entry(g).or_default().push((f, lo, hi));
+ // The axis placed by the column-major matrix (a direction: no translation).
+ let c = |k: usize| matrix[0][k] * a.x + matrix[1][k] * a.y + matrix[2][k] * a.z;
+ return c(3).abs() < 1e-12 && along(Vec3::new(c(0), c(1), c(2)));
}
- Stations { tops, cross }
- }
-
- /// The edges across wall `w`.
- fn of(&self, w: usize) -> &[(usize, f64, f64)] {
- self.cross.get(&w).map_or(&[], Vec::as_slice)
- }
-
- /// The operand's edge (in `index`) where wall `w` ends at level `z`, when it ends there in
- /// one edge: `z` is its top, no other wall crosses it there, and it meets the faces `caps`
- /// (the caps at `z`) in exactly one edge. Found by topology alone, no position compared. The wall reaching no higher, every segment beside
- /// it in a slab up to `z` ends on its edges at `z`, which are that one edge alone.
- fn top_edge(&self, index: &Index, w: usize, caps: &[usize], z: f64, tol: f64) -> Option<usize> {
- let ends = self.tops.get(&w).is_some_and(|t| (*t - z).abs() < tol);
- if !ends || self.of(w).iter().any(|(_, l, h)| *l < z + tol && *h > z - tol) {
- return None;
- }
- let mut edges = caps.iter().filter_map(|c| index.between.get(&(w.min(*c), w.max(*c)))).flatten();
- match (edges.next(), edges.next()) {
- (Some(e), None) => Some(*e),
- _ => None,
+ Surface::Spline { points, .. } => points.iter().map(|r| r.iter().map(|p| (v3(*p), 1.0)).collect()).collect(),
+ Surface::RationalSpline { homogeneous, .. } => {
+ homogeneous.iter().map(|r| r.iter().map(|p| (Vec3::new(p[0] / p[3], p[1] / p[3], p[2] / p[3]), p[3])).collect()).collect()
}
- }
-
- /// Does wall `w` meet another wall across it between levels `lo` and `hi` (not at them)?
- fn across(&self, w: usize, lo: f64, hi: f64, tol: f64) -> bool {
- self.of(w).iter().any(|(_, l, h)| *l < hi - tol && *h > lo + tol)
- }
-
- /// The wall over a section segment beside wall `w` just past level `z`, when the segment
- /// runs on through `z` without meeting a cap there: `w` itself when nothing crosses it at
- /// `z`, and it reaches past; the one wall across it at `z` when it ends there; else not
- /// known.
- fn past(&self, w: usize, z: f64, tol: f64) -> Option<usize> {
- let at: std::collections::BTreeSet<usize> =
- self.of(w).iter().filter(|(_, l, h)| (*l - z).abs() < tol && (*h - z).abs() < tol).map(|(y, _, _)| *y).collect();
- let reaches = self.tops.get(&w).is_some_and(|t| *t > z + tol);
- match (at.len(), reaches) {
- (0, true) => Some(w),
- (1, false) => at.first().copied(),
- _ => None,
- }
- }
-}
-
-/// The most control points [`control_hull`] reads of one curve.
-const MAX_HULL_POINTS: usize = 4096;
-
-/// The points curve `c` lies within: a B-spline's control points, or a NURBS curve's where its
-/// weights are positive (the curve then lies in their convex hull). `None` for a line, an
-/// intersection curve, other weights or too many points.
-fn control_hull(c: &mt::Curve) -> Option<Vec<Vec3>> {
- match c {
- mt::Curve::BSplineCurve(c) if c.control_points().len() <= MAX_HULL_POINTS => Some(c.control_points().iter().map(|p| from_p3(*p)).collect()),
- mt::Curve::NurbsCurve(c) if c.control_points().len() <= MAX_HULL_POINTS => {
- c.control_points().iter().map(|p| (p.w > 0.0 && p.w.is_finite()).then(|| Vec3::new(p.x / p.w, p.y / p.w, p.z / p.w))).collect()
- }
- _ => None,
- }
-}
-
-/// The lowest and highest levels of `points` (infinite where there are none, or one isn't
-/// finite).
-fn level_span(points: &[Vec3], plane: &Plane) -> (f64, f64) {
- let span = points
- .iter()
- .map(|p| plane.height(*p))
- .try_fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), h| h.is_finite().then(|| (lo.min(h), hi.max(h))));
- match span {
- Some((lo, hi)) if lo <= hi => (lo, hi),
- _ => (f64::NEG_INFINITY, f64::INFINITY),
- }
-}
-
-/// The highest level of face `f`'s vertices.
-fn top_of(f: &mt::Face, plane: &Plane) -> f64 {
- f.vertex_iter().map(|v| plane.height(from_p3(v.point()))).fold(f64::NEG_INFINITY, f64::max)
-}
-
-/// Certify that a curved wall is swept along `d` from its surface representation.
-/// Seam vertices alone cannot establish this: a half-cylinder's seam normals can
-/// both be perpendicular to a transverse direction, silently filling its hole.
-pub(crate) fn wall_along(surface: &mt::Surface, d: Vec3, tol: f64, remaining: &mut usize) -> bool {
- if let mt::Surface::RevolutedCurve(processor) = surface {
- let revolution = processor.entity();
- let mt::Curve::Line(line) = revolution.entity_curve() else { return false };
- let axis = revolution.axis();
- let meridian = line.1 - line.0;
- let local_axis = Vec3::new(axis.x, axis.y, axis.z);
- let local_meridian = Vec3::new(meridian.x, meridian.y, meridian.z);
- let (Some(a), Some(m)) = (local_axis.normalized(), local_meridian.normalized()) else { return false };
- if a.cross(m).len() > 1e-9 {
- return false; // A conical meridian is not a cylindrical wall.
- }
- let placed = *processor.transform() * mt::Vector4::new(axis.x, axis.y, axis.z, 0.0);
- return placed.w.abs() < 1e-12 && Vec3::new(placed.x, placed.y, placed.z).normalized().is_some_and(|a| a.cross(d).len() < 1e-9);
- }
- let dimensions = match surface {
- mt::Surface::BSplineSurface(s) => (s.control_points().len(), s.control_points().first().map_or(0, Vec::len)),
- mt::Surface::NurbsSurface(s) => (s.control_points().len(), s.control_points().first().map_or(0, Vec::len)),
_ => return false,
};
- let (rows, cols) = dimensions;
+ let (rows, cols) = (points.len(), points.first().map_or(0, Vec::len));
let count = rows.saturating_mul(cols);
- let rectangular = match surface {
- mt::Surface::BSplineSurface(s) => s.control_points().iter().all(|r| r.len() == cols),
- mt::Surface::NurbsSurface(s) => s.control_points().iter().all(|r| r.len() == cols),
- _ => false,
- };
- if rows < 2 || cols < 2 || count > 16_384 || !rectangular {
+ if rows < 2 || cols < 2 || count > 16_384 || points.iter().any(|r| r.len() != cols) {
return false;
}
let Some(left) = remaining.checked_sub(count.saturating_mul(2)) else { return false };
*remaining = left;
- let points: Vec<Vec<(Vec3, f64)>> = match surface {
- mt::Surface::BSplineSurface(s) => s.control_points().iter().map(|r| r.iter().map(|p| (from_p3(*p), 1.0)).collect()).collect(),
- mt::Surface::NurbsSurface(s) => {
- s.control_points().iter().map(|r| r.iter().map(|p| (Vec3::new(p.x / p.w, p.y / p.w, p.z / p.w), p.w)).collect()).collect()
- }
- _ => return false,
- };
- if points.iter().any(|r| r.len() != cols)
- || points.iter().flatten().any(|(p, w)| !w.is_finite() || *w <= 0.0 || [p.x, p.y, p.z].iter().any(|x| !x.is_finite()))
- {
+ if points.iter().flatten().any(|(p, w)| !w.is_finite() || *w <= 0.0 || !p.is_finite()) {
return false;
}
let max_weight = points.iter().flatten().map(|p| p.1).fold(0.0, f64::max);
@@ -722,98 +342,6 @@ pub(crate) fn wall_along(surface: &mt::Surface, d: Vec3, tol: f64, remaining: &m
false
}
-/// The body as a prism along `d` (unit), seen in `plane` (normal `d`).
-#[cfg(test)]
-fn prism_of(b: &Body, d: Vec3, plane: &Plane, tol: f64) -> Option<Prism> {
- prism_tagged(b, d, plane, tol, &LazyIndex::new(b, 0))
-}
-
-/// [`prism_of`], its section's segments tagged from `index` (the body's).
-fn prism_tagged(b: &Body, d: Vec3, plane: &Plane, tol: f64, index: &LazyIndex) -> Option<Prism> {
- // A simple extrusion with N section edges has N walls plus its cap faces.
- // Even disconnected two-arc sections need at most 2N faces. Keep that
- // complete planar arrangement envelope, independently of stepped limits.
- let mut remaining_faces = MAX_PLANAR_SEGMENTS * 2;
- let mut lo = f64::INFINITY;
- let mut hi = f64::NEG_INFINITY;
- let mut tops: Vec<(usize, &mt::Face)> = Vec::new();
- let mut top_h = Vec::new();
- let mut bottom_h = Vec::new();
- let mut walls = std::collections::HashMap::new();
- let mut wall_work = 262_144;
- let mut curve_work = 2_000_000usize;
- for (fi, f) in b.solid.face_iter().enumerate() {
- remaining_faces = remaining_faces.checked_sub(1)?;
- curve_work = curve_work.checked_sub(1)?;
- let surf = f.oriented_surface();
- if let mt::Surface::Plane(p) = &surf {
- let n = p.normal();
- let n = Vec3::new(n.x, n.y, n.z).normalized()?;
- let h = plane.height(from_p3(p.origin()));
- if n.dot(d) > 1.0 - 1e-9 {
- tops.push((fi, f));
- top_h.push(h);
- hi = hi.max(h);
- continue;
- }
- if n.dot(d) < -1.0 + 1e-9 {
- bottom_h.push(h);
- lo = lo.min(h);
- continue;
- }
- if n.dot(d).abs() > 1e-9 {
- return None;
- }
- walls.insert(fi, top_of(f, plane));
- continue;
- }
- if !wall_along(&surf, d, tol, &mut wall_work) {
- return None;
- }
- walls.insert(fi, top_of(f, plane));
- }
- // One height for every top (and bottom) cap.
- if top_h.iter().any(|h| (h - hi).abs() > tol) || bottom_h.iter().any(|h| (h - lo).abs() > tol) || !(lo.is_finite() && hi > lo + tol) {
- return None;
- }
- let mut section = Section::default();
- let mut remaining_segments = MAX_PLANAR_SEGMENTS;
- let mut remaining_loops = MAX_PLANAR_SEGMENTS;
- for (fi, f) in tops {
- remaining_loops = remaining_loops.checked_sub(f.boundaries().len())?;
- let loops = index.get().loops(f, fi, plane, tol, &mut curve_work, &mut remaining_segments)?;
- let one = Section::from_loops(loops)?;
- section.regions.extend(one.regions);
- section.tags.extend(one.tags);
- }
- section.drop_crossed(&Stations::new(index.get(), walls, d, plane, tol), lo, hi, tol);
- Some(Prism { lo, hi, section })
-}
-
-/// The loop with the largest area is the outer one.
-fn split_outer<T>(mut loops: Vec<(Loop2, T)>) -> Option<((Loop2, T), Vec<(Loop2, T)>)> {
- let i = (0..loops.len()).max_by(|a, b| loops[*a].0.signed_area().abs().total_cmp(&loops[*b].0.signed_area().abs()))?;
- let outer = loops.remove(i);
- Some((outer, loops))
-}
-
-fn heights_of(b: &Body, plane: &Plane) -> (f64, f64) {
- b.solid.vertex_iter().map(|v| plane.height(from_p3(v.point()))).fold((f64::INFINITY, f64::NEG_INFINITY), |m, h| (m.0.min(h), m.1.max(h)))
-}
-
-/// Does `s` run along `t` from end to end? Two lines, `s`'s ends on `t`; two arcs of one
-/// circle, `s`'s ends and middle on `t`.
-fn runs_along(s: &Seg2, t: &Seg2, tol: f64) -> bool {
- let on = |p: Vec2| t.point_at(closest_param(t, p)).dist(p) < tol;
- match (*s, *t) {
- (Seg2::Line { .. }, Seg2::Line { .. }) => on(s.start()) && on(s.end()),
- (Seg2::Arc { center: c, radius: r, .. }, Seg2::Arc { center: d, radius: q, .. }) => {
- c.dist(d) < tol && (r - q).abs() < tol && on(s.start()) && on(s.end()) && on(s.point_at(0.5))
- }
- _ => false,
- }
-}
-
/// Points where two segments cross (parameters on each), lines and arcs only.
///
/// Curves that touch within the tolerance (a line tangent to an arc, two circles tangent inside
@@ -1055,15 +583,6 @@ fn closest_param(segment: &Seg2, point: Vec2) -> f64 {
}
}
-fn dist_to(regions: &[Region2], p: Vec2) -> f64 {
- regions
- .iter()
- .flat_map(|r| std::iter::once(&r.outer).chain(&r.holes))
- .flat_map(|l| l.segs.iter())
- .map(|s| s.point_at(closest_param(s, p)).dist(p))
- .fold(f64::INFINITY, f64::min)
-}
-
/// The bounding box of a line or an arc, grown by twice the tolerance (and by the rounding of
/// its own corners). Whatever lies within the tolerance of the segment lies in the box. `None`
/// for other segments and for values that are not finite: no box, and nothing is skipped for it.
@@ -1121,8 +640,7 @@ fn boolean2d(a: &[Region2], b: &[Region2], op: BoolOp, tol: f64) -> Option<Vec<R
boolean2d_tagged(&Section::untagged(a), &Section::untagged(b), op, tol).map(|s| s.regions)
}
-/// [`boolean2d`] of tagged sections: each segment of the result tagged as the segment of `a` or
-/// `b` it is (a piece of). Free-form segments (a font's curves) take part as arcs within
+/// [`boolean2d`] of sections. Free-form segments (a font's curves) take part as arcs within
/// [`PLANAR_FIT_TOL`]; each piece of one in the result is the exact curve again, ending where
/// it exactly meets the segment next to it (see [`exact_again`]).
fn boolean2d_tagged(a: &Section, b: &Section, op: BoolOp, tol: f64) -> Option<Section> {
@@ -1147,16 +665,15 @@ fn fitted(s: &Section, sources: &mut Vec<Seg2>, fit: f64) -> Option<Section> {
for (l, lp) in std::iter::once(&reg.outer).chain(&reg.holes).enumerate() {
let (mut segs, mut ts) = (Vec::new(), Vec::new());
for (i, seg) in lp.segs.iter().enumerate() {
- let tag = s.tag(r, l, i);
if seg.is_line_or_arc() {
segs.push(*seg);
- ts.push(tag);
+ ts.push(s.tag(r, l, i));
continue;
}
let arcs = seg.fit_arcs(fit)?;
pieces = pieces.checked_add(arcs.len()).filter(|n| *n <= MAX_PLANAR_SEGMENTS)?;
let n = arcs.len();
- ts.extend((0..n).map(|k| Tag { free: Some(sources.len()), ..tag.piece(k, n) }));
+ ts.extend(std::iter::repeat_n(Tag { free: Some(sources.len()) }, n));
segs.extend(arcs);
sources.push(*seg);
}
@@ -1334,7 +851,7 @@ fn exact_again(out: Section, sources: &[Seg2], tol: f64) -> Section {
/// One loop of [`exact_again`]: its segments and their tags.
fn exact_loop(lp: &Loop2, tags: &[Tag], sources: &[Seg2], near: f64) -> (Vec<Seg2>, Vec<Tag>) {
let n = lp.segs.len();
- let tag = |i: usize| Tag { free: None, ..tags.get(i).copied().unwrap_or(BLANK) };
+ let tag = |_: usize| BLANK;
let free = |i: usize| tags.get(i).and_then(|t| t.free);
let plain = || (lp.segs.clone(), (0..n).map(tag).collect::<Vec<_>>());
// Start at the first segment of a run (a loop that is one run stays as it is).
@@ -1379,8 +896,7 @@ fn exact_loop(lp: &Loop2, tags: &[Tag], sources: &[Seg2], near: f64) -> (Vec<Seg
}
}
} else {
- let t = Tag { end: tag((first + j) % n).end, ..tag(i) };
- pieces.push(Piece::Exact { src: f, t0, t1, a: src.point_at(t0), b: src.point_at(t1), tag: t });
+ pieces.push(Piece::Exact { src: f, t0, t1, a: src.point_at(t0), b: src.point_at(t1), tag: BLANK });
}
k = j + 1;
}
@@ -1570,8 +1086,8 @@ fn boolean2d_arcs(a: &Section, b: &Section, op: BoolOp, tol: f64) -> Option<Sect
return None;
}
let split = pieces(s, cut_a.get_mut(i)?);
- let (n, tag) = (split.len(), ta.get(i).copied().unwrap_or(BLANK));
- for (k, p) in split.into_iter().enumerate() {
+ let tag = ta.get(i).copied().unwrap_or(BLANK);
+ for p in split {
let m = p.point_at(0.5);
let on = near_dist(&sb, &box_b, m) < tol;
let keep = if on {
@@ -1591,7 +1107,7 @@ fn boolean2d_arcs(a: &Section, b: &Section, op: BoolOp, tol: f64) -> Option<Sect
if kept.len() >= MAX_PLANAR_SEGMENTS {
return None;
}
- kept.push((p, tag.piece(k, n)));
+ kept.push((p, tag));
}
}
}
@@ -1601,8 +1117,8 @@ fn boolean2d_arcs(a: &Section, b: &Section, op: BoolOp, tol: f64) -> Option<Sect
return None;
}
let split = pieces(t, cut_b.get_mut(j)?);
- let (n, tag) = (split.len(), tb.get(j).copied().unwrap_or(BLANK));
- for (k, p) in split.into_iter().enumerate() {
+ let tag = tb.get(j).copied().unwrap_or(BLANK);
+ for p in split {
let m = p.point_at(0.5);
if near_dist(&sa, &box_a, m) < tol {
continue;
@@ -1611,11 +1127,10 @@ fn boolean2d_arcs(a: &Section, b: &Section, op: BoolOp, tol: f64) -> Option<Sect
if kept.len() >= MAX_PLANAR_SEGMENTS {
return None;
}
- let tag = tag.piece(k, n);
match op {
BoolOp::Union if !ins => kept.push((p, tag)),
BoolOp::Intersect if ins => kept.push((p, tag)),
- BoolOp::Cut if ins => kept.push((p.reversed(), tag.reversed())),
+ BoolOp::Cut if ins => kept.push((p.reversed(), tag)),
_ => {}
}
}
@@ -1698,8 +1213,6 @@ fn boolean2d_arcs(a: &Section, b: &Section, op: BoolOp, tol: f64) -> Option<Sect
Some(out)
}
-/// The boolean done on prism sections, or `None` when it doesn't apply.
-/// The pieces of a segment between the given points (those lying on it, inside it).
/// Of the pieces in `out` leaving the point where `incoming` ends, the one turning most to the
/// left: the largest counter-clockwise angle from the way back along `incoming`. A loop with
/// its material on its left that always takes it encloses the least, so material meeting
@@ -1755,832 +1268,6 @@ fn simple_loops(lp: Loop2, tags: Vec<Tag>, near: f64) -> Vec<(Loop2, Vec<Tag>)>
out
}
-fn split_seg(seg: &Seg2, pts: &[Vec2], tol: f64) -> Option<Vec<Seg2>> {
- let mut ts: Vec<f64> = pts
- .iter()
- .filter_map(|p| {
- // A point within `tol` of an arc is within `tol` of its circle: the others need no
- // (sampled) projection.
- if let Seg2::Arc { center, radius, .. } = seg
- && (p.dist(*center) - radius).abs() >= tol
- {
- return None;
- }
- // A point within `tol` of an end is that end (the sewing welds them into one): a cut
- // there would leave a piece with no length.
- if p.dist(seg.start()) < tol || p.dist(seg.end()) < tol {
- return None;
- }
- let t = closest_param(seg, *p);
- (t > 1e-9 && t < 1.0 - 1e-9 && seg.point_at(t).dist(*p) < tol).then_some(t)
- })
- .collect();
- ts.sort_by(f64::total_cmp);
- ts.dedup_by(|x, y| (*x - *y).abs() < 1e-9);
- let mut out = Vec::new();
- let mut t0 = 0.0;
- for t1 in ts.into_iter().chain(std::iter::once(1.0)) {
- out.push(match *seg {
- Seg2::Line { .. } => Seg2::Line { a: seg.point_at(t0), b: seg.point_at(t1) },
- Seg2::Arc { center, radius, start, sweep } => Seg2::Arc { center, radius, start: start + sweep * t0, sweep: sweep * (t1 - t0) },
- _ => trimmed(seg, t0, t1, seg.point_at(t0), seg.point_at(t1)),
- });
- t0 = t1;
- }
- Some(out)
-}
-
-/// The union of two prisms along `d` stacked end to end (or overlapping) with different
-/// sections, sewn from its faces: each slab between the prisms' end levels has walls over its
-/// section's outline; each level has a face up over the section below less the one above, and
-/// a face down over the one above less the one below. Every outline is split where any other
-/// meets it, so the faces share their edges. `None` when a slab is empty or a curve isn't a
-/// line or an arc.
-fn sew_stack(plane: &Plane, d: Vec3, pa: &Prism, pb: &Prism, tol: f64, history: &lineage::Context) -> Option<Result<Body>> {
- let mut levels = vec![pa.lo, pa.hi, pb.lo, pb.hi];
- levels.sort_by(f64::total_cmp);
- levels.dedup_by(|x, y| (*x - *y).abs() < tol);
- let covers = |p: &Prism, z0: f64, z1: f64| p.lo <= z0 + tol && p.hi >= z1 - tol;
- let mut slabs: Vec<Section> = Vec::new();
- for w in levels.windows(2) {
- let (z0, z1) = (*w.first()?, *w.get(1)?);
- let s = match (covers(pa, z0, z1), covers(pb, z0, z1)) {
- (true, true) => boolean2d_tagged(&pa.section, &pb.section, BoolOp::Union, tol)?,
- (true, false) => pa.section.clone(),
- (false, true) => pb.section.clone(),
- (false, false) => return None,
- };
- slabs.push(s.oriented());
- }
- sew_sections(plane, d, &levels, &slabs, tol, false, history)
-}
-
-/// Sew the exact sections between successive levels, including empty gaps. With `coalesce`,
-/// walls over one segment through successive slabs are one face.
-fn sew_sections(
- plane: &Plane,
- d: Vec3,
- levels: &[f64],
- slabs: &[Section],
- tol: f64,
- coalesce: bool,
- history: &lineage::Context,
-) -> Option<Result<Body>> {
- if levels.len() != slabs.len() + 1
- || slabs.len() > 128
- || plane.normal().dot(d) < 1. - 1e-12
- || levels.iter().any(|z| !z.is_finite())
- || levels.windows(2).any(|z| z[0] >= z[1])
- {
- return None;
- }
- let mut blocks = Vec::new();
- let mut start = None;
- for (i, slab) in slabs.iter().enumerate() {
- if slab.regions.is_empty() {
- if let Some(first) = start.take() {
- blocks.push((first, i));
- }
- } else if start.is_none() {
- start = Some(i);
- }
- }
- if let Some(first) = start {
- blocks.push((first, slabs.len()));
- }
- if blocks.is_empty() {
- return None;
- }
- Some((|| {
- let mut pieces = Vec::new();
- let mut remaining_constructed_faces = MAX_PLANAR_SEGMENTS * 2;
- let mut remaining_faces = MAX_PLANAR_SEGMENTS * 2;
- for (first, end) in blocks {
- let tagged = slabs.get(first).ok_or_else(|| KernelError::Failed("missing prism section".into()))?;
- let section = &tagged.regions;
- if slabs[first..end].iter().all(|s| s.regions == *section) {
- let edge_count = section.iter().flat_map(|r| std::iter::once(&r.outer).chain(&r.holes)).flat_map(|l| &l.segs).fold(0usize, |n, s| {
- n.saturating_add(match s {
- Seg2::Arc { sweep, .. } if sweep.abs() > 1.5 * std::f64::consts::PI => 2,
- _ => 1,
- })
- });
- remaining_constructed_faces = remaining_constructed_faces
- .checked_sub(edge_count.saturating_add(section.len().saturating_mul(2)))
- .ok_or_else(|| KernelError::Failed("prism construction face budget".into()))?;
- // This is a NEW exact extrusion of the current Boolean section,
- // not copied lineage from either operand's old footprint.
- for (r, piece) in crate::extrude(plane, section, levels[first], levels[end])?.into_iter().enumerate() {
- remaining_faces =
- remaining_faces.checked_sub(piece.face_count()).ok_or_else(|| KernelError::Failed("prism output face budget".into()))?;
- // Each slab's section, as read there: the same outline, but its walls
- // read beside whichever operand is there.
- let layers =
- (first..end).map(|k| Some((slabs.get(k)?.region(r), *levels.get(k)?, *levels.get(k + 1)?))).collect::<Option<Vec<_>>>();
- let layers = layers.ok_or_else(|| KernelError::Failed("missing prism section".into()))?;
- pieces.push((piece, lineage::Built::Extruded { layers }));
- }
- } else {
- let (piece, built) = sew_connected_sections(plane, d, &levels[first..=end], &slabs[first..end], tol, coalesce, history)
- .ok_or_else(|| KernelError::Failed("stepped prism construction failed".into()))??;
- remaining_faces =
- remaining_faces.checked_sub(piece.face_count()).ok_or_else(|| KernelError::Failed("prism output face budget".into()))?;
- pieces.push((piece, built));
- }
- }
- let mut old = std::collections::HashMap::new();
- let mut shells = Vec::new();
- let mut remaining_map_faces = MAX_PLANAR_SEGMENTS * 2;
- for (piece, _) in &pieces {
- for (index, face) in piece.solid.face_iter().enumerate() {
- remaining_map_faces = remaining_map_faces.checked_sub(1).ok_or_else(|| KernelError::Failed("prism output face budget".into()))?;
- let source = piece.face_sources().and_then(|s| s.get(index)).and_then(Option::as_ref);
- if old.insert(face.id(), Some((face.orientation(), source))).is_some() {
- old.insert(face.id(), None);
- }
- }
- shells.extend(piece.solid.boundaries().iter().cloned());
- }
- let body = Body::new(crate::body::Solid::try_new(shells).map_err(|e| KernelError::Failed(format!("prism compound: {e}")))?)?;
- let sources = body
- .solid
- .face_iter()
- .map(|face| match old.get(&face.id()) {
- Some(Some((orientation, source))) if *orientation == face.orientation() => source.cloned(),
- _ => None,
- })
- .collect();
- let body = body.with_face_sources(Some(std::sync::Arc::new(sources)));
- Ok(history.attach(body, &pieces))
- })())
-}
-
-/// Stable exact identity for the bounded analytic segment subset.
-fn wall_key(s: &Seg2) -> Option<[u64; 6]> {
- let bits = |v: f64| v.is_finite().then(|| if v == 0. { 0 } else { v.to_bits() });
- match s {
- Seg2::Line { a, b } => Some([0, bits(a.x)?, bits(a.y)?, bits(b.x)?, bits(b.y)?, 0]),
- Seg2::Arc { center, radius, start, sweep } => Some([1, bits(center.x)?, bits(center.y)?, bits(*radius)?, bits(*start)?, bits(*sweep)?]),
- // Its ends and a point between them: free-form segments with the same ones are the same
- // curve as far as a wall over it goes.
- _ => {
- let (a, m, b) = (s.start(), s.point_at(0.5), s.end());
- let h = |x: f64, y: f64| bits(x).zip(bits(y)).map(|(x, y)| x ^ y.rotate_left(17));
- Some([2, h(a.x, a.y)?, h(m.x, m.y)?, h(b.x, b.y)?, bits(m.x)?, bits(m.y)?])
- }
- }
-}
-
-/// A free-form segment as the control points of the cubic Bézier it is (a quadratic raised to
-/// a cubic); `None` for those no cubic is exactly (rational conics, higher degrees).
-fn cubic_of(s: &Seg2) -> Option<[Vec2; 4]> {
- match *s {
- Seg2::Cubic { p0, p1, p2, p3 } => Some([p0, p1, p2, p3]),
- Seg2::Conic { a, apex, b, w } if (w - 1.0).abs() < 1e-12 => Some([a, a + (apex - a) * (2.0 / 3.0), b + (apex - b) * (2.0 / 3.0), b]),
- Seg2::Bezier { n: 3, p } => Some([p[0], p[1], p[2], p[3]]),
- _ => None,
- }
-}
-
-/// A genuinely stepped connected axial block has no single extrusion footprint.
-fn sew_connected_sections(
- plane: &Plane,
- d: Vec3,
- levels: &[f64],
- slabs: &[Section],
- tol: f64,
- coalesce: bool,
- history: &lineage::Context,
-) -> Option<Result<(Body, lineage::Built)>> {
- use crate::sew::{EdgeSpec, FaceSpec, SurfSpec};
- // Faces at each level: up where the slab below sticks out, down where the one above does.
- let diff = |x: &Section, y: &Section| -> Option<Section> {
- match (x.regions.is_empty(), y.regions.is_empty()) {
- (true, _) => Some(Section::default()),
- (false, true) => Some(x.clone()),
- (false, false) => boolean2d_tagged(x, y, BoolOp::Cut, tol).map(|r| r.oriented()),
- }
- };
- let empty = Section::default();
- let mut caps: Vec<(f64, bool, Section)> = Vec::new();
- for (k, z) in levels.iter().enumerate() {
- let below: &Section = if k == 0 { &empty } else { slabs.get(k - 1)? };
- let above: &Section = slabs.get(k).unwrap_or(&empty);
- caps.push((*z, true, diff(below, above)?));
- caps.push((*z, false, diff(above, below)?));
- }
- // Every segment end, everywhere: outlines split there.
- let loops_of =
- |rs: &[Region2]| -> Vec<Loop2> { rs.iter().flat_map(|r| std::iter::once(r.outer.clone()).chain(r.holes.iter().cloned())).collect() };
- let mut pts: Vec<Vec2> = Vec::new();
- for lp in slabs.iter().flat_map(|s| loops_of(&s.regions)).chain(caps.iter().flat_map(|c| loops_of(&c.2.regions))) {
- for sg in &lp.segs {
- pts.push(sg.start());
- pts.push(sg.end());
- }
- }
- // Ends within `tol` of each other are one point. The 2D boolean closes its loops within
- // `tol`, not exactly: where a font's nearly round curve was read as an arc, the arc ends a
- // few hundredths of a micron from the curve next to it. Sewing joins only ends at the same
- // point, so such a loop would not close.
- let cell = |u: Vec2| ((u.x / tol).floor() as i64, (u.y / tol).floor() as i64);
- let mut ends: Vec<Vec2> = Vec::new();
- let mut grid: std::collections::HashMap<(i64, i64), Vec<usize>> = std::collections::HashMap::new();
- let weld = |ends: &[Vec2], grid: &std::collections::HashMap<(i64, i64), Vec<usize>>, u: Vec2| -> Option<Vec2> {
- let (cx, cy) = cell(u);
- (cx - 1..=cx + 1)
- .flat_map(|x| (cy - 1..=cy + 1).map(move |y| (x, y)))
- .filter_map(|c| grid.get(&c))
- .flatten()
- .filter_map(|&i| ends.get(i).copied())
- .find(|e| e.dist(u) <= tol)
- };
- for &u in &pts {
- if weld(&ends, &grid, u).is_none() {
- grid.entry(cell(u)).or_default().push(ends.len());
- ends.push(u);
- }
- }
- // Welding above keeps its original encounter order. Side splitting needs
- // only the distinct stations, whose resulting parameters are sorted anyway.
- // Deduplicate in place, with bounded sorting work and no extra point list.
- if pts.len() <= MAX_PLANAR_SEGMENTS * 8 {
- pts.sort_unstable_by(|a, b| a.x.total_cmp(&b.x).then(a.y.total_cmp(&b.y)));
- pts.dedup_by_key(|p| (p.x.to_bits(), p.y.to_bits()));
- }
- // A piece of a free-form curve whose ends weld into one point (a font's curve cut a hair from
- // its end) is no edge and has no wall: the pieces on either side meet there. (Lines and arcs
- // are left as they were: such a piece of one fails the sewing, as before.)
- let short = |s: &Seg2| {
- !s.is_line_or_arc()
- && s.length() <= 2.0 * tol
- && matches!((weld(&ends, &grid, s.start()), weld(&ends, &grid, s.end())), (Some(p), Some(q)) if p == q)
- };
- // One curve between two ends, as the walls and the caps beside them each read it: their
- // sections come from different booleans, which split it from different pieces, so the
- // control points can differ by a hair, and sewing tells edges apart by them. The first
- // reading stands for all of them.
- let chains: std::cell::RefCell<Vec<[Vec3; 4]>> = std::cell::RefCell::new(Vec::new());
- let same_chain = |c: [Vec3; 4]| -> [Vec3; 4] {
- let mid = |k: &[Vec3; 4]| (k[0] + (k[1] + k[2]) * 3.0 + k[3]) * 0.125;
- let mut known = chains.borrow_mut();
- for k in known.iter() {
- if mid(k).dist(mid(&c)) <= tol * 10.0 {
- if k[0] == c[0] && k[3] == c[3] {
- return *k;
- }
- if k[0] == c[3] && k[3] == c[0] {
- return [k[3], k[2], k[1], k[0]];
- }
- }
- }
- known.push(c);
- c
- };
- let at = |u: Vec2, z: f64| plane.to_world(u) + d * z;
- let welded = |u: Vec2, z: f64| at(weld(&ends, &grid, u).unwrap_or(u), z);
- // One edge between two ends, whichever way a wall or a cap reads the curve there: a piece of
- // a font's curve so short that one section reads it as an arc within the tolerance, where
- // another has the curve itself (the same letters cut again), is one edge. The first reading
- // stands for all of them.
- let readings: std::cell::RefCell<Vec<(Vec3, Vec3, Vec3, EdgeSpec)>> = std::cell::RefCell::new(Vec::new());
- let same_edge = |spec: EdgeSpec, a: Vec3, b: Vec3, mid: Vec3| -> EdgeSpec {
- let mut known = readings.borrow_mut();
- for (ka, kb, km, k) in known.iter() {
- if km.dist(mid) <= tol * 10.0 {
- if *ka == a && *kb == b {
- return k.clone();
- }
- if *ka == b && *kb == a {
- return k.reversed();
- }
- }
- }
- known.push((a, b, mid, spec.clone()));
- spec
- };
- let edge = |sg: &Seg2, z: f64| -> Option<EdgeSpec> {
- Some(match sg {
- Seg2::Line { .. } => EdgeSpec::Line { a: welded(sg.start(), z), b: welded(sg.end(), z) },
- Seg2::Arc { .. } => {
- let (a, b, mid) = (welded(sg.start(), z), welded(sg.end(), z), at(sg.point_at(0.5), z));
- same_edge(EdgeSpec::Arc { a, b, mid }, a, b, mid)
- }
- _ => {
- let [p0, p1, p2, p3] = cubic_of(sg)?;
- let c = same_chain([welded(p0, z), at(p1, z), at(p2, z), welded(p3, z)]);
- let mid = (c[0] + (c[1] + c[2]) * 3.0 + c[3]) * 0.125;
- same_edge(EdgeSpec::Chain { degree: 3, ctrl: c.to_vec().into() }, c[0], c[3], mid)
- }
- })
- };
- // Exact oriented generated segments alone define a run. No support fitting,
- // proximity matching, or old face lineage is used here.
- // Each run, with what its wall is over in each of its slabs (for the result's history).
- type Run = (usize, usize, Seg2, Vec<lineage::Slab>);
- let mut runs: Vec<Run> = Vec::new();
- let mut last = std::collections::BTreeMap::new();
- let mut remaining = MAX_PLANAR_SEGMENTS * 2;
- for (i, slab) in slabs.iter().enumerate() {
- for (r, reg) in slab.regions.iter().enumerate() {
- for (l, lp) in std::iter::once(&reg.outer).chain(&reg.holes).enumerate() {
- // The loop's walls in order: the run each joins, its tag and where it ends.
- let mut around: Vec<(usize, Tag, Vec2)> = Vec::new();
- for (si, sg0) in lp.segs.iter().enumerate() {
- let pieces = split_seg(sg0, &pts, tol)?;
- let (n, tag) = (pieces.len(), slab.tag(r, l, si));
- for (k, sg) in pieces.into_iter().enumerate() {
- if short(&sg) {
- continue;
- }
- remaining = remaining.checked_sub(1)?;
- let key = wall_key(&sg)?;
- let prior = if coalesce { last.get(&key).copied() } else { None };
- let run = match prior.map(|index| runs.get_mut(index).map(|run: &mut Run| (index, run))) {
- Some(None) => return None,
- Some(Some((index, run))) if run.1 == i => {
- run.1 = i + 1;
- index
- }
- // Duplicate oriented boundaries in one slab are not
- // a valid reason to reconstruct a larger wall.
- Some(Some((_, run))) if run.1 == i + 1 => return None,
- _ => {
- if coalesce {
- last.insert(key, runs.len());
- }
- runs.push((i, i + 1, sg, Vec::new()));
- runs.len() - 1
- }
- };
- around.push((run, tag.piece(k, n), sg.end()));
- }
- }
- // Each wall runs into the next one of its loop, the last into the first.
- for (k, (run, tag, at)) in around.iter().enumerate() {
- let next = around.get((k + 1) % around.len())?.0;
- runs.get_mut(*run)?.3.push(lineage::Slab { tag: *tag, next, at: *at });
- }
- }
- }
- }
- let mut faces: Vec<FaceSpec> = Vec::new();
- let mut sources = Vec::new();
- let mut specs: Vec<lineage::Spec> = Vec::with_capacity(runs.len());
- let frame_is_orthonormal = plane.origin.is_finite()
- && plane.x.is_finite()
- && plane.y.is_finite()
- && d.is_finite()
- && (plane.x.len2() - 1.).abs() <= 64. * f64::EPSILON
- && (plane.y.len2() - 1.).abs() <= 64. * f64::EPSILON
- && (d.len2() - 1.).abs() <= 64. * f64::EPSILON
- && plane.x.dot(plane.y).abs() <= 64. * f64::EPSILON
- && plane.x.dot(d).abs() <= 64. * f64::EPSILON
- && plane.y.dot(d).abs() <= 64. * f64::EPSILON;
- for (first, end, sg, over) in runs {
- let (z0, z1) = (levels[first], levels[end]);
- let (a, b) = (sg.start(), sg.end());
- let mut lp3 = Vec::with_capacity(2 + 2 * (end - first));
- lp3.push(edge(&sg, z0)?);
- // Keep station vertices at both ends: neighboring stepped walls/caps
- // must share complete edges rather than create T-junctions.
- for k in first..end {
- lp3.push(EdgeSpec::Line { a: welded(b, levels[k]), b: welded(b, levels[k + 1]) });
- }
- lp3.push(edge(&sg.reversed(), z1)?);
- for k in (first..end).rev() {
- lp3.push(EdgeSpec::Line { a: welded(a, levels[k + 1]), b: welded(a, levels[k]) });
- }
- let outward = plane.dir_to_world(sg.derivative(0.5)).cross(d).normalized()?;
- let surface = match sg {
- Seg2::Line { .. } => SurfSpec::Plane,
- Seg2::Arc { .. } => SurfSpec::Extruded { a: at(a, z0), b: at(b, z0), mid: at(sg.point_at(0.5), z0), dir: d * (z1 - z0) },
- // A free-form wall: the lines along `d` joining the curve at both levels.
- _ => SurfSpec::Ruled { a: edge(&sg, z0)?, b: edge(&sg, z1)? },
- };
- faces.push(FaceSpec { loops: vec![lp3], surface, probe: Some((at(sg.point_at(0.5), (z0 + z1) / 2.0), outward)) });
- // Axis-aligned generated lines have a common oriented support frame
- // independent of axial stations or along-line endpoint interpolation.
- let generated_plane = if coalesce
- && frame_is_orthonormal
- && let Seg2::Line { a, b } = sg
- {
- let (origin, x) = if a.y == b.y && a.x != b.x {
- (at(Vec2::new(0., a.y), 0.), plane.x * (b.x - a.x).signum())
- } else if a.x == b.x && a.y != b.y {
- (at(Vec2::new(a.x, 0.), 0.), plane.y * (b.y - a.y).signum())
- } else {
- (Vec3::ZERO, Vec3::ZERO)
- };
- (origin.is_finite() && x.len2() > 0.).then_some(Plane { origin, x, y: d })
- } else {
- None
- };
- sources.push((generated_plane.is_some() || end > first + 1).then_some(crate::FaceSource::ExtrudeSide {
- segment: sg,
- plane: generated_plane,
- coalesced: end > first + 1,
- }));
- specs.push(lineage::Spec::Wall { levels: levels.get(first..=end)?.to_vec(), slabs: over });
- }
- for (z, up, rs) in &caps {
- for (ri, r) in rs.regions.iter().enumerate() {
- let mut loops = Vec::new();
- for lp in std::iter::once(&r.outer).chain(&r.holes) {
- let mut segs: Vec<Seg2> = Vec::new();
- for sg in &lp.segs {
- segs.extend(split_seg(sg, &pts, tol)?.into_iter().filter(|s| !short(s)));
- }
- let segs: Vec<Seg2> = if *up { segs } else { segs.iter().rev().map(Seg2::reversed).collect() };
- loops.push(segs.iter().map(|sg| edge(sg, *z)).collect::<Option<Vec<_>>>()?);
- }
- faces.push(FaceSpec { loops, surface: SurfSpec::Plane, probe: None });
- sources.push(None);
- specs.push(lineage::Spec::Cap { section: rs.region(ri), z: *z, up: *up });
- }
- }
- let sewn = crate::sew::sew_touching_with_sources(&faces, &sources).map(|(body, from)| (body, lineage::Built::Sewn { specs, faces: from }));
- // Generated walls joined on their common supports: the piece's history over the operands,
- // carried through the joining.
- Some(if coalesce {
- sewn.and_then(|(body, built)| {
- let body = history.attach(body.clone(), &[(&body, built)]).regularize_generated_planar_faces()?;
- Ok((body, lineage::Built::Traced))
- })
- } else {
- sewn
- })
-}
-
-#[cfg(test)]
-fn simple_prism_boolean(a: &Body, b: &Body, op: BoolOp) -> Option<Result<Option<Body>>> {
- simple_prism_indexed(a, b, op, [&LazyIndex::new(a, 0), &LazyIndex::new(b, 1)])
-}
-
-/// [`prism_boolean`] of single prisms, the operands' indexes given.
-fn simple_prism_indexed(a: &Body, b: &Body, op: BoolOp, [ia, ib]: [&LazyIndex; 2]) -> Option<Result<Option<Body>>> {
- let size = a.size().max(b.size());
- let tol = (size * 1e-7).max(1e-9) * 10.0;
- // Candidate directions (each line once, pointing up).
- let dirs: Vec<Vec3> = directions(a, b)?.into_iter().map(|n| if n.dot(Vec3::new(1e-3, 1e-6, 1.0)) < 0.0 { -n } else { n }).collect();
- let (d, plane, pa, pb) = dirs.into_iter().find_map(|d| {
- let plane = Plane::from_normal(Vec3::ZERO, d)?;
- let pa = prism_tagged(a, d, &plane, tol, ia)?;
- let pb = prism_tagged(b, d, &plane, tol, ib)?;
- Some((d, plane, pa, pb))
- })?;
- let history = lineage::Context::new(op, [a, b], [ia.get(), ib.get()], plane, tol, Some([(pa.lo, pa.hi), (pb.lo, pb.hi)]));
- let (blo, bhi) = heights_of(b, &plane);
- let spans = blo <= pa.lo + tol && bhi >= pa.hi - tol;
- let same = (pb.lo - pa.lo).abs() < tol && (pb.hi - pa.hi).abs() < tol;
- let area =
- |rs: &[Region2]| rs.iter().map(|r| r.outer.signed_area().abs() - r.holes.iter().map(|h| h.signed_area().abs()).sum::<f64>()).sum::<f64>();
- // Prisms of one section overlapping or touching end to end: one longer prism.
- let stacked = op == BoolOp::Union && !same && pb.lo <= pa.hi + tol && pa.lo <= pb.hi + tol;
- let ok = match op {
- BoolOp::Cut | BoolOp::Intersect => spans,
- BoolOp::Union => same || stacked,
- };
- if !ok {
- return None;
- }
- let section = boolean2d_tagged(&pa.section, &pb.section, op, tol)?;
- let regions = &section.regions;
- if regions.is_empty() {
- return Some(Ok(None));
- }
- let (u, x, y) = (area(regions), area(&pa.section.regions), area(&pb.section.regions));
- let alike = |v: f64| (u - v).abs() <= tol * (1.0 + u);
- // A tool that misses its target (or an intersection that is one operand whole) leaves it
- // as it is: the B-rep boolean reuses that operand itself, where this would rebuild it.
- if matches!(op, BoolOp::Cut | BoolOp::Intersect) && (same_area(u, x, tol) || (op == BoolOp::Intersect && same_area(u, y, tol))) {
- return None;
- }
- let (lo, hi) = if stacked {
- // Different sections (a boss hanging over a plate's edge): sewn slab by slab.
- if !alike(x) || !alike(y) {
- return sew_stack(&plane, d, &pa, &pb, tol, &history).map(|r| r.map(Some));
- }
- // One outline end to end: also slab by slab, so the history follows each operand's
- // walls (one longer prism, whose walls are made from both).
- if let Some(Ok(body)) = sew_stack(&plane, d, &pa, &pb, tol, &history)
- && body.history().is_some()
- {
- return Some(Ok(Some(body)));
- }
- (pa.lo.min(pb.lo), pa.hi.max(pb.hi))
- } else {
- (pa.lo, pa.hi)
- };
- let base = plane.offset(lo);
- let bodies = match crate::extrude(&base, regions, 0.0, hi - lo) {
- Ok(b) => b,
- Err(e) => return Some(Err(e)),
- };
- // Each body over its region.
- let mut pieces: Vec<(Body, lineage::Built)> =
- bodies.into_iter().enumerate().map(|(r, b)| (b, lineage::Built::Extruded { layers: vec![(section.region(r), lo, hi)] })).collect();
- let last = pieces.pop()?;
- if !pieces.is_empty() {
- // Several pieces: one body of several lumps (the last first).
- pieces.push(last);
- pieces.rotate_right(1);
- let shells: Vec<mt::Shell> = pieces.iter().flat_map(|(b, _)| b.solid.boundaries().iter().cloned()).collect();
- return Some(
- crate::body::Solid::try_new(shells)
- .map_err(|e| crate::KernelError::Failed(e.to_string()))
- .and_then(Body::new)
- .map(|body| Some(history.attach(body, &pieces))),
- );
- }
- Some(Ok(Some(history.attach(last.0.clone(), &[last]))))
-}
-
-/// The directions to try the operands as prisms along: the first eight plane directions of the
-/// target (in its face order), then those of the tool's caps (a pair of opposite plane faces)
-/// that the target has further on. A target cut many times over (a line of text, a group of
-/// letters at a time) has more plane directions than eight, its walls' among them: in face
-/// order its caps' direction can come too late. `None` past the face budget.
-fn directions(a: &Body, b: &Body) -> Option<Vec<Vec3>> {
- if a.face_count().saturating_add(b.face_count()) > MAX_PLANAR_SEGMENTS * 2 {
- return None;
- }
- let normals = |x: &Body| -> Vec<Vec3> {
- x.solid
- .face_iter()
- .filter_map(|f| match f.oriented_surface() {
- mt::Surface::Plane(p) => {
- let n = p.normal();
- Vec3::new(n.x, n.y, n.z).normalized()
- }
- _ => None,
- })
- .collect()
- };
- let mut target: Vec<Vec3> = Vec::new();
- for n in normals(a) {
- if !target.iter().any(|m| m.dot(n).abs() > 1.0 - 1e-9) {
- target.push(n);
- }
- }
- let tool = normals(b);
- let capped = |d: &Vec3| tool.iter().any(|n| n.dot(*d) > 1.0 - 1e-9) && tool.iter().any(|n| n.dot(*d) < -1.0 + 1e-9);
- let mut dirs: Vec<Vec3> = target.iter().take(8).copied().collect();
- dirs.extend(target.iter().skip(8).filter(|d| capped(d)).take(8));
- Some(dirs)
-}
-
-/// The direction `b` is a prism (or a stack of prisms) along: the first of its planar faces'
-/// normals along which it is one. `None` when there is none.
-pub(crate) fn prism_axis(b: &Body) -> Option<Vec3> {
- if b.face_count() > MAX_PLANAR_SEGMENTS {
- return None;
- }
- let tol = (b.size() * 1e-7).max(1e-9) * 10.0;
- let index = LazyIndex::new(b, 1);
- let mut tried: Vec<Vec3> = Vec::new();
- for f in b.solid.face_iter() {
- let mt::Surface::Plane(p) = f.oriented_surface() else { continue };
- let n = p.normal();
- let Some(n) = Vec3::new(n.x, n.y, n.z).normalized() else { continue };
- if tried.iter().any(|m| m.dot(n).abs() > 1.0 - 1e-9) {
- continue;
- }
- tried.push(n);
- if tried.len() > 16 {
- return None;
- }
- let plane = Plane::from_normal(Vec3::ZERO, n)?;
- if stack_tagged(b, n, &plane, tol, &index).is_some() {
- return Some(n);
- }
- }
- None
-}
-
-/// Whether a boolean of sections left one of area `v` as it was (area `u` after): the same to
-/// within rounding, as the very same outline gives (a change is at least a sliver `tol` wide).
-fn same_area(u: f64, v: f64, tol: f64) -> bool {
- (u - v).abs() <= 1e-9 * u.abs().max(v.abs()) + tol * tol
-}
-
-/// A stepped extrusion (case floor plus walls), recovered from its cap events.
-/// Downward caps add a section above their level; upward caps remove one.
-#[cfg(test)]
-fn stack_of(b: &Body, d: Vec3, plane: &Plane, tol: f64) -> Option<Vec<Prism>> {
- stack_tagged(b, d, plane, tol, &LazyIndex::new(b, 0))
-}
-
-/// [`stack_of`], its sections' segments tagged from `index` (the body's).
-fn stack_tagged(b: &Body, d: Vec3, plane: &Plane, tol: f64, index: &LazyIndex) -> Option<Vec<Prism>> {
- if let Some(p) = prism_tagged(b, d, plane, tol, index) {
- return Some(vec![p]);
- }
- if b.face_count() > 2048 {
- return None;
- }
- let mut events = Vec::new();
- let mut walls = std::collections::HashMap::new();
- let mut wall_work = 262_144;
- let mut curve_work = 2_000_000;
- let mut segments = usize::MAX;
- for (fi, f) in b.solid.face_iter().enumerate() {
- let surf = f.oriented_surface();
- if let mt::Surface::Plane(p) = &surf {
- let n = p.normal();
- let n = Vec3::new(n.x, n.y, n.z).normalized()?;
- if n.dot(d).abs() > 1.0 - 1e-9 {
- let section = Section::from_loops(index.get().loops(f, fi, plane, tol, &mut curve_work, &mut segments)?)?;
- events.push((plane.height(from_p3(p.origin())), n.dot(d) > 0.0, section.oriented(), fi));
- continue;
- }
- if n.dot(d).abs() > 1e-9 {
- return None;
- }
- } else if !wall_along(&surf, d, tol, &mut wall_work) {
- return None;
- }
- walls.insert(fi, top_of(f, plane));
- }
- let mut levels: Vec<f64> = events.iter().map(|(z, _, _, _)| *z).collect();
- levels.sort_by(f64::total_cmp);
- levels.dedup_by(|x, y| (*x - *y).abs() < tol);
- if levels.len() < 2 || levels.len() > 64 || levels.iter().any(|z| !z.is_finite()) {
- return None;
- }
- let stations = Stations::new(index.get(), walls, d, plane, tol);
- let mut current = Section::default();
- let mut stack: Vec<Prism> = Vec::new();
- let mut budget = MAX_PLANAR_PAIRS;
- for (i, z) in levels.iter().enumerate() {
- // The caps here end the slab below: its walls meet them.
- if let Some(below) = stack.last_mut().filter(|p| (p.hi - *z).abs() < tol) {
- let (faces, caps): (Vec<usize>, Vec<&Section>) =
- events.iter().filter(|(h, _, _, _)| (*h - *z).abs() < tol).map(|(_, _, s, f)| (*f, s)).unzip();
- below.section.mark_far(&caps, |w| stations.top_edge(index.get(), w, &faces, *z, tol), tol, &mut budget);
- }
- // The segments carried here run on past it, beside the walls there.
- current.retag(|t| match t.wall {
- Some(w) => t.beside(stations.past(w, *z, tol)),
- None => t,
- });
- // Remove terminating material before adding any material starting here.
- for up in [true, false] {
- for (_, _, section, _) in events.iter().filter(|(h, u, _, _)| (*h - *z).abs() < tol && *u == up) {
- current = match (current.regions.is_empty(), up) {
- (true, false) => section.clone(),
- (true, true) => return None,
- (false, _) => boolean2d_tagged(&current, section, if up { BoolOp::Cut } else { BoolOp::Union }, tol)?,
- };
- }
- }
- if let Some(next) = levels.get(i + 1)
- && !current.regions.is_empty()
- {
- current.drop_crossed(&stations, *z, *next, tol);
- stack.push(Prism { lo: *z, hi: *next, section: current.oriented() });
- }
- }
- (current.regions.is_empty() && !stack.is_empty()).then_some(stack)
-}
-
-#[cfg(test)]
-fn stack_boolean(a: &Body, b: &Body, op: BoolOp) -> Option<Result<Option<Body>>> {
- stack_indexed(a, b, op, [&LazyIndex::new(a, 0), &LazyIndex::new(b, 1)], true)
-}
-
-/// [`prism_boolean`] of stepped prisms, the operands' indexes given. A union is taken of
-/// operands that end at a common level when `common_cap` is set, else of those that don't (see
-/// [`prism_union_between_caps`]).
-fn stack_indexed(a: &Body, b: &Body, op: BoolOp, [ia, ib]: [&LazyIndex; 2], common_cap: bool) -> Option<Result<Option<Body>>> {
- // Common-cap joins and overlapping partial-depth cuts of aligned stepped prisms can
- // retain their exact section boundaries instead of intersecting meshes.
- // Nonaligned bodies retain their existing B-rep path.
- if !matches!(op, BoolOp::Union | BoolOp::Cut) {
- return None;
- }
- if op == BoolOp::Cut && a.face_count().saturating_add(b.face_count()) > 2048 {
- return None;
- }
- fn section(ps: &[Prism], lo: f64, hi: f64, tol: f64) -> Section {
- ps.iter().find(|p| p.lo <= lo + tol && p.hi >= hi - tol).map(|p| p.section.clone()).unwrap_or_default()
- }
- let tol = (a.size().max(b.size()) * 1e-7).max(1e-9) * 10.0;
- let dirs = directions(a, b)?;
- let ends = |ps: &[Prism]| ps.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), p| (lo.min(p.lo), hi.max(p.hi)));
- let (d, plane, pa, pb) = dirs.into_iter().find_map(|d| {
- let plane = Plane::from_normal(Vec3::ZERO, d)?;
- let pa = stack_tagged(a, d, &plane, tol, ia)?;
- let pb = stack_tagged(b, d, &plane, tol, ib)?;
- let (ea, eb) = (ends(&pa), ends(&pb));
- let shared = (ea.0 - eb.0).abs() < tol || (ea.1 - eb.1).abs() < tol;
- match op {
- BoolOp::Union if shared != common_cap => return None,
- // A cut tool may extend past a cap into empty space. Exact slab sections
- // discard that space rather than intersecting coincident cylinder walls.
- BoolOp::Cut if ea.1 <= eb.0 + tol || eb.1 <= ea.0 + tol => return None,
- _ => {}
- }
- Some((d, plane, pa, pb))
- })?;
- let mut levels: Vec<f64> = pa.iter().chain(&pb).flat_map(|p| [p.lo, p.hi]).collect();
- levels.sort_by(f64::total_cmp);
- levels.dedup_by(|x, y| (*x - *y).abs() < tol);
- let mut slabs = Vec::new();
- let mut work = 0usize;
- let mut output_edges = 0usize;
- let area =
- |rs: &[Region2]| rs.iter().map(|r| r.outer.signed_area().abs() - r.holes.iter().map(|h| h.signed_area().abs()).sum::<f64>()).sum::<f64>();
- // Whether some slab's section came out other than the target's (else the tool missed it).
- let mut changed = false;
- let edges = |regions: &[Region2]| regions.iter().flat_map(|r| std::iter::once(&r.outer).chain(&r.holes)).map(|l| l.segs.len()).sum::<usize>();
- for w in levels.windows(2) {
- let (lo, hi) = (*w.first()?, *w.get(1)?);
- let (x, y) = (section(&pa, lo, hi, tol), section(&pb, lo, hi, tol));
- let before = area(&x.regions);
- if op == BoolOp::Cut {
- let count = edges(&x.regions).saturating_add(edges(&y.regions));
- work = work.saturating_add(count.saturating_mul(count));
- if work > 32_000_000 {
- return None;
- }
- }
- let s = match (x.regions.is_empty(), y.regions.is_empty(), op) {
- (true, _, BoolOp::Cut | BoolOp::Intersect) | (_, true, BoolOp::Intersect) => Section::default(),
- (true, _, BoolOp::Union) => y,
- (_, true, _) => x,
- _ => boolean2d_tagged(&x, &y, op, tol)?,
- };
- changed |= !same_area(area(&s.regions), before, tol);
- if op == BoolOp::Cut {
- output_edges = output_edges.saturating_add(edges(&s.regions));
- if output_edges > 8192 {
- return None;
- }
- }
- slabs.push(s.oriented());
- }
- if slabs.iter().all(|s| s.regions.is_empty()) {
- return Some(Ok(None));
- }
- // A cut that takes nothing leaves the target as it is: the B-rep boolean reuses it itself,
- // where this would rebuild it.
- if op == BoolOp::Cut && !changed {
- return None;
- }
- let history = lineage::Context::new(op, [a, b], [ia.get(), ib.get()], plane, tol, None);
- let coalesce = op == BoolOp::Cut
- && !a.regularization_protected
- && !b.regularization_protected
- && a.split_keep().is_empty()
- && b.split_keep().is_empty()
- && a.paint().is_none_or(|p| p.faces.is_empty())
- && b.paint().is_none_or(|p| p.faces.is_empty());
- sew_sections(&plane, d, &levels, &slabs, tol, coalesce, &history).map(|r| r.map(Some))
-}
-
-thread_local! {
- /// Set while [`prism_boolean_free_form`] runs: spline outlines are read as arcs within
- /// [`PLANAR_FIT_TOL`] instead of refusing the prism.
- static FREE_FORM: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
-}
-
-/// [`prism_boolean`] for prisms whose walls are splines (swept along one): the outlines are
-/// fitted by arcs within [`PLANAR_FIT_TOL`], so the result is exact to that, and the walls it
-/// keeps are those arcs. Only for bodies the caller knows are such sweeps.
-pub(crate) fn prism_boolean_free_form(a: &Body, b: &Body, op: BoolOp) -> Option<Result<Option<Body>>> {
- /// Clears the flag however the boolean ends, a caught panic included.
- struct Reset;
- impl Drop for Reset {
- fn drop(&mut self) {
- FREE_FORM.with(|c| c.set(false));
- }
- }
- FREE_FORM.with(|c| c.set(true));
- let _reset = Reset;
- prism_boolean(a, b, op)
-}
-
-/// Boolean of prisms along a common direction, in 2D (see the module notes); `None` when it
-/// doesn't apply. The result carries its history over `[a, b]` (see [`lineage`]).
-pub(crate) fn prism_boolean(a: &Body, b: &Body, op: BoolOp) -> Option<Result<Option<Body>>> {
- // Each operand's index is built once, and only if it is read as a prism.
- let index = [&LazyIndex::new(a, 0), &LazyIndex::new(b, 1)];
- crate::guard("prism boolean", || Ok(simple_prism_indexed(a, b, op, index).or_else(|| stack_indexed(a, b, op, index, true)))).ok().flatten()
-}
-
-/// [`prism_boolean`] of a union of stepped prisms along one direction that end at different
-/// levels (a barrel joined between two faces of a wider part, its ends flush with them), which
-/// that route leaves to the B-rep boolean: for when that boolean has failed. `None` for other
-/// operations and operands.
-pub(crate) fn prism_union_between_caps(a: &Body, b: &Body, op: BoolOp) -> Option<Result<Option<Body>>> {
- if op != BoolOp::Union {
- return None;
- }
- let index = [&LazyIndex::new(a, 0), &LazyIndex::new(b, 1)];
- crate::guard("prism boolean", || Ok(stack_indexed(a, b, op, index, false))).ok().flatten()
-}
-
#[cfg(test)]
mod planar_tests {
use super::*;
@@ -2644,370 +1331,17 @@ mod planar_tests {
Region2 { outer: Loop2::polygon(&[a, Vec2::new(b.x, a.y), b, Vec2::new(a.x, b.y)]), holes: vec![] }
}
#[test]
- fn simple_prism_retains_large_analytic_section_budget() {
- let count = 2050;
- let radius = 1000.;
- let points: Vec<_> = (0..count)
- .map(|i| {
- let angle = std::f64::consts::TAU * i as f64 / count as f64;
- Vec2::new(radius * angle.cos(), radius * angle.sin())
- })
- .collect();
- let region = Region2 { outer: Loop2::polygon(&points), holes: vec![] };
- let stock = crate::extrude(&Plane::XY, &[region], 0., 2.).unwrap().pop().unwrap();
- assert_eq!(stock.face_count(), count + 2);
- assert!(stock.face_count() > 2048 && stock.validity().is_empty());
- let before: Vec<_> = stock.solid.vertex_iter().map(|v| (v.id(), v.point())).collect();
- let recovered = prism_of(&stock, Vec3::Z, &Plane::XY, 1e-5).expect("large simple line prism remains supported");
- assert_eq!(recovered.section.regions.len(), 1);
- assert_eq!(recovered.section.regions[0].outer.segs.len(), count);
- assert!(recovered.section.regions[0].outer.segs.iter().all(|s| matches!(s, Seg2::Line { .. })));
- let area = count as f64 * radius * radius * (std::f64::consts::TAU / count as f64).sin() / 2.;
- assert!((recovered.section.regions[0].area() - area).abs() < area * 1e-12);
- assert!((recovered.lo - 0.).abs() < 1e-8 && (recovered.hi - 2.).abs() < 1e-8);
- let cutter = crate::box_solid(Vec3::new(-1001., -1001., -1.), Vec3::new(1001., 1001., 3.)).unwrap();
- assert!(
- simple_prism_boolean(&stock, &cutter, BoolOp::Cut)
- .expect("large analytic section routes through the exact simple path")
- .unwrap()
- .is_none()
- );
- assert_eq!(stock.solid.vertex_iter().map(|v| (v.id(), v.point())).collect::<Vec<_>>(), before);
- }
- #[test]
- fn curved_stop_cut_constructs_fresh_current_cap_for_only_uniform_lump() {
- let cylinder = crate::cylinder(Vec3::new(25., 25., 0.), Vec3::Z, 2., 20.).unwrap();
- let stop = crate::box_solid(Vec3::new(19., 19., 1.), Vec3::new(31., 31., 2.)).unwrap();
- let roof = crate::boolean(&cylinder, &stop, BoolOp::Union).unwrap().unwrap();
- let original = rectangle(Vec2::new(20., 20.), Vec2::new(30., 30.));
- let tool = crate::extrude(&Plane::XY, &[original], 0., 25.).unwrap().pop().unwrap();
- let before_tool = crate::step_export(&[&tool], "tool").unwrap();
- let before_roof = crate::step_export(&[&roof], "roof").unwrap();
- let trimmed = crate::boolean(&tool, &roof, BoolOp::Cut).unwrap().unwrap();
- let lumps = trimmed.lumps().unwrap();
- assert_eq!(lumps.len(), 2);
- let mut lower = 0;
- let mut upper = 0;
- for lump in &lumps {
- assert!(lump.validity().is_empty());
- let mesh = lump.mesh(&crate::MeshTolerance::chord(1e-5)).unwrap();
- if mesh.contains(Vec3::new(21., 21., 0.5)) {
- lower += 1;
- assert!(!mesh.contains(Vec3::new(25., 25., 0.5)));
- assert!(!mesh.contains(Vec3::new(21., 21., 1.5)));
- assert!((mesh.measure().volume - (100. - 4. * std::f64::consts::PI)).abs() < 0.002);
- let sources = lump.face_sources().expect("fresh actual extrusion has complete sources");
- assert_eq!(sources.len(), lump.face_count());
- assert!(sources.iter().all(Option::is_some));
- let mut caps = 0;
- for source in sources.iter().flatten() {
- match source {
- crate::FaceSource::ExtrudeCap { region, plane, .. } => {
- assert_eq!(region.holes.len(), 1);
- assert!((region.area() - (100. - 4. * std::f64::consts::PI)).abs() < 1e-8);
- assert!(plane.normal().z.abs() > 1. - 1e-10);
- assert!((plane.origin.z - if plane.normal().z > 0. { 1. } else { 0. }).abs() < 1e-8);
- caps += 1;
- }
- crate::FaceSource::ExtrudeSide { .. } => {}
- _ => panic!("old producer lineage must not survive a changed Boolean footprint"),
- }
- }
- assert_eq!(caps, 2);
- } else {
- upper += 1;
- assert!(mesh.contains(Vec3::new(21., 21., 3.)));
- assert!(!mesh.contains(Vec3::new(25., 25., 3.)));
- assert!(mesh.contains(Vec3::new(25., 25., 22.)));
- assert!(
- lump.face_sources().is_none_or(|s| s
- .iter()
- .all(|s| s.is_none() || matches!(s, Some(crate::FaceSource::ExtrudeSide { coalesced: true, plane: None, .. })))),
- "genuinely stepped geometry has no durable certificate"
- );
- assert!((mesh.measure().volume - (18. * (100. - 4. * std::f64::consts::PI) + 500.)).abs() < 0.02);
- }
- }
- assert_eq!((lower, upper), (1, 1));
- assert_eq!(crate::step_export(&[&tool], "tool").unwrap(), before_tool);
- assert_eq!(crate::step_export(&[&roof], "roof").unwrap(), before_roof);
- }
- fn stepped_tab_stock() -> Body {
- let stock = crate::box_solid(Vec3::new(-20., -15., 0.), Vec3::new(20., 15., 24.)).unwrap();
- let tab = crate::box_solid(Vec3::new(-12., -25., 8.), Vec3::new(-4., -15., 16.)).unwrap();
- crate::boolean(&stock, &tab, BoolOp::Union).unwrap().unwrap()
- }
-
- fn coplanar_joins(body: &Body) -> usize {
- let faces: Vec<_> = body.solid.face_iter().collect();
- let mut adjacency = std::collections::HashMap::<_, Vec<usize>>::new();
- for (i, face) in faces.iter().enumerate() {
- for edge in face.edge_iter() {
- adjacency.entry(edge.id()).or_default().push(i);
- }
- }
- adjacency
- .values()
- .filter(|faces| {
- let [a, b] = faces.as_slice() else { return false };
- let (Some(pa), Some(pb)) = (body.planar_face(*a), body.planar_face(*b)) else { return false };
- let (na, nb) = (pa.normal(), pb.normal());
- na.dot(nb) > 1. - 1e-12 && (pb.origin - pa.origin).dot(na).abs() < 1e-10
- })
- .count()
- }
-
- #[test]
- fn shell_of_joined_stepped_tabs_has_no_artificial_planar_stations() {
- let stock = stepped_tab_stock();
- let snapshot = crate::step_export(&[&stock], "unchanged stock").unwrap();
- assert_eq!(coplanar_joins(&stock), 0);
- let shell = crate::shell(&stock, &[Vec3::new(0., 0., 24.)], 1.).unwrap();
- assert_eq!(coplanar_joins(&shell), 0, "Shell must not add internal edges across continuous planar walls");
- assert!(shell.validity().is_empty());
- let mesh = shell.mesh(&crate::MeshTolerance::chord(1e-5)).unwrap();
- let expected = 40. * 30. * 24. + 8. * 10. * 8. - (38. * 28. * 23. + 6. * 10. * 6.);
- assert!((mesh.measure().volume - expected).abs() < 1e-6);
- for (point, material) in [
- (Vec3::new(0., 0., 0.5), true),
- (Vec3::new(0., 0., 10.), false),
- (Vec3::new(0., -14.5, 10.), true),
- (Vec3::new(19.5, 0., 10.), true),
- (Vec3::new(-8., -24.5, 12.), true),
- (Vec3::new(-8., -20., 12.), false),
- (Vec3::new(0., -18., 9.), false),
- ] {
- assert_eq!(mesh.contains(point), material, "wrong material at {point:?}");
- }
- let step = crate::step_export(&[&shell], "stepped tab shell").unwrap();
- let reopened = crate::step_import(&step).unwrap();
- let body = &reopened.bodies[0].body;
- assert_eq!(body.face_count(), shell.face_count());
- assert_eq!(coplanar_joins(body), 0);
- assert!((body.mesh(&crate::MeshTolerance::chord(1e-5)).unwrap().measure().volume - expected).abs() < 1e-6);
- assert_eq!(crate::step_export(&[&stock], "unchanged stock").unwrap(), snapshot);
- }
-
- #[test]
- fn contiguous_analytic_walls_remove_faces_but_retain_vertical_stations() {
- for curved in [false, true] {
- let outer = if curved {
- Region2 { outer: Loop2::circle(Vec2::ZERO, 10.), holes: vec![] }
- } else {
- rectangle(Vec2::new(-10., -10.), Vec2::new(10., 10.))
- };
- let mut upper = outer.clone();
- upper.holes.push(if curved {
- Loop2::circle(Vec2::ZERO, 5.).reversed()
- } else {
- rectangle(Vec2::new(-5., -5.), Vec2::new(5., 5.)).outer.reversed()
- });
- let slabs = vec![Section::untagged(&[outer]), Section::untagged(&[upper])];
- // Sections nothing is known of: no history, the construction alone is under test.
- let operand = crate::extrude(&Plane::XY, &[rectangle(Vec2::new(-1., -1.), Vec2::new(1., 1.))], 0., 1.).unwrap().pop().unwrap();
- let index = LazyIndex::new(&operand, 0);
- let history = lineage::Context::new(BoolOp::Cut, [&operand, &operand], [index.get(), index.get()], Plane::XY, 1e-7, None);
- let old = sew_sections(&Plane::XY, Vec3::Z, &[0., 2., 20.], &slabs, 1e-7, false, &history).unwrap().unwrap();
- let merged = sew_sections(&Plane::XY, Vec3::Z, &[0., 2., 20.], &slabs, 1e-7, true, &history).unwrap().unwrap();
- let count = if curved { 2 } else { 4 };
- assert_eq!(old.face_count() - merged.face_count(), count);
- let marked: Vec<_> = merged.solid.face_iter().enumerate().filter(|(i, _)| merged.face_was_coalesced(*i)).collect();
- assert_eq!(marked.len(), count);
- for (_, face) in marked {
- assert_eq!(face.boundaries()[0].len(), 6, "all axial station vertices are retained");
- let heights: Vec<_> = face.vertex_iter().map(|v| v.point().z).collect();
- for z in [0., 2., 20.] {
- assert!(heights.contains(&z));
- }
- }
- assert!(old.face_sources().is_none_or(|s| s.iter().all(Option::is_none)));
- let expected = if curved { std::f64::consts::PI * (100. * 20. - 25. * 18.) } else { 400. * 20. - 100. * 18. };
- let mesh = merged.mesh(&crate::MeshTolerance::chord(1e-5)).unwrap();
- assert!((mesh.measure().volume - expected).abs() < 0.03);
- assert!(mesh.contains(Vec3::new(0., 0., 1.)));
- assert!(!mesh.contains(Vec3::new(0., 0., 10.)));
- assert!(merged.validity().is_empty());
- assert_ne!(wall_key(&slabs[0].regions[0].outer.segs[0]), wall_key(&slabs[0].regions[0].outer.segs[0].reversed()));
- }
- }
-
- #[test]
- fn cut_run_coalescing_respects_authored_splits_and_face_paint() {
- let region = Region2 { outer: Loop2::circle(Vec2::ZERO, 10.), holes: vec![] };
- let tool_region = Region2 { outer: Loop2::circle(Vec2::ZERO, 5.), holes: vec![] };
- let stock = crate::extrude(&Plane::XY, &[region], 0., 20.).unwrap().pop().unwrap();
- let cutter = crate::extrude(&Plane::XY, &[tool_region], 2., 22.).unwrap().pop().unwrap();
- let merged = stack_boolean(&stock, &cutter, BoolOp::Cut).unwrap().unwrap().unwrap();
- let protected = [
- stock.clone().with_split_lines(Some(std::sync::Arc::new(vec![vec![Vec3::new(10., 0., 0.), Vec3::new(10., 0., 20.)]]))),
- stock.with_paint(Some(crate::Paint { opacity: 1., faces: vec![crate::FacePaint { face: 0, color: [1., 0., 0.], opacity: 1. }] })),
- ];
- for input in protected {
- let output = stack_boolean(&input, &cutter, BoolOp::Cut).unwrap().unwrap().unwrap();
- assert_eq!(output.face_count(), merged.face_count() + 2);
- assert!((0..output.face_count()).all(|i| !output.face_was_coalesced(i)));
- // Independent circular chord-volume bound: 2*pi*(10*20+5*18)*1e-5 < .019.
- let expected = std::f64::consts::PI * (100. * 20. - 25. * 18.);
- for body in [&output, &merged] {
- let mesh = body.mesh(&crate::MeshTolerance::chord(1e-5)).unwrap();
- assert!((mesh.measure().volume - expected).abs() < 0.03);
- assert!(mesh.contains(Vec3::new(0., 0., 1.)));
- assert!(!mesh.contains(Vec3::new(0., 0., 10.)));
- assert!(mesh.contains(Vec3::new(7., 0., 10.)));
- }
- }
- }
-
- #[test]
- fn annular_inward_tool_recovers_exact_stacks_before_cap_policy() {
- let plane = Plane::XY;
- let mut region = rectangle(Vec2::ZERO, Vec2::new(40.0, 30.0));
- region.holes.push(Loop2::circle(Vec2::new(20.0, 15.0), 5.0));
- let mut stock = crate::extrude(&plane, std::slice::from_ref(&region), 0.0, 20.0).unwrap().pop().unwrap();
- for (lo, hi) in [(20.0, 30.0), (30.0, 35.0)] {
- let positive = crate::extrude(&plane, std::slice::from_ref(&region), lo, hi).unwrap().pop().unwrap();
- stock = crate::boolean(&stock, &positive, BoolOp::Union).unwrap().unwrap();
- }
- let mut grown = rectangle(Vec2::new(-0.3, -0.3), Vec2::new(40.3, 30.3));
- grown.holes = region.holes;
- let tool = crate::extrude(&plane, &[grown], 30.0, 35.6).unwrap().pop().unwrap();
- let tol = stock.size().max(tool.size()) * 1e-6;
- let a = stack_of(&stock, Vec3::Z, &plane, tol).expect("annular stock qualifies");
- let b = stack_of(&tool, Vec3::Z, &plane, tol).expect("overrun tool qualifies");
- assert_eq!(a.len(), 1);
- assert_eq!(b.len(), 1);
- assert!((a[0].lo - 0.0).abs() < tol && (a[0].hi - 35.0).abs() < tol);
- assert!((b[0].lo - 30.0).abs() < tol && (b[0].hi - 35.6).abs() < tol);
- assert_eq!(a[0].section.regions[0].holes.len(), 1);
- assert_eq!(b[0].section.regions[0].holes.len(), 1);
- assert!((a[0].section.regions[0].area() - (1200.0 - 25.0 * std::f64::consts::PI)).abs() < 1e-8);
- assert!(simple_prism_boolean(&stock, &tool, BoolOp::Cut).is_none());
- let result = stack_boolean(&stock, &tool, BoolOp::Cut).expect("qualified overlapping stacks").unwrap().unwrap();
- assert_eq!(result.shell_count(), 1);
- assert!(result.validity().is_empty());
- let mesh = result.mesh(&crate::MeshTolerance::chord(1e-5)).unwrap();
- let expected = (1200.0 - 25.0 * std::f64::consts::PI) * 30.0;
- // An inscribed circular mesh at radial chord error 1e-5 has volume
- // deficit below 2*pi*R*height*error, conservatively 0.01 mm^3 here.
- assert!((mesh.measure().volume - expected).abs() < 0.02);
- for (point, present) in [
- (Vec3::new(5.0, 5.0, 29.0), true),
- (Vec3::new(5.0, 5.0, 31.0), false),
- (Vec3::new(20.0, 15.0, 29.0), false),
- (Vec3::new(24.8, 15.0, 29.0), false),
- (Vec3::new(25.2, 15.0, 29.0), true),
- ] {
- assert_eq!(mesh.contains(point), present, "{point:?}");
- }
- }
- #[test]
- fn annular_partial_cut_overruns_and_interior_lumps_preserve_material() {
- let area = 1200.0 - 25.0 * std::f64::consts::PI;
- for seam in [0.0, 0.37] {
- for plane in [Plane::XY, Plane::new(Vec3::new(30.0, 20.0, 10.0), Vec3::X, Vec3::Z).unwrap()] {
- let mut region = rectangle(Vec2::ZERO, Vec2::new(40.0, 30.0));
- region.holes.push(Loop2::circle_from(Vec2::new(20.0, 15.0), 5.0, seam));
- let stock = crate::extrude(&plane, std::slice::from_ref(&region), 0.0, 35.0).unwrap().pop().unwrap();
- let before = crate::step_export(&[&stock], "source").unwrap();
- for (lo, hi, retained, shells) in [(30.0, 35.6, 30.0, 1), (-0.6, 5.0, 30.0, 1), (10.0, 15.0, 30.0, 2), (30.0, 35.0, 30.0, 1)] {
- let tool = crate::extrude(&plane, std::slice::from_ref(&region), lo, hi).unwrap().pop().unwrap();
- let result = stack_boolean(&stock, &tool, BoolOp::Cut).expect("exact aligned cut path").unwrap().unwrap();
- assert_eq!(result.shell_count(), shells);
- assert!(result.validity().is_empty());
- let mesh = result.mesh(&crate::MeshTolerance::chord(1e-5)).unwrap();
- assert!((mesh.measure().volume - retained * area).abs() < 0.02);
- let at = |x: f64, y: f64, z: f64| plane.to_world(Vec2::new(x, y)) + plane.normal() * z;
- for z in [2.5, 12.5, 32.5] {
- let material = !(lo < z && z < hi);
- assert_eq!(mesh.contains(at(5.0, 5.0, z)), material);
- assert!(!mesh.contains(at(20.0, 15.0, z)));
- assert_eq!(mesh.contains(at(25.2, 15.0, z)), material);
- }
- let public = crate::boolean(&stock, &tool, BoolOp::Cut).unwrap().unwrap();
- assert!((public.mesh(&crate::MeshTolerance::chord(1e-5)).unwrap().measure().volume - retained * area).abs() < 0.02);
- if lo == 30.0 && hi > 35.0 {
- let imported = crate::step_import(&crate::step_export(&[&result], "inward annular cut").unwrap()).unwrap();
- assert!(imported.warnings.is_empty());
- let saved = &imported.bodies.first().unwrap().body;
- assert!((saved.mesh(&crate::MeshTolerance::chord(1e-5)).unwrap().measure().volume - 30.0 * area).abs() < 0.02);
- let next = crate::extrude(&plane, std::slice::from_ref(&region), 25.0, 31.0).unwrap().pop().unwrap();
- let shortened = crate::boolean(saved, &next, BoolOp::Cut).unwrap().unwrap();
- let next_volume = shortened.mesh(&crate::MeshTolerance::chord(1e-5)).unwrap().measure().volume;
- assert!(
- (next_volume - 25.0 * area).abs() < 0.02,
- "seam {seam}, plane {plane:?}, next cut volume {next_volume}, expected {}",
- 25.0 * area
- );
- assert!(shortened.contains(at(5.0, 5.0, 24.0)));
- assert!(!shortened.contains(at(5.0, 5.0, 26.0)));
- assert!(!shortened.contains(at(20.0, 15.0, 24.0)));
- }
- }
- let clear = crate::extrude(&plane, std::slice::from_ref(&region), 36.0, 40.0).unwrap().pop().unwrap();
- assert!(stack_boolean(&stock, &clear, BoolOp::Cut).is_none());
- let unchanged = crate::boolean(&stock, &clear, BoolOp::Cut).unwrap().unwrap();
- assert!(std::sync::Arc::ptr_eq(&stock.solid, &unchanged.solid), "disjoint Cut must retain exact source topology");
- let unchanged_mesh = unchanged.mesh(&crate::MeshTolerance::chord(1e-5)).unwrap();
- let source_mesh = stock.mesh(&crate::MeshTolerance::chord(1e-5)).unwrap();
- assert_eq!(unchanged_mesh.measure().volume, source_mesh.measure().volume);
- // tessellate() floors tolerance at body.size()*1e-6. The arc
- // polygon's area error is at most perimeter*radial chord error.
- let bound = std::f64::consts::TAU * 5.0 * 35.0 * (stock.size() * 1e-6).max(1e-5) + 1e-5;
- assert!((unchanged_mesh.measure().volume - 35.0 * area).abs() < bound);
- assert!(!unchanged_mesh.contains(plane.to_world(Vec2::new(20.0, 15.0)) + plane.normal() * 12.5));
- let all = crate::extrude(&plane, std::slice::from_ref(&region), -1.0, 36.0).unwrap().pop().unwrap();
- assert!(stack_boolean(&stock, &all, BoolOp::Cut).unwrap().unwrap().is_none());
- assert_eq!(crate::step_export(&[&stock], "source").unwrap(), before);
- }
- }
- }
- #[test]
- fn annular_partial_cut_preserves_unequal_radii_and_conservative_refusals() {
- let mut region = rectangle(Vec2::ZERO, Vec2::new(40.0, 30.0));
- region.holes.push(Loop2::circle(Vec2::new(20.0, 15.0), 5.0));
- let stock = crate::extrude(&Plane::XY, std::slice::from_ref(&region), 0.0, 35.0).unwrap().pop().unwrap();
- let before = crate::step_export(&[&stock], "unchanged source").unwrap();
- let mut larger_hole = region.clone();
- larger_hole.holes = vec![Loop2::circle(Vec2::new(20.0, 15.0), 5.1)];
- let tool = crate::extrude(&Plane::XY, &[larger_hole], 30.0, 36.0).unwrap().pop().unwrap();
- let result = stack_boolean(&stock, &tool, BoolOp::Cut).unwrap().unwrap().unwrap();
- let expected = (1200.0 - 25.0 * std::f64::consts::PI) * 30.0 + std::f64::consts::PI * (5.1_f64.powi(2) - 25.0) * 5.0;
- let mesh = result.mesh(&crate::MeshTolerance::chord(1e-5)).unwrap();
- assert!((mesh.measure().volume - expected).abs() < 0.02);
- assert!(mesh.contains(Vec3::new(25.05, 15.0, 32.0)));
- assert!(!mesh.contains(Vec3::new(25.2, 15.0, 32.0)));
- assert!(!mesh.contains(Vec3::new(20.0, 15.0, 32.0)));
- let interior = crate::extrude(&Plane::XY, std::slice::from_ref(&region), 10.0, 15.0).unwrap().pop().unwrap();
- for d in [Vec3::X, Vec3::Y] {
- let plane = Plane::from_normal(Vec3::ZERO, d).unwrap();
- let tol = stock.size() * 1e-6;
- assert!(stack_of(&stock, d, &plane, tol).is_none(), "transverse cylinder axis must not fill the hole");
- assert!(stack_of(&interior, d, &plane, tol).is_none());
- }
- assert!(stack_boolean(&stock, &interior, BoolOp::Union).is_none(), "Union retains its common-cap policy");
- let tapered = crate::extrude_tapered(&Plane::XY.offset(30.0), &rectangle(Vec2::ZERO, Vec2::new(40.0, 30.0)), 6.0, 1.0, 0.05).unwrap();
- assert!(stack_boolean(&stock, &tapered, BoolOp::Cut).is_none(), "slanted walls are not aligned prisms");
- let curved_cap = crate::sphere(Vec3::new(20.0, 15.0, 35.0), 5.0).unwrap();
- assert!(stack_boolean(&stock, &curved_cap, BoolOp::Cut).is_none());
- let pieces =
- (0..350).map(|i| crate::box_solid(Vec3::new(i as f64 * 3.0, 0.0, 0.0), Vec3::new(i as f64 * 3.0 + 1.0, 1.0, 1.0)).unwrap()).collect();
- let over_budget = crate::ops::join_pieces(pieces).unwrap().unwrap();
- assert!(over_budget.face_count() > 2048);
- assert!(stack_boolean(&over_budget, &interior, BoolOp::Cut).is_none());
- assert_eq!(crate::step_export(&[&stock], "unchanged source").unwrap(), before);
- }
- #[test]
fn curved_prism_wall_requires_positive_separable_rational_weights() {
let surface = |mixed: bool| {
let weight = if mixed { 2.0 } else { 1.0 };
- let points = vec![
- vec![mt::Vector4::new(0.0, 0.0, 0.0, 1.0), mt::Vector4::new(0.0, 0.0, 10.0, 1.0)],
- vec![mt::Vector4::new(5.0, 0.0, 0.0, 1.0), mt::Vector4::new(5.0 * weight, 0.0, 10.0 * weight, weight)],
- ];
- mt::Surface::NurbsSurface(mt::NurbsSurface::new(mt::BSplineSurface::new(
- (mt::KnotVec::bezier_knot(1), mt::KnotVec::bezier_knot(1)),
- points,
- )))
+ Surface::RationalSpline {
+ u_knots: vec![0., 0., 1., 1.],
+ v_knots: vec![0., 0., 1., 1.],
+ homogeneous: vec![
+ vec![[0.0, 0.0, 0.0, 1.0], [0.0, 0.0, 10.0, 1.0]],
+ vec![[5.0, 0.0, 0.0, 1.0], [5.0 * weight, 0.0, 10.0 * weight, weight]],
+ ],
+ }
};
assert!(wall_along(&surface(false), Vec3::Z, 1e-5, &mut 1000));
assert!(!wall_along(&surface(true), Vec3::Z, 1e-5, &mut 1000), "parallel Euclidean controls alone do not certify a rational sweep");
@@ -3015,86 +1349,6 @@ mod planar_tests {
assert!(!wall_along(&surface(false), Vec3::Z, 1e-5, &mut 0));
}
#[test]
- fn partial_depth_cuts_touching_a_through_hole_use_exact_stacked_sections() {
- let plane = Plane::named("XY").unwrap();
- let mut plate = rectangle(Vec2::ZERO, Vec2::new(100., 60.));
- plate.holes.push(rectangle(Vec2::new(25., 20.), Vec2::new(30., 30.)).outer);
- let stock = crate::extrude(&plane, &[plate], 0., 2.5).unwrap().pop().unwrap();
- let low = crate::extrude(&plane, &[rectangle(Vec2::new(20., 20.), Vec2::new(30., 30.))], 0., 1.5).unwrap().pop().unwrap();
- let high = crate::extrude(&plane, &[rectangle(Vec2::new(25., 20.), Vec2::new(35., 30.))], 1., 2.5).unwrap().pop().unwrap();
- for tools in [[&low, &high], [&high, &low]] {
- let mut result = stock.clone();
- for tool in tools {
- let target = result;
- result = stack_boolean(&target, tool, BoolOp::Cut).expect("exact stack path").unwrap().unwrap();
- // The second cut's target has walls in pieces across its slabs, followed level by
- // level: its history is exact.
- let exact = crate::boolean_record::tests::Reach { made: 0., moved: 0. };
- crate::boolean_record::tests::checked(&result, &[&target, tool], 1e-3, exact, &|_| false);
- }
- assert!(result.validity().is_empty());
- assert_eq!(result.shell_count(), 1);
- assert!((crate::measure(&result).unwrap().volume - 14_725.).abs() < 1e-6);
- let mesh = result.mesh(&crate::MeshTolerance::chord(1e-4)).unwrap();
- for (point, material) in [
- (Vec3::new(22.5, 25., 0.5), false),
- (Vec3::new(22.5, 25., 2.), true),
- (Vec3::new(32.5, 25., 0.5), true),
- (Vec3::new(32.5, 25., 2.), false),
- (Vec3::new(27.5, 25., 1.25), false),
- (Vec3::new(10., 10., 1.25), true),
- ] {
- assert_eq!(mesh.contains(point), material, "{point:?}");
- }
- let imported = crate::step_import(&crate::step_export(&[&result], "layered cut").unwrap()).unwrap();
- assert!(imported.warnings.is_empty());
- assert!((crate::measure(&imported.bodies.first().unwrap().body).unwrap().volume - 14_725.).abs() < 1e-6);
- let next = crate::extrude(&plane, &[rectangle(Vec2::new(20., 20.), Vec2::new(25., 30.))], 1.5, 2.5).unwrap().pop().unwrap();
- let opened = crate::boolean(&imported.bodies.first().unwrap().body, &next, BoolOp::Cut).unwrap().unwrap();
- assert!((crate::measure(&opened).unwrap().volume - 14_675.).abs() < 1e-6);
- assert!(opened.validity().is_empty());
- }
- }
- #[test]
- fn far_edges_of_a_stepped_slab_come_from_the_operand_topology() {
- // A block with a notch in its back, read along -y: the slab from the notch floor to the
- // front has three segments beside the top face, read off the back and the notch floor.
- // The top face ends at the front in one edge: the far edge of all three, found with no
- // position compared (no pair budget).
- let notched = Loop2::polygon(&[
- Vec2::new(0., 0.),
- Vec2::new(40., 0.),
- Vec2::new(40., 30.),
- Vec2::new(25., 30.),
- Vec2::new(25., 25.),
- Vec2::new(15., 25.),
- Vec2::new(15., 30.),
- Vec2::new(0., 30.),
- ]);
- let block = crate::extrude(&Plane::named("XY").unwrap(), &[Region2 { outer: notched, holes: vec![] }], 0., 20.).unwrap().pop().unwrap();
- let (d, tol) = (-Vec3::Y, 1e-6);
- let plane = Plane::from_normal(Vec3::ZERO, d).unwrap();
- let normal = |f: &mt::Face| crate::blend::plane_normal(f).unwrap_or(Vec3::ZERO);
- let faces: Vec<(usize, &mt::Face)> = block.solid.face_iter().enumerate().collect();
- let find = |n: Vec3| faces.iter().find(|(_, f)| normal(f).dot(n) > 1. - 1e-9).map(|(i, _)| *i).unwrap();
- let (top, front) = (find(Vec3::Z), find(-Vec3::Y));
- let walls = faces.iter().filter(|(_, f)| normal(f).dot(d).abs() < 1e-9).map(|(i, f)| (*i, top_of(f, &plane))).collect();
- let index = Index::new(&block, 0);
- let stations = Stations::new(&index, walls, d, &plane, tol);
- let cap = Section::from_loops(index.loops(faces[front].1, front, &plane, tol, &mut 1000, &mut 1000).unwrap()).unwrap().oriented();
- let edge = match index.between.get(&(top.min(front), top.max(front))).map(Vec::as_slice) {
- Some([e]) => *e,
- other => panic!("one edge between the top and the front: {other:?}"),
- };
- let mut slab = stack_of(&block, d, &plane, tol).unwrap().pop().unwrap();
- assert!((slab.lo + 25.).abs() < tol && slab.hi.abs() < tol);
- let beside_top = |s: &Section| s.segments().1.into_iter().filter(|t| t.wall == Some(top)).map(|t| t.far).collect::<Vec<_>>();
- assert_eq!(beside_top(&slab.section), vec![Some(edge); 3], "read as a stack");
- slab.section.retag(|t| Tag { far: None, ..t });
- slab.section.mark_far(&[&cap], |w| stations.top_edge(&index, w, &[front], 0., tol), tol, &mut 0);
- assert_eq!(beside_top(&slab.section), vec![Some(edge); 3], "by topology alone");
- }
- #[test]
fn compound_planar_extrusion_normalizes_overlap_and_retains_islands() {
let plane = Plane::named("XY").unwrap();
let a = rectangle(Vec2::ZERO, Vec2::new(10.0, 10.0));
@@ -3108,7 +1362,7 @@ mod planar_tests {
let body = extrude_planar_regions(&plane, &[annulus, inner], 0.0, 2.0).unwrap();
let expected = (100.0 - std::f64::consts::PI * 5.0) * 2.0;
assert!((crate::measure(&body).unwrap().volume - expected).abs() < 0.1);
- assert_eq!(body.solid.boundaries().len(), 2);
+ assert_eq!(body.shell_count(), 2);
let a = rectangle(Vec2::ZERO, Vec2::new(10.0, 10.0));
let b = rectangle(Vec2::new(10.0, 10.0), Vec2::new(20.0, 20.0));
assert!(extrude_planar_regions(&plane, &[a, b], 0.0, 2.0).is_err());
diff --git a/crates/kernel/src/prism_lineage.rs b/crates/kernel/src/prism_lineage.rs
deleted file mode 100644
index 0fb977595b..0000000000
--- a/crates/kernel/src/prism_lineage.rs
+++ /dev/null
@@ -1,538 +0,0 @@
-//! The history of a prism boolean's result (see [`super::prism_boolean`]), from what its faces
-//! were built over: each wall over a section segment whose [`Tag`] says which operand wall it
-//! was read beside, each cap over a section region lying on operand caps at its level. Edges
-//! follow from the same tags: a wall's edge with a cap is the operand's edge between them (or
-//! the meeting of the wall with the other operand's cap); an edge between walls at a section
-//! vertex is the operand's edge there (or the meeting of two operands' walls).
-
-use std::collections::{BTreeSet, HashMap};
-
-use solidcraft_geom::{Plane, Region2, Vec2, Vec3};
-use truck_modeling as mt;
-
-use super::{Index, Section, Tag, dist_to, inside};
-use crate::BoolOp;
-use crate::body::{Body, edge_order, from_p3};
-use crate::history::{EdgeOrigin, FaceOrigin, FaceOrigin::Face, FaceProv, Side};
-
-/// A cap of an operand: a planar face square to the prism direction.
-struct Cap {
- origin: FaceOrigin,
- /// Its level and whether it faces along the direction.
- z: f64,
- up: bool,
- outline: Outline,
-}
-
-/// A section's regions with the walls its outline was read beside and its segments' middles,
-/// to tell whether two sections overlap.
-struct Outline {
- regions: Vec<Region2>,
- walls: BTreeSet<(usize, usize)>,
- middles: Vec<Vec2>,
-}
-
-impl Outline {
- fn of(s: &Section) -> Outline {
- let (segs, tags) = s.segments();
- Outline {
- regions: s.regions.clone(),
- walls: tags.iter().filter_map(|t| Some((t.operand, t.wall?))).collect(),
- middles: segs.iter().map(|g| g.point_at(0.5)).collect(),
- }
- }
-}
-
-/// What a prism boolean's result is built from: the operands (target, tool), the direction and
-/// the plane square to it that sections are drawn in, and for simple prisms each operand's
-/// extent along the direction.
-pub(super) struct Context<'a> {
- pub op: BoolOp,
- pub operands: [&'a Body; 2],
- pub index: [&'a Index; 2],
- pub plane: Plane,
- pub tol: f64,
- pub heights: Option<[(f64, f64); 2]>,
- /// Both operands' caps, read once (see [`Context::caps`]).
- caps: std::cell::OnceCell<Option<Vec<Cap>>>,
-}
-
-/// How one piece of the result was built.
-pub(super) enum Built {
- /// One body of `crate::extrude` of a section's one region through `layers`: successive
- /// slabs (the section as read in each, between its two levels), bottom first, all of one
- /// outline. Several where operands stacked end to end share an outline (one wall then lies
- /// over each operand's wall in turn, and is made from all of them).
- Extruded { layers: Vec<(Section, f64, f64)> },
- /// Sewn (`sew_connected_sections`) from these faces, the sewing saying which each face of
- /// the piece was built from (`None`: it could not).
- Sewn { specs: Vec<Spec>, faces: Option<Vec<usize>> },
- /// Built some other way, carrying its own history over the operands (none: not known).
- Traced,
-}
-
-/// A face sewn into a stepped prism.
-pub(super) enum Spec {
- /// A wall over one section segment through successive slabs, between successive `levels`
- /// (one more than `slabs`): what it is over in each slab.
- Wall { levels: Vec<f64>, slabs: Vec<Slab> },
- /// A cap over `section` at level `z`, facing along the direction when `up`.
- Cap { section: Section, z: f64, up: bool },
-}
-
-/// A wall in one slab: over a segment tagged `tag`; `next` is the wall over the next segment
-/// of its loop in that slab, which it meets at `at`.
-pub(super) struct Slab {
- pub tag: Tag,
- pub next: usize,
- pub at: Vec2,
-}
-
-impl Spec {
- /// The wall's slab between levels `lo` and `hi` (`hi` above `lo`).
- fn slab(&self, lo: f64, hi: f64) -> Option<&Slab> {
- let Spec::Wall { levels, slabs } = self else { return None };
- let mid = (lo + hi) / 2.0;
- slabs.iter().zip(levels.windows(2)).find(|(_, z)| z[0] < mid && mid < z[1]).map(|(s, _)| s)
- }
-
- /// The wall's slab at its bottom level, when that is `z`.
- fn bottom(&self, z: f64, tol: f64) -> Option<&Slab> {
- let Spec::Wall { levels, slabs } = self else { return None };
- ((levels.first()? - z).abs() <= tol).then_some(slabs.first()?)
- }
-
- /// The wall's slab at its top level, when that is `z`.
- fn top(&self, z: f64, tol: f64) -> Option<&Slab> {
- let Spec::Wall { levels, slabs } = self else { return None };
- ((levels.last()? - z).abs() <= tol).then_some(slabs.last()?)
- }
-
- /// The wall's slab at its bottom or top level `z`.
- fn end(&self, z: f64, tol: f64) -> Option<&Slab> {
- self.bottom(z, tol).or_else(|| self.top(z, tol))
- }
-}
-
-/// A face of an extruded piece: a wall or a cap.
-#[derive(Clone, Copy)]
-enum Kind {
- /// The wall over this segment of the section.
- Wall(usize),
- Cap(usize),
-}
-
-impl<'a> Context<'a> {
- pub(super) fn new(op: BoolOp, operands: [&'a Body; 2], index: [&'a Index; 2], plane: Plane, tol: f64, heights: Option<[(f64, f64); 2]>) -> Self {
- Context { op, operands, index, plane, tol, heights, caps: std::cell::OnceCell::new() }
- }
-
- /// `body`, made of `pieces` (their shells in order), with its history over the operands
- /// (none where it is not known).
- pub(super) fn attach<B: std::borrow::Borrow<Body>>(&self, body: Body, pieces: &[(B, Built)]) -> Body {
- let pieces: Vec<(&Body, &Built)> = pieces.iter().map(|(b, k)| (b.borrow(), k)).collect();
- let (faces, edges) = self.history(&pieces).unzip();
- crate::record::traced(body, &crate::record::counts(&self.operands), faces, edges.as_ref())
- }
-
- /// The faces (each a region of operand faces, and whether it is one untouched) and the edges
- /// (by identity) of the pieces, in order; `None` where something is not known.
- pub(super) fn history(&self, pieces: &[(&Body, &Built)]) -> Option<(Vec<FaceProv>, HashMap<mt::EdgeID, Vec<EdgeOrigin>>)> {
- let caps = self.caps.get_or_init(|| self.caps()).as_deref()?;
- let mut faces = Vec::new();
- let mut edges = HashMap::new();
- for (body, built) in pieces {
- let (f, e) = match built {
- Built::Extruded { layers } => self.extruded(caps, body, layers)?,
- Built::Sewn { specs, faces } => self.sewn(caps, body, specs, faces.as_deref()?)?,
- Built::Traced => {
- let h = body.history()?;
- faces.extend(h.faces.iter().cloned());
- edges.extend(crate::record::edges_by_identity(body, h));
- continue;
- }
- };
- faces.extend(f.into_iter().map(|(origins, whole)| crate::record::region(origins, whole)));
- edges.extend(e);
- }
- // Pieces of one body can share an origin.
- crate::record::mark_shared_split(&mut faces);
- Some((faces, edges))
- }
-
- /// Both operands' caps, their outlines tagged.
- fn caps(&self) -> Option<Vec<Cap>> {
- let d = self.plane.normal();
- let mut caps = Vec::new();
- let (mut work, mut segments) = (2_000_000usize, super::MAX_PLANAR_SEGMENTS * 2);
- for (operand, (body, index)) in self.operands.iter().zip(self.index).enumerate() {
- for (face, f) in body.solid.face_iter().enumerate() {
- let mt::Surface::Plane(p) = f.oriented_surface() else { continue };
- let n = p.normal();
- let n = Vec3::new(n.x, n.y, n.z).normalized()?;
- if n.dot(d).abs() < 1.0 - 1e-9 {
- continue;
- }
- let section = Section::from_loops(index.loops(f, face, &self.plane, self.tol, &mut work, &mut segments)?)?;
- let (z, up) = (self.plane.height(from_p3(p.origin())), n.dot(d) > 0.0);
- caps.push(Cap { origin: Face { operand, face }, z, up, outline: Outline::of(&section.oriented()) });
- }
- }
- Some(caps)
- }
-
- /// The operand caps under a result cap over `section` at level `z` (facing along the
- /// direction when `up`): the target's caps there facing the same way, and the tool's facing
- /// the same way (a union or intersection) or the other way (a cut, whose tool's caps bound
- /// what it leaves), wherever they overlap the section.
- fn cap_origins(&self, caps: &[Cap], section: &Section, z: f64, up: bool) -> BTreeSet<FaceOrigin> {
- let outline = Outline::of(section);
- caps.iter()
- .filter(|c| {
- let facing = match c.origin {
- Face { operand: 1, .. } if self.op == BoolOp::Cut => c.up != up,
- _ => c.up == up,
- };
- facing && (c.z - z).abs() < self.tol && self.overlap(&outline, &c.outline)
- })
- .map(|c| c.origin)
- .collect()
- }
-
- /// Do two sections (at one level) overlap? Where their outlines share a wall, or a point of
- /// one's outline, clear of the other's, lies inside it.
- fn overlap(&self, x: &Outline, y: &Outline) -> bool {
- let within = |x: &Outline, y: &Outline| x.middles.iter().any(|m| dist_to(&y.regions, *m) > self.tol && inside(&y.regions, *m));
- !x.walls.is_disjoint(&y.walls) || within(x, y) || within(y, x)
- }
-
- /// The operand wall a segment was read beside.
- fn wall(t: Tag) -> Option<FaceOrigin> {
- Some(Face { operand: t.operand, face: t.wall? })
- }
-
- /// The operand's edges (by number) bounding exactly the faces `faces`.
- fn edges_between(&self, operand: usize, [f, g]: [usize; 2]) -> &[usize] {
- self.index.get(operand).and_then(|index| index.between.get(&(f.min(g), f.max(g)))).map_or(&[], Vec::as_slice)
- }
-
- /// Is the wall over a segment tagged `t` between `lo` and `hi` its operand wall untouched?
- /// The whole cap edge it was read off, the operand's whole height (simple prisms), and a
- /// wall with no other cap edges than its two.
- fn whole(&self, caps: &[Cap], t: Tag, lo: f64, hi: f64) -> bool {
- let (Some(heights), Some(wall), Some(_), Some(_)) = (self.heights, t.wall, t.start, t.end) else { return false };
- let Some((l, h)) = heights.get(t.operand) else { return false };
- let Some(index) = self.index.get(t.operand) else { return false };
- let cap_edges: usize = caps
- .iter()
- .filter_map(|c| match c.origin {
- Face { operand, face } if operand == t.operand => index.between.get(&(face.min(wall), face.max(wall))).map(Vec::len),
- _ => None,
- })
- .sum();
- (lo - l).abs() < self.tol && (hi - h).abs() < self.tol && cap_edges == 2
- }
-
- /// The origins of the edge between the wall over a segment tagged `t` and a cap lying on the
- /// operand faces `cap`: the operand's edge between the wall and its own cap there (the very
- /// edge the segment was read off, or the one it runs along where its slab ends: the one
- /// running through `at`, a point of the edge, where the wall meets its caps along several),
- /// else where the wall meets the cap (all of the faces it lies on).
- fn cap_edge(&self, t: Tag, cap: &BTreeSet<FaceOrigin>, at: Vec3) -> Option<Vec<EdgeOrigin>> {
- let (x, w) = (t.operand, t.wall?);
- let own: Vec<usize> =
- cap.iter().filter_map(|o| if let Face { operand, face } = *o { (operand == x).then_some(face) } else { None }).collect();
- let index = self.index.get(x)?;
- let beside = |e: &usize| index.bounds.get(*e).is_some_and(|(fs, _, _)| fs.contains(&w) && fs.iter().any(|f| own.contains(f)));
- if let Some(e) = [t.edge, t.far].into_iter().flatten().find(beside) {
- return Some(vec![EdgeOrigin::Edge { operand: x, edge: e }]);
- }
- let along: Vec<usize> = own.iter().flat_map(|c| self.edges_between(x, [w, *c])).copied().collect();
- match along.as_slice() {
- [e] => Some(vec![EdgeOrigin::Edge { operand: x, edge: *e }]),
- [] => Some(vec![EdgeOrigin::meet(Self::wall(t)?, Side::new(cap.iter().copied())?)]),
- // One wall with openings meets its caps along several edges (a side wall with ports
- // cut through it meets the ports' floors at each port): the one this edge lies on,
- // else (a new opening beside them) where the wall meets the cap.
- many => match self.edge_through(x, many, at)? {
- Some(edge) => Some(vec![EdgeOrigin::Edge { operand: x, edge }]),
- None => Some(vec![EdgeOrigin::meet(Self::wall(t)?, Side::new(cap.iter().copied())?)]),
- },
- }
- }
-
- /// Of the operand's edges `edges`, the one the point `at` lies on (`Some(None)` when none
- /// does; `None` when several do).
- fn edge_through(&self, operand: usize, edges: &[usize], at: Vec3) -> Option<Option<usize>> {
- if edges.len() > 4096 {
- return None;
- }
- let body = self.operands.get(operand)?;
- let order = crate::body::edge_order(body.solid.face_iter()).0;
- let mut on = edges.iter().filter(|e| {
- order.get(**e).is_some_and(|edge| {
- use mt::{BoundedCurve, ParametricCurve};
- let c = edge.curve();
- let (t0, t1) = c.range_tuple();
- // The edge as a fine polyline: a line exactly, an arc within its chords' sag.
- let n = if matches!(c, mt::Curve::Line(_)) { 1 } else { 64 };
- let pts: Vec<Vec3> = (0..=n).map(|k| from_p3(c.subs(t0 + (t1 - t0) * k as f64 / n as f64))).collect();
- let length: f64 = pts.windows(2).map(|w| w[0].dist(w[1])).sum();
- let near = self.tol * 10.0 + if n == 1 { 0.0 } else { length * 2e-3 };
- pts.windows(2).any(|w| at.dist_to_segment(w[0], w[1]) <= near)
- })
- });
- match (on.next(), on.next()) {
- (Some(e), None) => Some(Some(*e)),
- (None, _) => Some(None),
- _ => None,
- }
- }
-
- /// The origins of the edge between the walls over two segments where the first (tagged
- /// `t1`) runs into the second (`t2`), between levels `lo` and `hi`: the operand's edge there
- /// between its walls (along the line through the operand vertex the segments meet at, else
- /// the one edge between them), where two operands' walls meet, or none within one wall (a
- /// segment split there).
- fn junction(&self, t1: Tag, t2: Tag, lo: f64, hi: f64) -> Option<Vec<EdgeOrigin>> {
- let (p, q) = (Self::wall(t1)?, Self::wall(t2)?);
- if t1.operand != t2.operand {
- return Some(vec![EdgeOrigin::meet(p, q)]);
- }
- let (x, w1, w2) = (t1.operand, t1.wall?, t2.wall?);
- match (t1.end, t2.start) {
- // At that vertex: the operand's edge there (a seam, within one wall), else two edges
- // of one wall's cap outline running on through it.
- (Some(v), Some(u)) if v == u => self.edge_over(x, [w1, w2], Some(v), lo, hi).or_else(|| (w1 == w2).then(Vec::new)),
- _ if w1 == w2 => Some(Vec::new()),
- // Elsewhere (a segment split off there, or read off another cap): only the operand's
- // walls are around the edge, so the operand has its edge between them there, and
- // that is the one edge between them over these levels where there is one.
- _ => self.edge_over(x, [w1, w2], None, lo, hi),
- }
- }
-
- /// The operand's edge between the walls `faces` that runs over the levels `lo` to `hi`,
- /// when it has exactly one; with `at`, among the edges between them chained to that vertex.
- /// The segments' vertex was read at one level and carried through others, and the line
- /// between two walls is in several edges where vertices an earlier operation left (stations)
- /// split it: the levels say which of them a slab's edge runs along.
- fn edge_over(&self, operand: usize, faces: [usize; 2], at: Option<usize>, lo: f64, hi: f64) -> Option<Vec<EdgeOrigin>> {
- let index = self.index.get(operand)?;
- let between = self.edges_between(operand, faces);
- if between.len() > 4096 {
- return None;
- }
- let ends: Vec<(Option<usize>, Option<usize>)> =
- between.iter().map(|e| index.bounds.get(*e).map_or((None, None), |(_, front, back)| (*front, *back))).collect();
- // With `at`: the edges reached from it through shared vertices.
- let mut chained = vec![at.is_none(); between.len()];
- let mut reached: Vec<usize> = at.into_iter().collect();
- while let Some(p) = reached.pop() {
- for (k, (front, back)) in ends.iter().enumerate() {
- if !chained[k] && (*front == Some(p) || *back == Some(p)) {
- chained[k] = true;
- reached.extend(if *front == Some(p) { *back } else { *front });
- }
- }
- }
- let height = |v: Option<usize>| v.and_then(|v| index.points.get(v)).map(|p| self.plane.height(*p));
- let mut over = between.iter().zip(&ends).zip(chained).filter_map(|((e, (front, back)), chained)| {
- let (a, b) = (height(*front)?, height(*back)?);
- (chained && a.min(b) <= lo + self.tol && a.max(b) >= hi - self.tol).then_some(*e)
- });
- match (over.next(), over.next()) {
- (Some(edge), None) => Some(vec![EdgeOrigin::Edge { operand, edge }]),
- _ => None,
- }
- }
-
- /// The origins of the edge between walls over one segment stacked at a level (tagged `t1`
- /// below, `t2` above): within one wall (none), along the operand's edge between two of its
- /// walls, or where two operands' walls meet.
- fn stacked(&self, t1: Tag, t2: Tag) -> Option<Vec<EdgeOrigin>> {
- let (p, q) = (Self::wall(t1)?, Self::wall(t2)?);
- if p == q {
- return Some(Vec::new());
- }
- if t1.operand != t2.operand {
- return Some(vec![EdgeOrigin::meet(p, q)]);
- }
- // An edge across the direction at a level: the levels cannot tell edges apart here.
- self.one_edge(t1.operand, [t1.wall?, t2.wall?])
- }
-
- /// The operand's edge between the faces `faces`, when it has exactly one.
- fn one_edge(&self, operand: usize, faces: [usize; 2]) -> Option<Vec<EdgeOrigin>> {
- match self.edges_between(operand, faces) {
- [edge] => Some(vec![EdgeOrigin::Edge { operand, edge: *edge }]),
- _ => None,
- }
- }
-
- /// Faces and edges of a piece `crate::extrude` built from a section of one region through
- /// `layers` (see [`Built::Extruded`]). Its history says which faces are walls over which
- /// segment (numbered over the region's loops in order) and which are its caps; the start
- /// cap's wires run over the segments in loop order (as the extrude builds them), so the
- /// vertex after each wire edge is where one segment runs into the next, or splits. A wall
- /// through several layers is made from the wall each layer's segment was read beside, and
- /// an edge between two walls from the operand edges there in each layer.
- #[allow(clippy::type_complexity)]
- fn extruded(
- &self,
- caps: &[Cap],
- body: &Body,
- layers: &[(Section, f64, f64)],
- ) -> Option<(Vec<(BTreeSet<FaceOrigin>, bool)>, HashMap<mt::EdgeID, Vec<EdgeOrigin>>)> {
- let h = body.history()?;
- let ((first, lo, _), (last, _, hi)) = (layers.first()?, layers.last()?);
- let (lo, hi) = (*lo, *hi);
- let tags: Vec<Vec<Tag>> = layers.iter().map(|(section, ..)| section.segments().1).collect();
- let count = tags.first()?.len();
- if tags.iter().any(|t| t.len() != count) {
- return None;
- }
- let tag = |layer: usize, segment: usize| tags.get(layer).and_then(|t| t.get(segment)).copied();
- let tops = [self.cap_origins(caps, first, lo, false), self.cap_origins(caps, last, hi, true)];
- let kinds: Vec<Kind> = h
- .faces
- .iter()
- .map(|f| match f.origins.as_slice() {
- [FaceOrigin::Profile { segment }] => (*segment < count).then_some(Kind::Wall(*segment)),
- [FaceOrigin::Cap { end }] => Some(Kind::Cap(usize::from(*end))),
- _ => None,
- })
- .collect::<Option<_>>()?;
- let faces = kinds
- .iter()
- .map(|k| match *k {
- Kind::Wall(segment) => {
- let walls = (0..layers.len()).map(|layer| Self::wall(tag(layer, segment)?)).collect::<Option<BTreeSet<_>>>()?;
- let whole = match layers {
- [(_, lo, hi)] => self.whole(caps, tag(0, segment)?, *lo, *hi),
- _ => false,
- };
- Some((walls, whole))
- }
- Kind::Cap(end) => Some(tops.get(end).filter(|o| !o.is_empty())?.clone()).map(|o| (o, false)),
- })
- .collect::<Option<Vec<_>>>()?;
- let (edges, bounds) = edge_order(body.solid.face_iter());
- let position: HashMap<mt::EdgeID, usize> = edges.iter().enumerate().map(|(i, e)| (e.id(), i)).collect();
- // The segment of the wall beside an edge of the start cap.
- let segment_of = |e: &mt::Edge| -> Option<usize> {
- bounds.get(*position.get(&e.id())?)?.iter().find_map(|f| match h.faces.get(*f)?.origins.as_slice() {
- [FaceOrigin::Profile { segment }] => Some(*segment),
- _ => None,
- })
- };
- let start = kinds.iter().position(|k| matches!(k, Kind::Cap(0)))?;
- // At each vertex of the start cap: the segment running into it, the one running out,
- // and whether that is one segment the extrude split there.
- let mut junctions: HashMap<mt::VertexID, (usize, usize, bool)> = HashMap::new();
- for w in body.solid.face_iter().nth(start)?.absolute_boundaries() {
- let es: Vec<mt::Edge> = w.edge_iter().cloned().collect();
- let segs: Vec<usize> = es.iter().map(segment_of).collect::<Option<_>>()?;
- if segs.windows(2).any(|p| p.first() > p.get(1)) {
- return None;
- }
- for (k, e) in es.iter().enumerate() {
- let (s, next) = (*segs.get(k)?, *segs.get((k + 1) % segs.len())?);
- junctions.insert(e.back().id(), (s, next, s == next && k + 1 != segs.len()));
- }
- }
- let mut origins = HashMap::new();
- for (e, fs) in edges.iter().zip(&bounds) {
- let [f, g] = fs.as_slice() else { return None };
- let o = match (kinds.get(*f)?, kinds.get(*g)?) {
- (Kind::Wall(segment), Kind::Cap(end)) | (Kind::Cap(end), Kind::Wall(segment)) => {
- let layer = if *end == 0 { 0 } else { layers.len() - 1 };
- self.cap_edge(tag(layer, *segment)?, tops.get(*end)?, crate::heal::edge_points(e).get(2).copied()?)?
- }
- (Kind::Wall(..), Kind::Wall(..)) => {
- let (s, next, split) = *[e.absolute_front().id(), e.absolute_back().id()].iter().find_map(|v| junctions.get(v))?;
- let mut o = BTreeSet::new();
- for (layer, (_, lo, hi)) in layers.iter().enumerate() {
- let (t, u) = (tag(layer, s)?, tag(layer, next)?);
- // A segment the extrude split in two runs on through the vertex between.
- let (t, u) = if split { (Tag { end: None, ..t }, Tag { start: None, ..t }) } else { (t, u) };
- o.extend(self.junction(t, u, *lo, *hi)?);
- }
- o.into_iter().collect()
- }
- _ => return None,
- };
- origins.insert(e.id(), o);
- }
- Some((faces, origins))
- }
-
- /// Faces and edges of a piece sewn from `specs`: the sewing reports which spec each face was
- /// built from. Walls meeting at a vertex of their loop (when two walls meet at both ends,
- /// the edge's vertex says which); walls over one segment meeting at a level; walls meeting
- /// caps.
- #[allow(clippy::type_complexity)]
- fn sewn(
- &self,
- caps: &[Cap],
- body: &Body,
- specs: &[Spec],
- built: &[usize],
- ) -> Option<(Vec<(BTreeSet<FaceOrigin>, bool)>, HashMap<mt::EdgeID, Vec<EdgeOrigin>>)> {
- let cap_of: Vec<Option<BTreeSet<FaceOrigin>>> = specs
- .iter()
- .map(|s| match s {
- Spec::Cap { section, z, up } => Some(self.cap_origins(caps, section, *z, *up)).filter(|o| !o.is_empty()),
- Spec::Wall { .. } => None,
- })
- .collect();
- let faces = built
- .iter()
- .map(|i| match specs.get(*i)? {
- Spec::Wall { slabs, .. } => Some((slabs.iter().map(|s| Self::wall(s.tag)).collect::<Option<_>>()?, false)),
- Spec::Cap { .. } => cap_of.get(*i)?.clone().map(|o| (o, false)),
- })
- .collect::<Option<Vec<_>>>()?;
- let (edges, bounds) = edge_order(body.solid.face_iter());
- let mut origins = HashMap::new();
- for (e, fs) in edges.iter().zip(&bounds) {
- let [f, g] = fs.as_slice() else { return None };
- let (i, j) = (*built.get(*f)?, *built.get(*g)?);
- let (x, y) = (specs.get(i)?, specs.get(j)?);
- // The edge's levels, lower first, and where it stands in plan.
- let (front, back) = (from_p3(e.absolute_front().point()), from_p3(e.absolute_back().point()));
- let (h1, h2) = (self.plane.height(front), self.plane.height(back));
- let (lo, hi) = (h1.min(h2), h1.max(h2));
- let middle = || crate::heal::edge_points(e).get(2).copied();
- let o = match (x, y) {
- (Spec::Wall { .. }, Spec::Cap { .. }) => self.cap_edge(x.end(lo, self.tol)?.tag, cap_of.get(j)?.as_ref()?, middle()?)?,
- (Spec::Cap { .. }, Spec::Wall { .. }) => self.cap_edge(y.end(lo, self.tol)?.tag, cap_of.get(i)?.as_ref()?, middle()?)?,
- (Spec::Wall { .. }, Spec::Wall { .. }) if hi - lo <= self.tol => {
- // One over the other at a level: the lower first.
- let (below, above) = match (x.top(lo, self.tol), y.bottom(lo, self.tol)) {
- (Some(s), Some(t)) => (s, t),
- _ => (y.top(lo, self.tol)?, x.bottom(lo, self.tol)?),
- };
- self.stacked(below.tag, above.tag)?
- }
- (Spec::Wall { .. }, Spec::Wall { .. }) => {
- // Side by side within a slab: the vertex the edge stands on (in plan) says
- // which way round they meet.
- let (s, t) = (x.slab(lo, hi)?, y.slab(lo, hi)?);
- let p = self.plane.to_local(front);
- let at = |q: &Vec2| p.dist(*q) < self.tol * 10.0;
- if s.next == j && at(&s.at) {
- self.junction(s.tag, t.tag, lo, hi)?
- } else if t.next == i && at(&t.at) {
- self.junction(t.tag, s.tag, lo, hi)?
- } else {
- return None;
- }
- }
- _ => return None,
- };
- origins.insert(e.id(), o);
- }
- Some((faces, origins))
- }
-}
diff --git a/crates/kernel/src/prism_local.rs b/crates/kernel/src/prism_local.rs
deleted file mode 100644
index e2bbbcfc2f..0000000000
--- a/crates/kernel/src/prism_local.rs
+++ /dev/null
@@ -1,353 +0,0 @@
-//! Booleans of a prism tool with a target that is a prism along the tool's direction only round
-//! the tool: a pocket made deeper in a plate whose rim is chamfered, a ring cut round a
-//! counterbored hole in a chamfered disc. The tool's walls lie on the target's there, which the
-//! B-rep boolean can't intersect, and the 2D route ([`crate::prism::prism_boolean`]) declines the
-//! target for a face far away (the chamfer) that is neither a wall along the direction nor a cap
-//! square to it.
-//!
-//! The target is split by planes into a column round the tool that holds none of those faces;
-//! the column takes the exact 2D boolean, and the pieces are glued back along the cut faces, as
-//! [`crate::polybool::sliced_planar_boolean`] does for an all-planar tool beside curved faces.
-//! The cuts are imprints (no boolean), each placed beside the tool on one of three axes: the
-//! tool's direction and two square to it. A cut that leaves every offending face of the middle
-//! piece beyond it goes first; otherwise one close beside the tool, which splits them (a
-//! chamfer all round a disc is split into two pieces apart, which the next cut leaves out).
-
-use solidcraft_geom::{Plane, Vec3};
-use truck_modeling as mt;
-
-use crate::body::Body;
-use crate::boolean_record::{self as recorded, Traced};
-use crate::{BoolOp, KernelError, Result};
-
-/// Cuts at most, each splitting the middle piece once.
-const MAX_CUTS: usize = 6;
-
-/// Cuts made with half boxes at most (two booleans each, with their retries): an imprint traced
-/// wrong across a curved face is rare, and the booleans cost seconds on curved parts.
-const MAX_BOX_CUTS: usize = 2;
-
-/// Operands a piece's history is over: `a`, `b`, then the two half boxes each cut may be made
-/// with (dropped from the result, whose faces are none of theirs).
-const OPERANDS: usize = 2 + 2 * MAX_CUTS;
-
-thread_local! {
- /// Set while [`local_prism_boolean`] runs: the booleans it makes a cut with (a piece and a
- /// half box) take the general path, not this one again.
- static RUNNING: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
-}
-
-/// An extent along each of three axes.
-type Extent = [(f64, f64); 3];
-
-/// [`crate::prism::prism_boolean`] of `a` and the prism `b`, taken in a column of `a` round `b`
-/// (see the module notes). `None` when `b` is not a prism, `a` is one along `b`'s direction
-/// already, or no column round `b` is clear of `a`'s other faces: the caller goes on as before.
-pub(crate) fn local_prism_boolean(a: &Body, b: &Body, op: BoolOp) -> Option<Result<Option<Body>>> {
- // A cut or an intersection: what a tool meeting the target's walls fails on. A union (a
- // shell's cavity joined with its opening) is left to the general path.
- if !matches!(op, BoolOp::Cut | BoolOp::Intersect) || a.face_count() > 4096 || RUNNING.with(std::cell::Cell::get) {
- return None;
- }
- /// Clears the flag however the boolean ends, a caught panic included.
- struct Reset;
- impl Drop for Reset {
- fn drop(&mut self) {
- RUNNING.with(|r| r.set(false));
- }
- }
- RUNNING.with(|r| r.set(true));
- let _reset = Reset;
- let d = crate::prism::prism_axis(b)?;
- let size = a.size().max(b.size());
- let tol = (size * 1e-7).max(1e-9) * 10.0;
- let frame = Plane::from_normal(Vec3::ZERO, d)?;
- let axes = [frame.x, frame.y, d];
- // Extents come from meshes this close to the faces, widened by as much.
- let mesh_tol = (size * 1e-3).max(1e-4);
- let tool = widened(extent(&b.mesh(&crate::MeshTolerance::chord(mesh_tol)).ok()?.positions, axes)?, mesh_tol);
- let gap = size * 1e-4 + 1e-6;
- let pieces = survey(a, d, tol, mesh_tol, axes)?.pieces;
- if pieces.is_empty() {
- return None;
- }
- // A piece of an offending face within a hair of the tool's box: no column round the tool
- // can leave it out, so nothing is cut.
- let reach = size * 2e-3 + 2.0 * gap;
- if pieces.iter().any(|(_, e)| e.iter().zip(&tool).all(|((c0, c1), (t0, t1))| *c1 > t0 - reach && *c0 < t1 + reach)) {
- return None;
- }
- let run = || -> Result<Option<Body>> {
- let fail = |m: &str| KernelError::Failed(format!("prism boolean in a column round the tool: {m}"));
- let mut middle: Traced = (a.clone(), recorded::kept(a, 0, OPERANDS));
- let mut outside: Vec<Traced> = Vec::new();
- // The sides already cut (axis, positive side): each is cut once.
- let mut cut: Vec<(usize, bool)> = Vec::new();
- let mut box_cuts = 0;
- for _ in 0..MAX_CUTS {
- let survey = survey(&middle.0, d, tol, mesh_tol, axes).ok_or_else(|| fail("the middle piece"))?;
- let off = survey.faces();
- if off.is_empty() {
- break;
- }
- let (k, places, keep_positive) =
- next_cut(&off, &tool, &survey.here, &survey.flat, &cut, axes, size, gap).ok_or_else(|| fail("no cut leaves the other faces out"))?;
- cut.push((k, !keep_positive));
- let axis = axes[k];
- let (u, w) = (axes[(k + 1) % 3], axes[(k + 2) % 3]);
- // The first of the places where the piece splits into parts that add up to it (a
- // plane whose section through the piece doesn't close is passed over). The cut's
- // half boxes, if it takes them, are operands `slot` and `slot + 1`.
- let slot = 2 * cut.len();
- let (away, kept) = places
- .iter()
- .enumerate()
- .find_map(|(i, x)| {
- let plane = Plane::new(axis * *x, u, w)?;
- let with_boxes = i == 0 && box_cuts < MAX_BOX_CUTS;
- // Only a plane across an offending face can be traced wrong (a cone's piece
- // meshed past its bounds): the others are taken as they are.
- let verify = survey.pieces.iter().any(|(_, e)| e[k].0 < *x && e[k].1 > *x);
- let r = split(&middle, &plane, axis, *x, keep_positive, slot, with_boxes, verify)?;
- box_cuts += usize::from(r.2);
- Some((r.0, r.1))
- })
- .ok_or_else(|| fail("a cut beside the tool"))?;
- outside.extend(away);
- middle = kept;
- }
- if !survey(&middle.0, d, tol, mesh_tol, axes).is_some_and(|s| s.pieces.is_empty()) {
- return Err(fail("other faces are left round the tool"));
- }
- let r = match crate::prism::prism_boolean(&middle.0, b, op) {
- Some(r) => r?,
- None => return Err(fail("the column is not a prism along the tool")),
- };
- crate::polybool::reassembled(a, b, op, &middle, r, outside, OPERANDS, &fail)
- };
- Some(run())
-}
-
-/// `piece` split by `plane` (at `x` along `axis`, square to it): the parts away from the tool
-/// and the one on its side (positive along `axis` when `keep_positive`), with their histories.
-/// An imprint of the plane, taken as it is unless `verify`; else where its parts don't add up to
-/// the piece (a plane across a cone can be traced wrong) and `with_boxes`, the piece's intersections with the half boxes
-/// either side (the cut's operands `slot` and `slot + 1`), and then whether it took them. `None`
-/// when neither adds up.
-#[allow(clippy::too_many_arguments)]
-fn split(
- piece: &Traced,
- plane: &Plane,
- axis: Vec3,
- x: f64,
- keep_positive: bool,
- slot: usize,
- with_boxes: bool,
- verify: bool,
-) -> Option<(Vec<Traced>, Traced, bool)> {
- if !verify {
- let (away, kept) = crate::polybool::split_beside(piece, plane, axis, x, keep_positive)?;
- return Some((away, kept, false));
- }
- let whole = crate::measure(&piece.0).ok()?.volume;
- let adds_up = |away: &[Traced], kept: &Traced| {
- let sum: Option<f64> = away.iter().chain([kept]).map(|(p, _)| crate::measure(p).ok().map(|m| m.volume)).sum();
- sum.is_some_and(|sum| (sum - whole).abs() <= whole.abs() * 5e-5 + 1e-9)
- };
- if let Some((away, kept)) = crate::polybool::split_beside(piece, plane, axis, x, keep_positive)
- && adds_up(&away, &kept)
- {
- return Some((away, kept, false));
- }
- if !with_boxes {
- return None;
- }
- let boxes = (crate::ops::half_box(&piece.0, plane, !keep_positive).ok()?, crate::ops::half_box(&piece.0, plane, keep_positive).ok()?);
- let (h_away, h_kept) = (recorded::kept(&boxes.0, slot, OPERANDS), recorded::kept(&boxes.1, slot + 1, OPERANDS));
- let away = crate::ops::boolean(&piece.0, &boxes.0, BoolOp::Intersect).ok()?;
- let kept = crate::ops::boolean(&piece.0, &boxes.1, BoolOp::Intersect).ok()??;
- let away: Vec<Traced> = away
- .into_iter()
- .map(|o| {
- let h = recorded::of_pair(&o, &piece.1, &h_away);
- (o, h)
- })
- .collect();
- let kept: Traced = {
- let h = recorded::of_pair(&kept, &piece.1, &h_kept);
- (kept, h)
- };
- adds_up(&away, &kept).then_some((away, kept, true))
-}
-
-/// The extent of `points` along each of `axes`; `None` for no points.
-fn extent(points: &[Vec3], axes: [Vec3; 3]) -> Option<Extent> {
- if points.is_empty() {
- return None;
- }
- let mut e = [(f64::INFINITY, f64::NEG_INFINITY); 3];
- for p in points {
- for (slot, axis) in e.iter_mut().zip(axes) {
- let t = p.dot(axis);
- *slot = (slot.0.min(t), slot.1.max(t));
- }
- }
- e.iter().all(|(lo, hi)| lo.is_finite() && hi.is_finite()).then_some(e)
-}
-
-/// What a cut is chosen from: a piece's extent (`here`), the mesh triangles of its faces that
-/// are neither a wall along the direction nor a plane square to it (the faces that keep it from
-/// being a prism along it: each one's index and extent), and its planar faces (unit normal,
-/// offset along it) for a cut to keep out of. Extents are widened by the mesh's tolerance.
-struct Survey {
- here: Extent,
- pieces: Vec<(usize, Extent)>,
- flat: Vec<(Vec3, f64)>,
-}
-
-impl Survey {
- /// The extent of each offending face.
- fn faces(&self) -> Vec<Extent> {
- let mut faces: Vec<(usize, Extent)> = Vec::new();
- for (i, e) in &self.pieces {
- match faces.iter_mut().find(|(j, _)| j == i) {
- Some((_, acc)) => {
- for (x, y) in acc.iter_mut().zip(e) {
- *x = (x.0.min(y.0), x.1.max(y.1));
- }
- }
- None => faces.push((*i, *e)),
- }
- }
- faces.into_iter().map(|(_, e)| e).collect()
- }
-}
-
-/// [`Survey`] of `body` along `d`, from one mesh of it. `None` when it can't be meshed.
-fn survey(body: &Body, d: Vec3, tol: f64, mesh_tol: f64, axes: [Vec3; 3]) -> Option<Survey> {
- let mut work = 262_144usize;
- let mut flat = Vec::new();
- let off: Vec<bool> = body
- .solid
- .face_iter()
- .map(|f| {
- let surface = f.oriented_surface();
- match &surface {
- mt::Surface::Plane(p) => {
- let n = p.normal();
- let Some(n) = Vec3::new(n.x, n.y, n.z).normalized() else { return true };
- let o = p.origin();
- flat.push((n, n.dot(Vec3::new(o.x, o.y, o.z))));
- let along = n.dot(d).abs();
- // NaN counts as inside, as the comparisons it replaces did.
- along.is_nan() || (1e-9..=1.0 - 1e-9).contains(&along)
- }
- _ => !crate::prism::wall_along(&surface, d, tol, &mut work),
- }
- })
- .collect();
- let mesh = body.mesh(&crate::MeshTolerance::chord(mesh_tol)).ok()?;
- let here = widened(extent(&mesh.positions, axes)?, mesh_tol);
- let mut pieces = Vec::new();
- if off.iter().any(|x| *x) {
- for (t, fi) in mesh.triangles.iter().zip(&mesh.tri_face) {
- let i = *fi as usize;
- if !off.get(i).copied().unwrap_or(false) {
- continue;
- }
- let Some(tri) = mesh.tri(t) else { continue };
- if let Some(e) = extent(&tri, axes) {
- pieces.push((i, widened(e, mesh_tol)));
- }
- }
- }
- Some(Survey { here, pieces, flat })
-}
-
-/// `e` grown by `by` each way.
-fn widened(mut e: Extent, by: f64) -> Extent {
- for (lo, hi) in e.iter_mut() {
- *lo -= by;
- *hi += by;
- }
- e
-}
-
-/// The next cut of the middle piece (its extent `here`, its planar faces `flat`): the axis, the
-/// place along it and whether the tool's side is the positive one. A cut leaving the most
-/// offending faces (`off`) wholly beyond it, on a side not `cut` yet, placed halfway to the nearest of them; failing
-/// that, one beside the tool across the most of them (on an axis square to the direction
-/// first). `None` when no cut beside the tool has any offending face beyond it.
-#[allow(clippy::too_many_arguments)]
-fn next_cut(
- off: &[Extent],
- tool: &Extent,
- here: &Extent,
- flat: &[(Vec3, f64)],
- cut: &[(usize, bool)],
- axes: [Vec3; 3],
- size: f64,
- gap: f64,
-) -> Option<(usize, Vec<f64>, bool)> {
- // Places between `near` (beside the tool) and `far`, best first, out of the planes of the
- // piece's faces square to the axis.
- let place = |k: usize, near: f64, far: f64| -> Option<Vec<f64>> {
- let axis = axes[k];
- let places: Vec<f64> = [0.5, 0.37, 0.63, 0.25, 0.75, 0.1, 0.9]
- .iter()
- .map(|t| near + (far - near) * t)
- .filter(|x| !flat.iter().any(|(n, o)| n.dot(axis).abs() > 1.0 - 1e-9 && (o * n.dot(axis).signum() - x).abs() < gap))
- .collect();
- (!places.is_empty()).then_some(places)
- };
- let mut whole: Option<(usize, usize, Vec<f64>, bool)> = None;
- let mut across: Option<(usize, usize, Vec<f64>, bool)> = None;
- let beside = size * 2e-3;
- for k in [0usize, 1, 2] {
- let (t0, t1) = tool[k];
- let (h0, h1) = here[k];
- for positive_side in [true, false] {
- if cut.contains(&(k, positive_side)) {
- continue;
- }
- // Past the tool on this side: is there any of the piece to cut away?
- let (edge, room) = if positive_side { (t1 + gap, h1 - t1) } else { (t0 - gap, t0 - h0) };
- if room <= 2.0 * gap {
- continue;
- }
- let beyond: Vec<f64> = off
- .iter()
- .filter_map(|e| {
- let (c0, c1) = e[k];
- if positive_side { (c0 > edge).then_some(c0) } else { (c1 < edge).then_some(c1) }
- })
- .collect();
- if let Some(nearest) = beyond.iter().copied().reduce(if positive_side { f64::min } else { f64::max }) {
- let Some(x) = place(k, edge, nearest) else { continue };
- if whole.as_ref().is_none_or(|(_, n, ..)| beyond.len() > *n) {
- whole = Some((k, beyond.len(), x, !positive_side));
- }
- continue;
- }
- if k == 2 && across.is_some() {
- continue;
- }
- let near = edge + if positive_side { beside } else { -beside };
- let crossing = off.iter().filter(|e| if positive_side { e[k].1 > near } else { e[k].0 < near }).count();
- let limit = if positive_side { h1 } else { h0 };
- if crossing == 0 {
- continue;
- }
- let Some(x) = place(k, edge, near + (near - edge))
- .map(|p| p.into_iter().filter(|x| if positive_side { *x < limit - gap } else { *x > limit + gap }).collect::<Vec<_>>())
- .filter(|p| !p.is_empty())
- else {
- continue;
- };
- if across.as_ref().is_none_or(|(_, n, ..)| crossing > *n) {
- across = Some((k, crossing, x, !positive_side));
- }
- }
- }
- whole.or(across).map(|(k, _, x, keep_positive)| (k, x, keep_positive))
-}
diff --git a/crates/kernel/src/prism_spline_tests.rs b/crates/kernel/src/prism_spline_tests.rs
deleted file mode 100644
index 6fe0b48a72..0000000000
--- a/crates/kernel/src/prism_spline_tests.rs
+++ /dev/null
@@ -1,87 +0,0 @@
-use super::*;
-
-/// A rounded square of four quadratic curves (a font's kind) about (20, 15).
-fn rounded() -> Region2 {
- let p = Vec2::new;
- let q = |a: Vec2, apex: Vec2, b: Vec2| Seg2::Conic { a, apex, b, w: 1.0 };
- let segs = vec![
- q(p(10.0, 15.0), p(10.0, 5.0), p(20.0, 5.0)),
- q(p(20.0, 5.0), p(30.0, 5.0), p(30.0, 15.0)),
- q(p(30.0, 15.0), p(30.0, 25.0), p(20.0, 25.0)),
- q(p(20.0, 25.0), p(10.0, 25.0), p(10.0, 15.0)),
- ];
- Region2 { outer: Loop2 { segs }, holes: vec![] }
-}
-
-fn block() -> Body {
- crate::box_solid(Vec3::new(0.0, 0.0, 0.0), Vec3::new(40.0, 30.0, 10.0)).unwrap()
-}
-
-/// Its free-form faces (the tool's walls kept as the curves they were).
-fn spline_faces(b: &Body) -> usize {
- b.solid.face_iter().filter(|f| matches!(f.surface(), mt::Surface::BSplineSurface(_) | mt::Surface::NurbsSurface(_))).count()
-}
-
-/// A shape of a font's curves engraved into a block is decided in 2D, its walls the exact curves.
-#[test]
-fn an_engraving_of_quadratic_curves_is_exact_in_2d() {
- let region = rounded();
- let area = region.outer.signed_area().abs();
- let tool = crate::extrude(&Plane::XY, std::slice::from_ref(&region), 9.0, 11.0).unwrap().remove(0);
- let out = prism_boolean(&block(), &tool, BoolOp::Cut).expect("the 2D route takes it").unwrap().unwrap();
- assert!(out.validity().is_empty(), "{:?}", out.validity());
- // Half the tool, measured as the result is (meshes of curved faces are off by about 1e-4).
- let taken = 12000.0 - crate::measure(&out).unwrap().volume;
- let half = crate::measure(&tool).unwrap().volume / 2.0;
- assert!((taken - half).abs() < 1e-6 * half && (taken - area).abs() < 2e-4 * area, "{taken} vs {half} ({area})");
- assert_eq!(spline_faces(&out), 4);
-}
-
-/// A shape running off the block's side is cut where its curves exactly cross the side.
-#[test]
-fn an_engraving_running_off_the_side_ends_on_its_exact_crossings() {
- let region = rounded();
- // Moved 14 to the left: the block's side x = 0 cuts its two left curves.
- let shift = |s: &Seg2| match *s {
- Seg2::Conic { a, apex, b, w } => {
- Seg2::Conic { a: a - Vec2::new(14.0, 0.0), apex: apex - Vec2::new(14.0, 0.0), b: b - Vec2::new(14.0, 0.0), w }
- }
- other => other,
- };
- let moved = Region2 { outer: Loop2 { segs: region.outer.segs.iter().map(shift).collect() }, holes: vec![] };
- let tool = crate::extrude(&Plane::XY, std::slice::from_ref(&moved), 9.0, 11.0).unwrap().remove(0);
- let out = prism_boolean(&block(), &tool, BoolOp::Cut).expect("the 2D route takes it").unwrap().unwrap();
- assert!(out.validity().is_empty(), "{:?}", out.validity());
- // What the block keeps of the shape: the shape's part at x > 0.
- let inside = planar_regions_boolean(
- std::slice::from_ref(&moved),
- &[Region2 {
- outer: Loop2::polygon(&[Vec2::new(0.0, 0.0), Vec2::new(40.0, 0.0), Vec2::new(40.0, 30.0), Vec2::new(0.0, 30.0)]),
- holes: vec![],
- }],
- BoolOp::Intersect,
- 1e-6,
- )
- .unwrap();
- let area: f64 = inside.iter().map(|r| r.outer.signed_area().abs()).sum();
- let taken = 12000.0 - crate::measure(&out).unwrap().volume;
- assert!((taken - area).abs() < 2e-4 * area, "{taken} vs {area}");
- assert!(spline_faces(&out) >= 2, "{}", spline_faces(&out));
-}
-
-/// A tool that misses its target leaves it as it is: the 2D route declines it (the B-rep
-/// boolean then reuses the target itself). An engraving taking far less than a ten-thousandth
-/// of a large part is a change all the same, and the route keeps it: told from the exact
-/// sections, not from volumes measured off meshes, which could not tell it from no change.
-#[test]
-fn a_tool_that_misses_is_declined_and_a_fine_engraving_is_not() {
- let big = crate::box_solid(Vec3::new(0.0, 0.0, 0.0), Vec3::new(200.0, 200.0, 10.0)).unwrap();
- let region = rounded();
- let tool = |lo: f64, hi: f64| crate::extrude(&Plane::XY, std::slice::from_ref(&region), lo, hi).unwrap().remove(0);
- assert!(prism_boolean(&big, &tool(10.0, 12.0), BoolOp::Cut).is_none(), "a tool above the part misses it");
- // 0.05 mm deep: 17 mm³ of a 400000 mm³ part.
- let out = prism_boolean(&big, &tool(9.95, 11.0), BoolOp::Cut).expect("an engraving is a change").unwrap().unwrap();
- let taken = 400_000.0 - crate::measure(&out).unwrap().volume;
- let want = region.outer.signed_area().abs() * 0.05;
- assert!((taken - want).abs() < 2e-3 * want, "{taken} vs {want}");
-}