1pub mod profile;
2pub use crate::arrangement::Vec2;
3use crate::classification::{classify_point, parameter_point_in_face, PolygonClass};
4pub use crate::fragment::{FaceFragmentRecord, FragmentEdgeSource};
5pub use crate::imprint::{
6 EdgeSplitRecord, FaceImprints, FaceKey, ImprintOptions, ImprintPieceRecord,
7 ImprintResultRecord, ImprintVertex,
8};
9use crate::tolerance::{assembler_weld, commit_weld};
10pub use crate::topology::{
11 adaptive_coedge_error, BrepSolid, CoedgeRecord, EdgeRecord, FaceRecord, LoopRecord,
12 ShellRecord, VertexRecord,
13};
14pub use crate::{
15 KernelRefusal, OrRefuse, RefusalClass,
16 apply_edge_splits, apply_edge_splits_with_map, build_imprints, build_pcurve_on_surface,
17 build_pcurve_on_surface_range, classify_surface_pair,
18 fragment_solid, interpolate_curve, merge_curve_continuation_edges,
19 merge_same_surface_faces_excluding, merge_same_surface_faces_scoped,
20 project_point_to_curve, project_point_to_surface, solid_signed_volume, solid_signed_volume_for_sign, AffineTransform,
21 DiagnosticSeverity, KernelDiagnostics, KernelOutcome, KernelStage, KernelTolerances, NurbsCurve,
22 PointClass, SolidClassifier, SurfacePairRelation, Vec3,
23};
24pub use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
25use serde::{Deserialize, Serialize};
26pub use web_time::Instant;
27
28thread_local! {
29 pub static CONFORMANCE_REPAIRS: std::cell::Cell<u64> =
35 const { std::cell::Cell::new(0) };
36}
37
38#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
39#[serde(rename_all = "lowercase")]
40pub enum BooleanOperation {
41 Union,
42 Intersect,
43 Subtract,
44}
45
46#[derive(Clone, Debug, Deserialize)]
47pub struct BooleanOptions {
48 #[serde(default = "default_tolerance")]
49 pub tolerance: f64,
50 #[serde(default)]
53 pub tolerances: Option<KernelTolerances>,
54 #[serde(default)]
55 pub imprint: ImprintOptions,
56 #[serde(default = "default_true")]
59 pub merge_coplanar_faces: bool,
60 #[serde(default)]
70 pub keep_unmerged_name_substrs: Vec<String>,
71 #[serde(default = "default_true")]
75 pub untouched_passthrough: bool,
76 #[serde(default = "default_true")]
80 pub disjoint_fast_path: bool,
81 #[serde(default = "default_true")]
91 pub contact_fast_path: bool,
92 #[serde(default)]
100 pub touched_assembly: bool,
101 #[serde(default = "default_true")]
109 pub sector_classification: bool,
110 #[serde(default = "default_true")]
114 pub sheet_trim: bool,
115 #[serde(default)]
119 pub keep_cells: bool,
120 #[serde(default)]
125 pub seam_reseat_later_references: Option<Vec<String>>,
126 #[serde(default)]
133 pub seam_rejoin_later_references: Option<Vec<String>>,
134}
135
136fn touched_assembly(options: &BooleanOptions) -> bool {
138 match std::env::var("BREP_TOUCHED_ASSEMBLY").as_deref() {
139 Ok("0") => false,
140 Ok(_) => true,
141 Err(_) => options.touched_assembly,
142 }
143}
144
145fn disjoint_fast_path(options: &BooleanOptions) -> bool {
147 match std::env::var("BREP_DISJOINT_FAST_PATH").as_deref() {
148 Ok("0") => false,
149 Ok(_) => true,
150 Err(_) => options.disjoint_fast_path,
151 }
152}
153
154fn contact_fast_path(options: &BooleanOptions) -> bool {
156 match std::env::var("BREP_CONTACT_FAST_PATH").as_deref() {
157 Ok("0") => false,
158 Ok(_) => true,
159 Err(_) => options.contact_fast_path,
160 }
161}
162
163fn untouched_passthrough(options: &BooleanOptions) -> bool {
165 match std::env::var("BREP_UNTOUCHED_PASSTHROUGH").as_deref() {
166 Ok("0") => false,
167 Ok(_) => true,
168 Err(_) => options.untouched_passthrough,
169 }
170}
171
172fn default_tolerance() -> f64 {
173 1e-7
174}
175
176fn default_true() -> bool {
177 true
178}
179
180impl Default for BooleanOptions {
181 fn default() -> Self {
182 Self {
183 tolerance: default_tolerance(),
184 tolerances: None,
185 imprint: ImprintOptions::default(),
186 merge_coplanar_faces: true,
187 keep_unmerged_name_substrs: Vec::new(),
188 untouched_passthrough: true,
189 disjoint_fast_path: true,
190 contact_fast_path: true,
191 touched_assembly: false,
192 sector_classification: true,
193 sheet_trim: true,
194 keep_cells: false,
195 seam_reseat_later_references: None,
196 seam_rejoin_later_references: None,
197 }
198 }
199}
200
201mod select;
202mod sheet;
203mod cellular;
204pub mod sector;
205pub mod assemble;
206mod operand_state;
207mod rim;
208mod coincident;
209mod touch;
210pub(crate) mod reseat;
211mod rejoin;
212
213pub use rim::*;
214use select::*;
215use coincident::*;
216use touch::TouchCensus;
217pub use assemble::{
218 assemble_fragments, assemble_open_fragments, commit_nearby_edge_endpoints,
219 clear_candidate_memo, edge_interior_lies_on, finalize_assembled_solid, refresh_derived_genus,
220};
221use assemble::{assemble_fragments_scoped, AssemblyScope};
222#[allow(unused_imports)]
224pub use assemble::apply_assembly_heal_chain;
225
226
227struct WorkingScale {
230 factor: f64,
231 solids: Vec<BrepSolid>,
232 options: BooleanOptions,
233}
234
235impl WorkingScale {
236 fn of(operands: &[&BrepSolid], options: &BooleanOptions) -> Result<Option<Self>, KernelRefusal> {
237 let Some(bounds) = crate::rescale::bounds_of(operands.iter().copied()) else {
238 return Ok(None);
239 };
240 let Some(factor) = crate::rescale::guard_factor(bounds) else {
241 return Ok(None);
242 };
243 crate::rescale::profile_fired("boolean", factor, bounds);
244 let solids = operands
245 .iter()
246 .map(|solid| crate::rescale::scale_operand(solid, factor, "boolean"))
247 .collect::<Result<Vec<_>, _>>()?;
248 let mut options = options.clone();
250 options.imprint.maximum_ssi_step = options.imprint.maximum_ssi_step.map(|step| step * factor);
251 Ok(Some(Self { factor, solids, options }))
252 }
253
254 fn back(&self, solid: &BrepSolid) -> Result<BrepSolid, KernelRefusal> {
255 crate::rescale::scale_operand(solid, 1.0 / self.factor, "boolean")
256 }
257
258 fn refusal(&self, error: KernelRefusal) -> KernelRefusal {
259 crate::rescale::name_scale(error, self.factor)
260 }
261}
262
263pub fn boolean_operation(
264 first: &BrepSolid,
265 second: &BrepSolid,
266 operation: BooleanOperation,
267 options: &BooleanOptions,
268) -> Result<BrepSolid, KernelRefusal> {
269 if let Some(scaled) = WorkingScale::of(&[first, second], options)? {
270 return boolean_operation(&scaled.solids[0], &scaled.solids[1], operation, &scaled.options)
271 .map_err(|error| scaled.refusal(error))
272 .and_then(|solid| scaled.back(&solid));
273 }
274 match boolean_operation_with_diagnostics(first, second, operation, options) {
275 Ok(outcome) => {
276 if below_tolerance_refusal_enabled()
279 && outcome.value.shells.iter().all(|shell| shell.faces.is_empty())
280 && !matches!(operation, BooleanOperation::Union)
281 {
282 if let Some(refusal) = below_tolerance_refusal(first, second, None) {
283 return Err(refusal);
284 }
285 }
286 if unresolved_merge_refusal_enabled() && !matches!(operation, BooleanOperation::Subtract) {
287 if let Some(refusal) = unresolved_merge_refusal(first, second) {
288 return Err(refusal);
289 }
290 }
291 Ok(outcome.value)
292 }
293 Err(error) => {
294 if below_tolerance_refusal_enabled() {
295 if let Some(refusal) = below_tolerance_refusal(first, second, Some(&error)) {
296 return Err(refusal);
297 }
298 }
299 if std::env::var("BREP_NO_PERTURB").as_deref() == Ok("1")
307 || !error.class.perturbation_eligible()
308 {
309 return Err(error);
310 }
311 if std::env::var("BREP_OPEN_OPERAND_GATE").as_deref() != Ok("0") {
333 if let Some((operand, open)) = [first, second]
334 .iter()
335 .enumerate()
336 .find_map(|(operand, solid)| {
337 let open = one_use_edges(solid);
338 (open > 0).then_some((operand, open))
339 })
340 {
341 return Err(error.with_message(|message| format!(
342 "{message}; operand {operand} is not a closed shell: {open} of its edges bound \
343 only one face, so no boolean of it encloses a solid and no perturbation \
344 can close it"
345 )));
346 }
347 }
348 if let Some((operand, face_id, deviation, weld)) =
349 planar_operand_off_its_plane(first, second, options)
350 {
351 return Err(error.with_message(|message| format!(
352 "{message}; operand {operand} face {face_id} is a plane whose straight \
353 boundary sits {deviation:.3e} off it (assembly weld {weld:.1e}), which \
354 no perturbation can reconcile — the body's planes must contain their \
355 boundary before it can take part in an exact boolean"
356 )));
357 }
358 if matches!(operation, BooleanOperation::Subtract)
373 && std::env::var("BREP_PINCH_GATE").as_deref() != Ok("0")
374 && subtract_pinches_at_internal_tangency(first, second, options.tolerance)
375 .unwrap_or(false)
376 {
377 if let Some(solid) = subtract_through_the_common_part(first, second, options) {
380 return Ok(solid);
381 }
382 return Err(error.with_message(|message| format!(
383 "{message}; internal tangency: the operands touch tangentially with \
384 co-directed normals, so the exact difference pinches to zero thickness \
385 (non-manifold, unrepresentable in a boundary model) — refusing rather \
386 than returning a perturbed sliver"
387 )));
388 }
389 if matches!(error.class, RefusalClass::TangentNodeSingularity)
405 && std::env::var("BREP_TANGENT_NODE_GATE").as_deref() != Ok("0")
406 {
407 return Err(error);
408 }
409 if matches!(operation, BooleanOperation::Union) {
413 if let Some(solid) = union_through_the_difference(first, second, options) {
414 return Ok(solid);
415 }
416 }
417 match perturbation_retry(first, second, operation, options) {
418 Ok(solid) => Ok(solid),
419 Err(refused) if refused.is_empty() => Err(error),
420 Err(refused) => {
421 Err(error.with_message(|message| format!("{message}; {}", refused.join("; "))))
422 }
423 }
424 }
425 }
426}
427
428const PINCH_PROBE_STEPS: usize = 8;
433
434const PINCH_ANGULAR_TOLERANCE: f64 = 1e-4;
437
438const PINCH_SEPARATION_STEP: f64 = 1e-2;
442
443fn subtract_through_the_common_part(first: &BrepSolid, second: &BrepSolid, options: &BooleanOptions) -> Option<BrepSolid> {
461 if !switch!("BREP_PINCH_COMMON_RETRY", true) || !options.imprint.tangent_curve_imprint {
464 return None;
465 }
466 let common = boolean_operation_with_diagnostics(first, second, BooleanOperation::Intersect, options).ok()?.value;
467 if common.shells.iter().all(|shell| shell.faces.is_empty()) {
468 return None;
469 }
470 let cut = boolean_operation_with_diagnostics(first, &common, BooleanOperation::Subtract, options).ok()?.value;
471 if !cut.validate().is_empty() {
472 return None;
473 }
474 let volume = |solid: &BrepSolid| crate::solid_mass_properties(solid).ok().map(|mass| mass.volume);
475 let (whole, taken, left) = (volume(first)?, volume(&common)?, volume(&cut)?);
476 ((left - (whole - taken)).abs() <= 1e-9 * whole.abs().max(1.0)).then_some(cut)
477}
478
479fn union_through_the_difference(first: &BrepSolid, second: &BrepSolid, options: &BooleanOptions) -> Option<BrepSolid> {
492 if !switch!("BREP_TANGENT_UNION_DIFFERENCE_RETRY", true) || !options.imprint.tangent_curve_imprint {
493 return None;
494 }
495 let pinches = |a: &BrepSolid, b: &BrepSolid| subtract_pinches_at_internal_tangency(a, b, options.tolerance).unwrap_or(false);
496 if !pinches(first, second) && !pinches(second, first) {
497 return None;
498 }
499 let difference = match boolean_operation_with_diagnostics(first, second, BooleanOperation::Subtract, options) {
500 Ok(outcome) => outcome.value,
501 Err(_) => subtract_through_the_common_part(first, second, options)?,
502 };
503 if difference.shells.iter().all(|shell| shell.faces.is_empty()) || !difference.validate().is_empty() {
504 return None;
505 }
506 let union = boolean_operation_with_diagnostics(second, &difference, BooleanOperation::Union, options).ok()?.value;
507 if !union.validate().is_empty() {
508 return None;
509 }
510 let volume = |solid: &BrepSolid| crate::solid_mass_properties(solid).ok().map(|mass| mass.volume);
511 let (left, added, whole) = (volume(&difference)?, volume(second)?, volume(&union)?);
512 ((whole - (left + added)).abs() <= 1e-9 * whole.abs().max(1.0)).then_some(union)
513}
514
515pub fn subtract_pinches_at_internal_tangency(
537 first: &BrepSolid,
538 second: &BrepSolid,
539 tolerance: f64,
540) -> Result<bool, KernelRefusal> {
541 let contact = (tolerance * 100.0).max(1e-12);
544 let probes_a = first
545 .shells
546 .iter()
547 .flat_map(|shell| &shell.faces)
548 .map(PinchProbe::of)
549 .collect::<Result<Vec<_>, _>>()?;
550 let probes_b = second
551 .shells
552 .iter()
553 .flat_map(|shell| &shell.faces)
554 .map(PinchProbe::of)
555 .collect::<Result<Vec<_>, _>>()?;
556 for probe_a in &probes_a {
557 for probe_b in &probes_b {
558 let pad = 1e-2 * probe_a.extent().max(probe_b.extent());
565 if probe_a.separation(probe_b) > contact + pad {
566 continue;
567 }
568 if classify_surface_pair(
575 &probe_a.face.surface,
576 &probe_b.face.surface,
577 tolerance,
578 PINCH_ANGULAR_TOLERANCE,
579 ).or_refuse(KernelStage::Validate, "csg.boolean.mod")?
580 .relation
581 == SurfacePairRelation::Cosurface
582 {
583 continue;
584 }
585 if faces_touch_with_codirected_normals(probe_a, probe_b, contact)? {
586 return Ok(true);
587 }
588 }
589 }
590 Ok(false)
591}
592
593struct PinchProbe<'a> {
596 face: &'a FaceRecord,
597 samples: Vec<(f64, f64, Vec3)>,
599 minimum: [f64; 3],
600 maximum: [f64; 3],
601}
602
603impl<'a> PinchProbe<'a> {
604 fn of(face: &'a FaceRecord) -> Result<Self, KernelRefusal> {
605 let [u0, u1] = face.surface.domain_u().or_refuse(KernelStage::Validate, "domain_u")?;
606 let [v0, v1] = face.surface.domain_v().or_refuse(KernelStage::Validate, "domain_v")?;
607 let steps = PINCH_PROBE_STEPS as f64;
608 let mut samples = Vec::with_capacity((PINCH_PROBE_STEPS + 1).pow(2));
609 let mut minimum = [f64::INFINITY; 3];
610 let mut maximum = [f64::NEG_INFINITY; 3];
611 for i in 0..=PINCH_PROBE_STEPS {
612 let u = u0 + (u1 - u0) * i as f64 / steps;
613 for j in 0..=PINCH_PROBE_STEPS {
614 let v = v0 + (v1 - v0) * j as f64 / steps;
615 let Ok(point) = face.surface.evaluate(u, v) else {
616 continue;
617 };
618 for (axis, value) in [point.x, point.y, point.z].into_iter().enumerate() {
619 minimum[axis] = minimum[axis].min(value);
620 maximum[axis] = maximum[axis].max(value);
621 }
622 samples.push((u, v, point));
623 }
624 }
625 Ok(Self {
626 face,
627 samples,
628 minimum,
629 maximum,
630 })
631 }
632
633 fn extent(&self) -> f64 {
635 (0..3)
636 .map(|axis| self.maximum[axis] - self.minimum[axis])
637 .fold(0.0f64, f64::max)
638 }
639
640 fn separation(&self, other: &Self) -> f64 {
642 let mut gap: f64 = 0.0;
643 for axis in 0..3 {
644 gap = gap.max(self.minimum[axis] - other.maximum[axis]);
645 gap = gap.max(other.minimum[axis] - self.maximum[axis]);
646 }
647 gap
648 }
649}
650
651fn faces_touch_with_codirected_normals(
656 probe_a: &PinchProbe<'_>,
657 probe_b: &PinchProbe<'_>,
658 contact: f64,
659) -> Result<bool, KernelRefusal> {
660 for (probe, other) in [(probe_a, probe_b), (probe_b, probe_a)] {
661 let source = probe.face;
662 let target = other.face;
663 for &(u, v, point) in &probe.samples {
664 let projection = project_point_to_surface(&target.surface, point).or_refuse(KernelStage::Validate, "project_point_to_surface")?;
665 if projection.distance > contact {
666 continue;
667 }
668 let (Ok(source_normal), Ok(target_normal)) = (
671 source.surface.normal(u, v),
672 target.surface.normal(projection.u, projection.v),
673 ) else {
674 continue;
675 };
676 let source_outward = outward_normal(source_normal, source.same_sense);
677 let target_outward = outward_normal(target_normal, target.same_sense);
678 if source_outward.cross(target_outward).length() > PINCH_ANGULAR_TOLERANCE
679 || source_outward.dot(target_outward) <= 0.0
680 {
681 continue;
682 }
683 if parameter_point_in_face(source, Vec2 { x: u, y: v }, 1e-6).or_refuse(KernelStage::Validate, "parameter_point_in_face")?
684 == PolygonClass::Outside
685 || parameter_point_in_face(
686 target,
687 Vec2 {
688 x: projection.u,
689 y: projection.v,
690 },
691 1e-6,
692 ).or_refuse(KernelStage::Validate, "csg.boolean.mod")? == PolygonClass::Outside
693 {
694 continue;
695 }
696 if contact_separates_locally(source, target, u, v, contact)? {
697 return Ok(true);
698 }
699 }
700 }
701 Ok(false)
702}
703
704fn outward_normal(normal: Vec3, same_sense: bool) -> Vec3 {
705 if same_sense {
706 normal
707 } else {
708 normal.scale(-1.0)
709 }
710}
711
712fn contact_separates_locally(
718 source: &FaceRecord,
719 target: &FaceRecord,
720 u: f64,
721 v: f64,
722 contact: f64,
723) -> Result<bool, KernelRefusal> {
724 let [u0, u1] = source.surface.domain_u().or_refuse(KernelStage::Validate, "domain_u")?;
725 let [v0, v1] = source.surface.domain_v().or_refuse(KernelStage::Validate, "domain_v")?;
726 let step_u = (u1 - u0) * PINCH_SEPARATION_STEP;
727 let step_v = (v1 - v0) * PINCH_SEPARATION_STEP;
728 for (probe_u, probe_v) in [
729 ((u + step_u).min(u1), v),
730 ((u - step_u).max(u0), v),
731 (u, (v + step_v).min(v1)),
732 (u, (v - step_v).max(v0)),
733 ] {
734 if (probe_u - u).abs() < f64::EPSILON && (probe_v - v).abs() < f64::EPSILON {
735 continue;
736 }
737 let Ok(point) = source.surface.evaluate(probe_u, probe_v) else {
738 continue;
739 };
740 if project_point_to_surface(&target.surface, point).or_refuse(KernelStage::Validate, "project_point_to_surface")?.distance > contact * 10.0 {
743 return Ok(true);
744 }
745 }
746 Ok(false)
747}
748
749fn perturbation_retry(
803 first: &BrepSolid,
804 second: &BrepSolid,
805 operation: BooleanOperation,
806 options: &BooleanOptions,
807) -> Result<BrepSolid, Vec<String>> {
808 const DIRECTIONS: [[f64; 3]; 4] = [
819 [0.4034, 0.7973, 0.4491],
820 [0.7973, 0.4491, 0.4034],
821 [0.4491, 0.4034, 0.7973],
822 [0.5774, -0.5774, 0.5774],
823 ];
824 const FRACTIONS: [f64; 5] = PERTURBATION_FRACTIONS;
830
831 let debug = std::env::var("BREP_DEBUG_BOOL").is_ok();
832 let scale = crate::solid_tolerance::solid_scale(first)
833 .max(crate::solid_tolerance::solid_scale(second))
834 .max(1.0);
835
836 let _caller = crate::mass_caller("boolean.perturbation_rescue");
840 let va = solid_signed_volume(first).ok().map(f64::abs);
841 let vb = solid_signed_volume(second).ok().map(f64::abs);
842 let hold_identity = std::env::var("BREP_PERTURB_IDENTITY").as_deref() != Ok("0");
843 let hold_mirror = hold_identity && std::env::var("BREP_PERTURB_MIRROR").as_deref() != Ok("0");
846 let early_exit = std::env::var("BREP_MIRROR_EARLY_EXIT").as_deref() != Ok("0");
849 let mut trends = [MirrorTrend::default(); 4];
850 let mut identity: Option<Option<InclusionExclusion>> = None;
852 let mut refused = Vec::new();
853 let ladder = std::env::var("BREP_DEBUG_PERTURB_LADDER").is_ok();
857 let ladder_start = web_time::Instant::now();
858 if ladder {
859 let measured = inclusion_exclusion_volume(first, second, operation, options, va, vb, false);
860 match &measured {
861 Some(identity) => eprintln!(
862 "[ladder] identity {} = {:.9} from the exact lane's {} ({:.9}); V(first) {:?} V(second) {:?}",
863 identity.formula, identity.expected, identity.reading, identity.read, va, vb
864 ),
865 None => eprintln!("[ladder] no identity: no exact-lane boolean of these operands clears in either order"),
866 }
867 identity = Some(measured);
868 }
869 let rung_miss = |identity: &Option<Option<InclusionExclusion>>, candidate: &BrepSolid| -> String {
870 let volume = body_volume(candidate);
871 match (identity, volume) {
872 (Some(Some(identity)), Some(volume)) => format!(
873 "volume {volume:.9} miss {:+.3e} bar {:.3e}",
874 volume - identity.expected,
875 crate::VOLUME_DRIFT_ABS.max(crate::VOLUME_DRIFT_REL * identity.expected.abs())
876 ),
877 (_, Some(volume)) => format!("volume {volume:.9}"),
878 _ => "no volume".to_string(),
879 }
880 };
881
882 for &fraction in &FRACTIONS {
883 let magnitude = scale * fraction;
884 for (direction, dir) in DIRECTIONS.iter().enumerate() {
885 if trends[direction].closed {
886 if ladder {
887 eprintln!("[ladder] dir={dir:?} fraction={fraction:.1e} offset {magnitude:.3e}: not tried, its direction is closed");
888 }
889 continue;
890 }
891 let offset = [dir[0] * magnitude, dir[1] * magnitude, dir[2] * magnitude];
892 let translate = match AffineTransform::new([
893 1.0, 0.0, 0.0, offset[0], 0.0, 1.0, 0.0, offset[1], 0.0, 0.0, 1.0, offset[2], 0.0, 0.0, 0.0, 1.0,
897 ]) {
898 Ok(transform) => transform,
899 Err(_) => continue,
900 };
901 let moved = match crate::transform_brep(second, translate, false) {
902 Ok(solid) => solid,
903 Err(_) => continue,
904 };
905 let rung = format!("dir={dir:?} fraction={fraction:.1e} offset {magnitude:.3e}");
906 let rung_start = web_time::Instant::now();
907 let candidate =
908 match boolean_operation_with_diagnostics(first, &moved, operation, options) {
909 Ok(outcome) => outcome.value,
910 Err(error) => {
911 if ladder {
912 eprintln!("[ladder] {rung}: exact lane refused {:?}", error.class);
913 }
914 continue;
915 }
916 };
917 let built = rung_start.elapsed();
918 if candidate.shells.is_empty() {
920 if ladder {
921 eprintln!("[ladder] {rung}: empty");
922 }
923 continue;
924 }
925 if let (Some(va), Some(vb)) = (va, vb) {
930 if let Ok(vr) = solid_signed_volume(&candidate) {
931 if !volume_within_csg_bounds(operation, va, vb, vr.abs()) {
932 if ladder {
933 eprintln!("[ladder] {rung}: outside the CSG bound, {}", rung_miss(&identity, &candidate));
934 }
935 continue;
936 }
937 }
938 }
939 let bounded = rung_start.elapsed();
944 if hold_identity {
946 let identity = identity.get_or_insert_with(|| {
947 let identity =
948 inclusion_exclusion_volume(first, second, operation, options, va, vb, false);
949 if debug && identity.is_none() {
950 eprintln!(
951 "[perturb] no exact-lane boolean of these operands clears in either \
952 order; no identity to hold"
953 );
954 }
955 identity
956 });
957 if let Some(identity) = identity {
958 let expected = identity.expected;
959 let bar = crate::VOLUME_DRIFT_ABS.max(crate::VOLUME_DRIFT_REL * expected.abs());
960 let volume = body_volume(&candidate);
961 let miss = volume.map(|volume| (volume - expected).abs());
962 if !miss.is_some_and(|miss| miss <= bar) {
963 let sentence = format!(
964 "perturbation rung dir={dir:?} fraction={fraction:.1e} \
965 (offset {magnitude:.3e}) refused: its body reads {} against the \
966 inclusion–exclusion identity {} = {expected:.9} (the exact lane's \
967 {} reads {:.9}), a miss of {} beyond the volume drift bar {bar:.3e}",
968 volume.map_or("no volume".to_string(), |volume| format!("{volume:.9}")),
969 identity.formula,
970 identity.reading,
971 identity.read,
972 miss.map_or("unmeasured".to_string(), |miss| format!("{miss:.3e}")),
973 );
974 if debug {
975 eprintln!("[perturb] {sentence}");
976 }
977 if ladder {
978 eprintln!(
979 "[ladder] {rung}: refused by the identity, volume {} miss {} bar {bar:.3e}",
980 volume.map_or("none".to_string(), |volume| format!("{volume:.9}")),
981 volume.map_or("unmeasured".to_string(), |volume| format!("{:+.3e}", volume - expected)),
982 );
983 }
984 refused.push(sentence);
985 continue;
986 }
987 } else if hold_mirror {
988 let mirror_start = web_time::Instant::now();
991 let mirrored = AffineTransform::new([
992 1.0, 0.0, 0.0, -offset[0], 0.0, 1.0, 0.0, -offset[1], 0.0, 0.0, 1.0, -offset[2], 0.0, 0.0, 0.0, 1.0,
996 ])
997 .ok()
998 .and_then(|transform| crate::transform_brep(second, transform, false).ok());
999 let mirror = mirrored.as_ref().and_then(|mirrored| {
1000 inclusion_exclusion_volume(first, mirrored, operation, options, va, vb, true)
1001 });
1002 let mirror_time = mirror_start.elapsed();
1003 let volume = body_volume(&candidate);
1004 let mut measured = None;
1005 let verdict = match (&mirror, volume) {
1006 (Some(mirror), Some(volume)) => {
1007 let bar = crate::VOLUME_DRIFT_ABS.max(crate::VOLUME_DRIFT_REL * mirror.expected.abs());
1008 let miss = 0.5 * (volume - mirror.expected).abs();
1009 measured = Some((0.5 * (volume - mirror.expected), bar));
1010 if ladder {
1011 eprintln!(
1012 "[ladder] {rung}: mirror at −offset reads {} = {:.9} (the mirrored {} {:.9}); body {volume:.9}, first-order translation error {:+.3e} bar {bar:.3e}",
1013 mirror.formula, mirror.expected, mirror.reading, mirror.read, 0.5 * (volume - mirror.expected)
1014 );
1015 }
1016 (miss > bar).then(|| format!(
1017 "perturbation rung dir={dir:?} fraction={fraction:.1e} \
1018 (offset {magnitude:.3e}) refused: no exact-lane boolean of the \
1019 operands clears, so the rung is held to its mirror: its body reads \
1020 {volume:.9} with the second operand moved +offset and {} = {:.9} \
1021 with it moved −offset (the mirrored {} reads {:.9}), a first-order \
1022 translation error of {miss:.3e} beyond the volume drift bar {bar:.3e}",
1023 mirror.formula, mirror.expected, mirror.reading, mirror.read
1024 ))
1025 }
1026 _ => Some(format!(
1027 "perturbation rung dir={dir:?} fraction={fraction:.1e} \
1028 (offset {magnitude:.3e}) refused: no exact-lane boolean of the operands \
1029 clears, and none clears with the second operand moved −offset either, \
1030 so nothing checks the rung's body{}",
1031 volume.map_or(String::new(), |volume| format!(" ({volume:.9})"))
1032 )),
1033 };
1034 match verdict {
1035 None => trends[direction].cleared(),
1036 Some(sentence) => {
1037 if debug {
1038 eprintln!("[perturb] {sentence}");
1039 }
1040 if ladder {
1041 eprintln!(
1042 "[ladder] {rung}: refused by its mirror (rung {:.0} ms: built {:.0}, bound {:.0}, mirror {:.0} ms; ladder {:.1} s)",
1043 rung_start.elapsed().as_secs_f64() * 1e3,
1044 built.as_secs_f64() * 1e3,
1045 (bounded - built).as_secs_f64() * 1e3,
1046 mirror_time.as_secs_f64() * 1e3,
1047 ladder_start.elapsed().as_secs_f64()
1048 );
1049 }
1050 refused.push(sentence);
1051 let closure = measured.and_then(|(error, bar)| {
1054 let earlier = trends[direction].refused(magnitude, error, early_exit)?;
1055 Some((earlier, error, bar))
1056 });
1057 if let Some(((earlier_offset, earlier_error), error, bar)) = closure {
1058 let closed = format!(
1059 "perturbation direction dir={dir:?} closed after offset {magnitude:.3e}: its \
1060 rungs' first-order translation errors read {earlier_error:+.3e} at offset \
1061 {earlier_offset:.3e} and {error:+.3e} at {magnitude:.3e}, one sign and \
1062 growing, so no larger offset along it comes back to the volume drift bar \
1063 {bar:.3e}"
1064 );
1065 if debug {
1066 eprintln!("[perturb] {closed}");
1067 }
1068 if ladder {
1069 eprintln!("[ladder] {closed}");
1070 }
1071 refused.push(closed);
1072 }
1073 continue;
1074 }
1075 }
1076 }
1077 }
1078 match crate::oracle::boolean_semantic_disagreement(
1082 first, second, operation, &candidate, 400,
1083 ) {
1084 Ok(report) if report.considered >= 30 && !report.is_flagged() => {
1085 if ladder {
1086 eprintln!(
1087 "[ladder] {rung}: accepted (oracle {} considered, rate {:.4}), {}",
1088 report.considered, report.disagreement_rate, rung_miss(&identity, &candidate)
1089 );
1090 }
1091 if debug {
1092 eprintln!(
1093 "[perturb] rescued {operation:?}: dir={dir:?} fraction={fraction:.1e} \
1094 magnitude={magnitude:.3e} offset={offset:?} \
1095 (oracle considered={} rate={:.4})",
1096 report.considered, report.disagreement_rate
1097 );
1098 }
1099 return Ok(candidate);
1100 }
1101 report => {
1102 if ladder {
1103 let verdict = match &report {
1104 Ok(report) => format!("oracle {} considered, rate {:.4}", report.considered, report.disagreement_rate),
1105 Err(error) => format!("oracle error {error:?}"),
1106 };
1107 eprintln!("[ladder] {rung}: refused by the oracle ({verdict}), {}", rung_miss(&identity, &candidate));
1108 }
1109 continue;
1110 }
1111 }
1112 }
1113 }
1114 if debug {
1115 eprintln!("[perturb] ladder exhausted for {operation:?}; no rung produced a clean result");
1116 }
1117 Err(refused)
1118}
1119
1120pub const PERTURBATION_FRACTIONS: [f64; 5] = [3e-5, 1e-4, 3e-4, 1e-3, 3e-3];
1123
1124#[derive(Clone, Copy, Default)]
1148pub struct MirrorTrend {
1149 last: Option<(f64, f64)>,
1151 pub closed: bool,
1152}
1153
1154impl MirrorTrend {
1155 pub fn refused(&mut self, offset: f64, error: f64, close: bool) -> Option<(f64, f64)> {
1160 let earlier = self
1161 .last
1162 .filter(|&(_, earlier)| earlier.signum() == error.signum() && error.abs() >= earlier.abs())
1163 .filter(|_| close);
1164 self.last = Some((offset, error));
1165 self.closed |= earlier.is_some();
1166 earlier
1167 }
1168
1169 pub fn cleared(&mut self) {
1171 self.last = None;
1172 }
1173}
1174
1175pub fn below_tolerance_refusal_enabled() -> bool {
1190 crate::switch!("BREP_BELOW_TOLERANCE_REFUSAL", true)
1191}
1192
1193const BELOW_TOLERANCE_BAND: f64 = 10.0 * crate::tolerance::WELD_FLOOR;
1196
1197pub fn unresolved_merge_refusal_enabled() -> bool {
1207 crate::switch!("BREP_UNRESOLVED_MERGE_REFUSAL", false)
1208}
1209
1210pub fn sliver_shell_drop_enabled() -> bool {
1223 crate::switch!("BREP_SLIVER_SHELL_DROP", true)
1224}
1225
1226const SLIVER_SHELL_THICKNESS: f64 = 1e-12;
1230
1231fn drop_sliver_shells(solid: &mut BrepSolid) -> usize {
1234 if !sliver_shell_drop_enabled() || !solid.kind.is_solid() || solid.shells.len() < 2 {
1235 return 0;
1236 }
1237 let floor = SLIVER_SHELL_THICKNESS * crate::solid_tolerance::solid_scale(solid).max(1.0);
1238 let degenerate: std::collections::HashSet<u64> = solid.edges.iter().filter(|edge| edge.degenerate).map(|edge| edge.id).collect();
1239 let mut drop = vec![false; solid.shells.len()];
1240 for (index, shell) in solid.shells.iter().enumerate() {
1241 if shell.faces.is_empty() {
1242 continue;
1243 }
1244 let mut uses: HashMap<u64, usize> = HashMap::default();
1246 for coedge in shell.faces.iter().flat_map(|face| &face.loops).flat_map(|lp| &lp.coedges) {
1247 if !degenerate.contains(&coedge.edge_id) {
1248 *uses.entry(coedge.edge_id).or_default() += 1;
1249 }
1250 }
1251 if uses.is_empty() || uses.values().any(|&count| count != 2) {
1252 continue;
1253 }
1254 let alone = BrepSolid { shells: vec![shell.clone()], mass_properties_cache: Default::default(), ..solid.clone() };
1255 let Ok(mass) = crate::solid_mass_properties(&alone) else {
1256 continue;
1257 };
1258 let thickness = mass.volume.abs() / mass.surface_area.max(f64::MIN_POSITIVE);
1259 if env_read!("BREP_DEBUG_SLIVER_SHELL").is_some() {
1260 eprintln!(
1261 "sliver-shell: shell {index} of {}: volume {:.6e} area {:.6e} thickness {thickness:.3e}",
1262 solid.shells.len(),
1263 mass.volume,
1264 mass.surface_area
1265 );
1266 }
1267 drop[index] = thickness < floor;
1268 }
1269 let dropped = drop.iter().filter(|&&d| d).count();
1270 if dropped == 0 || dropped == solid.shells.len() {
1271 return 0;
1272 }
1273 let mut index = 0;
1274 solid.shells.retain(|_| {
1275 let keep = !drop[index];
1276 index += 1;
1277 keep
1278 });
1279 let used_edges: std::collections::HashSet<u64> = solid
1280 .shells
1281 .iter()
1282 .flat_map(|shell| &shell.faces)
1283 .flat_map(|face| &face.loops)
1284 .flat_map(|lp| &lp.coedges)
1285 .map(|coedge| coedge.edge_id)
1286 .collect();
1287 solid.edges.retain(|edge| used_edges.contains(&edge.id));
1288 let used_vertices: std::collections::HashSet<u64> =
1289 solid.edges.iter().flat_map(|edge| [edge.start_vertex_id, edge.end_vertex_id]).collect();
1290 solid.vertices.retain(|vertex| used_vertices.contains(&vertex.id));
1291 solid.mass_properties_cache = Default::default();
1292 refresh_derived_genus(solid);
1294 dropped
1295}
1296
1297fn unresolved_merge_refusal(first: &BrepSolid, second: &BrepSolid) -> Option<KernelRefusal> {
1298 let (lower, upper) = (crate::tolerance::COINCIDENCE_DISTANCE_FLOOR, crate::tolerance::WELD_FLOOR);
1299 let (face_a, face_b, separation) = planar_faces_apart_within(first, second, lower, upper)?;
1300 Some(KernelRefusal::unsupported(
1301 KernelStage::Intersect,
1302 "below_modelling_tolerance",
1303 format!(
1304 "boolean: face {face_a} of the first operand and face {face_b} of the second are planes nearly on one \
1305 another, {separation:.3e} apart at most over their shared extent: farther than a coincidence \
1306 ({lower:.0e}) and closer than the kernel resolves ({upper:.0e}), so the step between them would be \
1307 welded away"
1308 ),
1309 ))
1310}
1311
1312fn below_tolerance_refusal(first: &BrepSolid, second: &BrepSolid, error: Option<&KernelRefusal>) -> Option<KernelRefusal> {
1313 let (face_a, face_b, separation) = near_coincident_planar_faces(first, second)?;
1314 let message = format!(
1315 "boolean: face {face_a} of the first operand and face {face_b} of the second are planes nearly on one \
1316 another, {separation:.3e} apart at most over their shared extent: the slivers between them are below the \
1317 modelling tolerance ({BELOW_TOLERANCE_BAND:.0e}), so the kernel cannot resolve them{}",
1318 error.map(|error| format!(" (the exact arrangement said: {})", error.message.chars().take(160).collect::<String>())).unwrap_or_default()
1319 );
1320 Some(KernelRefusal::unsupported(KernelStage::Intersect, "below_modelling_tolerance", message))
1321}
1322
1323fn near_coincident_planar_faces(first: &BrepSolid, second: &BrepSolid) -> Option<(u64, u64, f64)> {
1327 let scale = crate::solid_tolerance::solid_scale(first).max(crate::solid_tolerance::solid_scale(second)).max(1.0);
1328 planar_faces_apart_within(first, second, 1e-9 * scale, BELOW_TOLERANCE_BAND)
1329}
1330
1331fn planar_faces_apart_within(first: &BrepSolid, second: &BrepSolid, lower: f64, upper: f64) -> Option<(u64, u64, f64)> {
1335 struct Planar {
1336 id: u64,
1337 origin: Vec3,
1338 normal: Vec3,
1339 corners: Vec<Vec3>,
1340 bounds: crate::spatial::Aabb,
1341 }
1342 let read = |solid: &BrepSolid| -> Vec<Planar> {
1343 let at = |id: u64| solid.vertices.iter().find(|vertex| vertex.id == id).map(|vertex| vertex.point);
1344 solid
1345 .shells
1346 .iter()
1347 .flat_map(|shell| &shell.faces)
1348 .filter_map(|face| {
1349 if !face.surface.is_affine().ok()? {
1350 return None;
1351 }
1352 let origin = face.surface.control_points[0][0].point().ok()?;
1353 let a = face.surface.control_points[1][0].point().ok()?.sub(origin);
1354 let b = face.surface.control_points[0][1].point().ok()?.sub(origin);
1355 let normal = a.cross(b).normalized().ok()?;
1356 let corners: Vec<Vec3> = face
1357 .loops
1358 .iter()
1359 .flat_map(|lp| &lp.coedges)
1360 .filter_map(|coedge| solid.edges.iter().find(|edge| edge.id == coedge.edge_id))
1361 .flat_map(|edge| [at(edge.start_vertex_id), at(edge.end_vertex_id)])
1362 .flatten()
1363 .collect();
1364 if corners.is_empty() {
1365 return None;
1366 }
1367 let bounds = crate::spatial::Aabb::from_points(corners.clone());
1368 Some(Planar { id: face.id, origin, normal, corners, bounds })
1369 })
1370 .collect()
1371 };
1372 let (faces_a, faces_b) = (read(first), read(second));
1373 for a in &faces_a {
1374 for b in &faces_b {
1375 if a.normal.cross(b.normal).length() > 1e-3 {
1376 continue;
1377 }
1378 if !a.bounds.intersects(b.bounds, upper) {
1379 continue;
1380 }
1381 let separation = a
1382 .corners
1383 .iter()
1384 .map(|corner| corner.sub(b.origin).dot(b.normal).abs())
1385 .chain(b.corners.iter().map(|corner| corner.sub(a.origin).dot(a.normal).abs()))
1386 .fold(0.0f64, f64::max);
1387 if separation > lower && separation <= upper {
1388 return Some((a.id, b.id, separation));
1389 }
1390 }
1391 }
1392 None
1393}
1394
1395pub fn one_use_edges(solid: &BrepSolid) -> usize {
1396 let mut uses: HashMap<u64, usize> = HashMap::default();
1397 for coedge in solid
1398 .shells
1399 .iter()
1400 .flat_map(|shell| &shell.faces)
1401 .flat_map(|face| &face.loops)
1402 .flat_map(|loop_record| &loop_record.coedges)
1403 {
1404 *uses.entry(coedge.edge_id).or_default() += 1;
1405 }
1406 solid
1407 .edges
1408 .iter()
1409 .filter(|edge| !edge.degenerate && uses.get(&edge.id) == Some(&1))
1410 .count()
1411}
1412
1413fn body_volume(solid: &BrepSolid) -> Option<f64> {
1415 if solid.shells.is_empty() {
1416 return Some(0.0);
1417 }
1418 solid_signed_volume(solid).ok().map(f64::abs)
1419}
1420
1421struct InclusionExclusion {
1424 formula: &'static str,
1427 reading: &'static str,
1429 read: f64,
1431 expected: f64,
1433}
1434
1435fn inclusion_exclusion_volume(
1446 first: &BrepSolid,
1447 second: &BrepSolid,
1448 operation: BooleanOperation,
1449 options: &BooleanOptions,
1450 va: Option<f64>,
1451 vb: Option<f64>,
1452 own_first: bool,
1453) -> Option<InclusionExclusion> {
1454 use BooleanOperation::{Intersect, Subtract, Union};
1455 let (va, vb) = (va?, vb?);
1456 let own = match operation {
1457 Intersect => (Intersect, false, "first ∩ second"),
1458 Union => (Union, false, "first ∪ second"),
1459 Subtract => (Subtract, false, "first − second"),
1460 };
1461 let readings = [
1462 (Intersect, false, "first ∩ second"),
1463 (Intersect, true, "second ∩ first"),
1464 (Union, false, "first ∪ second"),
1465 (Union, true, "second ∪ first"),
1466 (Subtract, false, "first − second"),
1467 (Subtract, true, "second − first"),
1468 ];
1469 let own_reading = own_first.then_some(own);
1470 let leading = usize::from(own_first);
1471 for (index, (other, swapped, reading)) in own_reading.into_iter().chain(readings).enumerate() {
1472 if index >= leading && !swapped && std::mem::discriminant(&other) == std::mem::discriminant(&operation) {
1473 continue;
1474 }
1475 let (x, y) = if swapped { (second, first) } else { (first, second) };
1476 let Some(read) = boolean_operation_with_diagnostics(x, y, other, options)
1477 .ok()
1478 .and_then(|outcome| body_volume(&outcome.value))
1479 else {
1480 continue;
1481 };
1482 let intersection = match (other, swapped) {
1483 (Intersect, _) => read,
1484 (Union, _) => va + vb - read,
1485 (Subtract, false) => va - read,
1486 (Subtract, true) => vb - read,
1487 };
1488 let (formula, expected) = match operation {
1489 Intersect => ("V(first ∩ second)", intersection),
1490 Union => ("V(first) + V(second) − V(first ∩ second)", va + vb - intersection),
1491 Subtract => ("V(first) − V(first ∩ second)", va - intersection),
1492 };
1493 return Some(InclusionExclusion { formula, reading, read, expected });
1494 }
1495 None
1496}
1497
1498fn planar_operand_off_its_plane(
1507 first: &BrepSolid,
1508 second: &BrepSolid,
1509 options: &BooleanOptions,
1510) -> Option<(u8, u64, f64, f64)> {
1511 let policy = options
1512 .tolerances
1513 .clone()
1514 .unwrap_or_else(|| KernelTolerances::for_pair(first, second, options.tolerance));
1515 let weld = crate::tolerance::assembler_weld(policy.model);
1516 let mut worst: Option<(u8, u64, f64)> = None;
1517 for (operand, solid) in [(0u8, first), (1u8, second)] {
1518 let vertex_point = |id: u64| solid.vertices.iter().find(|v| v.id == id).map(|v| v.point);
1519 for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
1520 let Some(crate::AnalyticSurface::Plane {
1521 origin,
1522 u_dir,
1523 v_dir,
1524 ..
1525 }) = face.surface.analytic()
1526 else {
1527 continue;
1528 };
1529 let [loop_record] = face.loops.as_slice() else {
1530 continue;
1531 };
1532 let Ok(normal) = u_dir.cross(*v_dir).normalized() else {
1533 continue;
1534 };
1535 let mut off_plane = 0.0f64;
1536 let mut straight = true;
1537 for coedge in &loop_record.coedges {
1538 let Some(edge) = solid.edges.iter().find(|edge| edge.id == coedge.edge_id) else {
1539 straight = false;
1540 break;
1541 };
1542 let (Some(start), Some(end)) =
1543 (vertex_point(edge.start_vertex_id), vertex_point(edge.end_vertex_id))
1544 else {
1545 straight = false;
1546 break;
1547 };
1548 let chord = end.sub(start);
1549 let length = chord.length();
1550 if edge.degenerate || length <= weld {
1551 straight = false;
1552 break;
1553 }
1554 let direction = chord.scale(1.0 / length);
1555 for fraction in [0.25, 0.5, 0.75] {
1556 let Ok(point) = edge.curve.evaluate(edge.t0 + (edge.t1 - edge.t0) * fraction) else {
1557 straight = false;
1558 break;
1559 };
1560 let delta = point.sub(start);
1561 let along = delta.dot(direction);
1562 if delta.sub(direction.scale(along)).length() > weld
1563 || along < -weld
1564 || along > length + weld
1565 {
1566 straight = false;
1567 break;
1568 }
1569 }
1570 if !straight {
1571 break;
1572 }
1573 off_plane = off_plane.max(start.sub(*origin).dot(normal).abs());
1574 }
1575 if straight && off_plane > weld && worst.is_none_or(|(_, _, gap)| off_plane > gap) {
1576 worst = Some((operand, face.id, off_plane));
1577 }
1578 }
1579 }
1580 worst.map(|(operand, face_id, gap)| (operand, face_id, gap, weld))
1581}
1582
1583fn volume_within_csg_bounds(operation: BooleanOperation, va: f64, vb: f64, vr: f64) -> bool {
1586 let slack = 1e-2 * (va + vb).max(1.0);
1587 match operation {
1588 BooleanOperation::Union => vr >= va.max(vb) - slack && vr <= va + vb + slack,
1590 BooleanOperation::Subtract => vr <= va + slack && vr >= -slack,
1592 BooleanOperation::Intersect => vr <= va.min(vb) + slack && vr >= -slack,
1594 }
1595}
1596
1597fn reverse_fragment(fragment: &mut FaceFragmentRecord) -> Result<(), KernelRefusal> {
1624 fragment.same_sense = !fragment.same_sense;
1625 for loop_record in &mut fragment.loops {
1626 loop_record.coedges.reverse();
1627 for coedge in &mut loop_record.coedges {
1628 coedge.forward = !coedge.forward;
1629 coedge.pcurve = coedge.pcurve.reversed().or_refuse(KernelStage::Validate, "reversed")?;
1630 }
1631 }
1632 Ok(())
1633}
1634
1635fn build_nary_imprint(
1642 operands: &[BrepSolid],
1643 options: &ImprintOptions,
1644) -> Result<ImprintResultRecord, KernelRefusal> {
1645 let mut section_evidence = false;
1646 let mut vertices: Vec<ImprintVertex> = Vec::new();
1647 let mut pieces: Vec<ImprintPieceRecord> = Vec::new();
1648 let mut by_face: HashMap<(u8, u64), Vec<u64>> = HashMap::default();
1649 let mut edge_splits: HashMap<(u8, u64), Vec<f64>> = HashMap::default();
1650 let mut next_vertex_id: u64 = 1;
1651 let mut next_piece_id: u64 = 1;
1652
1653 for i in 0..operands.len() {
1654 for j in (i + 1)..operands.len() {
1655 let pair = build_imprints(&operands[i], &operands[j], options)?;
1656 let remap = |operand: u8| -> u8 {
1657 if operand == 0 {
1658 i as u8
1659 } else {
1660 j as u8
1661 }
1662 };
1663
1664 section_evidence = section_evidence || pair.section_evidence;
1665 let mut vertex_map: HashMap<u64, u64> = HashMap::default();
1666 for vertex in &pair.vertices {
1667 let global = next_vertex_id;
1668 next_vertex_id += 1;
1669 vertex_map.insert(vertex.id, global);
1670 vertices.push(ImprintVertex {
1671 id: global,
1672 point: vertex.point,
1673 });
1674 }
1675
1676 let mut piece_map: HashMap<u64, u64> = HashMap::default();
1677 for piece in &pair.pieces {
1678 let global = next_piece_id;
1679 next_piece_id += 1;
1680 piece_map.insert(piece.id, global);
1681 let mut mapped = piece.clone();
1682 mapped.id = global;
1683 mapped.start_vertex_id = *vertex_map
1684 .get(&piece.start_vertex_id)
1685 .ok_or_else(|| KernelRefusal::internal(KernelStage::Intersect, "nary.imprint", "n-ary imprint: piece references unknown vertex"))?;
1686 mapped.end_vertex_id = *vertex_map
1687 .get(&piece.end_vertex_id)
1688 .ok_or_else(|| KernelRefusal::internal(KernelStage::Intersect, "nary.imprint", "n-ary imprint: piece references unknown vertex"))?;
1689 for pcurve in &mut mapped.pcurves {
1690 pcurve.operand = remap(pcurve.operand);
1691 }
1692 mapped.support_faces = [
1693 FaceKey {
1694 operand: remap(piece.support_faces[0].operand),
1695 face_id: piece.support_faces[0].face_id,
1696 },
1697 FaceKey {
1698 operand: remap(piece.support_faces[1].operand),
1699 face_id: piece.support_faces[1].face_id,
1700 },
1701 ];
1702 pieces.push(mapped);
1703 }
1704
1705 for entry in &pair.by_face {
1706 let list = by_face
1707 .entry((remap(entry.operand), entry.face_id))
1708 .or_default();
1709 for piece_id in &entry.piece_ids {
1710 let global = *piece_map.get(piece_id).ok_or_else(|| {
1711 KernelRefusal::internal(KernelStage::Intersect, "nary.imprint", "n-ary imprint: by_face references unknown piece")
1712 })?;
1713 list.push(global);
1714 }
1715 }
1716
1717 for split in &pair.edge_splits {
1718 edge_splits
1719 .entry((remap(split.operand), split.edge_id))
1720 .or_default()
1721 .extend(split.parameters.iter().copied());
1722 }
1723 }
1724 }
1725
1726 Ok(ImprintResultRecord {
1727 faces_in_unproved_pairs: None,
1728 vertices,
1729 pieces,
1730 tangent_nodes: Vec::new(),
1731 barrier_edges: Vec::new(),
1732 section_evidence,
1733 cosurface_pairs: Vec::new(),
1734 tangent_sections: Vec::new(),
1735 by_face: by_face
1736 .into_iter()
1737 .map(|((operand, face_id), piece_ids)| FaceImprints {
1738 operand,
1739 face_id,
1740 piece_ids,
1741 })
1742 .collect(),
1743 edge_splits: edge_splits
1744 .into_iter()
1745 .map(|((operand, edge_id), parameters)| EdgeSplitRecord {
1746 operand,
1747 edge_id,
1748 parameters,
1749 })
1750 .collect(),
1751 })
1752}
1753
1754pub fn boolean_operation_nary(
1765 operands: &[BrepSolid],
1766 operation: BooleanOperation,
1767) -> Result<BrepSolid, KernelRefusal> {
1768 boolean_operation_nary_with_options(operands, operation, &BooleanOptions::default())
1769}
1770
1771pub fn boolean_operation_nary_with_options(
1777 operands: &[BrepSolid],
1778 operation: BooleanOperation,
1779 options: &BooleanOptions,
1780) -> Result<BrepSolid, KernelRefusal> {
1781 if operands.len() > 1 {
1782 if let Some(scaled) = WorkingScale::of(&operands.iter().collect::<Vec<_>>(), options)? {
1783 return boolean_operation_nary_with_options(&scaled.solids, operation, &scaled.options)
1784 .map_err(|error| scaled.refusal(error))
1785 .and_then(|solid| scaled.back(&solid));
1786 }
1787 }
1788 if operands.is_empty() {
1789 return Err(KernelRefusal::input(KernelStage::Collect, "operands", "boolean_operation_nary: no operands provided"));
1790 }
1791 if operands.len() == 1 {
1792 return Ok(operands[0].clone());
1793 }
1794 if operands.len() > 255 {
1795 return Err(KernelRefusal::input(KernelStage::Collect, "operands", "boolean_operation_nary: at most 255 operands supported"));
1796 }
1797 let debug = std::env::var("BREP_DEBUG_BOOL").is_ok();
1798
1799 let mut policy = KernelTolerances::for_solid(&operands[0], options.tolerance);
1803 for operand in &operands[1..] {
1804 let candidate = KernelTolerances::for_solid(operand, options.tolerance);
1805 if candidate.sew_search > policy.sew_search {
1806 policy = candidate;
1807 }
1808 }
1809 policy.check().or_input(KernelStage::Collect, "tolerances")?;
1810 let tolerance = policy.model;
1811
1812 let mut healed = operands.to_vec();
1815 for operand in &mut healed {
1816 crate::heal::heal_operands(operand, &policy)?;
1817 crate::heal::refit_inherited_trims_reused(operand, &policy)?;
1820 normalize_operand_band_seams(operand)?;
1823 }
1824
1825 let mut imprint_options = options.imprint.clone();
1827 imprint_options.tolerance = tolerance;
1828 let imprint = build_nary_imprint(&healed, &imprint_options)?;
1829
1830 let mut split = Vec::with_capacity(healed.len());
1832 for (index, operand) in healed.iter().enumerate() {
1833 split.push(apply_edge_splits(operand, index as u8, &imprint)?);
1834 }
1835 let mut fragments = Vec::with_capacity(split.len());
1836 for (index, solid) in split.iter().enumerate() {
1837 fragments.push(fragment_solid(solid, index as u8, &imprint)?);
1838 }
1839
1840 let selected = select_fragments_nary(&fragments, &healed, operation, tolerance, debug)?;
1842
1843 let solids: HashMap<u8, &BrepSolid> = split
1845 .iter()
1846 .enumerate()
1847 .map(|(index, solid)| (index as u8, solid))
1848 .collect();
1849 let solid = assemble_fragments(selected, &solids, &imprint, tolerance)?;
1850 let solid = if options.merge_coplanar_faces
1851 && std::env::var("BREP_COPLANAR_MERGE").as_deref() != Ok("0")
1852 {
1853 let merged = merge_same_surface_faces_excluding(
1854 &solid,
1855 tolerance,
1856 &options.keep_unmerged_name_substrs,
1857 )?;
1858 let merged = merge_curve_continuation_edges(&merged, tolerance).map_err(|refusal| KernelRefusal { stage: KernelStage::Validate, ..refusal })?;
1859 rejoin::rejoin_unless_referenced(merged, options, tolerance)
1860 } else {
1861 solid
1862 };
1863 let validation = solid.validate_detailed(&policy);
1864 if !validation.issues.is_empty() {
1865 return Err(KernelRefusal::new(
1866 RefusalClass::InvalidResultTopology { issues: validation.issues.len() as u32 },
1867 KernelStage::Validate,
1868 format!(
1869 "boolean_operation_nary: invalid result: {:?}",
1870 validation.issues
1871 )));
1872 }
1873 if debug {
1874 if let Ok(report) =
1875 crate::oracle::boolean_semantic_disagreement_nary(&healed, operation, &solid, 300)
1876 {
1877 if report.is_flagged() {
1878 eprintln!(
1879 "[oracle] n-ary semantic disagreement rate {:.4} ({} of {} decidable points); sample {:?}",
1880 report.disagreement_rate,
1881 report.disagreements.len(),
1882 report.considered,
1883 report.sample_disagreement()
1884 );
1885 }
1886 }
1887 }
1888 Ok(solid)
1889}
1890
1891fn attribute_to_tangent_node(error: KernelRefusal, nodes: &[Vec3]) -> KernelRefusal {
1922 let Some(node) = nodes.first() else {
1923 return error;
1924 };
1925 if !error.class.perturbation_eligible()
1926 || matches!(error.class, RefusalClass::TangentNodeSingularity)
1927 {
1928 return error;
1929 }
1930 if std::env::var("BREP_DEBUG_BOOL").is_ok() {
1931 eprintln!(
1932 "boolean: tear downstream of the tangent node at ({:.6},{:.6},{:.6}) attributed to it; the stage read: {}",
1933 node.x, node.y, node.z, error.message
1934 );
1935 }
1936 KernelRefusal::new(
1937 RefusalClass::TangentNodeSingularity,
1938 error.stage,
1939 format!(
1940 "boolean: unsupported singular/tangent-node surface intersection \
1941 at the tangent node at ({:.6},{:.6},{:.6}): the section through it did not \
1942 assemble into a closed shell",
1943 node.x, node.y, node.z
1944 ),
1945 )
1946}
1947
1948pub fn attribute_to_tangent_section(
1970 error: KernelRefusal,
1971 sections: &[crate::imprint::TangentSectionRecord],
1972 origins: &[FaceKey],
1973) -> KernelRefusal {
1974 if sections.is_empty()
1975 || !error.class.perturbation_eligible()
1976 || matches!(error.class, RefusalClass::TangentNodeSingularity)
1977 {
1978 return error;
1979 }
1980 let named = refusal_result_faces(&error.message)
1981 .into_iter()
1982 .filter_map(|id| origins.get(id.checked_sub(1)? as usize).copied())
1983 .collect::<Vec<FaceKey>>();
1984 let involving = |fallback: bool| {
1988 sections.iter().find(|section| {
1989 section.grazing.is_empty() != fallback && named.iter().any(|face| section.faces.contains(face))
1990 })
1991 };
1992 let Some(section) = involving(false).or_else(|| involving(true)) else {
1993 return error;
1994 };
1995 let at = |point: Vec3| {
1998 let shown = |value: f64| if value.abs() < 5e-7 { 0.0 } else { value };
1999 format!("({:.6},{:.6},{:.6})", shown(point.x), shown(point.y), shown(point.z))
2000 };
2001 let pierces = (!section.grazing.is_empty()).then(|| {
2007 let shown = section.grazing.len().min(4);
2008 let mut listed = section.grazing[..shown]
2009 .iter()
2010 .map(|(point, tangency)| format!("{} at |tan·n| = {tangency:.4}", at(*point)))
2011 .collect::<Vec<_>>()
2012 .join(", ");
2013 if section.grazing.len() > shown {
2014 listed.push_str(&format!(" and {} more", section.grazing.len() - shown));
2015 }
2016 listed
2017 });
2018 let pierce_only = section.pierce_only();
2019 let shape = if let (true, Some(pierces)) = (pierce_only, pierces.as_deref()) {
2020 format!(
2021 "cross at a grazing angle: a trim edge pierces the other carrier inside both \
2022 trims at {pierces}, below the marcher's start gate, and no transverse section was \
2023 marched between the pierces — a near-tangent crossing born on a tangent contact \
2024 (a third-order singularity) the imprint does not build yet"
2025 )
2026 } else if section.planar {
2027 format!(
2028 "touch along a tangent curve from {} to {} (length {:.6}, {} stations{}) which the \
2029 imprint does not build yet",
2030 at(section.start),
2031 at(section.end),
2032 section.length,
2033 section.stations,
2034 if section.closed { ", closed" } else { "" }
2035 )
2036 } else {
2037 format!(
2038 "touch along a curve through {} with neither carrier planar, a curved/curved \
2039 tangent contact the lane does not trace yet",
2040 at(section.start)
2041 )
2042 };
2043 let shape = match (pierce_only, pierces) {
2044 (false, Some(pierces)) => format!(
2045 "{shape}; a trim edge also pierces the other carrier inside both trims at {pierces}, \
2046 below the marcher's start gate, with no transverse section marched"
2047 ),
2048 _ => shape,
2049 };
2050 let involved = named
2051 .iter()
2052 .filter(|face| section.faces.contains(face))
2053 .map(|face| format!("{}/{}", face.operand, face.face_id))
2054 .collect::<Vec<_>>()
2055 .join(", ");
2056 KernelRefusal::new(
2057 RefusalClass::TangentNodeSingularity,
2058 error.stage,
2059 format!(
2060 "boolean: unsupported tangent-curve surface intersection between faces {}/{} and {}/{}: \
2061 the carriers {shape}; the refusal names face(s) {involved} the contact involves; {}",
2062 section.first.operand, section.first.face_id, section.second.operand, section.second.face_id,
2063 error.message
2064 ),
2065 )
2066}
2067
2068pub fn refusal_result_faces(message: &str) -> Vec<u64> {
2073 let mut ids = Vec::new();
2074 let digits_after = |text: &str| -> Option<u64> {
2075 let end = text.find(|c: char| !c.is_ascii_digit()).unwrap_or(text.len());
2076 text[..end].parse().ok()
2077 };
2078 for (index, _) in message.match_indices("face ") {
2079 if let Some(id) = digits_after(&message[index + "face ".len()..]) {
2080 ids.push(id);
2081 }
2082 }
2083 if let Some(start) = message.find("on faces [") {
2084 let rest = &message[start + "on faces [".len()..];
2085 let list = &rest[..rest.find(']').unwrap_or(rest.len())];
2086 for entry in list.split(", ") {
2087 let entry = entry.trim_start();
2088 if let Some(id) = digits_after(entry) {
2089 if entry[id.to_string().len()..].starts_with(" '") {
2090 ids.push(id);
2091 }
2092 }
2093 }
2094 }
2095 ids.sort_unstable();
2096 ids.dedup();
2097 ids
2098}
2099
2100pub fn boolean_operation_with_diagnostics(
2101 first: &BrepSolid,
2102 second: &BrepSolid,
2103 operation: BooleanOperation,
2104 options: &BooleanOptions,
2105) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
2106 if let Some(scaled) = WorkingScale::of(&[first, second], options)? {
2107 let mut outcome = boolean_operation_with_diagnostics(&scaled.solids[0], &scaled.solids[1], operation, &scaled.options)
2108 .map_err(|error| scaled.refusal(error))?;
2109 outcome.value = scaled.back(&outcome.value)?;
2110 outcome.diagnostics.count_n("working_scale.fired", 1);
2111 outcome.diagnostics.measure_max("working_scale.factor", scaled.factor);
2112 return Ok(outcome);
2113 }
2114 let _account = profile::Scope::new("boolean.other");
2115 let closed_inputs = matches!(std::env::var("BREP_CLOSED_OPERAND_INPUT").as_deref(), Err(_) | Ok("1") | Ok("on"));
2116 if let (true, Some(later)) = (reseat::seam_reseat_enabled(), &options.seam_reseat_later_references) {
2117 let started = Instant::now();
2118 let (first, second) = reseat::reseat_tangent_seams(first, second, later, options.tolerance);
2119 profile_stage("seam_prepare_ms", started.elapsed().as_secs_f64() * 1000.0);
2120 return boolean_operation_with_diagnostics_impl(&first, &second, operation, options, closed_inputs).map(without_sliver_shells);
2121 }
2122 boolean_operation_with_diagnostics_impl(first, second, operation, options, closed_inputs).map(without_sliver_shells)
2123}
2124
2125fn without_sliver_shells(mut outcome: KernelOutcome<BrepSolid>) -> KernelOutcome<BrepSolid> {
2127 let dropped = drop_sliver_shells(&mut outcome.value);
2128 if dropped > 0 {
2129 outcome.diagnostics.count_n("sliver_shell.dropped", dropped as u64);
2130 }
2131 outcome
2132}
2133
2134pub fn boolean_operation_with_diagnostics_impl(
2135 first: &BrepSolid,
2136 second: &BrepSolid,
2137 operation: BooleanOperation,
2138 options: &BooleanOptions,
2139 closed_inputs: bool,
2140) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
2141 let _coedge_memo = crate::topology::CoedgeMemoScope::open(true);
2144 if matches!(operation, BooleanOperation::Intersect)
2147 && [first, second].iter().any(|body| body.kind == crate::BodyKind::Sheet)
2148 && match std::env::var("BREP_SHEET_TRIM").as_deref() {
2149 Ok("1") => true,
2150 Ok("0") => false,
2151 _ => options.sheet_trim,
2152 }
2153 {
2154 return sheet::trim(first, second, options);
2155 }
2156 if matches!(operation, BooleanOperation::Union | BooleanOperation::Subtract) {
2165 if let Some(operand) = [first, second]
2166 .iter()
2167 .position(|solid| solid.kind == crate::BodyKind::Sheet)
2168 {
2169 return Err(KernelRefusal::input(
2170 KernelStage::Collect,
2171 "sheet_operand",
2172 format!(
2173 "boolean: operand {operand} is a Sheet, which encloses no solid; union and \
2174 subtract of a sheet are refused; Intersect trims a Sheet by a Solid"
2175 ),
2176 ));
2177 }
2178 }
2179 let mut outcome = boolean_operation_with_diagnostics_core(first, second, operation, options)?;
2185 let closure_started = closed_inputs.then(Instant::now);
2186 if closed_inputs {
2187 for (operand, solid) in [first, second].into_iter().enumerate() {
2188 let open = one_use_edges(solid);
2189 if open > 0 {
2190 return Err(KernelRefusal::input(KernelStage::Collect, "operand_closure", format!(
2191 "boolean: operand {operand} is not a closed shell: {open} of its edges bound only one face, so its inside is undefined"
2192 )));
2193 }
2194 }
2195 }
2196 if let Some(started) = closure_started {
2197 let ms = started.elapsed().as_secs_f64() * 1000.0;
2198 profile_stage("operand_closure_ms", ms);
2199 outcome.diagnostics.measure_max("timing.operand_closure_ms", ms);
2200 }
2201 Ok(outcome)
2202}
2203
2204fn boolean_operation_with_diagnostics_core(
2205 first: &BrepSolid, second: &BrepSolid, operation: BooleanOperation, options: &BooleanOptions,
2206) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
2207
2208 if let Some(offset) = crate::recentre::control_offset_at_entry() {
2211 return boolean_operation_with_diagnostics_at_offset(first, second, operation, options, offset);
2212 }
2213 let mut bounds = operand_bounds(first);
2216 bounds.include(operand_bounds(second));
2217 if let Some(offset) = crate::recentre::guard_offset(bounds) {
2218 crate::recentre::profile_fired("boolean", offset, bounds);
2219 let mut outcome = boolean_translated(first, second, operation, options, offset, crate::recentre::EntryKind::Guard)?;
2220 outcome.diagnostics.count_n("recentre.fired", 1);
2221 outcome.diagnostics.measure_max("recentre.distance", offset.length());
2222 return Ok(outcome);
2223 }
2224 let mut tangent_nodes = Vec::new();
2225 let (mut outcome, soundness_candidates) =
2226 boolean_pipeline(first, second, operation, options, &mut tangent_nodes)
2227 .map_err(|error| attribute_to_tangent_node(error, &tangent_nodes))?;
2228 let stage_started = Instant::now();
2241 let accepted = match &soundness_candidates {
2242 Some(candidates) => crate::accept_sound_against_scoped(&[first, second], outcome.value, "boolean", candidates),
2245 None => crate::accept_sound_against(&[first, second], outcome.value, "boolean"),
2246 };
2247 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
2248 profile_stage("soundness_ms", stage_ms);
2249 outcome.diagnostics.measure_max("timing.soundness_ms", stage_ms);
2250 outcome.value = accepted?;
2251 Ok(outcome)
2252}
2253
2254pub fn boolean_operation_with_diagnostics_at_offset(
2258 first: &BrepSolid,
2259 second: &BrepSolid,
2260 operation: BooleanOperation,
2261 options: &BooleanOptions,
2262 offset: Vec3,
2263) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
2264 boolean_translated(first, second, operation, options, offset, crate::recentre::EntryKind::Control)
2265}
2266
2267fn boolean_translated(
2269 first: &BrepSolid,
2270 second: &BrepSolid,
2271 operation: BooleanOperation,
2272 options: &BooleanOptions,
2273 offset: Vec3,
2274 kind: crate::recentre::EntryKind,
2275) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
2276 let _entry = crate::recentre::TranslatedEntry::open(kind);
2277 let translate = |solid: &BrepSolid, offset: Vec3| {
2278 crate::recentre::translate_solid(solid, offset).map_err(|message| {
2279 KernelRefusal::internal(
2280 KernelStage::Collect,
2281 "translation_control",
2282 format!("boolean: the translation control could not move an operand: {message}"),
2283 )
2284 })
2285 };
2286 let moved_first = translate(first, offset)?;
2287 let moved_second = translate(second, offset)?;
2288 let outcome = boolean_operation_with_diagnostics(&moved_first, &moved_second, operation, options)?;
2289 let value = translate(&outcome.value, offset.scale(-1.0))?;
2290 Ok(KernelOutcome { value, diagnostics: outcome.diagnostics })
2291}
2292
2293fn profile_stage(code: &str, ms: f64) {
2297 let row = match code {
2298 "heal_ms" => Some("boolean.operand_prepare"),
2299 "imprint_ms" => Some("boolean.imprint"),
2300 "edge_split_ms" => Some("boolean.edge_split"),
2301 "fragment_ms" => Some("boolean.fragment"),
2302 "select_ms" => Some("boolean.select"),
2303 "assemble_ms" => Some("boolean.assemble"),
2304 "face_merge_ms" => Some("boolean.face_merge"),
2305 "soundness_ms" => Some("boolean.soundness"),
2306 "operand_closure_ms" => Some("boolean.operand_closure"),
2307 "seam_prepare_ms" => Some("boolean.seam_prepare"),
2308 "final_validate_ms" => Some("boolean.final_validate"),
2309 _ => None,
2310 };
2311 if let Some(row) = row { profile::record(row, ms); }
2312 if crate::profile::profile_enabled() {
2313 profile_line!("boolean.{code}={ms:.2}");
2314 }
2315}
2316
2317struct BooleanStageDump {
2322 directory: std::path::PathBuf,
2323 serial: usize,
2324}
2325
2326impl BooleanStageDump {
2327 fn open() -> Option<Self> {
2328 static SERIAL: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
2329 let directory = std::env::var("BREP_BOOLEAN_DUMP").ok().filter(|value| !value.is_empty())?;
2330 let serial = SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2331 Some(Self { directory: directory.into(), serial })
2332 }
2333
2334 fn write<T: Serialize + ?Sized>(&self, stage: &str, value: &T) {
2335 let path = self.directory.join(format!("{:03}-{stage}.json", self.serial));
2336 match serde_json::to_string(value) {
2337 Ok(text) => {
2338 if let Err(error) = std::fs::write(&path, text) {
2339 eprintln!("BREP_BOOLEAN_DUMP {}: {error}", path.display());
2340 }
2341 }
2342 Err(error) => eprintln!("BREP_BOOLEAN_DUMP {stage}: {error}"),
2343 }
2344 }
2345}
2346
2347pub fn boolean_policy(
2349 first: &BrepSolid,
2350 second: &BrepSolid,
2351 options: &BooleanOptions,
2352) -> Result<KernelTolerances, KernelRefusal> {
2353 let policy = options
2354 .tolerances
2355 .unwrap_or_else(|| KernelTolerances::for_pair(first, second, options.tolerance));
2356 policy.check().or_input(KernelStage::Collect, "tolerances")?;
2357 Ok(policy)
2358}
2359
2360fn prepared_operands(
2363 first: &BrepSolid,
2364 second: &BrepSolid,
2365 policy: &KernelTolerances,
2366) -> Result<(BrepSolid, BrepSolid), KernelRefusal> {
2367 let stage_started = Instant::now();
2376 let mut first_owned = first.clone();
2377 let mut second_owned = second.clone();
2378 crate::heal::heal_operands(&mut first_owned, policy)?;
2379 crate::heal::heal_operands(&mut second_owned, policy)?;
2380 profile_stage("heal.operands_ms", stage_started.elapsed().as_secs_f64() * 1_000.0);
2381 let refit_started = Instant::now();
2385 crate::heal::refit_inherited_trims_reused(&mut first_owned, policy)?;
2386 crate::heal::refit_inherited_trims_reused(&mut second_owned, policy)?;
2387 profile_stage("heal.refit_ms", refit_started.elapsed().as_secs_f64() * 1_000.0);
2388 if crate::profile::profile_enabled() {
2389 let (hits, misses) = crate::reading_memo::counts();
2390 profile_line!("boolean.reading_memo hits={hits} misses={misses}");
2391 let (served, stored) = crate::heal::refit_memo_counts_served_stored();
2392 profile_line!("boolean.refit_memo served={served} stored={stored}");
2393 }
2394 profile_stage("heal_ms", stage_started.elapsed().as_secs_f64() * 1_000.0);
2395 normalize_operand_band_seams(&mut first_owned)?;
2400 normalize_operand_band_seams(&mut second_owned)?;
2401 Ok((first_owned, second_owned))
2402}
2403
2404fn boolean_imprint_options(options: &BooleanOptions, tolerance: f64) -> ImprintOptions {
2405 let mut imprint_options = options.imprint.clone();
2406 imprint_options.tolerance = tolerance;
2407 imprint_options
2408}
2409
2410pub fn boolean_split_operands(
2420 first: &BrepSolid,
2421 second: &BrepSolid,
2422 options: &BooleanOptions,
2423) -> Result<(BrepSolid, BrepSolid), KernelRefusal> {
2424 if let Some(scaled) = WorkingScale::of(&[first, second], options)? {
2425 let (split_first, split_second) = boolean_split_operands(&scaled.solids[0], &scaled.solids[1], &scaled.options)
2426 .map_err(|error| scaled.refusal(error))?;
2427 return Ok((scaled.back(&split_first)?, scaled.back(&split_second)?));
2428 }
2429 let policy = boolean_policy(first, second, options)?;
2430 let (first, second) = prepared_operands(first, second, &policy)?;
2431 let imprint = build_imprints(&first, &second, &boolean_imprint_options(options, policy.model))?;
2432 let (split_first, _) = apply_edge_splits_with_map(&first, 0, &imprint)?;
2433 let (split_second, _) = apply_edge_splits_with_map(&second, 1, &imprint)?;
2434 Ok((split_first, split_second))
2435}
2436
2437fn operand_bounds(solid: &BrepSolid) -> crate::Aabb {
2441 let mut bounds = crate::Aabb::from_points(solid.vertices.iter().map(|vertex| vertex.point));
2442 for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
2443 match crate::Aabb::from_surface_controls(&face.surface) {
2444 Ok(face_bounds) => bounds.include(face_bounds),
2445 Err(_) => {
2446 return crate::Aabb {
2447 minimum: Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY),
2448 maximum: Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY),
2449 }
2450 }
2451 }
2452 }
2453 bounds
2454}
2455
2456fn line_or_point_contact(first: &BrepSolid, second: &BrepSolid, bounds: [crate::Aabb; 2]) -> bool {
2462 apart_axes(bounds) >= 2 && plain_hull_solid(first) && plain_hull_solid(second)
2463}
2464
2465fn boxes_share_no_interior(first: &BrepSolid, second: &BrepSolid, bounds: [crate::Aabb; 2]) -> bool {
2468 apart_axes(bounds) >= 1 && plain_hull_solid(first) && plain_hull_solid(second)
2469}
2470
2471fn apart_axes([a, b]: [crate::Aabb; 2]) -> usize {
2473 let apart = |a_min: f64, a_max: f64, b_min: f64, b_max: f64| a_max <= b_min || b_max <= a_min;
2474 [
2475 apart(a.minimum.x, a.maximum.x, b.minimum.x, b.maximum.x),
2476 apart(a.minimum.y, a.maximum.y, b.minimum.y, b.maximum.y),
2477 apart(a.minimum.z, a.maximum.z, b.minimum.z, b.maximum.z),
2478 ]
2479 .into_iter()
2480 .filter(|&apart| apart)
2481 .count()
2482}
2483
2484fn plain_hull_solid(solid: &BrepSolid) -> bool {
2486 solid.kind == crate::BodyKind::Solid
2487 && solid.cells.is_empty()
2488 && solid.shells.iter().flat_map(|shell| &shell.faces).all(|face| {
2489 face.surface.control_points.iter().flatten().all(|control| control.w > 0.0 && control.w.is_finite())
2490 })
2491}
2492
2493fn scope_proved_apart_on() -> bool {
2497 switch!(live "BREP_SCOPE_PROVED_APART", true)
2498}
2499
2500fn soundness_candidates(
2515 solid: &BrepSolid,
2516 scope: &AssemblyScope,
2517 bounds: [crate::Aabb; 2],
2518 band: f64,
2519 unproved: Option<&HashSet<crate::imprint::FaceKey>>,
2520) -> HashSet<u64> {
2521 let mut candidates = HashSet::default();
2522 for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
2523 if scope.examined.contains(&face.id) {
2524 candidates.insert(face.id);
2525 continue;
2526 }
2527 let Some(&operand) = scope.operand_of.get(&face.id) else {
2528 candidates.insert(face.id);
2529 continue;
2530 };
2531 let other = bounds[usize::from(operand == 0)];
2532 match crate::Aabb::from_surface_controls(&face.surface) {
2533 Ok(face_bounds) if !face_bounds.intersects(other, band) => {}
2534 _ => {
2535 let proved_clear = unproved.is_some_and(|unproved| {
2536 scope.source_of.get(&face.id).is_some_and(|key| !unproved.contains(key))
2537 });
2538 if !proved_clear {
2539 candidates.insert(face.id);
2540 }
2541 }
2542 }
2543 }
2544 candidates
2545}
2546
2547
2548fn empty_solid() -> BrepSolid {
2550 BrepSolid {
2551 mass_properties_cache: Default::default(),
2552 cells: Default::default(),
2553 id: 0,
2554 vertices: Vec::new(),
2555 edges: Vec::new(),
2556 shells: Vec::new(),
2557 genus: 0,
2558 kind: crate::BodyKind::Solid,
2559 }
2560}
2561
2562fn concatenate_disjoint(first: &BrepSolid, second: &BrepSolid) -> BrepSolid {
2568 let mut vertices = Vec::new();
2569 let mut edges = Vec::new();
2570 let mut shells = Vec::new();
2571 let mut used_face_names = HashSet::<String>::default();
2572 let (mut next_face_id, mut next_loop_id, mut next_coedge_id) = (1u64, 1u64, 1u64);
2573 for operand in [first, second] {
2574 let vertex_base = vertices.len() as u64;
2575 let edge_base = edges.len() as u64;
2576 let mut vertex_ids: HashMap<u64, u64> = HashMap::default();
2577 for (index, vertex) in operand.vertices.iter().enumerate() {
2578 let id = vertex_base + index as u64 + 1;
2579 vertex_ids.insert(vertex.id, id);
2580 vertices.push(VertexRecord { id, point: vertex.point });
2581 }
2582 let mut edge_ids: HashMap<u64, u64> = HashMap::default();
2583 for (index, edge) in operand.edges.iter().enumerate() {
2584 let id = edge_base + index as u64 + 1;
2585 edge_ids.insert(edge.id, id);
2586 edges.push(EdgeRecord {
2587 id,
2588 curve: edge.curve.clone(),
2589 t0: edge.t0,
2590 t1: edge.t1,
2591 start_vertex_id: vertex_ids.get(&edge.start_vertex_id).copied().unwrap_or(edge.start_vertex_id),
2592 end_vertex_id: vertex_ids.get(&edge.end_vertex_id).copied().unwrap_or(edge.end_vertex_id),
2593 degenerate: edge.degenerate,
2594 name: edge.name.clone(),
2595 });
2596 }
2597 for shell in &operand.shells {
2598 let mut faces = Vec::with_capacity(shell.faces.len());
2599 for face in &shell.faces {
2600 let loops = face
2601 .loops
2602 .iter()
2603 .map(|loop_record| {
2604 let coedges = loop_record
2605 .coedges
2606 .iter()
2607 .map(|coedge| {
2608 let id = next_coedge_id;
2609 next_coedge_id += 1;
2610 CoedgeRecord {
2611 id,
2612 edge_id: edge_ids.get(&coedge.edge_id).copied().unwrap_or(coedge.edge_id),
2613 forward: coedge.forward,
2614 pcurve: coedge.pcurve.clone(),
2615 }
2616 })
2617 .collect();
2618 let id = next_loop_id;
2619 next_loop_id += 1;
2620 LoopRecord { id, coedges }
2621 })
2622 .collect();
2623 let name = face.name.clone().map(|base| {
2624 if used_face_names.insert(base.clone()) {
2625 base
2626 } else {
2627 let mut suffix = 1usize;
2628 loop {
2629 let candidate = format!("{base}_{suffix}");
2630 if used_face_names.insert(candidate.clone()) {
2631 break candidate;
2632 }
2633 suffix += 1;
2634 }
2635 }
2636 });
2637 faces.push(FaceRecord {
2638 id: next_face_id,
2639 surface: face.surface.clone(),
2640 same_sense: face.same_sense,
2641 loops,
2642 name,
2643 });
2644 next_face_id += 1;
2645 }
2646 shells.push(ShellRecord { id: shells.len() as u64 + 1, faces });
2647 }
2648 }
2649 BrepSolid {
2650 mass_properties_cache: Default::default(),
2651 cells: Default::default(),
2652 id: 1,
2653 vertices,
2654 edges,
2655 shells,
2656 genus: first.genus + second.genus,
2657 kind: crate::BodyKind::Solid,
2658 }
2659}
2660
2661fn boolean_pipeline(
2664 first: &BrepSolid,
2665 second: &BrepSolid,
2666 operation: BooleanOperation,
2667 options: &BooleanOptions,
2668 tangent_nodes: &mut Vec<Vec3>,
2669) -> Result<(KernelOutcome<BrepSolid>, Option<HashSet<u64>>), KernelRefusal> {
2670 let _work = crate::imprint::work_profile::Scope::open("boolean");
2671 let replaced_operands = operand_state::replace_operands(first, second, operation, options);
2672 let (first, second) = match &replaced_operands {
2673 Some((first, second)) => (first, second),
2674 None => (first, second),
2675 };
2676 let policy = boolean_policy(first, second, options)?;
2677 let tolerance = policy.model;
2678 let bounds = [operand_bounds(first), operand_bounds(second)];
2693 let disjoint = disjoint_fast_path(options) && !bounds[0].intersects(bounds[1], policy.sew_search);
2694 let contact = !disjoint
2695 && contact_fast_path(options)
2696 && options.seam_reseat_later_references.is_some()
2697 && line_or_point_contact(first, second, bounds);
2698 let contact = contact
2703 || (!disjoint
2704 && matches!(operation, BooleanOperation::Intersect)
2705 && contact_fast_path(options)
2706 && boxes_share_no_interior(first, second, bounds));
2707 if disjoint || contact {
2708 let operation_started = Instant::now();
2709 let mut diagnostics = KernelDiagnostics::default();
2710 diagnostics.count_n(
2711 "collect.faces",
2712 first.shells.iter().chain(&second.shells).map(|shell| shell.faces.len() as u64).sum(),
2713 );
2714 diagnostics.count(if contact { "boolean.contact_fast_path" } else { "boolean.disjoint_fast_path" });
2715 diagnostics.measure_max("tolerance.model", policy.model);
2716 diagnostics.measure_max("tolerance.sew_search", policy.sew_search);
2717 let value = match operation {
2718 BooleanOperation::Union => concatenate_disjoint(first, second),
2719 BooleanOperation::Subtract => first.clone(),
2720 BooleanOperation::Intersect => {
2721 diagnostics.event(
2722 DiagnosticSeverity::Info,
2723 KernelStage::Select,
2724 "boolean.empty_result",
2725 format!("{operation:?} of witnessed-non-overlapping operands is empty"),
2726 );
2727 empty_solid()
2728 }
2729 };
2730 let stage_ms = operation_started.elapsed().as_secs_f64() * 1_000.0;
2731 profile_stage("disjoint_fast_path_ms", stage_ms);
2732 diagnostics.measure_max("timing.total_ms", stage_ms);
2733 return Ok((KernelOutcome { value, diagnostics }, Some(HashSet::default())));
2734 }
2735 let heal_started = Instant::now();
2736 let (first_owned, second_owned) = prepared_operands(first, second, &policy)?;
2737 let heal_ms = heal_started.elapsed().as_secs_f64() * 1_000.0;
2738 let first = &first_owned;
2739 let second = &second_owned;
2740
2741 let mut diagnostics = KernelDiagnostics::default();
2742 diagnostics.measure_max("timing.heal_ms", heal_ms);
2745 let fit_scope = crate::PcurveFitScope::open();
2750 let polyline_scope = crate::PolylineFitScope::open();
2754 let operation_started = Instant::now();
2755 diagnostics.count_n(
2756 "collect.faces",
2757 first
2758 .shells
2759 .iter()
2760 .chain(&second.shells)
2761 .map(|shell| shell.faces.len() as u64)
2762 .sum(),
2763 );
2764 diagnostics.measure_max("tolerance.model", policy.model);
2765 diagnostics.measure_max("tolerance.sew_search", policy.sew_search);
2766
2767 let imprint_options = boolean_imprint_options(options, tolerance);
2768 let stage_started = Instant::now();
2769 let imprint = build_imprints(first, second, &imprint_options)?;
2770 tangent_nodes.extend_from_slice(&imprint.tangent_nodes);
2771 if std::env::var("BREP_DEBUG_BOOL").is_ok() {
2772 for piece in &imprint.pieces {
2773 let start = piece.curve.evaluate(piece.t0);
2774 let end = piece.curve.evaluate(piece.t1);
2775 eprintln!(
2776 "piece {} supports={:?} t=[{:.6},{:.6}] start={:?} end={:?}",
2777 piece.id, piece.support_faces, piece.t0, piece.t1, start, end
2778 );
2779 }
2780 for entry in &imprint.by_face {
2781 eprintln!(
2782 "by_face operand={} face={} pieces={:?}",
2783 entry.operand, entry.face_id, entry.piece_ids
2784 );
2785 }
2786 for split in &imprint.edge_splits {
2787 eprintln!(
2788 "edge_split operand={} edge={} params={:?}",
2789 split.operand, split.edge_id, split.parameters
2790 );
2791 }
2792 }
2793 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
2794 profile_stage("imprint_ms", stage_ms);
2795 diagnostics.measure_max("timing.imprint_ms", stage_ms);
2796 diagnostics.count_n("intersect.pieces", imprint.pieces.len() as u64);
2797 diagnostics.count_n("intersect.vertices", imprint.vertices.len() as u64);
2798 diagnostics.count_n("intersect.edge_splits", imprint.edge_splits.len() as u64);
2799 let (march_swap_rescues, clip_swap_rescues) = crate::imprint::take_rescue_firings();
2800 diagnostics.count_n("intersect.march_swap_rescue", march_swap_rescues);
2801 diagnostics.count_n("intersect.clip_swap_rescue", clip_swap_rescues);
2802 let touch = TouchCensus::build([first, second], &imprint);
2803 touch.report(&mut diagnostics);
2804 let stage_started = Instant::now();
2805 let (split_first, split_map_first) = apply_edge_splits_with_map(first, 0, &imprint)?;
2806 let (split_second, split_map_second) = apply_edge_splits_with_map(second, 1, &imprint)?;
2807 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
2808 profile_stage("edge_split_ms", stage_ms);
2809 diagnostics.measure_max("timing.edge_split_ms", stage_ms);
2810 let stage_started = Instant::now();
2811 crate::classification::classify_profile_begin();
2812 let fragments_a = crate::fragment::fragment_solid_against(&split_first, 0, &imprint, crate::fragment::bounded_carriers(second).then_some((bounds[1], policy.sew_search)))?;
2813 let fragments_b = crate::fragment::fragment_solid_against(&split_second, 1, &imprint, crate::fragment::bounded_carriers(first).then_some((bounds[0], policy.sew_search)))?;
2814 crate::classification::classify_profile_report("fragment");
2815 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
2816 profile_stage("fragment_ms", stage_ms);
2817 diagnostics.measure_max("timing.fragment_ms", stage_ms);
2818 diagnostics.count_n(
2819 "fragment.candidates",
2820 (fragments_a.len() + fragments_b.len()) as u64,
2821 );
2822 touch.report_fragments(&[&fragments_a, &fragments_b], &mut diagnostics);
2823 let a_surface_samples: Vec<Vec3> = fragments_a
2828 .iter()
2829 .flat_map(|fragment| {
2830 std::iter::once(fragment.test_point).chain(fragment.extra_test_points.iter().copied())
2831 })
2832 .collect();
2833 let b_surface_samples: Vec<Vec3> = fragments_b
2834 .iter()
2835 .flat_map(|fragment| {
2836 std::iter::once(fragment.test_point).chain(fragment.extra_test_points.iter().copied())
2837 })
2838 .collect();
2839 let stage_started = Instant::now();
2840 let mut barrier_edges: HashSet<(u8, u64)> = imprint
2841 .pieces
2842 .iter()
2843 .filter_map(|piece| piece.shared_edge.map(|(operand, edge_id, _)| (operand, edge_id)))
2844 .collect();
2845 barrier_edges.extend(imprint.barrier_edges.iter().copied());
2846 for (operand, split_map) in [(0u8, &split_map_first), (1u8, &split_map_second)] {
2852 let minted: Vec<(u8, u64)> = barrier_edges
2853 .iter()
2854 .filter(|(barrier_operand, _)| *barrier_operand == operand)
2855 .filter_map(|(_, edge_id)| split_map.get(edge_id))
2856 .flat_map(|sub_ids| sub_ids.iter().map(|sub_id| (operand, *sub_id)))
2857 .collect();
2858 barrier_edges.extend(minted);
2859 }
2860 crate::classification::classify_profile_begin();
2861 let coincident = coincident_pairs(
2862 &fragments_a,
2863 &fragments_b,
2864 first,
2865 second,
2866 &imprint.cosurface_pairs,
2867 tolerance,
2868 )?;
2869 let sector_mode = sector::sector_mode(options);
2870 let mut select_census = sector::SelectCensus::default();
2871 let mut selected = select_fragments(
2872 fragments_a,
2873 fragments_b,
2874 first,
2875 second,
2876 operation,
2877 tolerance,
2878 &barrier_edges,
2879 &imprint,
2880 &coincident,
2881 sector_mode,
2882 &mut select_census,
2883 )?;
2884 let resewn = resew_coincident_rims(
2885 &mut selected,
2886 [&split_first, &split_second],
2887 [first, second],
2888 &imprint.cosurface_pairs,
2889 operation,
2890 tolerance,
2891 )?;
2892 diagnostics.count_n("select.coincident_pairs", coincident.len() as u64);
2893 diagnostics.count_n("select.rims_resewn", resewn as u64);
2894 crate::classification::classify_profile_report("select");
2895 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
2896 profile_stage("select_ms", stage_ms);
2897 diagnostics.measure_max("timing.select_ms", stage_ms);
2898 diagnostics.count_n("select.fragments", selected.len() as u64);
2899 diagnostics.count_n("select.sector_eligible", select_census.eligible);
2901 diagnostics.count_n("select.sector_primary", select_census.sector_primary);
2902 diagnostics.count_n("select.sector_fallback", select_census.sector_fallback);
2903 diagnostics.count_n("select.sector_disagree", select_census.disagree);
2904 diagnostics.count_n("select.ray_casts", select_census.ray_casts);
2905 diagnostics.count_n("select.on_votes", select_census.on_votes);
2906 diagnostics.count_n("select.overturns", select_census.overturns);
2907 if sector_mode != sector::SectorMode::Off || std::env::var_os("BREP_SECTOR_CENSUS").is_some() {
2908 sector::sector_census_line(|| {
2909 format!(
2910 "selection mode={sector_mode:?} select_ms={stage_ms:.3} selected={} eligible={} primary={} fallback={} disagree={} ray_casts={} on_votes={} overturns={}",
2911 selected.len(),
2912 select_census.eligible,
2913 select_census.sector_primary,
2914 select_census.sector_fallback,
2915 select_census.disagree,
2916 select_census.ray_casts,
2917 select_census.on_votes,
2918 select_census.overturns
2919 )
2920 });
2921 }
2922 if selected.is_empty()
2944 && !imprint.section_evidence
2945 && std::env::var("BREP_EMPTY_BOOLEAN").as_deref() != Ok("0")
2946 {
2947 let strictly_inside = |samples: &[Vec3], other: &BrepSolid| -> Result<bool, KernelRefusal> {
2948 for &sample in samples {
2949 if classify_point(sample, other, tolerance).or_refuse(KernelStage::Validate, "classify_point")?.class == PointClass::In {
2950 return Ok(true);
2951 }
2952 }
2953 Ok(false)
2954 };
2955 let outside_witness = |samples: &[Vec3], other: &BrepSolid| -> Result<bool, KernelRefusal> {
2956 for &sample in samples {
2957 if classify_point(sample, other, tolerance).or_refuse(KernelStage::Validate, "classify_point")?.class == PointClass::Out {
2958 return Ok(true);
2959 }
2960 }
2961 Ok(false)
2962 };
2963 let legitimate = match operation {
2964 BooleanOperation::Intersect => {
2965 !strictly_inside(&a_surface_samples, second)?
2966 && !strictly_inside(&b_surface_samples, first)?
2967 }
2968 BooleanOperation::Subtract => !outside_witness(&a_surface_samples, second)?,
2969 BooleanOperation::Union => false,
2970 };
2971 if legitimate {
2972 diagnostics.event(
2973 DiagnosticSeverity::Info,
2974 KernelStage::Select,
2975 "boolean.empty_result",
2976 format!("{operation:?} of witnessed-non-overlapping operands is empty"),
2977 );
2978 fit_scope.close().report_into(&mut diagnostics);
2979 polyline_scope.close().report_into(&mut diagnostics);
2980 diagnostics.measure_max(
2981 "timing.total_ms",
2982 operation_started.elapsed().as_secs_f64() * 1_000.0,
2983 );
2984 return Ok((
2985 KernelOutcome {
2986 value: empty_solid(),
2987 diagnostics,
2988 },
2989 None,
2990 ));
2991 }
2992 }
2993 let solids = [(0, &split_first), (1, &split_second)]
2994 .into_iter()
2995 .collect::<HashMap<_, _>>();
2996 let dump = BooleanStageDump::open();
2997 if let Some(dump) = &dump {
2998 dump.write("first", &split_first);
2999 dump.write("second", &split_second);
3000 dump.write("selected", &selected);
3001 }
3002 let stage_started = Instant::now();
3003 let assembled_origins: Vec<FaceKey> = if imprint.tangent_sections.is_empty() {
3007 Vec::new()
3008 } else {
3009 selected
3010 .iter()
3011 .map(|fragment| FaceKey { operand: fragment.operand, face_id: fragment.source_face_id })
3012 .collect()
3013 };
3014 let attributable: Vec<crate::imprint::TangentSectionRecord> = imprint
3021 .tangent_sections
3022 .iter()
3023 .filter(|section| imprint.tangent_nodes.is_empty() || section.grazing.is_empty())
3024 .cloned()
3025 .collect();
3026 let attribute = |error: KernelRefusal| {
3027 attribute_to_tangent_section(error, &attributable, &assembled_origins)
3028 };
3029 let cellular_result = matches!(operation, BooleanOperation::Union)
3030 && cellular::enabled(options)
3031 && cellular::complete_contact(first, second, &selected, tolerance);
3032 let (solid, scope) = if cellular_result {
3033 (assemble::assemble_cellular_fragments(selected, &solids, &imprint, tolerance)
3034 .map_err(attribute)?, None)
3035 } else if untouched_passthrough(options) {
3036 assemble_fragments_scoped(selected, &solids, &imprint, tolerance, &touch, touched_assembly(options))
3037 .map_err(attribute)?
3038 } else {
3039 (assemble_fragments(selected, &solids, &imprint, tolerance).map_err(attribute)?, None)
3040 };
3041 if let Some(scope) = &scope {
3042 diagnostics.count_n("passthrough.faces_examined", scope.examined.len() as u64);
3043 }
3044 if let Some(dump) = &dump {
3045 dump.write("assembled", &solid);
3046 }
3047 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
3048 profile_stage("assemble_ms", stage_ms);
3049 diagnostics.measure_max("timing.assemble_ms", stage_ms);
3050 let stage_started = Instant::now();
3051 let declines_before = crate::face_merge::declines_served();
3052 let area_checks_before = crate::face_merge::boundary_area_checks();
3053 if std::env::var("BREP_DEBUG_PREMERGE_VALIDATE").is_ok() {
3054 let issues = solid.validate();
3055 eprintln!(
3056 "pre-merge validation: {} issue(s){}",
3057 issues.len(),
3058 issues
3059 .first()
3060 .map(|issue| format!(" — first: {}", issue.message))
3061 .unwrap_or_default()
3062 );
3063 }
3064 let solid = if solid.kind != crate::BodyKind::Cellular && options.merge_coplanar_faces
3065 && std::env::var("BREP_COPLANAR_MERGE").as_deref() != Ok("0")
3066 {
3067 let merged = match &scope {
3068 Some(scope) => merge_same_surface_faces_scoped(
3072 &solid,
3073 tolerance,
3074 &options.keep_unmerged_name_substrs,
3075 &scope.examined,
3076 )?,
3077 None => merge_same_surface_faces_excluding(
3078 &solid,
3079 tolerance,
3080 &options.keep_unmerged_name_substrs,
3081 )?,
3082 };
3083 let merged = merge_curve_continuation_edges(&merged, tolerance).map_err(|refusal| KernelRefusal { stage: KernelStage::Validate, ..refusal })?;
3088 rejoin::rejoin_unless_referenced(merged, options, tolerance)
3089 } else {
3090 solid
3091 };
3092 if let Some(dump) = &dump {
3093 dump.write("merged", &solid);
3094 }
3095 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
3096 profile_stage("face_merge_ms", stage_ms);
3097 if crate::profile::profile_enabled() {
3098 profile_line!("boolean.merge_declines served={}", crate::face_merge::declines_served() - declines_before);
3099 let area_checks = crate::face_merge::boundary_area_checks();
3100 if area_checks != area_checks_before {
3101 profile_line!("boolean.merge_area_checks boundary={} integrated={}", area_checks.0 - area_checks_before.0, area_checks.1 - area_checks_before.1);
3102 }
3103 }
3104 diagnostics.measure_max("timing.face_merge_ms", stage_ms);
3105 let validation_started = Instant::now();
3106 let validation = solid.validate_detailed_scoped(&policy, scope.as_ref().map(|scope| &scope.examined));
3107 profile_stage("final_validate_ms", validation_started.elapsed().as_secs_f64() * 1000.0);
3108 diagnostics.count_n("validate.issues", validation.issues.len() as u64);
3109 diagnostics.count_n(
3110 "validate.wire_warnings",
3111 validation.wire_warnings.len() as u64,
3112 );
3113 diagnostics.measure_max("validate.max_pcurve_error", validation.max_pcurve_error);
3114 for warning in &validation.wire_warnings {
3115 diagnostics.event(
3116 DiagnosticSeverity::Warning,
3117 KernelStage::Validate,
3118 "validate.uv_wire",
3119 warning.message.clone(),
3120 );
3121 }
3122 for issue in &validation.issues {
3123 diagnostics.event(
3124 DiagnosticSeverity::Error,
3125 KernelStage::Validate,
3126 "validate.brep",
3127 issue.message.clone(),
3128 );
3129 }
3130 fit_scope.close().report_into(&mut diagnostics);
3131 polyline_scope.close().report_into(&mut diagnostics);
3132 diagnostics.measure_max(
3133 "timing.total_ms",
3134 operation_started.elapsed().as_secs_f64() * 1_000.0,
3135 );
3136 if !validation.issues.is_empty() {
3137 return Err(KernelRefusal::new(
3138 RefusalClass::InvalidResultTopology { issues: validation.issues.len() as u32 },
3139 KernelStage::Validate,
3140 format!(
3141 "boolean_operation: invalid result: {:?}",
3142 validation.issues
3143 )));
3144 }
3145 if std::env::var("BREP_DEBUG_BOOL").is_ok() {
3151 if let Ok(report) =
3152 crate::oracle::boolean_semantic_disagreement(first, second, operation, &solid, 200)
3153 {
3154 if report.is_flagged() {
3155 eprintln!(
3156 "[oracle] semantic disagreement rate {:.4} ({} of {} decidable points); sample {:?}",
3157 report.disagreement_rate,
3158 report.disagreements.len(),
3159 report.considered,
3160 report.sample_disagreement()
3161 );
3162 }
3163 }
3164 let fusable_band = crate::tolerance::assembler_weld(policy.model);
3165 let fusables = crate::oracle::boolean_residual_fusables(&solid, fusable_band);
3166 if !fusables.is_empty() {
3167 eprintln!(
3168 "[oracle] {} residual fusable(s) after weld; sample {:?}",
3169 fusables.len(),
3170 fusables.first()
3171 );
3172 }
3173 }
3174 let candidates = scope.as_ref().map(|scope| {
3175 let unproved = (scope_proved_apart_on() && plain_hull_solid(first) && plain_hull_solid(second))
3176 .then(|| imprint.faces_in_unproved_pairs.as_ref())
3177 .flatten()
3178 .map(|faces| faces.iter().copied().collect::<HashSet<_>>());
3179 let candidates = soundness_candidates(
3180 &solid,
3181 scope,
3182 [operand_bounds(first), operand_bounds(second)],
3183 policy.sew_search,
3184 unproved.as_ref(),
3185 );
3186 diagnostics.count_n("passthrough.soundness_candidates", candidates.len() as u64);
3187 crate::soundness::census::profile_operation(&solid, &[first, second], Some(&scope.touched), "boolean");
3188 candidates
3189 });
3190 Ok((
3191 KernelOutcome {
3192 value: solid,
3193 diagnostics,
3194 },
3195 candidates,
3196 ))
3197}
3198