diff --git a/solidcore/crates/solidcore-ops/tests/boolean.rs b/solidcore/crates/solidcore-ops/tests/boolean.rs index 350f1e65a64..d44d442b1c1 100644 --- a/solidcore/crates/solidcore-ops/tests/boolean.rs +++ b/solidcore/crates/solidcore-ops/tests/boolean.rs @@ -1122,3 +1122,213 @@ fn a_box_mirrored_into_an_opening_of_a_spline_loft_stays_clear_of_it() { } assert!(near(volume(&mirrored()), boxed), "{}", volume(&mirrored())); } + +/// Sets the calling thread's fixes: none, or every one (SolidCraft's set). +fn with_fixes(all: bool) { + if all { + all_fixes(); + } else { + session::set_thread_fixes(std::iter::empty::<&str>()).unwrap(); + } +} + +/// `body` as SolidCraft hands it to the next feature: through its record. +fn round_tripped(body: &Body) -> Body { + let (record, _) = body.to_record().unwrap(); + Body::from_record(&record, true).unwrap().0 +} + +/// solidcraft#12785 (solidcore #13650): a block with a hexagonal pocket through it and a +/// round hole drilled from an end face along the pocket's axis plane, ending exactly at a +/// corner of the pocket, so the hole's bottom meets the two pocket walls along a segment of +/// the corner edge (a solid touching itself along a line). The cut leaves that segment as one +/// edge of four faces; a record round trip (`to_record`, `from_record`: SolidCraft's body +/// between features) writes it as two edges of two faces each, and filling the pocket with +/// the same hexagon as a join failed there (`topology_intersector::p1::relate`, status 1001, +/// or a result that is not a closed solid). Without the hole, or without the round trip, the +/// same join works. Carried from bherbruck's +/// `boolean_join_fills_pocket_with_hole_at_its_corner.rs`. +#[allow(clippy::expect_used, clippy::panic)] // test helpers +mod pocket_with_hole_at_its_corner { + use std::f64::consts::TAU; + + use solidcore_ops::boolean::{boolean, BooleanOp}; + use solidcore_ops::sweep::{extrude, Curve, DraftCorner}; + use solidcore_ops::{Body, CheckLevel}; + + use super::{round_tripped, with_fixes}; + + /// The hexagon's circumradius. + const R: f64 = 6.3685; + const Z: [f64; 3] = [0.0, 0.0, 1.0]; + + fn line(start: [f64; 3], end: [f64; 3]) -> Curve { + Curve::Line { start, end } + } + + /// The regular hexagon of circumradius `R` about the origin with a corner on +X, at z = 0 + /// (the reporter's sketch: the corner at (R, 0), the next at (R/2, R sqrt(3)/2)). + fn hexagon() -> Vec { + const H: f64 = 5.515_282_784_001_197; + let corners = [ + [R, 0.0, 0.0], + [R / 2.0, H, 0.0], + [-R / 2.0, H, 0.0], + [-R, 0.0, 0.0], + [-R / 2.0, -H, 0.0], + [R / 2.0, -H, 0.0], + ]; + (0..6) + .map(|i| line(corners[i], corners[(i + 1) % 6])) + .collect() + } + + /// The block 100.29 x 32 x 10. + fn block() -> Body { + extrude( + &[ + line([-50.145, -16.0, 0.0], [50.145, -16.0, 0.0]), + line([50.145, -16.0, 0.0], [50.145, 16.0, 0.0]), + line([50.145, 16.0, 0.0], [-50.145, 16.0, 0.0]), + line([-50.145, 16.0, 0.0], [-50.145, -16.0, 0.0]), + ], + Z, + 10.0, + 0.0, + DraftCorner::Curvature, + true, + ) + .unwrap() + } + + /// The hexagon extruded through the block's height: the pocket's cutter and the join's + /// tool. + fn tool() -> Body { + extrude(&hexagon(), Z, 10.0, 0.0, DraftCorner::Curvature, true).unwrap() + } + + /// The block with the pocket through it and the hole: 2.5 mm across, along -X from the + /// end face x = 50.145, 43.7765 deep, so it ends at the pocket's corner (R, 0). + fn target() -> Body { + let pocketed = boolean(block(), tool(), BooleanOp::Subtract) + .unwrap() + .expect("the pocketed block"); + let hole = extrude( + &[Curve::Arc { + center: [50.145, 0.0, 5.0], + axis: [-1.0, 0.0, 0.0], + reference: [0.0, 1.0, 0.0], + radius: 1.25, + start: 0.0, + end: TAU, + }], + [-1.0, 0.0, 0.0], + 50.145 - R, + 0.0, + DraftCorner::Curvature, + true, + ) + .unwrap(); + boolean(pocketed, hole, BooleanOp::Subtract) + .unwrap() + .expect("the drilled block") + } + + /// Joins `target` and the hexagon, checks the result and compares its volume with the + /// sum. + fn join_fills(target: Body, what: &str) { + let want = target.volume(1e-9).unwrap() + tool().volume(1e-9).unwrap(); + let b = match boolean(target, tool(), BooleanOp::Union) { + Ok(Some(b)) => b, + Ok(None) => panic!("{what}: no body"), + Err(e) => panic!("{what}: {e}"), + }; + let report = b.check(CheckLevel::All).unwrap(); + assert!(report.is_valid(), "{what}:\n{}", report.text); + let got = b.volume(1e-9).unwrap(); + assert!( + (got - want).abs() <= 1e-6 * want, + "{what}: volume {got} vs {want}" + ); + } + + /// The cut's own body: the corner segment is one edge of four faces, and the join works. + #[test] + fn filling_a_pocket_whose_corner_a_hole_reaches_joins() { + let target = target(); + assert_eq!(target.counts().unwrap(), [15, 37, 24]); + join_fills(target, "the cut's body"); + } + + /// The same body after its record round trip: the corner segment is two coincident edges + /// of two faces each, and the join works as well, with no fixes and with every fix. + #[test] + fn filling_a_pocket_whose_corner_a_hole_reaches_joins_after_a_record_round_trip() { + for all in [false, true] { + with_fixes(all); + let target = round_tripped(&target()); + assert_eq!(target.counts().unwrap(), [15, 38, 24]); + assert!(target.check(CheckLevel::All).unwrap().is_valid()); + join_fills(target, &format!("the round-tripped body, all fixes {all}")); + } + } + + /// The control: without the hole the same join works, round trip or not. + #[test] + fn filling_a_pocket_without_the_hole_joins() { + let pocketed = boolean(block(), tool(), BooleanOp::Subtract) + .unwrap() + .expect("the pocketed block"); + join_fills(round_tripped(&pocketed), "the pocketed block"); + } +} + +/// Two unit boxes touching along the edge x = y = 1 in one body (two solids), after a record +/// round trip (`split_shared` writes the edge once per solid, so the operand carries it as two +/// coincident edges, which the boolean glues back into the one edge the kernel's union shares). +/// Booleans on it give the exact volumes, whether the tool reaches the shared edge or not, +/// with no fixes and with every fix: subtract `[0.5, 1.5]^2 x [0, 0.5]` (an eighth of a unit +/// from each box, across the edge) leaves 1.75; intersect `[0.5, 1.5]^2 x [0, 1]` keeps 0.5; +/// union with a far unit box gives 3. +#[test] +fn two_solids_touching_along_an_edge_survive_a_round_trip_and_booleans() { + for all in [false, true] { + with_fixes(all); + let touching = || { + let a = make_box([0.0, 0.0, 0.0], [1.0, 1.0, 1.0]).unwrap(); + let b = make_box([1.0, 1.0, 0.0], [1.0, 1.0, 1.0]).unwrap(); + round_tripped(&boolean(a, b, BooleanOp::Union).unwrap().unwrap()) + }; + let cases = [ + ( + BooleanOp::Subtract, + make_box([0.5, 0.5, 0.0], [1.0, 1.0, 0.5]).unwrap(), + 1.75, + ), + ( + BooleanOp::Intersect, + make_box([0.5, 0.5, 0.0], [1.0, 1.0, 1.0]).unwrap(), + 0.5, + ), + ( + BooleanOp::Union, + make_box([5.0, 0.0, 0.0], [1.0, 1.0, 1.0]).unwrap(), + 3.0, + ), + ]; + for (op, tool, want) in cases { + let r = boolean(touching(), tool, op).unwrap().unwrap(); + let report = r.check(CheckLevel::All).unwrap(); + assert!( + report.is_valid(), + "all fixes {all}, {op:?}:\n{}", + report.text + ); + assert!( + near(volume(&r), want), + "all fixes {all}, {op:?}: {} vs {want}", + volume(&r) + ); + } + } +} diff --git a/solidcore/crates/solidcore/src/boolean/api_brep.rs b/solidcore/crates/solidcore/src/boolean/api_brep.rs index 8544e1091ba..c727c6dc85b 100644 --- a/solidcore/crates/solidcore/src/boolean/api_brep.rs +++ b/solidcore/crates/solidcore/src/boolean/api_brep.rs @@ -204,6 +204,366 @@ enum MergeMethod { NonManifold, } +/// One edge of a boolean operand, as [`glue_self_touching_edges`] compares them: its +/// vertices (the lower index first), its shell, its faces, whether a face lies on both sides +/// of it, and its curve's kind (the shell, faces, crack flag and kind only for an edge that +/// shares its vertices with another). +struct TouchingEdge { + edge: EdgeId, + start: crate::topology::VertexId, + ends: (u32, u32), + shell: Option, + faces: Vec, + /// A face on both sides of the edge (more than two of its edge uses on one face: the + /// kernel's crack edge, which its check refuses glued to another edge). + crack: bool, + kind: Option>, +} + +impl TouchingEdge { + /// Whether `other` may be a second copy of this edge, before its geometry is compared: + /// the same vertices and curve kind, both on faces (not wires), and neither a crack edge + /// (a face on both sides of it). The faces against those already glued are checked by + /// [`copy_pairs`]. The shells may differ: the record round trip leaves a solid touching + /// itself in two shells joined along the line, and the kernel shares one edge between + /// shells that touch. + fn may_copy(&self, other: &Self) -> bool { + self.shell.is_some() + && other.shell.is_some() + && !self.crack + && !other.crack + && self.ends == other.ends + && self.kind.is_some() + && self.kind == other.kind + } +} + +/// The edges to glue, `(surviving, to_delete, orientation)`: in each bucket of edges that +/// share their vertices (indices into `touches`), each edge not yet glued away keeps every +/// later edge that [`TouchingEdge::may_copy`] it, shares no face with it **or with any copy +/// already glued into it**, and whose curve `coincide` proves within the tolerance. So no +/// face ever ends up on both sides of the glued edge (the crack-glued form the kernel's check +/// refuses), however many copies a bucket holds. +/// +/// # Errors +/// +/// Those of `coincide`. +fn copy_pairs( + touches: &[TouchingEdge], + crowded: &[Vec], + mut coincide: impl FnMut(EdgeId, EdgeId) -> Result, +) -> Result< + Vec<( + EdgeId, + EdgeId, + crate::nurbs::b_spline_surface_n_lib::p2::OrientType, + )>, +> { + use crate::nurbs::b_spline_surface_n_lib::p2::OrientType; + use std::collections::BTreeSet; + + let mut pairs = Vec::new(); + let mut taken: BTreeSet = BTreeSet::new(); + for bucket in crowded { + for (n, &i) in bucket.iter().enumerate() { + let Some(first) = touches.get(i) else { + continue; + }; + if taken.contains(&first.edge) { + continue; + } + // the faces of the glued edge so far: this edge's and every accepted copy's + let mut faces: BTreeSet = + first.faces.iter().copied().collect(); + for &j in bucket.iter().skip(n + 1) { + let Some(other) = touches.get(j) else { + continue; + }; + if taken.contains(&other.edge) + || !first.may_copy(other) + || other.faces.iter().any(|f| faces.contains(f)) + || !coincide(first.edge, other.edge)? + { + continue; + } + let orientation = if first.start == other.start { + OrientType::Same + } else { + OrientType::Opposite + }; + pairs.push((first.edge, other.edge, orientation)); + taken.insert(other.edge); + faces.extend(other.faces.iter().copied()); + } + } + } + Ok(pairs) +} + +/// Not upstream: a bound `d` such that every point of curve `a` over `ia` is within `d` of a +/// point of curve `b` over `ib` and every point of `b` over `ib` within `d` of a point of `a` +/// over `ia` (their Hausdorff distance), every rounding of computing it included; `None` when +/// no bound is certain for the pair, which then is not glued. +/// +/// - Two lines: each edge is the segment between its curve's points at its interval's ends +/// ([`Line::segment_over`](crate::curve::line::Line::segment_over), each end with the error +/// bound of its coordinates). With the ends paired either way round, the distance between +/// `(1 - s) a0 + s a1` and `(1 - s) b0 + s b1` is at most `(1 - s)|a0 - b0| + s|a1 - b1|` +/// (the triangle inequality), so at most the larger end distance at every `s`: both +/// segments lie within it of each other. The pairing with the smaller bound is taken; each +/// end's coordinate error `e` moves it by at most `sqrt(3) e < 2 e`. +/// - Two B-splines (no other kind: their evaluation is their NURB's) on the same interval, +/// inside both NURBs' domains: at every parameter of the NURBs' common domain the two are +/// within [`certified_distance`](crate::nurbs::crv_deviation::certified_distance) of each +/// other, so each edge's point at `t` is within it of the other's point at the same `t`. +/// Rational and 2D NURBs, and NURBs on different domains, have no bound. +/// - Every other pair: no bound. +fn coincidence_bound( + a: &crate::curve::curve::p2::Curve, + ia: &crate::geom::extent1d::Extent1d, + b: &crate::curve::curve::p2::Curve, + ib: &crate::geom::extent1d::Extent1d, +) -> Option { + use crate::curve::curve::p2::CurveKind; + use crate::nurbs::crv_deviation::{certified_distance, norm_up}; + use crate::nurbs::math::gamma; + + match (a.kind(), b.kind()) { + (CurveKind::Line(la), CurveKind::Line(lb)) => { + let [(a0, ea0), (a1, ea1)] = la.segment_over(ia)?; + let [(b0, eb0), (b1, eb1)] = lb.segment_over(ib)?; + let dist = + |p: crate::Point3, q: crate::Point3| norm_up(p.x - q.x, p.y - q.y, p.z - q.z); + let along = dist(a0, b0)?.max(dist(a1, b1)?); + let across = dist(a0, b1)?.max(dist(a1, b0)?); + let err = 2.0 * (ea0.max(ea1) + eb0.max(eb1)); + let bound = (along.min(across) + err) * (1.0 + gamma(2)); + bound.is_finite().then_some(bound) + } + (CurveKind::BSpline(ca), CurveKind::BSpline(cb)) => { + if ia != ib { + return None; + } + let (na, nb) = (ca.nurb_ref().ok()?, cb.nurb_ref().ok()?); + let inside = |n: &crate::nurbs::crv_basic::Curve| { + matches!( + (n.knots().first(), n.knots().last()), + (Some(&lo), Some(&hi)) if lo <= ia.min() && ia.max() <= hi + ) + }; + if !(inside(na) && inside(nb)) { + return None; + } + certified_distance(na, nb).ok() + } + _ => None, + } +} + +/// Not upstream (WR-754): the coincident edges along which a solid touches itself, glued back +/// into one edge each. +/// +/// A solid touching itself along a line (a hole's bottom meeting two pocket walls along a +/// segment of their corner edge) is one edge of four faces in the form the merge handles. The +/// record format writes such an edge as one edge per face pair (`split_touching`), and the +/// merge of an operand in that form gives a body that is not a closed solid, or +/// fails in `topology_intersector::p1::relate` (1001). So each group of edges with the same +/// two vertices and curve kind, whose faces are all distinct and whose curves are proved +/// within the B-rep tolerance of each other over their whole intervals +/// ([`coincidence_bound`]: a bound over the whole edge, never samples; a pair with no bound, +/// or a NaN, is not glued), is glued into its first edge (`GlueEdgesGeneral`, no gap, with +/// region nesting), whether the copies lie in one shell or in two shells that touch along the +/// line (the round trip leaves a self-touching solid in two). Edges whose faces repeat (a +/// face on both sides of the line: the kernel's crack edges, which its check refuses glued) +/// are left alone, and a copy sharing a face with the edge or with a copy already glued into +/// it is not glued ([`copy_pairs`]). Returns the number of edges glued away. +/// +/// The edges are bucketed by their vertex pair; only a bucket of two or more edges has its +/// pairs compared, so a body without self-touch costs one pass over its edges. +/// +/// # Errors +/// +/// Those of the topology walk and the coincidence checks; those of `GlueEdgesGeneral` that +/// stand for no upstream status ([`crate::error::native_failure`]: a port invariant, a stale +/// id, an unported call, cancellation). +/// +/// **A gluing that fails leaves the operand as given.** The glue is all or nothing +/// ([`glue_all_or_none`]): the operand, `k.rng` and `k.upstream_ub_passed` are saved before +/// the first pair, and any other failure of `GlueEdgesGeneral` restores them exactly, so the +/// merge then runs as main does (0 is returned). `GlueEdgesGeneral` can fail on a valid operand, both before its +/// first change to the topology (`b.remove_from_edge_list(del)`) and after it: +/// - before: the notifications (`PreEdit`, `MergeInBrep`, each face's `PreEdit`), the +/// intervals and `curve_max_distance_between` of the same-geometry test (orientation +/// `Same`, equal intervals), the vertex reads and the shared-vertex precondition; +/// - after, for each moved use pair: the radial-sector search and its `InvalidInput` errors +/// (an edge or mate without edge use, shell, radial or region), `set_uv_trim_curve`, +/// `edge_remove` of the pair, the sector's mate and loop tests, `set_orientation`, +/// `add_oriented_eu_pair`, a surviving wire's `edge_remove` and vertex-use unlinking, the +/// surviving edge's `set_tolerance` and `destroy` of the deleted edge; then `merge_shells`, +/// `test_closure_split_region_attempt` (whose status passes on with +/// `brep_edit_statuses_pass_on`, and which may draw from `k.rng`), `is_spine` and +/// `test_closure_split_region_edge`. +/// +/// A failure at an "after" site would leave the operand half glued, so a check up front +/// cannot replace the snapshot. A snapshot the B-rep cannot take (a cleared surface owner, +/// or nesting past the copy bound) means no gluing at all. +fn glue_self_touching_edges(k: &mut Kernel, b: &mut Brep) -> Result { + use std::collections::BTreeMap; + + use crate::topology::brep::p7::glue_edges_general; + use crate::topology::edge; + use crate::topology::edgeuse::p1 as eu1; + + let tol = b.tolerance(); + // Every edge with a curve and two vertices, by vertex pair. + let mut touches: Vec = Vec::new(); + let mut buckets: BTreeMap<(u32, u32), Vec> = BTreeMap::new(); + for &e in b.edge_list() { + let data = b.edge(e)?; + if data.curve.is_none() { + continue; + } + let Some(start) = edge::start_vertex(b, e)? else { + continue; + }; + let Some(end) = edge::other_vertex(b, e, Some(start))? else { + continue; + }; + if start == end { + continue; + } + let (a, z) = (start.index(), end.index()); + let ends = (a.min(z), a.max(z)); + buckets.entry(ends).or_default().push(touches.len()); + touches.push(TouchingEdge { + edge: e, + start, + ends, + shell: None, + faces: Vec::new(), + crack: false, + kind: None, + }); + } + let crowded: Vec> = buckets.into_values().filter(|v| v.len() > 1).collect(); + // The shells, faces and curve kinds of the edges that share their vertices. + for &i in crowded.iter().flatten() { + let Some(touch) = touches.get_mut(i) else { + continue; + }; + let data = b.edge(touch.edge)?; + let Some(curve) = data.curve.as_ref() else { + continue; + }; + touch.kind = Some(core::mem::discriminant(curve.kind())); + for &eu in &data.edgeuses { + let Some(fu) = eu1::faceuse(b, eu)? else { + continue; + }; + if let Some(f) = b.faceuse(fu)?.face { + touch.faces.push(f); + } + if touch.shell.is_none() { + touch.shell = eu1::faceuse_shell(b, fu)?; + } + } + // each face of a manifold edge holds two of its uses (an edge use and its mate) + let uses = touch.faces.len(); + touch.faces.sort_unstable(); + touch.faces.dedup(); + touch.crack = uses > 2 * touch.faces.len(); + } + // Whether the two edges' curves are proved within `tol` of each other. + let coincide = |b: &Brep, x: EdgeId, y: EdgeId| -> Result { + let (dx, dy) = (b.edge(x)?, b.edge(y)?); + let (Some(cx), Some(cy)) = (dx.curve.as_ref(), dy.curve.as_ref()) else { + return Ok(false); + }; + // written so that a NaN bound or tolerance refuses + Ok(coincidence_bound(cx, &dx.interval, cy, &dy.interval).is_some_and(|d| d <= tol)) + }; + let pairs = copy_pairs(&touches, &crowded, |x, y| coincide(b, x, y))?; + glue_all_or_none( + k, + b, + &pairs, + |k, b, &(surviving, to_delete, orientation), env| { + glue_edges_general( + k, + b, + Some(surviving), + orientation, + 0.0, + true, + Some(to_delete), + None, + env, + ) + }, + ) +} + +/// One pair to glue: `(surviving, to_delete, orientation)`. +type GluePair = ( + EdgeId, + EdgeId, + crate::nurbs::b_spline_surface_n_lib::p2::OrientType, +); + +/// Runs `glue` on every pair, all or nothing ([`glue_self_touching_edges`]'s errors): the +/// operand, `k.rng` and `k.upstream_ub_passed` are saved first, and when a pair fails they +/// are all put back exactly, so the merge then runs as on main. An ordinary failure +/// ([`crate::error::native_failure`]) returns 0; a port defect or a cancellation is returned. +/// No snapshot ([`Brep::snapshot`]) means nothing is glued. Returns the number of pairs +/// glued. +/// +/// # Errors +/// +/// The failures of `glue` that stand for no upstream status; those of restoring the +/// operand's attributes after a gluing that succeeded. +fn glue_all_or_none( + k: &mut Kernel, + b: &mut Brep, + pairs: &[GluePair], + mut glue: impl FnMut( + &mut Kernel, + &mut Brep, + &GluePair, + &mut crate::topology::edge::NotifyEnv<'_>, + ) -> Result<()>, +) -> Result { + use crate::topology::brep::p2::ArenaNotifyState; + + if pairs.is_empty() { + return Ok(0); + } + let Ok(saved) = b.snapshot() else { + return Ok(0); + }; + let (rng, ub) = (k.rng.clone(), k.upstream_ub_passed.clone()); + let mut state = ArenaNotifyState::with_attributes_of(b); + let mut failure = None; + for pair in pairs { + if let Err(e) = glue(k, b, pair, &mut state.env(None)) { + failure = Some(e); + break; + } + } + if let Some(e) = failure { + // the snapshot holds the attributes too: the store moved out is dropped + drop(state); + b.restore(saved); + k.rng = rng; + k.upstream_ub_passed = ub; + // a port defect or a cancellation goes on; an ordinary failure merges as given + crate::error::native_failure::<()>(Err(e))?; + return Ok(0); + } + state.restore_attributes(b)?; + b.refresh_cached_topology(); + Ok(pairs.len()) +} + /// The body shared by the two-B-rep entry points after validation: build the merge /// (`SmMerge sMerge(*pContext, pBrep1, pBrep2)`, or with `0, 0, &sOptions` when /// `options` is given), then run `ManifoldBoolean` when both operands are manifold @@ -223,8 +583,8 @@ fn merge_boolean( /// B-rep (`SmMerge::m_vEdges`) as it left them. fn merge_boolean_by( k: &mut Kernel, - brep1: Brep, - brep2: Brep, + mut brep1: Brep, + mut brep2: Brep, operation: BooleanOperation, options: Option, method: MergeMethod, @@ -232,6 +592,9 @@ fn merge_boolean_by( // SmMerge sMerge(*pContext, pBrep1, pBrep2) (or 0, 0, &sOptions): tolerance and // angle 0, both computed by the constructor. use crate::boolean::merge::p3::BooleanDriver; + // (not upstream: WR-754) the operands' self-touch edge copies glued first + glue_self_touching_edges(k, &mut brep1)?; + glue_self_touching_edges(k, &mut brep2)?; // (not upstream) the driver carries the operands' attributes through the merge, as // upstream's live on the objects the merge edits let mut driver = crate::boolean::merge::p3::DependencyMerge::carrying_attributes(); @@ -620,6 +983,266 @@ mod tests { use super::*; use crate::geom::context::MarkType; + /// A geometry curve over a cubic NURB on `knots` with the control points `pts`. + fn cubic(pts: &[[f64; 3]], knots: Vec) -> crate::curve::curve::p2::Curve { + use crate::curve::curve::p2::{Curve, CurveKind}; + use crate::nurbs::b_spline_curve::p1::BSplineCurve; + use crate::nurbs::math::{CPoint, NOW}; + let pw = pts + .iter() + .map(|p| CPoint::new(p[0], p[1], p[2], NOW)) + .collect(); + let nurb = crate::nurbs::crv_basic::Curve::new(pw, 3, knots).unwrap(); + Curve::new(CurveKind::BSpline(BSplineCurve::from_nurb(nurb, 3, false))) + } + + fn segment(a: [f64; 3], z: [f64; 3]) -> crate::curve::curve::p2::Curve { + use crate::curve::curve::p2::{Curve, CurveKind}; + let p = |v: [f64; 3]| crate::math::Point3::new(v[0], v[1], v[2]); + Curve::new(CurveKind::Line(crate::curve::line::Line::from_points( + p(a), + p(z), + 3, + ))) + } + + /// What [`glue_all_or_none`] must put back: the edge list and every edge's uses, + /// tolerance and interval, and the counts of faces and vertices. + fn fingerprint(b: &Brep) -> String { + let edges: Vec = b + .edge_list() + .iter() + .map(|&e| { + let d = b.edge(e).unwrap(); + format!("{e:?} {:?} {} {:?}", d.edgeuses, d.tolerance, d.interval) + }) + .collect(); + format!("{edges:?} {} {}", b.faces().len(), b.vertices().len()) + } + + fn unit_box(k: &mut Kernel) -> Brep { + crate::primitive::api_primitives::create_box(k, crate::math::Point3::ZERO, 1.0, 1.0, 1.0) + .unwrap() + } + + /// A gluing whose second pair fails after the first changed the operand and drew from + /// the kernel's rng: the operand, the rng and the upstream-UB list are put back exactly. + /// An ordinary failure (`InvalidInput`) then lets the merge go on (0 glued); a failure + /// that stands for no upstream status (`NotFound`, a stale id) is returned. + #[test] + fn a_failed_gluing_restores_the_operand_and_the_rng() { + use crate::nurbs::b_spline_surface_n_lib::p2::OrientType; + let stale = SolidError::NotFound { + operation: "test", + entity: crate::error::EntityRef::Edge(EdgeId::from_index(9999)), + }; + for (failure, propagates) in [ + (SolidError::invalid_input("test", "a broken link"), false), + (stale, true), + ] { + let mut k = Kernel::default(); + let mut b = unit_box(&mut k); + let (before, rng, ub) = (fingerprint(&b), k.rng.clone(), k.upstream_ub_passed.clone()); + let e = b.edge_list()[0]; + let pairs = [(e, e, OrientType::Same), (e, e, OrientType::Same)]; + let mut failure = Some(failure); + let mut first = true; + let r = glue_all_or_none(&mut k, &mut b, &pairs, |k, b, &(e, _, _), _| { + if first { + first = false; + b.edge_mut(e)?.tolerance = 7.0; + let _ = k.rng.next_u64(); + k.note_upstream_ub("test"); + return Ok(()); + } + Err(failure.take().unwrap()) + }); + assert_eq!(r.is_err(), propagates, "{r:?}"); + if !propagates { + assert_eq!(r.unwrap(), 0); + } + assert_eq!(fingerprint(&b), before); + assert_eq!(k.rng, rng); + assert_eq!(k.upstream_ub_passed, ub); + } + } + + /// The real `GlueEdgesGeneral` through [`glue_all_or_none`]: two box edges that do not + /// share both vertices fail its precondition (an ordinary failure: nothing glued, the + /// operand as given), and a stale edge id is returned as an error, the operand again as + /// given. + #[test] + fn glue_edges_general_failures_leave_the_operand_as_given() { + use crate::nurbs::b_spline_surface_n_lib::p2::OrientType; + use crate::topology::brep::p7::glue_edges_general; + let mut k = Kernel::default(); + let mut b = unit_box(&mut k); + let before = fingerprint(&b); + let list = b.edge_list().to_vec(); + let (e0, far) = ( + list[0], + *list + .iter() + .find(|&&f| { + let ends = |x| { + let s = crate::topology::edge::start_vertex(&b, x).unwrap(); + (s, crate::topology::edge::other_vertex(&b, x, s).unwrap()) + }; + let ((a, z), (c, d)) = (ends(list[0]), ends(f)); + a != c && a != d && z != c && z != d + }) + .unwrap(), + ); + let glue = |k: &mut Kernel, + b: &mut Brep, + &(s, d, o): &GluePair, + env: &mut crate::topology::edge::NotifyEnv<'_>| { + glue_edges_general(k, b, Some(s), o, 0.0, true, Some(d), None, env) + }; + let r = glue_all_or_none(&mut k, &mut b, &[(e0, far, OrientType::Same)], glue); + assert_eq!(r.unwrap(), 0); + assert_eq!(fingerprint(&b), before); + let r = glue_all_or_none( + &mut k, + &mut b, + &[(e0, EdgeId::from_index(9999), OrientType::Same)], + glue, + ); + assert!(r.is_err(), "{r:?}"); + assert_eq!(fingerprint(&b), before); + } + + /// A [`TouchingEdge`] for [`copy_pairs`]: edge `e` between vertices 1 and 2 on `faces` + /// in shell 0, a line. + fn touching(e: u32, faces: &[u32], crack: bool) -> TouchingEdge { + use crate::topology::{FaceId, ShellId, VertexId}; + let line = segment([0.0; 3], [1.0, 0.0, 0.0]); + TouchingEdge { + edge: EdgeId::from_index(e), + start: VertexId::from_index(1), + ends: (1, 2), + shell: Some(ShellId::from_index(0)), + faces: faces.iter().map(|&f| FaceId::from_index(f)).collect(), + crack, + kind: Some(core::mem::discriminant(line.kind())), + } + } + + fn glued(touches: &[TouchingEdge], coincide: bool) -> Vec<(u32, u32)> { + let bucket: Vec = (0..touches.len()).collect(); + copy_pairs(touches, &[bucket], |_, _| Ok(coincide)) + .unwrap() + .into_iter() + .map(|(a, b, _)| (a.index(), b.index())) + .collect() + } + + /// Three coincident edges in one bucket: the copies are checked against every face + /// already glued, not only the first edge's, so no face ends up on both sides of the + /// glued edge. Crack edges (a face on both sides) are never glued; true copies on distinct + /// faces all glue into the first; unproved geometry glues nothing. + #[test] + fn copies_are_checked_against_every_face_already_glued() { + // two copies on face 5 and a first edge on faces 1, 2: only one copy on face 5 joins + let t = [ + touching(0, &[1, 2], false), + touching(1, &[5, 6], false), + touching(2, &[5, 7], false), + ]; + assert_eq!(glued(&t, true), vec![(0, 1)]); + // three copies on distinct faces all glue into the first + let t = [ + touching(0, &[1, 2], false), + touching(1, &[3, 4], false), + touching(2, &[5, 6], false), + ]; + assert_eq!(glued(&t, true), vec![(0, 1), (0, 2)]); + // a crack edge (face 5 on both sides) is not glued, as first or as copy + let t = [touching(0, &[5], true), touching(1, &[3, 4], false)]; + assert_eq!(glued(&t, true), Vec::<(u32, u32)>::new()); + let t = [touching(0, &[3, 4], false), touching(1, &[5], true)]; + assert_eq!(glued(&t, true), Vec::<(u32, u32)>::new()); + // a shared face with the first edge, or no coincidence proof: nothing + let t = [touching(0, &[1, 2], false), touching(1, &[2, 3], false)]; + assert_eq!(glued(&t, true), Vec::<(u32, u32)>::new()); + let t = [touching(0, &[1, 2], false), touching(1, &[3, 4], false)]; + assert_eq!(glued(&t, false), Vec::<(u32, u32)>::new()); + } + + /// Two lines between the same ends, either way round, are within rounding of each other; + /// a line whose far end is 3e-6 off is bounded by at least that (the bound is sound) and + /// barely more (it is tight), so with a tolerance of 1e-6 it is not glued. + #[test] + fn the_coincidence_bound_of_two_lines_is_their_end_distance() { + let ivl = crate::geom::extent1d::Extent1d::from_min_max(0.0, 1.0); + let a = segment([1.0, 2.0, 3.0], [11.0, 2.0, 3.0]); + let same = segment([1.0, 2.0, 3.0], [11.0, 2.0, 3.0]); + let reversed = segment([11.0, 2.0, 3.0], [1.0, 2.0, 3.0]); + for b in [&same, &reversed] { + let d = coincidence_bound(&a, &ivl, b, &ivl).unwrap(); + assert!(d <= 1e-13, "{d}"); + } + let off = segment([1.0, 2.0, 3.0], [11.0, 2.0 + 3e-6, 3.0]); + let d = coincidence_bound(&a, &ivl, &off, &ivl).unwrap(); + assert!((3e-6..=3e-6 + 1e-13).contains(&d), "{d}"); + assert!(d > 1e-6); + // a NaN end has no bound + let nan = segment([1.0, 2.0, 3.0], [f64::NAN, 2.0, 3.0]); + assert!(coincidence_bound(&a, &ivl, &nan, &ivl).is_none()); + } + + /// The real defect three samples miss: two cubics between the same ends, one straight and + /// one with a bump of 1e-4 confined to its first eighth (one control point lifted, whose + /// basis function vanishes outside [0, 1/8]). At t = 1/4, 1/2 and 3/4 they agree exactly, + /// which the sampled check accepted; the bound over the whole span is at least the bump's + /// height there, so the pair is not glued. A copy of the straight cubic is within the bound's rounding allowance. + #[test] + fn a_bump_between_the_samples_is_not_coincident() { + let knots = vec![ + 0.0, 0.0, 0.0, 0.0, 0.0625, 0.125, 0.1875, 0.25, 0.5, 0.75, 1.0, 1.0, 1.0, 1.0, + ]; + // the Greville abscissae, so the straight cubic is the line x = 10 t + let greville: Vec = (0..10) + .map(|i| (knots[i + 1] + knots[i + 2] + knots[i + 3]) / 3.0) + .collect(); + let straight: Vec<[f64; 3]> = greville.iter().map(|&g| [10.0 * g, 0.0, 0.0]).collect(); + let mut bumped = straight.clone(); + bumped[1][1] = 1e-4; + let (a, b) = ( + cubic(&straight, knots.clone()), + cubic(&bumped, knots.clone()), + ); + let k = Kernel::default(); + for t in [0.25, 0.5, 0.75] { + let (p, q) = ( + a.evaluate_point(&k, t).unwrap(), + b.evaluate_point(&k, t).unwrap(), + ); + assert_eq!(p.distance(q), 0.0, "t = {t}"); + } + let peak = (0..=1000) + .map(|i| { + let t = 0.125 * f64::from(i) / 1000.0; + a.evaluate_point(&k, t) + .unwrap() + .distance(b.evaluate_point(&k, t).unwrap()) + }) + .fold(0.0, f64::max); + let ivl = crate::geom::extent1d::Extent1d::from_min_max(0.0, 1.0); + let d = coincidence_bound(&a, &ivl, &b, &ivl).unwrap(); + assert!(peak > 1e-5 && d >= peak, "bound {d}, peak {peak}"); + assert!(d > 1e-6); + let copy = cubic(&straight, knots.clone()); + let d = coincidence_bound(&a, &ivl, ©, &ivl).unwrap(); + // the hull bound charges the rounding of its refinement and elevation + assert!(d <= 1e-11, "{d}"); + // on different intervals, or a line against a cubic, there is no bound + let half = crate::geom::extent1d::Extent1d::from_min_max(0.0, 0.5); + assert!(coincidence_bound(&a, &ivl, ©, &half).is_none()); + let line = segment([0.0; 3], [10.0, 0.0, 0.0]); + assert!(coincidence_bound(&a, &ivl, &line, &ivl).is_none()); + } + /// `TestSmTessellateBoundaries` (`tests/SM_API_test/src/TestSmBrep.cpp:1328`): a /// box's 12 edges are 2 points each; an edge without curve has none and makes the /// result incomplete; an invalid angle tolerance is refused. diff --git a/solidcore/crates/solidcore/src/nurbs/b_spline_curve/p1.rs b/solidcore/crates/solidcore/src/nurbs/b_spline_curve/p1.rs index 0bbf8d01ca5..db3b9be7e83 100644 --- a/solidcore/crates/solidcore/src/nurbs/b_spline_curve/p1.rs +++ b/solidcore/crates/solidcore/src/nurbs/b_spline_curve/p1.rs @@ -607,7 +607,7 @@ impl BSplineCurve { /// The NURB for read-only callers (`GetOrCreateGwNurbPointer` through a const /// cast), or `SM_ERR` without one (upstream dereferences `NULL`). - pub(super) fn nurb_ref(&self) -> Result<&Curve> { + pub(crate) fn nurb_ref(&self) -> Result<&Curve> { self.nurb .as_ref() .ok_or_else(|| SolidError::sm_err(OP_NURB)) diff --git a/solidcore/plan/upstream-issues/WR-754--boolean-operand-touching-itself-along-two-coincident-edges.md b/solidcore/plan/upstream-issues/WR-754--boolean-operand-touching-itself-along-two-coincident-edges.md new file mode 100644 index 00000000000..265cc6e17fb --- /dev/null +++ b/solidcore/plan/upstream-issues/WR-754--boolean-operand-touching-itself-along-two-coincident-edges.md @@ -0,0 +1,11 @@ +#### WR-754. `SmApiBoolean` fails on an operand that touches itself along a line carried as two coincident edges of two faces each +- **Severity:** Wrong result or refusal (a union filling a pocket gives a body that is not a closed solid with the default fixes, or fails in `boolean::topology_intersector::p1::relate` with 1001 under SolidCraft's fix set; SolidCraft refuses the Join) +- **Area:** Booleans / operand representation +- **Location:** `crates/solidcore/src/boolean/api_brep.rs`, `merge_boolean_by`: the operands go to the merge as given. The representation comes from the record round trip: `crates/solidcore-convert/src/brep/record.rs` `split_touching` writes an edge a shell uses more than twice as one edge per face pair, and `to_kernel` builds one kernel edge per record edge (its contract: counts and `Order` match the record). +- **What happens:** the kernel's own results carry a solid that touches itself along a line as one edge of all four faces (a hole's bottom meeting two pocket walls along a segment of their corner edge), and the merge handles that form. The same solid after a record round trip (SolidCraft's body between features) carries the line as two coincident edges of two faces each, sharing both vertices; the body passes `check(All)`, but the merge of a tool whose edge lies along that line relates to two operand edges and either builds a bad body or fails in `relate`. +- **Trigger:** tangency-labs/solidcraft#12785: a block with a hexagonal pocket through it and a 2.5 mm hole from an end face ending exactly at a pocket corner; filling the pocket with the same hexagon as a Join. The cut's own body joins; after `to_record`/`from_record` the join fails. Sonnet's stand-in with the hole ending in a flat wall (no self-touch) joins. The rc.3 rig's dumped operands (`SmApiBoolean-a.smb`, 38 edges) fail the same way on upstream main and on the pin a445bdaac; the cut's body has 37 edges. +- **How found:** SolidCraft triage of #12785; the rig's `--dumps` of the failing call, a topology listing of the dumped operand against the ops-crate stand-in (one 8-use edge versus two 4-use edges), and a probe gluing the two edges back before the union (works with the default fixes and with the imprint flags). +- **Confirmed:** yes, in the port, with the ops crate (`crates/solidcore-ops/tests/boolean.rs`, `mod pocket_with_hole_at_its_corner`: the round-trip case fails without the glue) and the rig's dumps. Not against the C++ fork: upstream SMLib has no record format and never meets this form from its own results; given such a body it would merge it as given. +- **Fix:** always on (no flag): `merge_boolean_by` first glues, in each operand, the coincident edges that share both vertices and the curve kind, whose faces are all distinct and whose curves are proved within the B-rep tolerance of each other over their whole intervals, into one edge (in one shell, or in two shells that touch along the line: the round trip leaves the self-touching solid as two shells, ShellId 0 and 1 in the test's body) (`GlueEdgesGeneral`, no gap, with region nesting), restoring the kernel's own form. The proof is a bound on the two edges' Hausdorff distance, rounding included (`coincidence_bound`): for two lines, the larger distance between their segments' ends; for two non-rational B-splines on one interval, the convex-hull bound of `nurbs::crv_deviation::certified_distance`. Any other pair, a NaN, or a bound above the tolerance is not glued, and the operand goes to the merge as given. The gluing is all or nothing: an ordinary `GlueEdgesGeneral` failure restores the operand from a snapshot and the merge runs on it as given. Edges whose faces repeat (a face on both sides of the line: the kernel's crack edges, which its check refuses glued) are left alone; the result's export splits the edge again as before. The import keeps its one-edge-per-record-edge contract. +- **Also covered:** two solids touching along an edge (`split_shared`: one copy per shell) are glued the same way, as the kernel's own union of such solids shares the edge between the shells (the convert crate's `lumps_and_solids_touching_along_an_edge_go_round`). +- Fixes tangency-labs/solidcore#3160.