From b4701ad4ff1050da8d158af72b6890e833e8a520 Mon Sep 17 00:00:00 2001 From: dudedagger42 Date: Sun, 8 Nov 2026 00:20:39 -0500 Subject: [PATCH 1/7] test(boolean): a join filling a pocket whose corner a hole reaches, after a record round trip solidcraft#12785: a block with a hexagonal pocket through it and a 2.5 mm hole drilled from an end face that ends 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, and filling the pocket with the same hexagon as a join works. After a record round trip (`to_record`, `from_record`: the body SolidCraft hands its next feature) the segment is two coincident edges of two faces each, the body still passes the check, and the join fails: with the default fixes the result is not a closed solid, with SolidCraft's fix set `topology_intersector::p1::relate` fails (status 1001). The operands are built with the ops crate from the reporter's numbers (the Opus trial's prejoin.sc). Controls: the cut's own body joins; the pocket without the hole joins after the round trip. Co-Authored-By: Claude Fable 5.1 --- ...in_fills_pocket_with_hole_at_its_corner.rs | 145 ++++++++++++++++++ 1 file changed, 145 insertions(+) create mode 100644 solidcore/crates/solidcore-ops/tests/boolean_join_fills_pocket_with_hole_at_its_corner.rs diff --git a/solidcore/crates/solidcore-ops/tests/boolean_join_fills_pocket_with_hole_at_its_corner.rs b/solidcore/crates/solidcore-ops/tests/boolean_join_fills_pocket_with_hole_at_its_corner.rs new file mode 100644 index 00000000000..2f71d6be754 --- /dev/null +++ b/solidcore/crates/solidcore-ops/tests/boolean_join_fills_pocket_with_hole_at_its_corner.rs @@ -0,0 +1,145 @@ +//! solidcraft#12785: 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 +//! then fails (`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. +#![allow( + clippy::unwrap_used, + clippy::expect_used, + clippy::panic, + clippy::indexing_slicing +)] // test helpers + +use std::f64::consts::TAU; + +use solidcore_ops::boolean::{boolean, BooleanOp}; +use solidcore_ops::sweep::{extrude, Curve, DraftCorner}; +use solidcore_ops::{Body, CheckLevel}; + +/// 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") +} + +/// `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 +} + +/// 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 must work as well. +#[test] +fn filling_a_pocket_whose_corner_a_hole_reaches_joins_after_a_record_round_trip() { + let target = round_tripped(&target()); + assert_eq!(target.counts().unwrap(), [15, 38, 24]); + assert!(target.check(CheckLevel::All).unwrap().is_valid()); + join_fills(target, "the round-tripped body"); +} + +/// 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"); +} From 7d913562d781865f165ea4a2515e7be471c841f7 Mon Sep 17 00:00:00 2001 From: dudedagger42 Date: Sun, 8 Nov 2026 01:12:45 -0500 Subject: [PATCH 2/7] fix(boolean): an operand touching itself along two coincident edges is glued before the merge (WR-754, #3160) The kernel's own results carry a solid that touches itself along a line as one edge of all four faces, and the merge handles that form. The record format writes such an edge as one edge per face pair (`split_touching`), and the body SolidCraft hands its next feature comes back with two coincident edges of two faces each: the merge of a tool whose edge lies along that line then gives a body that is not a closed solid, or fails in `topology_intersector::p1::relate` with 1001 (solidcraft#12785: a hexagon pocket joined back where a hole ends at its corner). New opt-in flag `Kernel::fixes.boolean_glues_self_touching_edges`: `merge_boolean_by` first glues, in each operand, the coincident edges that share both vertices, the curve kind and their points (three samples within the B-rep tolerance) and whose faces are all distinct, into one edge (`GlueEdgesGeneral`, no gap, with region nesting), in one shell or in two shells touching along the line (the round trip leaves the solid in two). Edges whose faces repeat (the kernel's crack edges) are left alone. Off by default: upstream merges the operand as given. Record: plan/upstream-issues/WR-754--boolean-operand-touching-itself-along-two-coincident-edges.md. Test: crates/solidcore-ops/tests/boolean_join_fills_pocket_with_hole_at_its_corner.rs (the round-trip case sets the flag; fails without it). Co-Authored-By: Claude Fable 5.1 --- ...in_fills_pocket_with_hole_at_its_corner.rs | 5 +- .../crates/solidcore/src/boolean/api_brep.rs | 170 +++++++++++++++++- solidcore/crates/solidcore/src/kernel.rs | 2 + ...ching-itself-along-two-coincident-edges.md | 11 ++ 4 files changed, 184 insertions(+), 4 deletions(-) create mode 100644 solidcore/plan/upstream-issues/WR-754--boolean-operand-touching-itself-along-two-coincident-edges.md diff --git a/solidcore/crates/solidcore-ops/tests/boolean_join_fills_pocket_with_hole_at_its_corner.rs b/solidcore/crates/solidcore-ops/tests/boolean_join_fills_pocket_with_hole_at_its_corner.rs index 2f71d6be754..04b41aad509 100644 --- a/solidcore/crates/solidcore-ops/tests/boolean_join_fills_pocket_with_hole_at_its_corner.rs +++ b/solidcore/crates/solidcore-ops/tests/boolean_join_fills_pocket_with_hole_at_its_corner.rs @@ -17,7 +17,7 @@ use std::f64::consts::TAU; use solidcore_ops::boolean::{boolean, BooleanOp}; use solidcore_ops::sweep::{extrude, Curve, DraftCorner}; -use solidcore_ops::{Body, CheckLevel}; +use solidcore_ops::{session, Body, CheckLevel}; /// The hexagon's circumradius. const R: f64 = 6.3685; @@ -126,9 +126,10 @@ fn filling_a_pocket_whose_corner_a_hole_reaches_joins() { } /// The same body after its record round trip: the corner segment is two coincident edges of -/// two faces each, and the join must work as well. +/// two faces each, and with `boolean_glues_self_touching_edges` the join works as well. #[test] fn filling_a_pocket_whose_corner_a_hole_reaches_joins_after_a_record_round_trip() { + session::set_fixes(["boolean_glues_self_touching_edges"]).unwrap(); let target = round_tripped(&target()); assert_eq!(target.counts().unwrap(), [15, 38, 24]); assert!(target.check(CheckLevel::All).unwrap().is_valid()); diff --git a/solidcore/crates/solidcore/src/boolean/api_brep.rs b/solidcore/crates/solidcore/src/boolean/api_brep.rs index 8544e1091ba..827ef72516d 100644 --- a/solidcore/crates/solidcore/src/boolean/api_brep.rs +++ b/solidcore/crates/solidcore/src/boolean/api_brep.rs @@ -208,6 +208,167 @@ enum MergeMethod { /// (`SmMerge sMerge(*pContext, pBrep1, pBrep2)`, or with `0, 0, &sOptions` when /// `options` is given), then run `ManifoldBoolean` when both operands are manifold /// solids (`SmBrep::IsManifoldSolid`) and `NonManifoldBoolean` otherwise. +/// One edge of a boolean operand, as [`glue_self_touching_edges`] compares them: its +/// vertices (the lower index first), its shell, its faces, its curve's kind and three +/// points along it. +struct TouchingEdge { + edge: EdgeId, + start: crate::topology::VertexId, + ends: (u32, u32), + shell: Option, + faces: Vec, + kind: core::mem::Discriminant, + samples: [crate::Point3; 3], +} + +impl TouchingEdge { + /// Whether `other` is a second copy of this edge: the same vertices and curve kind, + /// points within `tol`, both on faces (not wires), and no face in common (two faces + /// meeting across the line, the kernel's crack edges, are not copies). 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 is_copy_of(&self, other: &Self, tol: f64) -> bool { + if self.shell.is_none() + || other.shell.is_none() + || self.ends != other.ends + || self.kind != other.kind + || self.faces.iter().any(|f| other.faces.contains(f)) + { + return false; + } + if self.start == other.start { + self.samples + .iter() + .zip(&other.samples) + .all(|(a, c)| a.distance(*c) <= tol) + } else { + self.samples + .iter() + .zip(other.samples.iter().rev()) + .all(|(a, c)| a.distance(*c) <= tol) + } + } +} + +/// Not upstream (opt-in, `Kernel::fixes.boolean_glues_self_touching_edges`, 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 kernel's own results, and +/// its merge handles that form. 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` +/// (tangency-labs/solidcraft#12785). So each group of edges with the same two vertices, the +/// same curve kind and coincident points (three samples within the B-rep tolerance), whose +/// faces are all distinct, 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. Returns the number of edges glued away. +/// +/// # Errors +/// +/// Those of the topology walk, the curve evaluations and `GlueEdgesGeneral`. +fn glue_self_touching_edges(k: &mut Kernel, b: &mut Brep) -> Result { + use crate::nurbs::b_spline_surface_n_lib::p2::OrientType; + use crate::topology::brep::p2::ArenaNotifyState; + use crate::topology::brep::p7::glue_edges_general; + use crate::topology::edge; + use crate::topology::edgeuse::p1 as eu1; + + let tol = b.tolerance(); + let mut touches: Vec = Vec::new(); + for &e in b.edge_list() { + let data = b.edge(e)?; + let Some(curve) = data.curve.as_ref() else { + 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 interval = data.interval; + let mut samples = [crate::Point3::ZERO; 3]; + for (s, t) in samples.iter_mut().zip([0.25, 0.5, 0.75]) { + *s = curve.evaluate_point(k, interval.evaluate(t))?; + } + let mut shell = None; + let mut faces = Vec::new(); + for &eu in &data.edgeuses { + let Some(fu) = eu1::faceuse(b, eu)? else { + continue; + }; + if let Some(f) = b.faceuse(fu)?.face { + faces.push(f); + } + if shell.is_none() { + shell = eu1::faceuse_shell(b, fu)?; + } + } + faces.sort_unstable(); + faces.dedup(); + let (a, z) = (start.index(), end.index()); + touches.push(TouchingEdge { + edge: e, + start, + ends: (a.min(z), a.max(z)), + shell, + faces, + kind: core::mem::discriminant(curve.kind()), + samples, + }); + } + let mut pairs: Vec<(EdgeId, EdgeId, OrientType)> = Vec::new(); + let mut taken: Vec = Vec::new(); + for (i, first) in touches.iter().enumerate() { + if taken.contains(&first.edge) { + continue; + } + for other in touches.iter().skip(i + 1) { + if taken.contains(&other.edge) || !first.is_copy_of(other, tol) { + continue; + } + let orientation = if first.start == other.start { + OrientType::Same + } else { + OrientType::Opposite + }; + pairs.push((first.edge, other.edge, orientation)); + taken.push(other.edge); + } + } + if pairs.is_empty() { + return Ok(0); + } + let mut state = ArenaNotifyState::with_attributes_of(b); + let mut result = Ok(()); + for &(surviving, to_delete, orientation) in &pairs { + if let Err(e) = glue_edges_general( + k, + b, + Some(surviving), + orientation, + 0.0, + true, + Some(to_delete), + None, + &mut state.env(None), + ) { + result = Err(e); + break; + } + } + state.restore_attributes(b)?; + result?; + b.refresh_cached_topology(); + Ok(pairs.len()) +} + fn merge_boolean( k: &mut Kernel, brep1: Brep, @@ -223,8 +384,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 +393,11 @@ 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, opt-in: WR-754) the operands' self-touch edge copies glued first + if k.fixes.boolean_glues_self_touching_edges { + 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(); diff --git a/solidcore/crates/solidcore/src/kernel.rs b/solidcore/crates/solidcore/src/kernel.rs index c3656e808b5..c56043c1d42 100644 --- a/solidcore/crates/solidcore/src/kernel.rs +++ b/solidcore/crates/solidcore/src/kernel.rs @@ -901,6 +901,8 @@ pub struct UpstreamFixes { pub analytic_corner_failure_is_false: bool, /// `SmEdgeDefinition::Imprint` continues an intersection edge's 3d and UV curves, each by the polynomial of its own end span, to a proto vertex that lies a few tolerances past the curve's end, so the edge reaches its vertex (internal thread cuts; WR-453, #410; tangency-labs/smlib bf5d3ae (was a8caccd)). The end goes to its proto vertex's position only when that proto vertex is one vertex in each B-rep, else to its own final vertex (WR-498, #1480; tangency-labs/smlib 0b1b945 (was ffaf4e8)). pub imprint_extends_edge_to_proto_vertex: bool, + /// `SmApiBoolean` first glues, in each operand, the coincident edges that share both vertices, the curve kind and their points, and whose faces are all distinct (in one shell or in two shells that touch along the line), into one edge of all those faces (`GlueEdgesGeneral`): a solid that touches itself along a line is written by the record format as one edge per face pair (`split_touching`), and the merge of such an operand gives a body that is not a closed solid or fails in `topology_intersector::p1::relate` (1001), while the kernel's own form of the same solid, one edge of four faces, merges (a hexagon pocket joined back where a hole ends at its corner; WR-754, tangency-labs/solidcraft#12785). Off by default: upstream merges the operand as given. + pub boolean_glues_self_touching_edges: bool, /// `SmEdgeDefinition::Imprint` takes an edge Brep2's face already has between the definition's two vertices along its curve (`SmTools::FindCoincidentEdge` within the larger of the face's and the definition's tolerance) as the definition's edge there, where upstream makes a second edge beside it: the face then has coincident edges and the merge copies the boundary edge into Brep1 beside the curve's (`SmFace` tests 33 and 34; two equal tubes meeting end to end) (WR-580, #1519; the fork's tangency-labs/smlib@81cd61a). pub imprint_reuses_coincident_face_edge: bool, /// `SmFilletSolver::ComputePointValues` chooses its finite-difference step for each point (1e-3 at a tangent point, 1e-5 otherwise), not once per process as the function-local static `sdStaticStep`, so a blend does not depend on the blends before it ([`Kernel::fillet_point_step`] is then neither read nor set, and an existing latch is kept as it is) (ND-3, #1173; the fork's tangency-labs/smlib@9e17f64 (was 0a05860)). 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..d36245dcd37 --- /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_join_fills_pocket_with_hole_at_its_corner.rs`, committed first, failing) 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:** `Kernel::fixes.boolean_glues_self_touching_edges` (opt-in, off by default): `merge_boolean_by` first glues, in each operand, the coincident edges that share both vertices, the curve kind and their points (three samples within the B-rep tolerance), whose faces are all distinct, 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. 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. From 4a0facda7dee477b0725a100eb1dcec1d2c44c10 Mon Sep 17 00:00:00 2001 From: dudedagger42 Date: Sun, 8 Nov 2026 03:37:55 -0500 Subject: [PATCH 3/7] fix(boolean): the self-touch glue buckets edges by vertex pair (#3167 review) `glue_self_touching_edges` compared every edge pair and kept its glued edges in a Vec, close to cubic on a body of thousands of edges, on every boolean while the flag is on. The edges are now bucketed by their vertex pair, only a bucket of two or more edges has its curves evaluated and its pairs compared, and the glued edges are a HashSet. A body without self-touch costs one pass over its edges. Co-Authored-By: Claude Fable 5.1 --- .../crates/solidcore/src/boolean/api_brep.rs | 104 +++++++++++------- 1 file changed, 67 insertions(+), 37 deletions(-) diff --git a/solidcore/crates/solidcore/src/boolean/api_brep.rs b/solidcore/crates/solidcore/src/boolean/api_brep.rs index 827ef72516d..5a20d0c9409 100644 --- a/solidcore/crates/solidcore/src/boolean/api_brep.rs +++ b/solidcore/crates/solidcore/src/boolean/api_brep.rs @@ -210,14 +210,15 @@ enum MergeMethod { /// solids (`SmBrep::IsManifoldSolid`) and `NonManifoldBoolean` otherwise. /// One edge of a boolean operand, as [`glue_self_touching_edges`] compares them: its /// vertices (the lower index first), its shell, its faces, its curve's kind and three -/// points along it. +/// points along it (the kind and points 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, - kind: core::mem::Discriminant, + kind: Option>, samples: [crate::Point3; 3], } @@ -231,6 +232,7 @@ impl TouchingEdge { if self.shell.is_none() || other.shell.is_none() || self.ends != other.ends + || self.kind.is_none() || self.kind != other.kind || self.faces.iter().any(|f| other.faces.contains(f)) { @@ -266,10 +268,16 @@ impl TouchingEdge { /// on both sides of the line: the kernel's crack edges, which its check refuses glued) are /// left alone. 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 +/// curves evaluated and its pairs compared, so a body without self-touch costs one pass over +/// its edges. +/// /// # Errors /// /// Those of the topology walk, the curve evaluations and `GlueEdgesGeneral`. fn glue_self_touching_edges(k: &mut Kernel, b: &mut Brep) -> Result { + use std::collections::{HashMap, HashSet}; + use crate::nurbs::b_spline_surface_n_lib::p2::OrientType; use crate::topology::brep::p2::ArenaNotifyState; use crate::topology::brep::p7::glue_edges_general; @@ -277,12 +285,14 @@ fn glue_self_touching_edges(k: &mut Kernel, b: &mut Brep) -> Result { use crate::topology::edgeuse::p1 as eu1; let tol = b.tolerance(); + // Every edge with two vertices, by vertex pair. let mut touches: Vec = Vec::new(); + let mut buckets: HashMap<(u32, u32), Vec> = HashMap::new(); for &e in b.edge_list() { let data = b.edge(e)?; - let Some(curve) = data.curve.as_ref() else { + if data.curve.is_none() { continue; - }; + } let Some(start) = edge::start_vertex(b, e)? else { continue; }; @@ -292,54 +302,74 @@ fn glue_self_touching_edges(k: &mut Kernel, b: &mut Brep) -> Result { 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(), + kind: None, + samples: [crate::Point3::ZERO; 3], + }); + } + let mut crowded: Vec> = buckets.into_values().filter(|v| v.len() > 1).collect(); + crowded.sort_unstable(); + // The shells, faces, curve kinds and points 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; + }; let interval = data.interval; - let mut samples = [crate::Point3::ZERO; 3]; - for (s, t) in samples.iter_mut().zip([0.25, 0.5, 0.75]) { + for (s, t) in touch.samples.iter_mut().zip([0.25, 0.5, 0.75]) { *s = curve.evaluate_point(k, interval.evaluate(t))?; } - let mut shell = None; - let mut faces = Vec::new(); + 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 { - faces.push(f); + touch.faces.push(f); } - if shell.is_none() { - shell = eu1::faceuse_shell(b, fu)?; + if touch.shell.is_none() { + touch.shell = eu1::faceuse_shell(b, fu)?; } } - faces.sort_unstable(); - faces.dedup(); - let (a, z) = (start.index(), end.index()); - touches.push(TouchingEdge { - edge: e, - start, - ends: (a.min(z), a.max(z)), - shell, - faces, - kind: core::mem::discriminant(curve.kind()), - samples, - }); + touch.faces.sort_unstable(); + touch.faces.dedup(); } let mut pairs: Vec<(EdgeId, EdgeId, OrientType)> = Vec::new(); - let mut taken: Vec = Vec::new(); - for (i, first) in touches.iter().enumerate() { - if taken.contains(&first.edge) { - continue; - } - for other in touches.iter().skip(i + 1) { - if taken.contains(&other.edge) || !first.is_copy_of(other, tol) { + let mut taken: HashSet = HashSet::new(); + for bucket in &crowded { + for (n, &i) in bucket.iter().enumerate() { + let Some(first) = touches.get(i) else { continue; - } - let orientation = if first.start == other.start { - OrientType::Same - } else { - OrientType::Opposite }; - pairs.push((first.edge, other.edge, orientation)); - taken.push(other.edge); + if taken.contains(&first.edge) { + continue; + } + for &j in bucket.iter().skip(n + 1) { + let Some(other) = touches.get(j) else { + continue; + }; + if taken.contains(&other.edge) || !first.is_copy_of(other, tol) { + continue; + } + let orientation = if first.start == other.start { + OrientType::Same + } else { + OrientType::Opposite + }; + pairs.push((first.edge, other.edge, orientation)); + taken.insert(other.edge); + } } } if pairs.is_empty() { From 6fd06cfbd129453f4b35e68c19c9b75d3a5a275a Mon Sep 17 00:00:00 2001 From: Brett Lawson Date: Sat, 14 Nov 2026 01:17:03 +0100 Subject: [PATCH 4/7] solidcore: the self-touch glue is always on and proves coincidence over the whole edge (#13650) The glue of an operand's coincident self-touch edges before the merge (carried from #13576) is now unconditional: the `boolean_glues_self_touching_edges` flag is gone. Two edges are glued only when their curves are proved within the B-rep tolerance of each other over their whole intervals, never on samples (`coincidence_bound`, rounding included, a NaN refuses): - two lines: the larger distance between their segments' ends (either pairing), each end widened by its evaluation error (`Line::segment_over`); - two non-rational B-splines on the same interval inside both domains: the convex-hull bound of `nurbs::crv_deviation::certified_distance`; - any other pair: no bound, not glued (the operand goes to the merge as given). The buckets and the glued set are a BTreeMap and BTreeSet. The #13576 tests move into the boolean area file (`tests/boolean.rs`, module `pocket_with_hole_at_its_corner`), the round-trip case now runs with no fixes and with every fix, and new unit tests check both bounds, including a bump between the old sample points that three samples accepted and the bound refuses. Carries #13576 by @bherbruck. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SdcgEtwSrdwZxqTQp5MfnU --- .../crates/solidcore-ops/tests/boolean.rs | 160 ++++++++++ ...in_fills_pocket_with_hole_at_its_corner.rs | 146 ---------- .../crates/solidcore/src/boolean/api_brep.rs | 275 +++++++++++++----- solidcore/crates/solidcore/src/kernel.rs | 2 - .../solidcore/src/nurbs/b_spline_curve/p1.rs | 2 +- ...ching-itself-along-two-coincident-edges.md | 2 +- 6 files changed, 372 insertions(+), 215 deletions(-) delete mode 100644 solidcore/crates/solidcore-ops/tests/boolean_join_fills_pocket_with_hole_at_its_corner.rs diff --git a/solidcore/crates/solidcore-ops/tests/boolean.rs b/solidcore/crates/solidcore-ops/tests/boolean.rs index 350f1e65a64..12a3059100a 100644 --- a/solidcore/crates/solidcore-ops/tests/boolean.rs +++ b/solidcore/crates/solidcore-ops/tests/boolean.rs @@ -1122,3 +1122,163 @@ 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"); + } +} diff --git a/solidcore/crates/solidcore-ops/tests/boolean_join_fills_pocket_with_hole_at_its_corner.rs b/solidcore/crates/solidcore-ops/tests/boolean_join_fills_pocket_with_hole_at_its_corner.rs deleted file mode 100644 index 04b41aad509..00000000000 --- a/solidcore/crates/solidcore-ops/tests/boolean_join_fills_pocket_with_hole_at_its_corner.rs +++ /dev/null @@ -1,146 +0,0 @@ -//! solidcraft#12785: 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 -//! then fails (`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. -#![allow( - clippy::unwrap_used, - clippy::expect_used, - clippy::panic, - clippy::indexing_slicing -)] // test helpers - -use std::f64::consts::TAU; - -use solidcore_ops::boolean::{boolean, BooleanOp}; -use solidcore_ops::sweep::{extrude, Curve, DraftCorner}; -use solidcore_ops::{session, Body, CheckLevel}; - -/// 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") -} - -/// `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 -} - -/// 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 with `boolean_glues_self_touching_edges` the join works as well. -#[test] -fn filling_a_pocket_whose_corner_a_hole_reaches_joins_after_a_record_round_trip() { - session::set_fixes(["boolean_glues_self_touching_edges"]).unwrap(); - let target = round_tripped(&target()); - assert_eq!(target.counts().unwrap(), [15, 38, 24]); - assert!(target.check(CheckLevel::All).unwrap().is_valid()); - join_fills(target, "the round-tripped body"); -} - -/// 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"); -} diff --git a/solidcore/crates/solidcore/src/boolean/api_brep.rs b/solidcore/crates/solidcore/src/boolean/api_brep.rs index 5a20d0c9409..25e0ad0eb40 100644 --- a/solidcore/crates/solidcore/src/boolean/api_brep.rs +++ b/solidcore/crates/solidcore/src/boolean/api_brep.rs @@ -204,14 +204,9 @@ enum MergeMethod { NonManifold, } -/// 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 -/// solids (`SmBrep::IsManifoldSolid`) and `NonManifoldBoolean` otherwise. /// One edge of a boolean operand, as [`glue_self_touching_edges`] compares them: its -/// vertices (the lower index first), its shell, its faces, its curve's kind and three -/// points along it (the kind and points only for an edge that shares its vertices with -/// another). +/// vertices (the lower index first), its shell, its faces and its curve's kind (the shell, +/// faces and kind only for an edge that shares its vertices with another). struct TouchingEdge { edge: EdgeId, start: crate::topology::VertexId, @@ -219,64 +214,109 @@ struct TouchingEdge { shell: Option, faces: Vec, kind: Option>, - samples: [crate::Point3; 3], } impl TouchingEdge { - /// Whether `other` is a second copy of this edge: the same vertices and curve kind, - /// points within `tol`, both on faces (not wires), and no face in common (two faces - /// meeting across the line, the kernel's crack edges, are not copies). 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 is_copy_of(&self, other: &Self, tol: f64) -> bool { - if self.shell.is_none() - || other.shell.is_none() - || self.ends != other.ends - || self.kind.is_none() - || self.kind != other.kind - || self.faces.iter().any(|f| other.faces.contains(f)) - { - return false; + /// 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 no face in common + /// (two faces meeting across the line, the kernel's crack edges, are not copies). 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.ends == other.ends + && self.kind.is_some() + && self.kind == other.kind + && !self.faces.iter().any(|f| other.faces.contains(f)) + } +} + +/// 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) } - if self.start == other.start { - self.samples - .iter() - .zip(&other.samples) - .all(|(a, c)| a.distance(*c) <= tol) - } else { - self.samples - .iter() - .zip(other.samples.iter().rev()) - .all(|(a, c)| a.distance(*c) <= tol) + (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 (opt-in, `Kernel::fixes.boolean_glues_self_touching_edges`, WR-754): the -/// coincident edges along which a solid touches itself, glued back into one edge each. +/// 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 kernel's own results, and -/// its merge handles that form. 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` -/// (tangency-labs/solidcraft#12785). So each group of edges with the same two vertices, the -/// same curve kind and coincident points (three samples within the B-rep tolerance), whose -/// faces are all distinct, is glued into its first edge (`GlueEdgesGeneral`, no gap, with +/// 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. Returns the number of edges glued away. +/// 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. 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 -/// curves evaluated and its pairs compared, so a body without self-touch costs one pass over -/// its edges. +/// pairs compared, so a body without self-touch costs one pass over its edges. /// /// # Errors /// -/// Those of the topology walk, the curve evaluations and `GlueEdgesGeneral`. +/// Those of the topology walk and of `GlueEdgesGeneral`. fn glue_self_touching_edges(k: &mut Kernel, b: &mut Brep) -> Result { - use std::collections::{HashMap, HashSet}; + use std::collections::{BTreeMap, BTreeSet}; use crate::nurbs::b_spline_surface_n_lib::p2::OrientType; use crate::topology::brep::p2::ArenaNotifyState; @@ -285,9 +325,9 @@ fn glue_self_touching_edges(k: &mut Kernel, b: &mut Brep) -> Result { use crate::topology::edgeuse::p1 as eu1; let tol = b.tolerance(); - // Every edge with two vertices, by vertex pair. + // Every edge with a curve and two vertices, by vertex pair. let mut touches: Vec = Vec::new(); - let mut buckets: HashMap<(u32, u32), Vec> = HashMap::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() { @@ -312,12 +352,10 @@ fn glue_self_touching_edges(k: &mut Kernel, b: &mut Brep) -> Result { shell: None, faces: Vec::new(), kind: None, - samples: [crate::Point3::ZERO; 3], }); } - let mut crowded: Vec> = buckets.into_values().filter(|v| v.len() > 1).collect(); - crowded.sort_unstable(); - // The shells, faces, curve kinds and points of the edges that share their vertices. + 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; @@ -326,10 +364,6 @@ fn glue_self_touching_edges(k: &mut Kernel, b: &mut Brep) -> Result { let Some(curve) = data.curve.as_ref() else { continue; }; - let interval = data.interval; - for (s, t) in touch.samples.iter_mut().zip([0.25, 0.5, 0.75]) { - *s = curve.evaluate_point(k, interval.evaluate(t))?; - } touch.kind = Some(core::mem::discriminant(curve.kind())); for &eu in &data.edgeuses { let Some(fu) = eu1::faceuse(b, eu)? else { @@ -345,8 +379,17 @@ fn glue_self_touching_edges(k: &mut Kernel, b: &mut Brep) -> Result { touch.faces.sort_unstable(); touch.faces.dedup(); } + // 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 mut pairs: Vec<(EdgeId, EdgeId, OrientType)> = Vec::new(); - let mut taken: HashSet = HashSet::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 { @@ -359,7 +402,10 @@ fn glue_self_touching_edges(k: &mut Kernel, b: &mut Brep) -> Result { let Some(other) = touches.get(j) else { continue; }; - if taken.contains(&other.edge) || !first.is_copy_of(other, tol) { + if taken.contains(&other.edge) + || !first.may_copy(other) + || !coincide(b, first.edge, other.edge)? + { continue; } let orientation = if first.start == other.start { @@ -399,6 +445,10 @@ fn glue_self_touching_edges(k: &mut Kernel, b: &mut Brep) -> Result { 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 +/// solids (`SmBrep::IsManifoldSolid`) and `NonManifoldBoolean` otherwise. fn merge_boolean( k: &mut Kernel, brep1: Brep, @@ -423,11 +473,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, opt-in: WR-754) the operands' self-touch edge copies glued first - if k.fixes.boolean_glues_self_touching_edges { - glue_self_touching_edges(k, &mut brep1)?; - glue_self_touching_edges(k, &mut brep2)?; - } + // (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(); @@ -816,6 +864,103 @@ 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, + ))) + } + + /// 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/kernel.rs b/solidcore/crates/solidcore/src/kernel.rs index c56043c1d42..c3656e808b5 100644 --- a/solidcore/crates/solidcore/src/kernel.rs +++ b/solidcore/crates/solidcore/src/kernel.rs @@ -901,8 +901,6 @@ pub struct UpstreamFixes { pub analytic_corner_failure_is_false: bool, /// `SmEdgeDefinition::Imprint` continues an intersection edge's 3d and UV curves, each by the polynomial of its own end span, to a proto vertex that lies a few tolerances past the curve's end, so the edge reaches its vertex (internal thread cuts; WR-453, #410; tangency-labs/smlib bf5d3ae (was a8caccd)). The end goes to its proto vertex's position only when that proto vertex is one vertex in each B-rep, else to its own final vertex (WR-498, #1480; tangency-labs/smlib 0b1b945 (was ffaf4e8)). pub imprint_extends_edge_to_proto_vertex: bool, - /// `SmApiBoolean` first glues, in each operand, the coincident edges that share both vertices, the curve kind and their points, and whose faces are all distinct (in one shell or in two shells that touch along the line), into one edge of all those faces (`GlueEdgesGeneral`): a solid that touches itself along a line is written by the record format as one edge per face pair (`split_touching`), and the merge of such an operand gives a body that is not a closed solid or fails in `topology_intersector::p1::relate` (1001), while the kernel's own form of the same solid, one edge of four faces, merges (a hexagon pocket joined back where a hole ends at its corner; WR-754, tangency-labs/solidcraft#12785). Off by default: upstream merges the operand as given. - pub boolean_glues_self_touching_edges: bool, /// `SmEdgeDefinition::Imprint` takes an edge Brep2's face already has between the definition's two vertices along its curve (`SmTools::FindCoincidentEdge` within the larger of the face's and the definition's tolerance) as the definition's edge there, where upstream makes a second edge beside it: the face then has coincident edges and the merge copies the boundary edge into Brep1 beside the curve's (`SmFace` tests 33 and 34; two equal tubes meeting end to end) (WR-580, #1519; the fork's tangency-labs/smlib@81cd61a). pub imprint_reuses_coincident_face_edge: bool, /// `SmFilletSolver::ComputePointValues` chooses its finite-difference step for each point (1e-3 at a tangent point, 1e-5 otherwise), not once per process as the function-local static `sdStaticStep`, so a blend does not depend on the blends before it ([`Kernel::fillet_point_step`] is then neither read nor set, and an existing latch is kept as it is) (ND-3, #1173; the fork's tangency-labs/smlib@9e17f64 (was 0a05860)). 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 index d36245dcd37..559c34a2160 100644 --- 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 @@ -6,6 +6,6 @@ - **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_join_fills_pocket_with_hole_at_its_corner.rs`, committed first, failing) 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:** `Kernel::fixes.boolean_glues_self_touching_edges` (opt-in, off by default): `merge_boolean_by` first glues, in each operand, the coincident edges that share both vertices, the curve kind and their points (three samples within the B-rep tolerance), whose faces are all distinct, 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. 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. +- **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. 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. From 7c5c25a307c3cad524cc5b3eaf463e66dc229b2b Mon Sep 17 00:00:00 2001 From: Brett Lawson Date: Sat, 14 Nov 2026 02:04:45 +0100 Subject: [PATCH 5/7] solidcore: the self-touch glue never glues a crack edge or a copy sharing a glued face (#13650) Review of #16392: in a bucket of three or more coincident edges, each copy was checked only against the first edge's faces, so two copies on one face could both glue in and leave that face on both sides of the glued edge. `copy_pairs` (now a separate function) checks each copy against the faces of the first edge and of every copy already glued. An edge with a face on both sides (more than two of its uses on one face: the kernel's crack edge) is never glued, as the doc already said. Unit test: `copies_are_checked_against_every_face_already_glued`. The errors of `GlueEdgesGeneral` still fail the boolean, now documented: the pairs meet its precondition, so what is left are broken topology links or notification failures, and a half-glued operand cannot be merged as given. New ops test: two solids touching along an edge, after a record round trip, give the exact volumes under a cut and an intersection across the edge and a union far from it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SdcgEtwSrdwZxqTQp5MfnU --- .../crates/solidcore-ops/tests/boolean.rs | 50 +++++ .../crates/solidcore/src/boolean/api_brep.rs | 186 ++++++++++++++---- 2 files changed, 195 insertions(+), 41 deletions(-) diff --git a/solidcore/crates/solidcore-ops/tests/boolean.rs b/solidcore/crates/solidcore-ops/tests/boolean.rs index 12a3059100a..d44d442b1c1 100644 --- a/solidcore/crates/solidcore-ops/tests/boolean.rs +++ b/solidcore/crates/solidcore-ops/tests/boolean.rs @@ -1282,3 +1282,53 @@ mod pocket_with_hole_at_its_corner { 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 25e0ad0eb40..e8167af7b61 100644 --- a/solidcore/crates/solidcore/src/boolean/api_brep.rs +++ b/solidcore/crates/solidcore/src/boolean/api_brep.rs @@ -205,33 +205,101 @@ enum MergeMethod { } /// One edge of a boolean operand, as [`glue_self_touching_edges`] compares them: its -/// vertices (the lower index first), its shell, its faces and its curve's kind (the shell, -/// faces and kind only for an edge that shares its vertices with another). +/// 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 no face in common - /// (two faces meeting across the line, the kernel's crack edges, are not copies). 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. + /// 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 - && !self.faces.iter().any(|f| other.faces.contains(f)) } } +/// 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 @@ -307,18 +375,22 @@ fn coincidence_bound( /// 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. Returns the number of edges glued away. +/// 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 of `GlueEdgesGeneral`. +/// Those of the topology walk and of `GlueEdgesGeneral`. They fail the boolean: the pairs +/// passed meet `GlueEdgesGeneral`'s precondition (both vertices shared, both on faces), so +/// its remaining errors are broken links in the operand's topology (an edge use without +/// mate, radial, shell or vertex use) or its notifications' failures, and an operand left +/// half glued could not be merged "as given" anyway. fn glue_self_touching_edges(k: &mut Kernel, b: &mut Brep) -> Result { - use std::collections::{BTreeMap, BTreeSet}; + use std::collections::BTreeMap; - use crate::nurbs::b_spline_surface_n_lib::p2::OrientType; use crate::topology::brep::p2::ArenaNotifyState; use crate::topology::brep::p7::glue_edges_general; use crate::topology::edge; @@ -351,6 +423,7 @@ fn glue_self_touching_edges(k: &mut Kernel, b: &mut Brep) -> Result { ends, shell: None, faces: Vec::new(), + crack: false, kind: None, }); } @@ -376,8 +449,11 @@ fn glue_self_touching_edges(k: &mut Kernel, b: &mut Brep) -> Result { 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 { @@ -388,36 +464,7 @@ fn glue_self_touching_edges(k: &mut Kernel, b: &mut Brep) -> Result { // 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 mut pairs: Vec<(EdgeId, EdgeId, OrientType)> = 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; - } - 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) - || !coincide(b, 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); - } - } - } + let pairs = copy_pairs(&touches, &crowded, |x, y| coincide(b, x, y))?; if pairs.is_empty() { return Ok(0); } @@ -887,6 +934,63 @@ mod tests { ))) } + /// 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. From 9cb66f6cbcd5cc094e3805c2168a763b92178576 Mon Sep 17 00:00:00 2001 From: Brett Lawson Date: Sat, 14 Nov 2026 02:48:29 +0100 Subject: [PATCH 6/7] solidcore: a self-touch gluing that fails leaves the operand as given (#13650) Review of #16392: `GlueEdgesGeneral` can fail on a valid operand, before its first topology change (notifications, `curve_max_distance_between` of the same-geometry test) and after it (`set_tolerance`, `merge_shells`, `test_closure_split_region_attempt`, whose statuses pass on under `brep_edit_statuses_pass_on`). The gluing is now all or nothing: the operand is snapshotted before the first pair, and an ordinary failure (`error::native_failure`) restores it exactly, so the merge runs on it as on main. Port defects and cancellation still propagate; no gluing when no snapshot can be taken. The doc lists every site and whether it comes before or after the first change. WR-754 now points at the test's new home, `tests/boolean.rs` `mod pocket_with_hole_at_its_corner`, and states the rollback. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SdcgEtwSrdwZxqTQp5MfnU --- .../crates/solidcore/src/boolean/api_brep.rs | 42 +++++++++++++++---- ...ching-itself-along-two-coincident-edges.md | 4 +- 2 files changed, 36 insertions(+), 10 deletions(-) diff --git a/solidcore/crates/solidcore/src/boolean/api_brep.rs b/solidcore/crates/solidcore/src/boolean/api_brep.rs index e8167af7b61..868b263a535 100644 --- a/solidcore/crates/solidcore/src/boolean/api_brep.rs +++ b/solidcore/crates/solidcore/src/boolean/api_brep.rs @@ -383,11 +383,26 @@ fn coincidence_bound( /// /// # Errors /// -/// Those of the topology walk and of `GlueEdgesGeneral`. They fail the boolean: the pairs -/// passed meet `GlueEdgesGeneral`'s precondition (both vertices shared, both on faces), so -/// its remaining errors are broken links in the operand's topology (an edge use without -/// mate, radial, shell or vertex use) or its notifications' failures, and an operand left -/// half glued could not be merged "as given" anyway. +/// 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: the +/// operand is snapshotted ([`Brep::snapshot`]) before the first pair, and any other failure +/// of `GlueEdgesGeneral` restores it exactly, so the merge then runs on the operand 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: `edge_remove` and `add_oriented_eu_pair` of each moved use pair, the surviving +/// edge's `set_tolerance`, `destroy` of the deleted edge, `merge_shells`, and +/// `test_closure_split_region_attempt` / `test_closure_split_region_edge` (whose statuses +/// pass on with `brep_edit_statuses_pass_on`). +/// +/// 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; @@ -468,8 +483,12 @@ fn glue_self_touching_edges(k: &mut Kernel, b: &mut Brep) -> Result { if pairs.is_empty() { return Ok(0); } + // all or nothing: a failed gluing puts the operand back as it came in + let Ok(saved) = b.snapshot() else { + return Ok(0); + }; let mut state = ArenaNotifyState::with_attributes_of(b); - let mut result = Ok(()); + let mut failure = None; for &(surviving, to_delete, orientation) in &pairs { if let Err(e) = glue_edges_general( k, @@ -482,12 +501,19 @@ fn glue_self_touching_edges(k: &mut Kernel, b: &mut Brep) -> Result { None, &mut state.env(None), ) { - result = Err(e); + 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); + // 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)?; - result?; b.refresh_cached_topology(); Ok(pairs.len()) } 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 index 559c34a2160..265cc6e17fb 100644 --- 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 @@ -5,7 +5,7 @@ - **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_join_fills_pocket_with_hole_at_its_corner.rs`, committed first, failing) 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. 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. +- **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. From 2374968e2a0ce2c862d82bbf05dd007c96ddb126 Mon Sep 17 00:00:00 2001 From: Brett Lawson Date: Sat, 14 Nov 2026 03:32:44 +0100 Subject: [PATCH 7/7] solidcore: a failed self-touch gluing also puts back the kernel's rng and UB list (#13650) Review of #16392: `test_closure_split_region_attempt` can draw from `k.rng`, so a gluing that failed on a later pair left the merge running with an advanced rng, unlike main. `glue_all_or_none` (the gluing loop, now its own function taking the glue step) saves `k.rng` and `k.upstream_ub_passed` with the operand's snapshot and restores all three on any failure. The doc's list of `GlueEdgesGeneral` sites after the first topology change is completed (radial-sector `InvalidInput`s, `set_uv_trim_curve`, `set_orientation`, a surviving wire's unlinking, `is_spine`). Unit tests reach the restore on both branches: a second pair failing after the first changed an edge and drew from the rng restores the edges, counts, rng and UB list, then continues for an `InvalidInput` and returns a `NotFound`; and the real `GlueEdgesGeneral` with non-shared vertices (0 glued) or a stale id (an error) leaves the operand as given. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SdcgEtwSrdwZxqTQp5MfnU --- .../crates/solidcore/src/boolean/api_brep.rs | 196 ++++++++++++++++-- 1 file changed, 174 insertions(+), 22 deletions(-) diff --git a/solidcore/crates/solidcore/src/boolean/api_brep.rs b/solidcore/crates/solidcore/src/boolean/api_brep.rs index 868b263a535..c727c6dc85b 100644 --- a/solidcore/crates/solidcore/src/boolean/api_brep.rs +++ b/solidcore/crates/solidcore/src/boolean/api_brep.rs @@ -387,18 +387,22 @@ fn coincidence_bound( /// 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: the -/// operand is snapshotted ([`Brep::snapshot`]) before the first pair, and any other failure -/// of `GlueEdgesGeneral` restores it exactly, so the merge then runs on the operand as main -/// does (0 is returned). `GlueEdgesGeneral` can fail on a valid operand, both before its +/// **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: `edge_remove` and `add_oriented_eu_pair` of each moved use pair, the surviving -/// edge's `set_tolerance`, `destroy` of the deleted edge, `merge_shells`, and -/// `test_closure_split_region_attempt` / `test_closure_split_region_edge` (whose statuses -/// pass on with `brep_edit_statuses_pass_on`). +/// - 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, @@ -406,7 +410,6 @@ fn coincidence_bound( fn glue_self_touching_edges(k: &mut Kernel, b: &mut Brep) -> Result { use std::collections::BTreeMap; - use crate::topology::brep::p2::ArenaNotifyState; use crate::topology::brep::p7::glue_edges_general; use crate::topology::edge; use crate::topology::edgeuse::p1 as eu1; @@ -480,27 +483,68 @@ fn glue_self_touching_edges(k: &mut Kernel, b: &mut Brep) -> Result { 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); } - // all or nothing: a failed gluing puts the operand back as it came in 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 &(surviving, to_delete, orientation) in &pairs { - if let Err(e) = glue_edges_general( - k, - b, - Some(surviving), - orientation, - 0.0, - true, - Some(to_delete), - None, - &mut state.env(None), - ) { + for pair in pairs { + if let Err(e) = glue(k, b, pair, &mut state.env(None)) { failure = Some(e); break; } @@ -509,6 +553,8 @@ fn glue_self_touching_edges(k: &mut Kernel, b: &mut Brep) -> Result { // 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); @@ -960,6 +1006,112 @@ mod tests { ))) } + /// 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 {