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}
127
128fn touched_assembly(options: &BooleanOptions) -> bool {
130 match std::env::var("BREP_TOUCHED_ASSEMBLY").as_deref() {
131 Ok("0") => false,
132 Ok(_) => true,
133 Err(_) => options.touched_assembly,
134 }
135}
136
137fn disjoint_fast_path(options: &BooleanOptions) -> bool {
139 match std::env::var("BREP_DISJOINT_FAST_PATH").as_deref() {
140 Ok("0") => false,
141 Ok(_) => true,
142 Err(_) => options.disjoint_fast_path,
143 }
144}
145
146fn contact_fast_path(options: &BooleanOptions) -> bool {
148 match std::env::var("BREP_CONTACT_FAST_PATH").as_deref() {
149 Ok("0") => false,
150 Ok(_) => true,
151 Err(_) => options.contact_fast_path,
152 }
153}
154
155fn untouched_passthrough(options: &BooleanOptions) -> bool {
157 match std::env::var("BREP_UNTOUCHED_PASSTHROUGH").as_deref() {
158 Ok("0") => false,
159 Ok(_) => true,
160 Err(_) => options.untouched_passthrough,
161 }
162}
163
164fn default_tolerance() -> f64 {
165 1e-7
166}
167
168fn default_true() -> bool {
169 true
170}
171
172impl Default for BooleanOptions {
173 fn default() -> Self {
174 Self {
175 tolerance: default_tolerance(),
176 tolerances: None,
177 imprint: ImprintOptions::default(),
178 merge_coplanar_faces: true,
179 keep_unmerged_name_substrs: Vec::new(),
180 untouched_passthrough: true,
181 disjoint_fast_path: true,
182 contact_fast_path: true,
183 touched_assembly: false,
184 sector_classification: true,
185 sheet_trim: true,
186 keep_cells: false,
187 seam_reseat_later_references: None,
188 }
189 }
190}
191
192mod select;
193mod sheet;
194mod cellular;
195pub mod sector;
196pub mod assemble;
197mod operand_state;
198mod rim;
199mod coincident;
200mod touch;
201mod reseat;
202
203pub use rim::*;
204use select::*;
205use coincident::*;
206use touch::TouchCensus;
207pub use assemble::{
208 assemble_fragments, assemble_open_fragments, commit_nearby_edge_endpoints,
209 clear_candidate_memo, edge_interior_lies_on, finalize_assembled_solid, refresh_derived_genus,
210};
211use assemble::{assemble_fragments_scoped, AssemblyScope};
212#[allow(unused_imports)]
214pub use assemble::apply_assembly_heal_chain;
215
216
217struct WorkingScale {
220 factor: f64,
221 solids: Vec<BrepSolid>,
222 options: BooleanOptions,
223}
224
225impl WorkingScale {
226 fn of(operands: &[&BrepSolid], options: &BooleanOptions) -> Result<Option<Self>, KernelRefusal> {
227 let Some(bounds) = crate::rescale::bounds_of(operands.iter().copied()) else {
228 return Ok(None);
229 };
230 let Some(factor) = crate::rescale::guard_factor(bounds) else {
231 return Ok(None);
232 };
233 crate::rescale::profile_fired("boolean", factor, bounds);
234 let solids = operands
235 .iter()
236 .map(|solid| crate::rescale::scale_operand(solid, factor, "boolean"))
237 .collect::<Result<Vec<_>, _>>()?;
238 let mut options = options.clone();
240 options.imprint.maximum_ssi_step = options.imprint.maximum_ssi_step.map(|step| step * factor);
241 Ok(Some(Self { factor, solids, options }))
242 }
243
244 fn back(&self, solid: &BrepSolid) -> Result<BrepSolid, KernelRefusal> {
245 crate::rescale::scale_operand(solid, 1.0 / self.factor, "boolean")
246 }
247
248 fn refusal(&self, error: KernelRefusal) -> KernelRefusal {
249 crate::rescale::name_scale(error, self.factor)
250 }
251}
252
253pub fn boolean_operation(
254 first: &BrepSolid,
255 second: &BrepSolid,
256 operation: BooleanOperation,
257 options: &BooleanOptions,
258) -> Result<BrepSolid, KernelRefusal> {
259 if let Some(scaled) = WorkingScale::of(&[first, second], options)? {
260 return boolean_operation(&scaled.solids[0], &scaled.solids[1], operation, &scaled.options)
261 .map_err(|error| scaled.refusal(error))
262 .and_then(|solid| scaled.back(&solid));
263 }
264 match boolean_operation_with_diagnostics(first, second, operation, options) {
265 Ok(outcome) => {
266 if below_tolerance_refusal_enabled()
269 && outcome.value.shells.iter().all(|shell| shell.faces.is_empty())
270 && !matches!(operation, BooleanOperation::Union)
271 {
272 if let Some(refusal) = below_tolerance_refusal(first, second, None) {
273 return Err(refusal);
274 }
275 }
276 if unresolved_merge_refusal_enabled() && !matches!(operation, BooleanOperation::Subtract) {
277 if let Some(refusal) = unresolved_merge_refusal(first, second) {
278 return Err(refusal);
279 }
280 }
281 Ok(outcome.value)
282 }
283 Err(error) => {
284 if below_tolerance_refusal_enabled() {
285 if let Some(refusal) = below_tolerance_refusal(first, second, Some(&error)) {
286 return Err(refusal);
287 }
288 }
289 if std::env::var("BREP_NO_PERTURB").as_deref() == Ok("1")
297 || !error.class.perturbation_eligible()
298 {
299 return Err(error);
300 }
301 if std::env::var("BREP_OPEN_OPERAND_GATE").as_deref() != Ok("0") {
323 if let Some((operand, open)) = [first, second]
324 .iter()
325 .enumerate()
326 .find_map(|(operand, solid)| {
327 let open = one_use_edges(solid);
328 (open > 0).then_some((operand, open))
329 })
330 {
331 return Err(error.with_message(|message| format!(
332 "{message}; operand {operand} is not a closed shell: {open} of its edges bound \
333 only one face, so no boolean of it encloses a solid and no perturbation \
334 can close it"
335 )));
336 }
337 }
338 if let Some((operand, face_id, deviation, weld)) =
339 planar_operand_off_its_plane(first, second, options)
340 {
341 return Err(error.with_message(|message| format!(
342 "{message}; operand {operand} face {face_id} is a plane whose straight \
343 boundary sits {deviation:.3e} off it (assembly weld {weld:.1e}), which \
344 no perturbation can reconcile — the body's planes must contain their \
345 boundary before it can take part in an exact boolean"
346 )));
347 }
348 if matches!(operation, BooleanOperation::Subtract)
363 && std::env::var("BREP_PINCH_GATE").as_deref() != Ok("0")
364 && subtract_pinches_at_internal_tangency(first, second, options.tolerance)
365 .unwrap_or(false)
366 {
367 if let Some(solid) = subtract_through_the_common_part(first, second, options) {
370 return Ok(solid);
371 }
372 return Err(error.with_message(|message| format!(
373 "{message}; internal tangency: the operands touch tangentially with \
374 co-directed normals, so the exact difference pinches to zero thickness \
375 (non-manifold, unrepresentable in a boundary model) — refusing rather \
376 than returning a perturbed sliver"
377 )));
378 }
379 if matches!(error.class, RefusalClass::TangentNodeSingularity)
395 && std::env::var("BREP_TANGENT_NODE_GATE").as_deref() != Ok("0")
396 {
397 return Err(error);
398 }
399 if matches!(operation, BooleanOperation::Union) {
403 if let Some(solid) = union_through_the_difference(first, second, options) {
404 return Ok(solid);
405 }
406 }
407 match perturbation_retry(first, second, operation, options) {
408 Ok(solid) => Ok(solid),
409 Err(refused) if refused.is_empty() => Err(error),
410 Err(refused) => {
411 Err(error.with_message(|message| format!("{message}; {}", refused.join("; "))))
412 }
413 }
414 }
415 }
416}
417
418const PINCH_PROBE_STEPS: usize = 8;
423
424const PINCH_ANGULAR_TOLERANCE: f64 = 1e-4;
427
428const PINCH_SEPARATION_STEP: f64 = 1e-2;
432
433fn subtract_through_the_common_part(first: &BrepSolid, second: &BrepSolid, options: &BooleanOptions) -> Option<BrepSolid> {
451 if !switch!("BREP_PINCH_COMMON_RETRY", true) || !options.imprint.tangent_curve_imprint {
454 return None;
455 }
456 let common = boolean_operation_with_diagnostics(first, second, BooleanOperation::Intersect, options).ok()?.value;
457 if common.shells.iter().all(|shell| shell.faces.is_empty()) {
458 return None;
459 }
460 let cut = boolean_operation_with_diagnostics(first, &common, BooleanOperation::Subtract, options).ok()?.value;
461 if !cut.validate().is_empty() {
462 return None;
463 }
464 let volume = |solid: &BrepSolid| crate::solid_mass_properties(solid).ok().map(|mass| mass.volume);
465 let (whole, taken, left) = (volume(first)?, volume(&common)?, volume(&cut)?);
466 ((left - (whole - taken)).abs() <= 1e-9 * whole.abs().max(1.0)).then_some(cut)
467}
468
469fn union_through_the_difference(first: &BrepSolid, second: &BrepSolid, options: &BooleanOptions) -> Option<BrepSolid> {
482 if !switch!("BREP_TANGENT_UNION_DIFFERENCE_RETRY", true) || !options.imprint.tangent_curve_imprint {
483 return None;
484 }
485 let pinches = |a: &BrepSolid, b: &BrepSolid| subtract_pinches_at_internal_tangency(a, b, options.tolerance).unwrap_or(false);
486 if !pinches(first, second) && !pinches(second, first) {
487 return None;
488 }
489 let difference = match boolean_operation_with_diagnostics(first, second, BooleanOperation::Subtract, options) {
490 Ok(outcome) => outcome.value,
491 Err(_) => subtract_through_the_common_part(first, second, options)?,
492 };
493 if difference.shells.iter().all(|shell| shell.faces.is_empty()) || !difference.validate().is_empty() {
494 return None;
495 }
496 let union = boolean_operation_with_diagnostics(second, &difference, BooleanOperation::Union, options).ok()?.value;
497 if !union.validate().is_empty() {
498 return None;
499 }
500 let volume = |solid: &BrepSolid| crate::solid_mass_properties(solid).ok().map(|mass| mass.volume);
501 let (left, added, whole) = (volume(&difference)?, volume(second)?, volume(&union)?);
502 ((whole - (left + added)).abs() <= 1e-9 * whole.abs().max(1.0)).then_some(union)
503}
504
505pub fn subtract_pinches_at_internal_tangency(
527 first: &BrepSolid,
528 second: &BrepSolid,
529 tolerance: f64,
530) -> Result<bool, KernelRefusal> {
531 let contact = (tolerance * 100.0).max(1e-12);
534 let probes_a = first
535 .shells
536 .iter()
537 .flat_map(|shell| &shell.faces)
538 .map(PinchProbe::of)
539 .collect::<Result<Vec<_>, _>>()?;
540 let probes_b = second
541 .shells
542 .iter()
543 .flat_map(|shell| &shell.faces)
544 .map(PinchProbe::of)
545 .collect::<Result<Vec<_>, _>>()?;
546 for probe_a in &probes_a {
547 for probe_b in &probes_b {
548 let pad = 1e-2 * probe_a.extent().max(probe_b.extent());
555 if probe_a.separation(probe_b) > contact + pad {
556 continue;
557 }
558 if classify_surface_pair(
565 &probe_a.face.surface,
566 &probe_b.face.surface,
567 tolerance,
568 PINCH_ANGULAR_TOLERANCE,
569 ).or_refuse(KernelStage::Validate, "csg.boolean.mod")?
570 .relation
571 == SurfacePairRelation::Cosurface
572 {
573 continue;
574 }
575 if faces_touch_with_codirected_normals(probe_a, probe_b, contact)? {
576 return Ok(true);
577 }
578 }
579 }
580 Ok(false)
581}
582
583struct PinchProbe<'a> {
586 face: &'a FaceRecord,
587 samples: Vec<(f64, f64, Vec3)>,
589 minimum: [f64; 3],
590 maximum: [f64; 3],
591}
592
593impl<'a> PinchProbe<'a> {
594 fn of(face: &'a FaceRecord) -> Result<Self, KernelRefusal> {
595 let [u0, u1] = face.surface.domain_u().or_refuse(KernelStage::Validate, "domain_u")?;
596 let [v0, v1] = face.surface.domain_v().or_refuse(KernelStage::Validate, "domain_v")?;
597 let steps = PINCH_PROBE_STEPS as f64;
598 let mut samples = Vec::with_capacity((PINCH_PROBE_STEPS + 1).pow(2));
599 let mut minimum = [f64::INFINITY; 3];
600 let mut maximum = [f64::NEG_INFINITY; 3];
601 for i in 0..=PINCH_PROBE_STEPS {
602 let u = u0 + (u1 - u0) * i as f64 / steps;
603 for j in 0..=PINCH_PROBE_STEPS {
604 let v = v0 + (v1 - v0) * j as f64 / steps;
605 let Ok(point) = face.surface.evaluate(u, v) else {
606 continue;
607 };
608 for (axis, value) in [point.x, point.y, point.z].into_iter().enumerate() {
609 minimum[axis] = minimum[axis].min(value);
610 maximum[axis] = maximum[axis].max(value);
611 }
612 samples.push((u, v, point));
613 }
614 }
615 Ok(Self {
616 face,
617 samples,
618 minimum,
619 maximum,
620 })
621 }
622
623 fn extent(&self) -> f64 {
625 (0..3)
626 .map(|axis| self.maximum[axis] - self.minimum[axis])
627 .fold(0.0f64, f64::max)
628 }
629
630 fn separation(&self, other: &Self) -> f64 {
632 let mut gap: f64 = 0.0;
633 for axis in 0..3 {
634 gap = gap.max(self.minimum[axis] - other.maximum[axis]);
635 gap = gap.max(other.minimum[axis] - self.maximum[axis]);
636 }
637 gap
638 }
639}
640
641fn faces_touch_with_codirected_normals(
646 probe_a: &PinchProbe<'_>,
647 probe_b: &PinchProbe<'_>,
648 contact: f64,
649) -> Result<bool, KernelRefusal> {
650 for (probe, other) in [(probe_a, probe_b), (probe_b, probe_a)] {
651 let source = probe.face;
652 let target = other.face;
653 for &(u, v, point) in &probe.samples {
654 let projection = project_point_to_surface(&target.surface, point).or_refuse(KernelStage::Validate, "project_point_to_surface")?;
655 if projection.distance > contact {
656 continue;
657 }
658 let (Ok(source_normal), Ok(target_normal)) = (
661 source.surface.normal(u, v),
662 target.surface.normal(projection.u, projection.v),
663 ) else {
664 continue;
665 };
666 let source_outward = outward_normal(source_normal, source.same_sense);
667 let target_outward = outward_normal(target_normal, target.same_sense);
668 if source_outward.cross(target_outward).length() > PINCH_ANGULAR_TOLERANCE
669 || source_outward.dot(target_outward) <= 0.0
670 {
671 continue;
672 }
673 if parameter_point_in_face(source, Vec2 { x: u, y: v }, 1e-6).or_refuse(KernelStage::Validate, "parameter_point_in_face")?
674 == PolygonClass::Outside
675 || parameter_point_in_face(
676 target,
677 Vec2 {
678 x: projection.u,
679 y: projection.v,
680 },
681 1e-6,
682 ).or_refuse(KernelStage::Validate, "csg.boolean.mod")? == PolygonClass::Outside
683 {
684 continue;
685 }
686 if contact_separates_locally(source, target, u, v, contact)? {
687 return Ok(true);
688 }
689 }
690 }
691 Ok(false)
692}
693
694fn outward_normal(normal: Vec3, same_sense: bool) -> Vec3 {
695 if same_sense {
696 normal
697 } else {
698 normal.scale(-1.0)
699 }
700}
701
702fn contact_separates_locally(
708 source: &FaceRecord,
709 target: &FaceRecord,
710 u: f64,
711 v: f64,
712 contact: f64,
713) -> Result<bool, KernelRefusal> {
714 let [u0, u1] = source.surface.domain_u().or_refuse(KernelStage::Validate, "domain_u")?;
715 let [v0, v1] = source.surface.domain_v().or_refuse(KernelStage::Validate, "domain_v")?;
716 let step_u = (u1 - u0) * PINCH_SEPARATION_STEP;
717 let step_v = (v1 - v0) * PINCH_SEPARATION_STEP;
718 for (probe_u, probe_v) in [
719 ((u + step_u).min(u1), v),
720 ((u - step_u).max(u0), v),
721 (u, (v + step_v).min(v1)),
722 (u, (v - step_v).max(v0)),
723 ] {
724 if (probe_u - u).abs() < f64::EPSILON && (probe_v - v).abs() < f64::EPSILON {
725 continue;
726 }
727 let Ok(point) = source.surface.evaluate(probe_u, probe_v) else {
728 continue;
729 };
730 if project_point_to_surface(&target.surface, point).or_refuse(KernelStage::Validate, "project_point_to_surface")?.distance > contact * 10.0 {
733 return Ok(true);
734 }
735 }
736 Ok(false)
737}
738
739fn perturbation_retry(
793 first: &BrepSolid,
794 second: &BrepSolid,
795 operation: BooleanOperation,
796 options: &BooleanOptions,
797) -> Result<BrepSolid, Vec<String>> {
798 const DIRECTIONS: [[f64; 3]; 4] = [
809 [0.4034, 0.7973, 0.4491],
810 [0.7973, 0.4491, 0.4034],
811 [0.4491, 0.4034, 0.7973],
812 [0.5774, -0.5774, 0.5774],
813 ];
814 const FRACTIONS: [f64; 5] = PERTURBATION_FRACTIONS;
820
821 let debug = std::env::var("BREP_DEBUG_BOOL").is_ok();
822 let scale = crate::solid_tolerance::solid_scale(first)
823 .max(crate::solid_tolerance::solid_scale(second))
824 .max(1.0);
825
826 let _caller = crate::mass_caller("boolean.perturbation_rescue");
830 let va = solid_signed_volume(first).ok().map(f64::abs);
831 let vb = solid_signed_volume(second).ok().map(f64::abs);
832 let hold_identity = std::env::var("BREP_PERTURB_IDENTITY").as_deref() != Ok("0");
833 let hold_mirror = hold_identity && std::env::var("BREP_PERTURB_MIRROR").as_deref() != Ok("0");
836 let early_exit = std::env::var("BREP_MIRROR_EARLY_EXIT").as_deref() != Ok("0");
839 let mut trends = [MirrorTrend::default(); 4];
840 let mut identity: Option<Option<InclusionExclusion>> = None;
842 let mut refused = Vec::new();
843 let ladder = std::env::var("BREP_DEBUG_PERTURB_LADDER").is_ok();
847 let ladder_start = web_time::Instant::now();
848 if ladder {
849 let measured = inclusion_exclusion_volume(first, second, operation, options, va, vb, false);
850 match &measured {
851 Some(identity) => eprintln!(
852 "[ladder] identity {} = {:.9} from the exact lane's {} ({:.9}); V(first) {:?} V(second) {:?}",
853 identity.formula, identity.expected, identity.reading, identity.read, va, vb
854 ),
855 None => eprintln!("[ladder] no identity: no exact-lane boolean of these operands clears in either order"),
856 }
857 identity = Some(measured);
858 }
859 let rung_miss = |identity: &Option<Option<InclusionExclusion>>, candidate: &BrepSolid| -> String {
860 let volume = body_volume(candidate);
861 match (identity, volume) {
862 (Some(Some(identity)), Some(volume)) => format!(
863 "volume {volume:.9} miss {:+.3e} bar {:.3e}",
864 volume - identity.expected,
865 crate::VOLUME_DRIFT_ABS.max(crate::VOLUME_DRIFT_REL * identity.expected.abs())
866 ),
867 (_, Some(volume)) => format!("volume {volume:.9}"),
868 _ => "no volume".to_string(),
869 }
870 };
871
872 for &fraction in &FRACTIONS {
873 let magnitude = scale * fraction;
874 for (direction, dir) in DIRECTIONS.iter().enumerate() {
875 if trends[direction].closed {
876 if ladder {
877 eprintln!("[ladder] dir={dir:?} fraction={fraction:.1e} offset {magnitude:.3e}: not tried, its direction is closed");
878 }
879 continue;
880 }
881 let offset = [dir[0] * magnitude, dir[1] * magnitude, dir[2] * magnitude];
882 let translate = match AffineTransform::new([
883 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,
887 ]) {
888 Ok(transform) => transform,
889 Err(_) => continue,
890 };
891 let moved = match crate::transform_brep(second, translate, false) {
892 Ok(solid) => solid,
893 Err(_) => continue,
894 };
895 let rung = format!("dir={dir:?} fraction={fraction:.1e} offset {magnitude:.3e}");
896 let rung_start = web_time::Instant::now();
897 let candidate =
898 match boolean_operation_with_diagnostics(first, &moved, operation, options) {
899 Ok(outcome) => outcome.value,
900 Err(error) => {
901 if ladder {
902 eprintln!("[ladder] {rung}: exact lane refused {:?}", error.class);
903 }
904 continue;
905 }
906 };
907 let built = rung_start.elapsed();
908 if candidate.shells.is_empty() {
910 if ladder {
911 eprintln!("[ladder] {rung}: empty");
912 }
913 continue;
914 }
915 if let (Some(va), Some(vb)) = (va, vb) {
920 if let Ok(vr) = solid_signed_volume(&candidate) {
921 if !volume_within_csg_bounds(operation, va, vb, vr.abs()) {
922 if ladder {
923 eprintln!("[ladder] {rung}: outside the CSG bound, {}", rung_miss(&identity, &candidate));
924 }
925 continue;
926 }
927 }
928 }
929 let bounded = rung_start.elapsed();
934 if hold_identity {
936 let identity = identity.get_or_insert_with(|| {
937 let identity =
938 inclusion_exclusion_volume(first, second, operation, options, va, vb, false);
939 if debug && identity.is_none() {
940 eprintln!(
941 "[perturb] no exact-lane boolean of these operands clears in either \
942 order; no identity to hold"
943 );
944 }
945 identity
946 });
947 if let Some(identity) = identity {
948 let expected = identity.expected;
949 let bar = crate::VOLUME_DRIFT_ABS.max(crate::VOLUME_DRIFT_REL * expected.abs());
950 let volume = body_volume(&candidate);
951 let miss = volume.map(|volume| (volume - expected).abs());
952 if !miss.is_some_and(|miss| miss <= bar) {
953 let sentence = format!(
954 "perturbation rung dir={dir:?} fraction={fraction:.1e} \
955 (offset {magnitude:.3e}) refused: its body reads {} against the \
956 inclusion–exclusion identity {} = {expected:.9} (the exact lane's \
957 {} reads {:.9}), a miss of {} beyond the volume drift bar {bar:.3e}",
958 volume.map_or("no volume".to_string(), |volume| format!("{volume:.9}")),
959 identity.formula,
960 identity.reading,
961 identity.read,
962 miss.map_or("unmeasured".to_string(), |miss| format!("{miss:.3e}")),
963 );
964 if debug {
965 eprintln!("[perturb] {sentence}");
966 }
967 if ladder {
968 eprintln!(
969 "[ladder] {rung}: refused by the identity, volume {} miss {} bar {bar:.3e}",
970 volume.map_or("none".to_string(), |volume| format!("{volume:.9}")),
971 volume.map_or("unmeasured".to_string(), |volume| format!("{:+.3e}", volume - expected)),
972 );
973 }
974 refused.push(sentence);
975 continue;
976 }
977 } else if hold_mirror {
978 let mirror_start = web_time::Instant::now();
981 let mirrored = AffineTransform::new([
982 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,
986 ])
987 .ok()
988 .and_then(|transform| crate::transform_brep(second, transform, false).ok());
989 let mirror = mirrored.as_ref().and_then(|mirrored| {
990 inclusion_exclusion_volume(first, mirrored, operation, options, va, vb, true)
991 });
992 let mirror_time = mirror_start.elapsed();
993 let volume = body_volume(&candidate);
994 let mut measured = None;
995 let verdict = match (&mirror, volume) {
996 (Some(mirror), Some(volume)) => {
997 let bar = crate::VOLUME_DRIFT_ABS.max(crate::VOLUME_DRIFT_REL * mirror.expected.abs());
998 let miss = 0.5 * (volume - mirror.expected).abs();
999 measured = Some((0.5 * (volume - mirror.expected), bar));
1000 if ladder {
1001 eprintln!(
1002 "[ladder] {rung}: mirror at −offset reads {} = {:.9} (the mirrored {} {:.9}); body {volume:.9}, first-order translation error {:+.3e} bar {bar:.3e}",
1003 mirror.formula, mirror.expected, mirror.reading, mirror.read, 0.5 * (volume - mirror.expected)
1004 );
1005 }
1006 (miss > bar).then(|| format!(
1007 "perturbation rung dir={dir:?} fraction={fraction:.1e} \
1008 (offset {magnitude:.3e}) refused: no exact-lane boolean of the \
1009 operands clears, so the rung is held to its mirror: its body reads \
1010 {volume:.9} with the second operand moved +offset and {} = {:.9} \
1011 with it moved −offset (the mirrored {} reads {:.9}), a first-order \
1012 translation error of {miss:.3e} beyond the volume drift bar {bar:.3e}",
1013 mirror.formula, mirror.expected, mirror.reading, mirror.read
1014 ))
1015 }
1016 _ => Some(format!(
1017 "perturbation rung dir={dir:?} fraction={fraction:.1e} \
1018 (offset {magnitude:.3e}) refused: no exact-lane boolean of the operands \
1019 clears, and none clears with the second operand moved −offset either, \
1020 so nothing checks the rung's body{}",
1021 volume.map_or(String::new(), |volume| format!(" ({volume:.9})"))
1022 )),
1023 };
1024 match verdict {
1025 None => trends[direction].cleared(),
1026 Some(sentence) => {
1027 if debug {
1028 eprintln!("[perturb] {sentence}");
1029 }
1030 if ladder {
1031 eprintln!(
1032 "[ladder] {rung}: refused by its mirror (rung {:.0} ms: built {:.0}, bound {:.0}, mirror {:.0} ms; ladder {:.1} s)",
1033 rung_start.elapsed().as_secs_f64() * 1e3,
1034 built.as_secs_f64() * 1e3,
1035 (bounded - built).as_secs_f64() * 1e3,
1036 mirror_time.as_secs_f64() * 1e3,
1037 ladder_start.elapsed().as_secs_f64()
1038 );
1039 }
1040 refused.push(sentence);
1041 let closure = measured.and_then(|(error, bar)| {
1044 let earlier = trends[direction].refused(magnitude, error, early_exit)?;
1045 Some((earlier, error, bar))
1046 });
1047 if let Some(((earlier_offset, earlier_error), error, bar)) = closure {
1048 let closed = format!(
1049 "perturbation direction dir={dir:?} closed after offset {magnitude:.3e}: its \
1050 rungs' first-order translation errors read {earlier_error:+.3e} at offset \
1051 {earlier_offset:.3e} and {error:+.3e} at {magnitude:.3e}, one sign and \
1052 growing, so no larger offset along it comes back to the volume drift bar \
1053 {bar:.3e}"
1054 );
1055 if debug {
1056 eprintln!("[perturb] {closed}");
1057 }
1058 if ladder {
1059 eprintln!("[ladder] {closed}");
1060 }
1061 refused.push(closed);
1062 }
1063 continue;
1064 }
1065 }
1066 }
1067 }
1068 match crate::oracle::boolean_semantic_disagreement(
1072 first, second, operation, &candidate, 400,
1073 ) {
1074 Ok(report) if report.considered >= 30 && !report.is_flagged() => {
1075 if ladder {
1076 eprintln!(
1077 "[ladder] {rung}: accepted (oracle {} considered, rate {:.4}), {}",
1078 report.considered, report.disagreement_rate, rung_miss(&identity, &candidate)
1079 );
1080 }
1081 if debug {
1082 eprintln!(
1083 "[perturb] rescued {operation:?}: dir={dir:?} fraction={fraction:.1e} \
1084 magnitude={magnitude:.3e} offset={offset:?} \
1085 (oracle considered={} rate={:.4})",
1086 report.considered, report.disagreement_rate
1087 );
1088 }
1089 return Ok(candidate);
1090 }
1091 report => {
1092 if ladder {
1093 let verdict = match &report {
1094 Ok(report) => format!("oracle {} considered, rate {:.4}", report.considered, report.disagreement_rate),
1095 Err(error) => format!("oracle error {error:?}"),
1096 };
1097 eprintln!("[ladder] {rung}: refused by the oracle ({verdict}), {}", rung_miss(&identity, &candidate));
1098 }
1099 continue;
1100 }
1101 }
1102 }
1103 }
1104 if debug {
1105 eprintln!("[perturb] ladder exhausted for {operation:?}; no rung produced a clean result");
1106 }
1107 Err(refused)
1108}
1109
1110pub const PERTURBATION_FRACTIONS: [f64; 5] = [3e-5, 1e-4, 3e-4, 1e-3, 3e-3];
1113
1114#[derive(Clone, Copy, Default)]
1138pub struct MirrorTrend {
1139 last: Option<(f64, f64)>,
1141 pub closed: bool,
1142}
1143
1144impl MirrorTrend {
1145 pub fn refused(&mut self, offset: f64, error: f64, close: bool) -> Option<(f64, f64)> {
1150 let earlier = self
1151 .last
1152 .filter(|&(_, earlier)| earlier.signum() == error.signum() && error.abs() >= earlier.abs())
1153 .filter(|_| close);
1154 self.last = Some((offset, error));
1155 self.closed |= earlier.is_some();
1156 earlier
1157 }
1158
1159 pub fn cleared(&mut self) {
1161 self.last = None;
1162 }
1163}
1164
1165pub fn below_tolerance_refusal_enabled() -> bool {
1180 crate::switch!("BREP_BELOW_TOLERANCE_REFUSAL", true)
1181}
1182
1183const BELOW_TOLERANCE_BAND: f64 = 10.0 * crate::tolerance::WELD_FLOOR;
1186
1187pub fn unresolved_merge_refusal_enabled() -> bool {
1197 crate::switch!("BREP_UNRESOLVED_MERGE_REFUSAL", false)
1198}
1199
1200pub fn sliver_shell_drop_enabled() -> bool {
1213 crate::switch!("BREP_SLIVER_SHELL_DROP", true)
1214}
1215
1216const SLIVER_SHELL_THICKNESS: f64 = 1e-12;
1220
1221fn drop_sliver_shells(solid: &mut BrepSolid) -> usize {
1224 if !sliver_shell_drop_enabled() || !solid.kind.is_solid() || solid.shells.len() < 2 {
1225 return 0;
1226 }
1227 let floor = SLIVER_SHELL_THICKNESS * crate::solid_tolerance::solid_scale(solid).max(1.0);
1228 let degenerate: std::collections::HashSet<u64> = solid.edges.iter().filter(|edge| edge.degenerate).map(|edge| edge.id).collect();
1229 let mut drop = vec![false; solid.shells.len()];
1230 for (index, shell) in solid.shells.iter().enumerate() {
1231 if shell.faces.is_empty() {
1232 continue;
1233 }
1234 let mut uses: HashMap<u64, usize> = HashMap::default();
1236 for coedge in shell.faces.iter().flat_map(|face| &face.loops).flat_map(|lp| &lp.coedges) {
1237 if !degenerate.contains(&coedge.edge_id) {
1238 *uses.entry(coedge.edge_id).or_default() += 1;
1239 }
1240 }
1241 if uses.is_empty() || uses.values().any(|&count| count != 2) {
1242 continue;
1243 }
1244 let alone = BrepSolid { shells: vec![shell.clone()], mass_properties_cache: Default::default(), ..solid.clone() };
1245 let Ok(mass) = crate::solid_mass_properties(&alone) else {
1246 continue;
1247 };
1248 let thickness = mass.volume.abs() / mass.surface_area.max(f64::MIN_POSITIVE);
1249 if env_read!("BREP_DEBUG_SLIVER_SHELL").is_some() {
1250 eprintln!(
1251 "sliver-shell: shell {index} of {}: volume {:.6e} area {:.6e} thickness {thickness:.3e}",
1252 solid.shells.len(),
1253 mass.volume,
1254 mass.surface_area
1255 );
1256 }
1257 drop[index] = thickness < floor;
1258 }
1259 let dropped = drop.iter().filter(|&&d| d).count();
1260 if dropped == 0 || dropped == solid.shells.len() {
1261 return 0;
1262 }
1263 let mut index = 0;
1264 solid.shells.retain(|_| {
1265 let keep = !drop[index];
1266 index += 1;
1267 keep
1268 });
1269 let used_edges: std::collections::HashSet<u64> = solid
1270 .shells
1271 .iter()
1272 .flat_map(|shell| &shell.faces)
1273 .flat_map(|face| &face.loops)
1274 .flat_map(|lp| &lp.coedges)
1275 .map(|coedge| coedge.edge_id)
1276 .collect();
1277 solid.edges.retain(|edge| used_edges.contains(&edge.id));
1278 let used_vertices: std::collections::HashSet<u64> =
1279 solid.edges.iter().flat_map(|edge| [edge.start_vertex_id, edge.end_vertex_id]).collect();
1280 solid.vertices.retain(|vertex| used_vertices.contains(&vertex.id));
1281 solid.mass_properties_cache = Default::default();
1282 refresh_derived_genus(solid);
1284 dropped
1285}
1286
1287fn unresolved_merge_refusal(first: &BrepSolid, second: &BrepSolid) -> Option<KernelRefusal> {
1288 let (lower, upper) = (crate::tolerance::COINCIDENCE_DISTANCE_FLOOR, crate::tolerance::WELD_FLOOR);
1289 let (face_a, face_b, separation) = planar_faces_apart_within(first, second, lower, upper)?;
1290 Some(KernelRefusal::unsupported(
1291 KernelStage::Intersect,
1292 "below_modelling_tolerance",
1293 format!(
1294 "boolean: face {face_a} of the first operand and face {face_b} of the second are planes nearly on one \
1295 another, {separation:.3e} apart at most over their shared extent: farther than a coincidence \
1296 ({lower:.0e}) and closer than the kernel resolves ({upper:.0e}), so the step between them would be \
1297 welded away"
1298 ),
1299 ))
1300}
1301
1302fn below_tolerance_refusal(first: &BrepSolid, second: &BrepSolid, error: Option<&KernelRefusal>) -> Option<KernelRefusal> {
1303 let (face_a, face_b, separation) = near_coincident_planar_faces(first, second)?;
1304 let message = format!(
1305 "boolean: face {face_a} of the first operand and face {face_b} of the second are planes nearly on one \
1306 another, {separation:.3e} apart at most over their shared extent: the slivers between them are below the \
1307 modelling tolerance ({BELOW_TOLERANCE_BAND:.0e}), so the kernel cannot resolve them{}",
1308 error.map(|error| format!(" (the exact arrangement said: {})", error.message.chars().take(160).collect::<String>())).unwrap_or_default()
1309 );
1310 Some(KernelRefusal::unsupported(KernelStage::Intersect, "below_modelling_tolerance", message))
1311}
1312
1313fn near_coincident_planar_faces(first: &BrepSolid, second: &BrepSolid) -> Option<(u64, u64, f64)> {
1317 let scale = crate::solid_tolerance::solid_scale(first).max(crate::solid_tolerance::solid_scale(second)).max(1.0);
1318 planar_faces_apart_within(first, second, 1e-9 * scale, BELOW_TOLERANCE_BAND)
1319}
1320
1321fn planar_faces_apart_within(first: &BrepSolid, second: &BrepSolid, lower: f64, upper: f64) -> Option<(u64, u64, f64)> {
1325 struct Planar {
1326 id: u64,
1327 origin: Vec3,
1328 normal: Vec3,
1329 corners: Vec<Vec3>,
1330 bounds: crate::spatial::Aabb,
1331 }
1332 let read = |solid: &BrepSolid| -> Vec<Planar> {
1333 let at = |id: u64| solid.vertices.iter().find(|vertex| vertex.id == id).map(|vertex| vertex.point);
1334 solid
1335 .shells
1336 .iter()
1337 .flat_map(|shell| &shell.faces)
1338 .filter_map(|face| {
1339 if !face.surface.is_affine().ok()? {
1340 return None;
1341 }
1342 let origin = face.surface.control_points[0][0].point().ok()?;
1343 let a = face.surface.control_points[1][0].point().ok()?.sub(origin);
1344 let b = face.surface.control_points[0][1].point().ok()?.sub(origin);
1345 let normal = a.cross(b).normalized().ok()?;
1346 let corners: Vec<Vec3> = face
1347 .loops
1348 .iter()
1349 .flat_map(|lp| &lp.coedges)
1350 .filter_map(|coedge| solid.edges.iter().find(|edge| edge.id == coedge.edge_id))
1351 .flat_map(|edge| [at(edge.start_vertex_id), at(edge.end_vertex_id)])
1352 .flatten()
1353 .collect();
1354 if corners.is_empty() {
1355 return None;
1356 }
1357 let bounds = crate::spatial::Aabb::from_points(corners.clone());
1358 Some(Planar { id: face.id, origin, normal, corners, bounds })
1359 })
1360 .collect()
1361 };
1362 let (faces_a, faces_b) = (read(first), read(second));
1363 for a in &faces_a {
1364 for b in &faces_b {
1365 if a.normal.cross(b.normal).length() > 1e-3 {
1366 continue;
1367 }
1368 if !a.bounds.intersects(b.bounds, upper) {
1369 continue;
1370 }
1371 let separation = a
1372 .corners
1373 .iter()
1374 .map(|corner| corner.sub(b.origin).dot(b.normal).abs())
1375 .chain(b.corners.iter().map(|corner| corner.sub(a.origin).dot(a.normal).abs()))
1376 .fold(0.0f64, f64::max);
1377 if separation > lower && separation <= upper {
1378 return Some((a.id, b.id, separation));
1379 }
1380 }
1381 }
1382 None
1383}
1384
1385pub fn one_use_edges(solid: &BrepSolid) -> usize {
1386 let mut uses: HashMap<u64, usize> = HashMap::default();
1387 for coedge in solid
1388 .shells
1389 .iter()
1390 .flat_map(|shell| &shell.faces)
1391 .flat_map(|face| &face.loops)
1392 .flat_map(|loop_record| &loop_record.coedges)
1393 {
1394 *uses.entry(coedge.edge_id).or_default() += 1;
1395 }
1396 solid
1397 .edges
1398 .iter()
1399 .filter(|edge| !edge.degenerate && uses.get(&edge.id) == Some(&1))
1400 .count()
1401}
1402
1403fn body_volume(solid: &BrepSolid) -> Option<f64> {
1405 if solid.shells.is_empty() {
1406 return Some(0.0);
1407 }
1408 solid_signed_volume(solid).ok().map(f64::abs)
1409}
1410
1411struct InclusionExclusion {
1414 formula: &'static str,
1417 reading: &'static str,
1419 read: f64,
1421 expected: f64,
1423}
1424
1425fn inclusion_exclusion_volume(
1436 first: &BrepSolid,
1437 second: &BrepSolid,
1438 operation: BooleanOperation,
1439 options: &BooleanOptions,
1440 va: Option<f64>,
1441 vb: Option<f64>,
1442 own_first: bool,
1443) -> Option<InclusionExclusion> {
1444 use BooleanOperation::{Intersect, Subtract, Union};
1445 let (va, vb) = (va?, vb?);
1446 let own = match operation {
1447 Intersect => (Intersect, false, "first ∩ second"),
1448 Union => (Union, false, "first ∪ second"),
1449 Subtract => (Subtract, false, "first − second"),
1450 };
1451 let readings = [
1452 (Intersect, false, "first ∩ second"),
1453 (Intersect, true, "second ∩ first"),
1454 (Union, false, "first ∪ second"),
1455 (Union, true, "second ∪ first"),
1456 (Subtract, false, "first − second"),
1457 (Subtract, true, "second − first"),
1458 ];
1459 let own_reading = own_first.then_some(own);
1460 let leading = usize::from(own_first);
1461 for (index, (other, swapped, reading)) in own_reading.into_iter().chain(readings).enumerate() {
1462 if index >= leading && !swapped && std::mem::discriminant(&other) == std::mem::discriminant(&operation) {
1463 continue;
1464 }
1465 let (x, y) = if swapped { (second, first) } else { (first, second) };
1466 let Some(read) = boolean_operation_with_diagnostics(x, y, other, options)
1467 .ok()
1468 .and_then(|outcome| body_volume(&outcome.value))
1469 else {
1470 continue;
1471 };
1472 let intersection = match (other, swapped) {
1473 (Intersect, _) => read,
1474 (Union, _) => va + vb - read,
1475 (Subtract, false) => va - read,
1476 (Subtract, true) => vb - read,
1477 };
1478 let (formula, expected) = match operation {
1479 Intersect => ("V(first ∩ second)", intersection),
1480 Union => ("V(first) + V(second) − V(first ∩ second)", va + vb - intersection),
1481 Subtract => ("V(first) − V(first ∩ second)", va - intersection),
1482 };
1483 return Some(InclusionExclusion { formula, reading, read, expected });
1484 }
1485 None
1486}
1487
1488fn planar_operand_off_its_plane(
1497 first: &BrepSolid,
1498 second: &BrepSolid,
1499 options: &BooleanOptions,
1500) -> Option<(u8, u64, f64, f64)> {
1501 let policy = options
1502 .tolerances
1503 .clone()
1504 .unwrap_or_else(|| KernelTolerances::for_pair(first, second, options.tolerance));
1505 let weld = crate::tolerance::assembler_weld(policy.model);
1506 let mut worst: Option<(u8, u64, f64)> = None;
1507 for (operand, solid) in [(0u8, first), (1u8, second)] {
1508 let vertex_point = |id: u64| solid.vertices.iter().find(|v| v.id == id).map(|v| v.point);
1509 for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
1510 let Some(crate::AnalyticSurface::Plane {
1511 origin,
1512 u_dir,
1513 v_dir,
1514 ..
1515 }) = face.surface.analytic()
1516 else {
1517 continue;
1518 };
1519 let [loop_record] = face.loops.as_slice() else {
1520 continue;
1521 };
1522 let Ok(normal) = u_dir.cross(*v_dir).normalized() else {
1523 continue;
1524 };
1525 let mut off_plane = 0.0f64;
1526 let mut straight = true;
1527 for coedge in &loop_record.coedges {
1528 let Some(edge) = solid.edges.iter().find(|edge| edge.id == coedge.edge_id) else {
1529 straight = false;
1530 break;
1531 };
1532 let (Some(start), Some(end)) =
1533 (vertex_point(edge.start_vertex_id), vertex_point(edge.end_vertex_id))
1534 else {
1535 straight = false;
1536 break;
1537 };
1538 let chord = end.sub(start);
1539 let length = chord.length();
1540 if edge.degenerate || length <= weld {
1541 straight = false;
1542 break;
1543 }
1544 let direction = chord.scale(1.0 / length);
1545 for fraction in [0.25, 0.5, 0.75] {
1546 let Ok(point) = edge.curve.evaluate(edge.t0 + (edge.t1 - edge.t0) * fraction) else {
1547 straight = false;
1548 break;
1549 };
1550 let delta = point.sub(start);
1551 let along = delta.dot(direction);
1552 if delta.sub(direction.scale(along)).length() > weld
1553 || along < -weld
1554 || along > length + weld
1555 {
1556 straight = false;
1557 break;
1558 }
1559 }
1560 if !straight {
1561 break;
1562 }
1563 off_plane = off_plane.max(start.sub(*origin).dot(normal).abs());
1564 }
1565 if straight && off_plane > weld && worst.is_none_or(|(_, _, gap)| off_plane > gap) {
1566 worst = Some((operand, face.id, off_plane));
1567 }
1568 }
1569 }
1570 worst.map(|(operand, face_id, gap)| (operand, face_id, gap, weld))
1571}
1572
1573fn volume_within_csg_bounds(operation: BooleanOperation, va: f64, vb: f64, vr: f64) -> bool {
1576 let slack = 1e-2 * (va + vb).max(1.0);
1577 match operation {
1578 BooleanOperation::Union => vr >= va.max(vb) - slack && vr <= va + vb + slack,
1580 BooleanOperation::Subtract => vr <= va + slack && vr >= -slack,
1582 BooleanOperation::Intersect => vr <= va.min(vb) + slack && vr >= -slack,
1584 }
1585}
1586
1587fn reverse_fragment(fragment: &mut FaceFragmentRecord) -> Result<(), KernelRefusal> {
1614 fragment.same_sense = !fragment.same_sense;
1615 for loop_record in &mut fragment.loops {
1616 loop_record.coedges.reverse();
1617 for coedge in &mut loop_record.coedges {
1618 coedge.forward = !coedge.forward;
1619 coedge.pcurve = coedge.pcurve.reversed().or_refuse(KernelStage::Validate, "reversed")?;
1620 }
1621 }
1622 Ok(())
1623}
1624
1625fn build_nary_imprint(
1632 operands: &[BrepSolid],
1633 options: &ImprintOptions,
1634) -> Result<ImprintResultRecord, KernelRefusal> {
1635 let mut section_evidence = false;
1636 let mut vertices: Vec<ImprintVertex> = Vec::new();
1637 let mut pieces: Vec<ImprintPieceRecord> = Vec::new();
1638 let mut by_face: HashMap<(u8, u64), Vec<u64>> = HashMap::default();
1639 let mut edge_splits: HashMap<(u8, u64), Vec<f64>> = HashMap::default();
1640 let mut next_vertex_id: u64 = 1;
1641 let mut next_piece_id: u64 = 1;
1642
1643 for i in 0..operands.len() {
1644 for j in (i + 1)..operands.len() {
1645 let pair = build_imprints(&operands[i], &operands[j], options)?;
1646 let remap = |operand: u8| -> u8 {
1647 if operand == 0 {
1648 i as u8
1649 } else {
1650 j as u8
1651 }
1652 };
1653
1654 section_evidence = section_evidence || pair.section_evidence;
1655 let mut vertex_map: HashMap<u64, u64> = HashMap::default();
1656 for vertex in &pair.vertices {
1657 let global = next_vertex_id;
1658 next_vertex_id += 1;
1659 vertex_map.insert(vertex.id, global);
1660 vertices.push(ImprintVertex {
1661 id: global,
1662 point: vertex.point,
1663 });
1664 }
1665
1666 let mut piece_map: HashMap<u64, u64> = HashMap::default();
1667 for piece in &pair.pieces {
1668 let global = next_piece_id;
1669 next_piece_id += 1;
1670 piece_map.insert(piece.id, global);
1671 let mut mapped = piece.clone();
1672 mapped.id = global;
1673 mapped.start_vertex_id = *vertex_map
1674 .get(&piece.start_vertex_id)
1675 .ok_or_else(|| KernelRefusal::internal(KernelStage::Intersect, "nary.imprint", "n-ary imprint: piece references unknown vertex"))?;
1676 mapped.end_vertex_id = *vertex_map
1677 .get(&piece.end_vertex_id)
1678 .ok_or_else(|| KernelRefusal::internal(KernelStage::Intersect, "nary.imprint", "n-ary imprint: piece references unknown vertex"))?;
1679 for pcurve in &mut mapped.pcurves {
1680 pcurve.operand = remap(pcurve.operand);
1681 }
1682 mapped.support_faces = [
1683 FaceKey {
1684 operand: remap(piece.support_faces[0].operand),
1685 face_id: piece.support_faces[0].face_id,
1686 },
1687 FaceKey {
1688 operand: remap(piece.support_faces[1].operand),
1689 face_id: piece.support_faces[1].face_id,
1690 },
1691 ];
1692 pieces.push(mapped);
1693 }
1694
1695 for entry in &pair.by_face {
1696 let list = by_face
1697 .entry((remap(entry.operand), entry.face_id))
1698 .or_default();
1699 for piece_id in &entry.piece_ids {
1700 let global = *piece_map.get(piece_id).ok_or_else(|| {
1701 KernelRefusal::internal(KernelStage::Intersect, "nary.imprint", "n-ary imprint: by_face references unknown piece")
1702 })?;
1703 list.push(global);
1704 }
1705 }
1706
1707 for split in &pair.edge_splits {
1708 edge_splits
1709 .entry((remap(split.operand), split.edge_id))
1710 .or_default()
1711 .extend(split.parameters.iter().copied());
1712 }
1713 }
1714 }
1715
1716 Ok(ImprintResultRecord {
1717 vertices,
1718 pieces,
1719 tangent_nodes: Vec::new(),
1720 barrier_edges: Vec::new(),
1721 section_evidence,
1722 cosurface_pairs: Vec::new(),
1723 tangent_sections: Vec::new(),
1724 by_face: by_face
1725 .into_iter()
1726 .map(|((operand, face_id), piece_ids)| FaceImprints {
1727 operand,
1728 face_id,
1729 piece_ids,
1730 })
1731 .collect(),
1732 edge_splits: edge_splits
1733 .into_iter()
1734 .map(|((operand, edge_id), parameters)| EdgeSplitRecord {
1735 operand,
1736 edge_id,
1737 parameters,
1738 })
1739 .collect(),
1740 })
1741}
1742
1743pub fn boolean_operation_nary(
1754 operands: &[BrepSolid],
1755 operation: BooleanOperation,
1756) -> Result<BrepSolid, KernelRefusal> {
1757 boolean_operation_nary_with_options(operands, operation, &BooleanOptions::default())
1758}
1759
1760pub fn boolean_operation_nary_with_options(
1766 operands: &[BrepSolid],
1767 operation: BooleanOperation,
1768 options: &BooleanOptions,
1769) -> Result<BrepSolid, KernelRefusal> {
1770 if operands.len() > 1 {
1771 if let Some(scaled) = WorkingScale::of(&operands.iter().collect::<Vec<_>>(), options)? {
1772 return boolean_operation_nary_with_options(&scaled.solids, operation, &scaled.options)
1773 .map_err(|error| scaled.refusal(error))
1774 .and_then(|solid| scaled.back(&solid));
1775 }
1776 }
1777 if operands.is_empty() {
1778 return Err(KernelRefusal::input(KernelStage::Collect, "operands", "boolean_operation_nary: no operands provided"));
1779 }
1780 if operands.len() == 1 {
1781 return Ok(operands[0].clone());
1782 }
1783 if operands.len() > 255 {
1784 return Err(KernelRefusal::input(KernelStage::Collect, "operands", "boolean_operation_nary: at most 255 operands supported"));
1785 }
1786 let debug = std::env::var("BREP_DEBUG_BOOL").is_ok();
1787
1788 let mut policy = KernelTolerances::for_solid(&operands[0], options.tolerance);
1792 for operand in &operands[1..] {
1793 let candidate = KernelTolerances::for_solid(operand, options.tolerance);
1794 if candidate.sew_search > policy.sew_search {
1795 policy = candidate;
1796 }
1797 }
1798 policy.check().or_input(KernelStage::Collect, "tolerances")?;
1799 let tolerance = policy.model;
1800
1801 let mut healed = operands.to_vec();
1804 for operand in &mut healed {
1805 crate::heal::heal_operands(operand, &policy)?;
1806 crate::heal::refit_inherited_trims(operand, &policy)?;
1809 normalize_operand_band_seams(operand)?;
1812 }
1813
1814 let mut imprint_options = options.imprint.clone();
1816 imprint_options.tolerance = tolerance;
1817 let imprint = build_nary_imprint(&healed, &imprint_options)?;
1818
1819 let mut split = Vec::with_capacity(healed.len());
1821 for (index, operand) in healed.iter().enumerate() {
1822 split.push(apply_edge_splits(operand, index as u8, &imprint)?);
1823 }
1824 let mut fragments = Vec::with_capacity(split.len());
1825 for (index, solid) in split.iter().enumerate() {
1826 fragments.push(fragment_solid(solid, index as u8, &imprint)?);
1827 }
1828
1829 let selected = select_fragments_nary(&fragments, &healed, operation, tolerance, debug)?;
1831
1832 let solids: HashMap<u8, &BrepSolid> = split
1834 .iter()
1835 .enumerate()
1836 .map(|(index, solid)| (index as u8, solid))
1837 .collect();
1838 let solid = assemble_fragments(selected, &solids, &imprint, tolerance)?;
1839 let solid = if options.merge_coplanar_faces
1840 && std::env::var("BREP_COPLANAR_MERGE").as_deref() != Ok("0")
1841 {
1842 let merged = merge_same_surface_faces_excluding(
1843 &solid,
1844 tolerance,
1845 &options.keep_unmerged_name_substrs,
1846 )?;
1847 merge_curve_continuation_edges(&merged, tolerance).map_err(|refusal| KernelRefusal { stage: KernelStage::Validate, ..refusal })?
1848 } else {
1849 solid
1850 };
1851 let validation = solid.validate_detailed(&policy);
1852 if !validation.issues.is_empty() {
1853 return Err(KernelRefusal::new(
1854 RefusalClass::InvalidResultTopology { issues: validation.issues.len() as u32 },
1855 KernelStage::Validate,
1856 format!(
1857 "boolean_operation_nary: invalid result: {:?}",
1858 validation.issues
1859 )));
1860 }
1861 if debug {
1862 if let Ok(report) =
1863 crate::oracle::boolean_semantic_disagreement_nary(&healed, operation, &solid, 300)
1864 {
1865 if report.is_flagged() {
1866 eprintln!(
1867 "[oracle] n-ary semantic disagreement rate {:.4} ({} of {} decidable points); sample {:?}",
1868 report.disagreement_rate,
1869 report.disagreements.len(),
1870 report.considered,
1871 report.sample_disagreement()
1872 );
1873 }
1874 }
1875 }
1876 Ok(solid)
1877}
1878
1879fn attribute_to_tangent_node(error: KernelRefusal, nodes: &[Vec3]) -> KernelRefusal {
1910 let Some(node) = nodes.first() else {
1911 return error;
1912 };
1913 if !error.class.perturbation_eligible()
1914 || matches!(error.class, RefusalClass::TangentNodeSingularity)
1915 {
1916 return error;
1917 }
1918 if std::env::var("BREP_DEBUG_BOOL").is_ok() {
1919 eprintln!(
1920 "boolean: tear downstream of the tangent node at ({:.6},{:.6},{:.6}) attributed to it; the stage read: {}",
1921 node.x, node.y, node.z, error.message
1922 );
1923 }
1924 KernelRefusal::new(
1925 RefusalClass::TangentNodeSingularity,
1926 error.stage,
1927 format!(
1928 "boolean: unsupported singular/tangent-node surface intersection \
1929 at the tangent node at ({:.6},{:.6},{:.6}): the section through it did not \
1930 assemble into a closed shell",
1931 node.x, node.y, node.z
1932 ),
1933 )
1934}
1935
1936pub fn attribute_to_tangent_section(
1958 error: KernelRefusal,
1959 sections: &[crate::imprint::TangentSectionRecord],
1960 origins: &[FaceKey],
1961) -> KernelRefusal {
1962 if sections.is_empty()
1963 || !error.class.perturbation_eligible()
1964 || matches!(error.class, RefusalClass::TangentNodeSingularity)
1965 {
1966 return error;
1967 }
1968 let named = refusal_result_faces(&error.message)
1969 .into_iter()
1970 .filter_map(|id| origins.get(id.checked_sub(1)? as usize).copied())
1971 .collect::<Vec<FaceKey>>();
1972 let involving = |fallback: bool| {
1976 sections.iter().find(|section| {
1977 section.grazing.is_empty() != fallback && named.iter().any(|face| section.faces.contains(face))
1978 })
1979 };
1980 let Some(section) = involving(false).or_else(|| involving(true)) else {
1981 return error;
1982 };
1983 let at = |point: Vec3| {
1986 let shown = |value: f64| if value.abs() < 5e-7 { 0.0 } else { value };
1987 format!("({:.6},{:.6},{:.6})", shown(point.x), shown(point.y), shown(point.z))
1988 };
1989 let pierces = (!section.grazing.is_empty()).then(|| {
1995 let shown = section.grazing.len().min(4);
1996 let mut listed = section.grazing[..shown]
1997 .iter()
1998 .map(|(point, tangency)| format!("{} at |tan·n| = {tangency:.4}", at(*point)))
1999 .collect::<Vec<_>>()
2000 .join(", ");
2001 if section.grazing.len() > shown {
2002 listed.push_str(&format!(" and {} more", section.grazing.len() - shown));
2003 }
2004 listed
2005 });
2006 let pierce_only = section.pierce_only();
2007 let shape = if let (true, Some(pierces)) = (pierce_only, pierces.as_deref()) {
2008 format!(
2009 "cross at a grazing angle: a trim edge pierces the other carrier inside both \
2010 trims at {pierces}, below the marcher's start gate, and no transverse section was \
2011 marched between the pierces — a near-tangent crossing born on a tangent contact \
2012 (a third-order singularity) the imprint does not build yet"
2013 )
2014 } else if section.planar {
2015 format!(
2016 "touch along a tangent curve from {} to {} (length {:.6}, {} stations{}) which the \
2017 imprint does not build yet",
2018 at(section.start),
2019 at(section.end),
2020 section.length,
2021 section.stations,
2022 if section.closed { ", closed" } else { "" }
2023 )
2024 } else {
2025 format!(
2026 "touch along a curve through {} with neither carrier planar, a curved/curved \
2027 tangent contact the lane does not trace yet",
2028 at(section.start)
2029 )
2030 };
2031 let shape = match (pierce_only, pierces) {
2032 (false, Some(pierces)) => format!(
2033 "{shape}; a trim edge also pierces the other carrier inside both trims at {pierces}, \
2034 below the marcher's start gate, with no transverse section marched"
2035 ),
2036 _ => shape,
2037 };
2038 let involved = named
2039 .iter()
2040 .filter(|face| section.faces.contains(face))
2041 .map(|face| format!("{}/{}", face.operand, face.face_id))
2042 .collect::<Vec<_>>()
2043 .join(", ");
2044 KernelRefusal::new(
2045 RefusalClass::TangentNodeSingularity,
2046 error.stage,
2047 format!(
2048 "boolean: unsupported tangent-curve surface intersection between faces {}/{} and {}/{}: \
2049 the carriers {shape}; the refusal names face(s) {involved} the contact involves; {}",
2050 section.first.operand, section.first.face_id, section.second.operand, section.second.face_id,
2051 error.message
2052 ),
2053 )
2054}
2055
2056pub fn refusal_result_faces(message: &str) -> Vec<u64> {
2061 let mut ids = Vec::new();
2062 let digits_after = |text: &str| -> Option<u64> {
2063 let end = text.find(|c: char| !c.is_ascii_digit()).unwrap_or(text.len());
2064 text[..end].parse().ok()
2065 };
2066 for (index, _) in message.match_indices("face ") {
2067 if let Some(id) = digits_after(&message[index + "face ".len()..]) {
2068 ids.push(id);
2069 }
2070 }
2071 if let Some(start) = message.find("on faces [") {
2072 let rest = &message[start + "on faces [".len()..];
2073 let list = &rest[..rest.find(']').unwrap_or(rest.len())];
2074 for entry in list.split(", ") {
2075 let entry = entry.trim_start();
2076 if let Some(id) = digits_after(entry) {
2077 if entry[id.to_string().len()..].starts_with(" '") {
2078 ids.push(id);
2079 }
2080 }
2081 }
2082 }
2083 ids.sort_unstable();
2084 ids.dedup();
2085 ids
2086}
2087
2088pub fn boolean_operation_with_diagnostics(
2089 first: &BrepSolid,
2090 second: &BrepSolid,
2091 operation: BooleanOperation,
2092 options: &BooleanOptions,
2093) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
2094 if let Some(scaled) = WorkingScale::of(&[first, second], options)? {
2095 let mut outcome = boolean_operation_with_diagnostics(&scaled.solids[0], &scaled.solids[1], operation, &scaled.options)
2096 .map_err(|error| scaled.refusal(error))?;
2097 outcome.value = scaled.back(&outcome.value)?;
2098 outcome.diagnostics.count_n("working_scale.fired", 1);
2099 outcome.diagnostics.measure_max("working_scale.factor", scaled.factor);
2100 return Ok(outcome);
2101 }
2102 let _account = profile::Scope::new("boolean.other");
2103 let closed_inputs = matches!(std::env::var("BREP_CLOSED_OPERAND_INPUT").as_deref(), Err(_) | Ok("1") | Ok("on"));
2104 if let (true, Some(later)) = (reseat::seam_reseat_enabled(), &options.seam_reseat_later_references) {
2105 let started = Instant::now();
2106 let (first, second) = reseat::reseat_tangent_seams(first, second, later, options.tolerance);
2107 profile_stage("seam_prepare_ms", started.elapsed().as_secs_f64() * 1000.0);
2108 return boolean_operation_with_diagnostics_impl(&first, &second, operation, options, closed_inputs).map(without_sliver_shells);
2109 }
2110 boolean_operation_with_diagnostics_impl(first, second, operation, options, closed_inputs).map(without_sliver_shells)
2111}
2112
2113fn without_sliver_shells(mut outcome: KernelOutcome<BrepSolid>) -> KernelOutcome<BrepSolid> {
2115 let dropped = drop_sliver_shells(&mut outcome.value);
2116 if dropped > 0 {
2117 outcome.diagnostics.count_n("sliver_shell.dropped", dropped as u64);
2118 }
2119 outcome
2120}
2121
2122pub fn boolean_operation_with_diagnostics_impl(
2123 first: &BrepSolid,
2124 second: &BrepSolid,
2125 operation: BooleanOperation,
2126 options: &BooleanOptions,
2127 closed_inputs: bool,
2128) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
2129 let _coedge_memo = crate::topology::CoedgeMemoScope::open(true);
2132 if matches!(operation, BooleanOperation::Intersect)
2135 && [first, second].iter().any(|body| body.kind == crate::BodyKind::Sheet)
2136 && match std::env::var("BREP_SHEET_TRIM").as_deref() {
2137 Ok("1") => true,
2138 Ok("0") => false,
2139 _ => options.sheet_trim,
2140 }
2141 {
2142 return sheet::trim(first, second, options);
2143 }
2144 if matches!(operation, BooleanOperation::Union | BooleanOperation::Subtract) {
2153 if let Some(operand) = [first, second]
2154 .iter()
2155 .position(|solid| solid.kind == crate::BodyKind::Sheet)
2156 {
2157 return Err(KernelRefusal::input(
2158 KernelStage::Collect,
2159 "sheet_operand",
2160 format!(
2161 "boolean: operand {operand} is a Sheet, which encloses no solid; union and \
2162 subtract of a sheet are refused; Intersect trims a Sheet by a Solid"
2163 ),
2164 ));
2165 }
2166 }
2167 let mut outcome = boolean_operation_with_diagnostics_core(first, second, operation, options)?;
2173 let closure_started = closed_inputs.then(Instant::now);
2174 if closed_inputs {
2175 for (operand, solid) in [first, second].into_iter().enumerate() {
2176 let open = one_use_edges(solid);
2177 if open > 0 {
2178 return Err(KernelRefusal::input(KernelStage::Collect, "operand_closure", format!(
2179 "boolean: operand {operand} is not a closed shell: {open} of its edges bound only one face, so its inside is undefined"
2180 )));
2181 }
2182 }
2183 }
2184 if let Some(started) = closure_started {
2185 let ms = started.elapsed().as_secs_f64() * 1000.0;
2186 profile_stage("operand_closure_ms", ms);
2187 outcome.diagnostics.measure_max("timing.operand_closure_ms", ms);
2188 }
2189 Ok(outcome)
2190}
2191
2192fn boolean_operation_with_diagnostics_core(
2193 first: &BrepSolid, second: &BrepSolid, operation: BooleanOperation, options: &BooleanOptions,
2194) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
2195
2196 if let Some(offset) = crate::recentre::control_offset_at_entry() {
2199 return boolean_operation_with_diagnostics_at_offset(first, second, operation, options, offset);
2200 }
2201 let mut bounds = operand_bounds(first);
2204 bounds.include(operand_bounds(second));
2205 if let Some(offset) = crate::recentre::guard_offset(bounds) {
2206 crate::recentre::profile_fired("boolean", offset, bounds);
2207 let mut outcome = boolean_translated(first, second, operation, options, offset, crate::recentre::EntryKind::Guard)?;
2208 outcome.diagnostics.count_n("recentre.fired", 1);
2209 outcome.diagnostics.measure_max("recentre.distance", offset.length());
2210 return Ok(outcome);
2211 }
2212 let mut tangent_nodes = Vec::new();
2213 let (mut outcome, soundness_candidates) =
2214 boolean_pipeline(first, second, operation, options, &mut tangent_nodes)
2215 .map_err(|error| attribute_to_tangent_node(error, &tangent_nodes))?;
2216 let stage_started = Instant::now();
2229 let accepted = match &soundness_candidates {
2230 Some(candidates) => crate::accept_sound_against_scoped(&[first, second], outcome.value, "boolean", candidates),
2233 None => crate::accept_sound_against(&[first, second], outcome.value, "boolean"),
2234 };
2235 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
2236 profile_stage("soundness_ms", stage_ms);
2237 outcome.diagnostics.measure_max("timing.soundness_ms", stage_ms);
2238 outcome.value = accepted?;
2239 Ok(outcome)
2240}
2241
2242pub fn boolean_operation_with_diagnostics_at_offset(
2246 first: &BrepSolid,
2247 second: &BrepSolid,
2248 operation: BooleanOperation,
2249 options: &BooleanOptions,
2250 offset: Vec3,
2251) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
2252 boolean_translated(first, second, operation, options, offset, crate::recentre::EntryKind::Control)
2253}
2254
2255fn boolean_translated(
2257 first: &BrepSolid,
2258 second: &BrepSolid,
2259 operation: BooleanOperation,
2260 options: &BooleanOptions,
2261 offset: Vec3,
2262 kind: crate::recentre::EntryKind,
2263) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
2264 let _entry = crate::recentre::TranslatedEntry::open(kind);
2265 let translate = |solid: &BrepSolid, offset: Vec3| {
2266 crate::recentre::translate_solid(solid, offset).map_err(|message| {
2267 KernelRefusal::internal(
2268 KernelStage::Collect,
2269 "translation_control",
2270 format!("boolean: the translation control could not move an operand: {message}"),
2271 )
2272 })
2273 };
2274 let moved_first = translate(first, offset)?;
2275 let moved_second = translate(second, offset)?;
2276 let outcome = boolean_operation_with_diagnostics(&moved_first, &moved_second, operation, options)?;
2277 let value = translate(&outcome.value, offset.scale(-1.0))?;
2278 Ok(KernelOutcome { value, diagnostics: outcome.diagnostics })
2279}
2280
2281fn profile_stage(code: &str, ms: f64) {
2285 let row = match code {
2286 "heal_ms" => Some("boolean.operand_prepare"),
2287 "imprint_ms" => Some("boolean.imprint"),
2288 "edge_split_ms" => Some("boolean.edge_split"),
2289 "fragment_ms" => Some("boolean.fragment"),
2290 "select_ms" => Some("boolean.select"),
2291 "assemble_ms" => Some("boolean.assemble"),
2292 "face_merge_ms" => Some("boolean.face_merge"),
2293 "soundness_ms" => Some("boolean.soundness"),
2294 "operand_closure_ms" => Some("boolean.operand_closure"),
2295 "seam_prepare_ms" => Some("boolean.seam_prepare"),
2296 "final_validate_ms" => Some("boolean.final_validate"),
2297 _ => None,
2298 };
2299 if let Some(row) = row { profile::record(row, ms); }
2300 if crate::profile::profile_enabled() {
2301 profile_line!("boolean.{code}={ms:.2}");
2302 }
2303}
2304
2305struct BooleanStageDump {
2310 directory: std::path::PathBuf,
2311 serial: usize,
2312}
2313
2314impl BooleanStageDump {
2315 fn open() -> Option<Self> {
2316 static SERIAL: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
2317 let directory = std::env::var("BREP_BOOLEAN_DUMP").ok().filter(|value| !value.is_empty())?;
2318 let serial = SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2319 Some(Self { directory: directory.into(), serial })
2320 }
2321
2322 fn write<T: Serialize + ?Sized>(&self, stage: &str, value: &T) {
2323 let path = self.directory.join(format!("{:03}-{stage}.json", self.serial));
2324 match serde_json::to_string(value) {
2325 Ok(text) => {
2326 if let Err(error) = std::fs::write(&path, text) {
2327 eprintln!("BREP_BOOLEAN_DUMP {}: {error}", path.display());
2328 }
2329 }
2330 Err(error) => eprintln!("BREP_BOOLEAN_DUMP {stage}: {error}"),
2331 }
2332 }
2333}
2334
2335pub fn boolean_policy(
2337 first: &BrepSolid,
2338 second: &BrepSolid,
2339 options: &BooleanOptions,
2340) -> Result<KernelTolerances, KernelRefusal> {
2341 let policy = options
2342 .tolerances
2343 .unwrap_or_else(|| KernelTolerances::for_pair(first, second, options.tolerance));
2344 policy.check().or_input(KernelStage::Collect, "tolerances")?;
2345 Ok(policy)
2346}
2347
2348fn prepared_operands(
2351 first: &BrepSolid,
2352 second: &BrepSolid,
2353 policy: &KernelTolerances,
2354) -> Result<(BrepSolid, BrepSolid), KernelRefusal> {
2355 let stage_started = Instant::now();
2364 let mut first_owned = first.clone();
2365 let mut second_owned = second.clone();
2366 crate::heal::heal_operands(&mut first_owned, policy)?;
2367 crate::heal::heal_operands(&mut second_owned, policy)?;
2368 profile_stage("heal.operands_ms", stage_started.elapsed().as_secs_f64() * 1_000.0);
2369 let refit_started = Instant::now();
2373 crate::heal::refit_inherited_trims(&mut first_owned, policy)?;
2374 crate::heal::refit_inherited_trims(&mut second_owned, policy)?;
2375 profile_stage("heal.refit_ms", refit_started.elapsed().as_secs_f64() * 1_000.0);
2376 if crate::profile::profile_enabled() {
2377 let (hits, misses) = crate::reading_memo::counts();
2378 profile_line!("boolean.reading_memo hits={hits} misses={misses}");
2379 }
2380 profile_stage("heal_ms", stage_started.elapsed().as_secs_f64() * 1_000.0);
2381 normalize_operand_band_seams(&mut first_owned)?;
2386 normalize_operand_band_seams(&mut second_owned)?;
2387 Ok((first_owned, second_owned))
2388}
2389
2390fn boolean_imprint_options(options: &BooleanOptions, tolerance: f64) -> ImprintOptions {
2391 let mut imprint_options = options.imprint.clone();
2392 imprint_options.tolerance = tolerance;
2393 imprint_options
2394}
2395
2396pub fn boolean_split_operands(
2406 first: &BrepSolid,
2407 second: &BrepSolid,
2408 options: &BooleanOptions,
2409) -> Result<(BrepSolid, BrepSolid), KernelRefusal> {
2410 if let Some(scaled) = WorkingScale::of(&[first, second], options)? {
2411 let (split_first, split_second) = boolean_split_operands(&scaled.solids[0], &scaled.solids[1], &scaled.options)
2412 .map_err(|error| scaled.refusal(error))?;
2413 return Ok((scaled.back(&split_first)?, scaled.back(&split_second)?));
2414 }
2415 let policy = boolean_policy(first, second, options)?;
2416 let (first, second) = prepared_operands(first, second, &policy)?;
2417 let imprint = build_imprints(&first, &second, &boolean_imprint_options(options, policy.model))?;
2418 let (split_first, _) = apply_edge_splits_with_map(&first, 0, &imprint)?;
2419 let (split_second, _) = apply_edge_splits_with_map(&second, 1, &imprint)?;
2420 Ok((split_first, split_second))
2421}
2422
2423fn operand_bounds(solid: &BrepSolid) -> crate::Aabb {
2427 let mut bounds = crate::Aabb::from_points(solid.vertices.iter().map(|vertex| vertex.point));
2428 for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
2429 match crate::Aabb::from_surface_controls(&face.surface) {
2430 Ok(face_bounds) => bounds.include(face_bounds),
2431 Err(_) => {
2432 return crate::Aabb {
2433 minimum: Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY),
2434 maximum: Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY),
2435 }
2436 }
2437 }
2438 }
2439 bounds
2440}
2441
2442fn line_or_point_contact(first: &BrepSolid, second: &BrepSolid, bounds: [crate::Aabb; 2]) -> bool {
2448 apart_axes(bounds) >= 2 && plain_hull_solid(first) && plain_hull_solid(second)
2449}
2450
2451fn boxes_share_no_interior(first: &BrepSolid, second: &BrepSolid, bounds: [crate::Aabb; 2]) -> bool {
2454 apart_axes(bounds) >= 1 && plain_hull_solid(first) && plain_hull_solid(second)
2455}
2456
2457fn apart_axes([a, b]: [crate::Aabb; 2]) -> usize {
2459 let apart = |a_min: f64, a_max: f64, b_min: f64, b_max: f64| a_max <= b_min || b_max <= a_min;
2460 [
2461 apart(a.minimum.x, a.maximum.x, b.minimum.x, b.maximum.x),
2462 apart(a.minimum.y, a.maximum.y, b.minimum.y, b.maximum.y),
2463 apart(a.minimum.z, a.maximum.z, b.minimum.z, b.maximum.z),
2464 ]
2465 .into_iter()
2466 .filter(|&apart| apart)
2467 .count()
2468}
2469
2470fn plain_hull_solid(solid: &BrepSolid) -> bool {
2472 solid.kind == crate::BodyKind::Solid
2473 && solid.cells.is_empty()
2474 && solid.shells.iter().flat_map(|shell| &shell.faces).all(|face| {
2475 face.surface.control_points.iter().flatten().all(|control| control.w > 0.0 && control.w.is_finite())
2476 })
2477}
2478
2479fn soundness_candidates(
2484 solid: &BrepSolid,
2485 scope: &AssemblyScope,
2486 bounds: [crate::Aabb; 2],
2487 band: f64,
2488) -> HashSet<u64> {
2489 let mut candidates = HashSet::default();
2490 for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
2491 if scope.examined.contains(&face.id) {
2492 candidates.insert(face.id);
2493 continue;
2494 }
2495 let Some(&operand) = scope.operand_of.get(&face.id) else {
2496 candidates.insert(face.id);
2497 continue;
2498 };
2499 let other = bounds[usize::from(operand == 0)];
2500 match crate::Aabb::from_surface_controls(&face.surface) {
2501 Ok(face_bounds) if !face_bounds.intersects(other, band) => {}
2502 _ => {
2503 candidates.insert(face.id);
2504 }
2505 }
2506 }
2507 candidates
2508}
2509
2510fn empty_solid() -> BrepSolid {
2512 BrepSolid {
2513 mass_properties_cache: Default::default(),
2514 cells: Default::default(),
2515 id: 0,
2516 vertices: Vec::new(),
2517 edges: Vec::new(),
2518 shells: Vec::new(),
2519 genus: 0,
2520 kind: crate::BodyKind::Solid,
2521 }
2522}
2523
2524fn concatenate_disjoint(first: &BrepSolid, second: &BrepSolid) -> BrepSolid {
2530 let mut vertices = Vec::new();
2531 let mut edges = Vec::new();
2532 let mut shells = Vec::new();
2533 let mut used_face_names = HashSet::<String>::default();
2534 let (mut next_face_id, mut next_loop_id, mut next_coedge_id) = (1u64, 1u64, 1u64);
2535 for operand in [first, second] {
2536 let vertex_base = vertices.len() as u64;
2537 let edge_base = edges.len() as u64;
2538 let mut vertex_ids: HashMap<u64, u64> = HashMap::default();
2539 for (index, vertex) in operand.vertices.iter().enumerate() {
2540 let id = vertex_base + index as u64 + 1;
2541 vertex_ids.insert(vertex.id, id);
2542 vertices.push(VertexRecord { id, point: vertex.point });
2543 }
2544 let mut edge_ids: HashMap<u64, u64> = HashMap::default();
2545 for (index, edge) in operand.edges.iter().enumerate() {
2546 let id = edge_base + index as u64 + 1;
2547 edge_ids.insert(edge.id, id);
2548 edges.push(EdgeRecord {
2549 id,
2550 curve: edge.curve.clone(),
2551 t0: edge.t0,
2552 t1: edge.t1,
2553 start_vertex_id: vertex_ids.get(&edge.start_vertex_id).copied().unwrap_or(edge.start_vertex_id),
2554 end_vertex_id: vertex_ids.get(&edge.end_vertex_id).copied().unwrap_or(edge.end_vertex_id),
2555 degenerate: edge.degenerate,
2556 name: edge.name.clone(),
2557 });
2558 }
2559 for shell in &operand.shells {
2560 let mut faces = Vec::with_capacity(shell.faces.len());
2561 for face in &shell.faces {
2562 let loops = face
2563 .loops
2564 .iter()
2565 .map(|loop_record| {
2566 let coedges = loop_record
2567 .coedges
2568 .iter()
2569 .map(|coedge| {
2570 let id = next_coedge_id;
2571 next_coedge_id += 1;
2572 CoedgeRecord {
2573 id,
2574 edge_id: edge_ids.get(&coedge.edge_id).copied().unwrap_or(coedge.edge_id),
2575 forward: coedge.forward,
2576 pcurve: coedge.pcurve.clone(),
2577 }
2578 })
2579 .collect();
2580 let id = next_loop_id;
2581 next_loop_id += 1;
2582 LoopRecord { id, coedges }
2583 })
2584 .collect();
2585 let name = face.name.clone().map(|base| {
2586 if used_face_names.insert(base.clone()) {
2587 base
2588 } else {
2589 let mut suffix = 1usize;
2590 loop {
2591 let candidate = format!("{base}_{suffix}");
2592 if used_face_names.insert(candidate.clone()) {
2593 break candidate;
2594 }
2595 suffix += 1;
2596 }
2597 }
2598 });
2599 faces.push(FaceRecord {
2600 id: next_face_id,
2601 surface: face.surface.clone(),
2602 same_sense: face.same_sense,
2603 loops,
2604 name,
2605 });
2606 next_face_id += 1;
2607 }
2608 shells.push(ShellRecord { id: shells.len() as u64 + 1, faces });
2609 }
2610 }
2611 BrepSolid {
2612 mass_properties_cache: Default::default(),
2613 cells: Default::default(),
2614 id: 1,
2615 vertices,
2616 edges,
2617 shells,
2618 genus: first.genus + second.genus,
2619 kind: crate::BodyKind::Solid,
2620 }
2621}
2622
2623fn boolean_pipeline(
2626 first: &BrepSolid,
2627 second: &BrepSolid,
2628 operation: BooleanOperation,
2629 options: &BooleanOptions,
2630 tangent_nodes: &mut Vec<Vec3>,
2631) -> Result<(KernelOutcome<BrepSolid>, Option<HashSet<u64>>), KernelRefusal> {
2632 let _work = crate::imprint::work_profile::Scope::open("boolean");
2633 let replaced_operands = operand_state::replace_operands(first, second, operation, options);
2634 let (first, second) = match &replaced_operands {
2635 Some((first, second)) => (first, second),
2636 None => (first, second),
2637 };
2638 let policy = boolean_policy(first, second, options)?;
2639 let tolerance = policy.model;
2640 let bounds = [operand_bounds(first), operand_bounds(second)];
2655 let disjoint = disjoint_fast_path(options) && !bounds[0].intersects(bounds[1], policy.sew_search);
2656 let contact = !disjoint
2657 && contact_fast_path(options)
2658 && options.seam_reseat_later_references.is_some()
2659 && line_or_point_contact(first, second, bounds);
2660 let contact = contact
2665 || (!disjoint
2666 && matches!(operation, BooleanOperation::Intersect)
2667 && contact_fast_path(options)
2668 && boxes_share_no_interior(first, second, bounds));
2669 if disjoint || contact {
2670 let operation_started = Instant::now();
2671 let mut diagnostics = KernelDiagnostics::default();
2672 diagnostics.count_n(
2673 "collect.faces",
2674 first.shells.iter().chain(&second.shells).map(|shell| shell.faces.len() as u64).sum(),
2675 );
2676 diagnostics.count(if contact { "boolean.contact_fast_path" } else { "boolean.disjoint_fast_path" });
2677 diagnostics.measure_max("tolerance.model", policy.model);
2678 diagnostics.measure_max("tolerance.sew_search", policy.sew_search);
2679 let value = match operation {
2680 BooleanOperation::Union => concatenate_disjoint(first, second),
2681 BooleanOperation::Subtract => first.clone(),
2682 BooleanOperation::Intersect => {
2683 diagnostics.event(
2684 DiagnosticSeverity::Info,
2685 KernelStage::Select,
2686 "boolean.empty_result",
2687 format!("{operation:?} of witnessed-non-overlapping operands is empty"),
2688 );
2689 empty_solid()
2690 }
2691 };
2692 let stage_ms = operation_started.elapsed().as_secs_f64() * 1_000.0;
2693 profile_stage("disjoint_fast_path_ms", stage_ms);
2694 diagnostics.measure_max("timing.total_ms", stage_ms);
2695 return Ok((KernelOutcome { value, diagnostics }, Some(HashSet::default())));
2696 }
2697 let heal_started = Instant::now();
2698 let (first_owned, second_owned) = prepared_operands(first, second, &policy)?;
2699 let heal_ms = heal_started.elapsed().as_secs_f64() * 1_000.0;
2700 let first = &first_owned;
2701 let second = &second_owned;
2702
2703 let mut diagnostics = KernelDiagnostics::default();
2704 diagnostics.measure_max("timing.heal_ms", heal_ms);
2707 let fit_scope = crate::PcurveFitScope::open();
2712 let polyline_scope = crate::PolylineFitScope::open();
2716 let operation_started = Instant::now();
2717 diagnostics.count_n(
2718 "collect.faces",
2719 first
2720 .shells
2721 .iter()
2722 .chain(&second.shells)
2723 .map(|shell| shell.faces.len() as u64)
2724 .sum(),
2725 );
2726 diagnostics.measure_max("tolerance.model", policy.model);
2727 diagnostics.measure_max("tolerance.sew_search", policy.sew_search);
2728
2729 let imprint_options = boolean_imprint_options(options, tolerance);
2730 let stage_started = Instant::now();
2731 let imprint = build_imprints(first, second, &imprint_options)?;
2732 tangent_nodes.extend_from_slice(&imprint.tangent_nodes);
2733 if std::env::var("BREP_DEBUG_BOOL").is_ok() {
2734 for piece in &imprint.pieces {
2735 let start = piece.curve.evaluate(piece.t0);
2736 let end = piece.curve.evaluate(piece.t1);
2737 eprintln!(
2738 "piece {} supports={:?} t=[{:.6},{:.6}] start={:?} end={:?}",
2739 piece.id, piece.support_faces, piece.t0, piece.t1, start, end
2740 );
2741 }
2742 for entry in &imprint.by_face {
2743 eprintln!(
2744 "by_face operand={} face={} pieces={:?}",
2745 entry.operand, entry.face_id, entry.piece_ids
2746 );
2747 }
2748 for split in &imprint.edge_splits {
2749 eprintln!(
2750 "edge_split operand={} edge={} params={:?}",
2751 split.operand, split.edge_id, split.parameters
2752 );
2753 }
2754 }
2755 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
2756 profile_stage("imprint_ms", stage_ms);
2757 diagnostics.measure_max("timing.imprint_ms", stage_ms);
2758 diagnostics.count_n("intersect.pieces", imprint.pieces.len() as u64);
2759 diagnostics.count_n("intersect.vertices", imprint.vertices.len() as u64);
2760 diagnostics.count_n("intersect.edge_splits", imprint.edge_splits.len() as u64);
2761 let (march_swap_rescues, clip_swap_rescues) = crate::imprint::take_rescue_firings();
2762 diagnostics.count_n("intersect.march_swap_rescue", march_swap_rescues);
2763 diagnostics.count_n("intersect.clip_swap_rescue", clip_swap_rescues);
2764 let touch = TouchCensus::build([first, second], &imprint);
2765 touch.report(&mut diagnostics);
2766 let stage_started = Instant::now();
2767 let (split_first, split_map_first) = apply_edge_splits_with_map(first, 0, &imprint)?;
2768 let (split_second, split_map_second) = apply_edge_splits_with_map(second, 1, &imprint)?;
2769 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
2770 profile_stage("edge_split_ms", stage_ms);
2771 diagnostics.measure_max("timing.edge_split_ms", stage_ms);
2772 let stage_started = Instant::now();
2773 crate::classification::classify_profile_begin();
2774 let fragments_a = crate::fragment::fragment_solid_against(&split_first, 0, &imprint, crate::fragment::bounded_carriers(second).then_some((bounds[1], policy.sew_search)))?;
2775 let fragments_b = crate::fragment::fragment_solid_against(&split_second, 1, &imprint, crate::fragment::bounded_carriers(first).then_some((bounds[0], policy.sew_search)))?;
2776 crate::classification::classify_profile_report("fragment");
2777 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
2778 profile_stage("fragment_ms", stage_ms);
2779 diagnostics.measure_max("timing.fragment_ms", stage_ms);
2780 diagnostics.count_n(
2781 "fragment.candidates",
2782 (fragments_a.len() + fragments_b.len()) as u64,
2783 );
2784 touch.report_fragments(&[&fragments_a, &fragments_b], &mut diagnostics);
2785 let a_surface_samples: Vec<Vec3> = fragments_a
2790 .iter()
2791 .flat_map(|fragment| {
2792 std::iter::once(fragment.test_point).chain(fragment.extra_test_points.iter().copied())
2793 })
2794 .collect();
2795 let b_surface_samples: Vec<Vec3> = fragments_b
2796 .iter()
2797 .flat_map(|fragment| {
2798 std::iter::once(fragment.test_point).chain(fragment.extra_test_points.iter().copied())
2799 })
2800 .collect();
2801 let stage_started = Instant::now();
2802 let mut barrier_edges: HashSet<(u8, u64)> = imprint
2803 .pieces
2804 .iter()
2805 .filter_map(|piece| piece.shared_edge.map(|(operand, edge_id, _)| (operand, edge_id)))
2806 .collect();
2807 barrier_edges.extend(imprint.barrier_edges.iter().copied());
2808 for (operand, split_map) in [(0u8, &split_map_first), (1u8, &split_map_second)] {
2814 let minted: Vec<(u8, u64)> = barrier_edges
2815 .iter()
2816 .filter(|(barrier_operand, _)| *barrier_operand == operand)
2817 .filter_map(|(_, edge_id)| split_map.get(edge_id))
2818 .flat_map(|sub_ids| sub_ids.iter().map(|sub_id| (operand, *sub_id)))
2819 .collect();
2820 barrier_edges.extend(minted);
2821 }
2822 crate::classification::classify_profile_begin();
2823 let coincident = coincident_pairs(
2824 &fragments_a,
2825 &fragments_b,
2826 first,
2827 second,
2828 &imprint.cosurface_pairs,
2829 tolerance,
2830 )?;
2831 let sector_mode = sector::sector_mode(options);
2832 let mut select_census = sector::SelectCensus::default();
2833 let mut selected = select_fragments(
2834 fragments_a,
2835 fragments_b,
2836 first,
2837 second,
2838 operation,
2839 tolerance,
2840 &barrier_edges,
2841 &imprint,
2842 &coincident,
2843 sector_mode,
2844 &mut select_census,
2845 )?;
2846 let resewn = resew_coincident_rims(
2847 &mut selected,
2848 [&split_first, &split_second],
2849 [first, second],
2850 &imprint.cosurface_pairs,
2851 operation,
2852 tolerance,
2853 )?;
2854 diagnostics.count_n("select.coincident_pairs", coincident.len() as u64);
2855 diagnostics.count_n("select.rims_resewn", resewn as u64);
2856 crate::classification::classify_profile_report("select");
2857 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
2858 profile_stage("select_ms", stage_ms);
2859 diagnostics.measure_max("timing.select_ms", stage_ms);
2860 diagnostics.count_n("select.fragments", selected.len() as u64);
2861 diagnostics.count_n("select.sector_eligible", select_census.eligible);
2863 diagnostics.count_n("select.sector_primary", select_census.sector_primary);
2864 diagnostics.count_n("select.sector_fallback", select_census.sector_fallback);
2865 diagnostics.count_n("select.sector_disagree", select_census.disagree);
2866 diagnostics.count_n("select.ray_casts", select_census.ray_casts);
2867 diagnostics.count_n("select.on_votes", select_census.on_votes);
2868 diagnostics.count_n("select.overturns", select_census.overturns);
2869 if sector_mode != sector::SectorMode::Off || std::env::var_os("BREP_SECTOR_CENSUS").is_some() {
2870 sector::sector_census_line(|| {
2871 format!(
2872 "selection mode={sector_mode:?} select_ms={stage_ms:.3} selected={} eligible={} primary={} fallback={} disagree={} ray_casts={} on_votes={} overturns={}",
2873 selected.len(),
2874 select_census.eligible,
2875 select_census.sector_primary,
2876 select_census.sector_fallback,
2877 select_census.disagree,
2878 select_census.ray_casts,
2879 select_census.on_votes,
2880 select_census.overturns
2881 )
2882 });
2883 }
2884 if selected.is_empty()
2906 && !imprint.section_evidence
2907 && std::env::var("BREP_EMPTY_BOOLEAN").as_deref() != Ok("0")
2908 {
2909 let strictly_inside = |samples: &[Vec3], other: &BrepSolid| -> Result<bool, KernelRefusal> {
2910 for &sample in samples {
2911 if classify_point(sample, other, tolerance).or_refuse(KernelStage::Validate, "classify_point")?.class == PointClass::In {
2912 return Ok(true);
2913 }
2914 }
2915 Ok(false)
2916 };
2917 let outside_witness = |samples: &[Vec3], other: &BrepSolid| -> Result<bool, KernelRefusal> {
2918 for &sample in samples {
2919 if classify_point(sample, other, tolerance).or_refuse(KernelStage::Validate, "classify_point")?.class == PointClass::Out {
2920 return Ok(true);
2921 }
2922 }
2923 Ok(false)
2924 };
2925 let legitimate = match operation {
2926 BooleanOperation::Intersect => {
2927 !strictly_inside(&a_surface_samples, second)?
2928 && !strictly_inside(&b_surface_samples, first)?
2929 }
2930 BooleanOperation::Subtract => !outside_witness(&a_surface_samples, second)?,
2931 BooleanOperation::Union => false,
2932 };
2933 if legitimate {
2934 diagnostics.event(
2935 DiagnosticSeverity::Info,
2936 KernelStage::Select,
2937 "boolean.empty_result",
2938 format!("{operation:?} of witnessed-non-overlapping operands is empty"),
2939 );
2940 fit_scope.close().report_into(&mut diagnostics);
2941 polyline_scope.close().report_into(&mut diagnostics);
2942 diagnostics.measure_max(
2943 "timing.total_ms",
2944 operation_started.elapsed().as_secs_f64() * 1_000.0,
2945 );
2946 return Ok((
2947 KernelOutcome {
2948 value: empty_solid(),
2949 diagnostics,
2950 },
2951 None,
2952 ));
2953 }
2954 }
2955 let solids = [(0, &split_first), (1, &split_second)]
2956 .into_iter()
2957 .collect::<HashMap<_, _>>();
2958 let dump = BooleanStageDump::open();
2959 if let Some(dump) = &dump {
2960 dump.write("first", &split_first);
2961 dump.write("second", &split_second);
2962 dump.write("selected", &selected);
2963 }
2964 let stage_started = Instant::now();
2965 let assembled_origins: Vec<FaceKey> = if imprint.tangent_sections.is_empty() {
2969 Vec::new()
2970 } else {
2971 selected
2972 .iter()
2973 .map(|fragment| FaceKey { operand: fragment.operand, face_id: fragment.source_face_id })
2974 .collect()
2975 };
2976 let attributable: Vec<crate::imprint::TangentSectionRecord> = imprint
2983 .tangent_sections
2984 .iter()
2985 .filter(|section| imprint.tangent_nodes.is_empty() || section.grazing.is_empty())
2986 .cloned()
2987 .collect();
2988 let attribute = |error: KernelRefusal| {
2989 attribute_to_tangent_section(error, &attributable, &assembled_origins)
2990 };
2991 let cellular_result = matches!(operation, BooleanOperation::Union)
2992 && cellular::enabled(options)
2993 && cellular::complete_contact(first, second, &selected, tolerance);
2994 let (solid, scope) = if cellular_result {
2995 (assemble::assemble_cellular_fragments(selected, &solids, &imprint, tolerance)
2996 .map_err(attribute)?, None)
2997 } else if untouched_passthrough(options) {
2998 assemble_fragments_scoped(selected, &solids, &imprint, tolerance, &touch, touched_assembly(options))
2999 .map_err(attribute)?
3000 } else {
3001 (assemble_fragments(selected, &solids, &imprint, tolerance).map_err(attribute)?, None)
3002 };
3003 if let Some(scope) = &scope {
3004 diagnostics.count_n("passthrough.faces_examined", scope.examined.len() as u64);
3005 }
3006 if let Some(dump) = &dump {
3007 dump.write("assembled", &solid);
3008 }
3009 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
3010 profile_stage("assemble_ms", stage_ms);
3011 diagnostics.measure_max("timing.assemble_ms", stage_ms);
3012 let stage_started = Instant::now();
3013 let declines_before = crate::face_merge::declines_served();
3014 let area_checks_before = crate::face_merge::boundary_area_checks();
3015 if std::env::var("BREP_DEBUG_PREMERGE_VALIDATE").is_ok() {
3016 let issues = solid.validate();
3017 eprintln!(
3018 "pre-merge validation: {} issue(s){}",
3019 issues.len(),
3020 issues
3021 .first()
3022 .map(|issue| format!(" — first: {}", issue.message))
3023 .unwrap_or_default()
3024 );
3025 }
3026 let solid = if solid.kind != crate::BodyKind::Cellular && options.merge_coplanar_faces
3027 && std::env::var("BREP_COPLANAR_MERGE").as_deref() != Ok("0")
3028 {
3029 let merged = match &scope {
3030 Some(scope) => merge_same_surface_faces_scoped(
3034 &solid,
3035 tolerance,
3036 &options.keep_unmerged_name_substrs,
3037 &scope.examined,
3038 )?,
3039 None => merge_same_surface_faces_excluding(
3040 &solid,
3041 tolerance,
3042 &options.keep_unmerged_name_substrs,
3043 )?,
3044 };
3045 merge_curve_continuation_edges(&merged, tolerance).map_err(|refusal| KernelRefusal { stage: KernelStage::Validate, ..refusal })?
3050 } else {
3051 solid
3052 };
3053 if let Some(dump) = &dump {
3054 dump.write("merged", &solid);
3055 }
3056 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
3057 profile_stage("face_merge_ms", stage_ms);
3058 if crate::profile::profile_enabled() {
3059 profile_line!("boolean.merge_declines served={}", crate::face_merge::declines_served() - declines_before);
3060 let area_checks = crate::face_merge::boundary_area_checks();
3061 if area_checks != area_checks_before {
3062 profile_line!("boolean.merge_area_checks boundary={} integrated={}", area_checks.0 - area_checks_before.0, area_checks.1 - area_checks_before.1);
3063 }
3064 }
3065 diagnostics.measure_max("timing.face_merge_ms", stage_ms);
3066 let validation_started = Instant::now();
3067 let validation = solid.validate_detailed_scoped(&policy, scope.as_ref().map(|scope| &scope.examined));
3068 profile_stage("final_validate_ms", validation_started.elapsed().as_secs_f64() * 1000.0);
3069 diagnostics.count_n("validate.issues", validation.issues.len() as u64);
3070 diagnostics.count_n(
3071 "validate.wire_warnings",
3072 validation.wire_warnings.len() as u64,
3073 );
3074 diagnostics.measure_max("validate.max_pcurve_error", validation.max_pcurve_error);
3075 for warning in &validation.wire_warnings {
3076 diagnostics.event(
3077 DiagnosticSeverity::Warning,
3078 KernelStage::Validate,
3079 "validate.uv_wire",
3080 warning.message.clone(),
3081 );
3082 }
3083 for issue in &validation.issues {
3084 diagnostics.event(
3085 DiagnosticSeverity::Error,
3086 KernelStage::Validate,
3087 "validate.brep",
3088 issue.message.clone(),
3089 );
3090 }
3091 fit_scope.close().report_into(&mut diagnostics);
3092 polyline_scope.close().report_into(&mut diagnostics);
3093 diagnostics.measure_max(
3094 "timing.total_ms",
3095 operation_started.elapsed().as_secs_f64() * 1_000.0,
3096 );
3097 if !validation.issues.is_empty() {
3098 return Err(KernelRefusal::new(
3099 RefusalClass::InvalidResultTopology { issues: validation.issues.len() as u32 },
3100 KernelStage::Validate,
3101 format!(
3102 "boolean_operation: invalid result: {:?}",
3103 validation.issues
3104 )));
3105 }
3106 if std::env::var("BREP_DEBUG_BOOL").is_ok() {
3112 if let Ok(report) =
3113 crate::oracle::boolean_semantic_disagreement(first, second, operation, &solid, 200)
3114 {
3115 if report.is_flagged() {
3116 eprintln!(
3117 "[oracle] semantic disagreement rate {:.4} ({} of {} decidable points); sample {:?}",
3118 report.disagreement_rate,
3119 report.disagreements.len(),
3120 report.considered,
3121 report.sample_disagreement()
3122 );
3123 }
3124 }
3125 let fusable_band = crate::tolerance::assembler_weld(policy.model);
3126 let fusables = crate::oracle::boolean_residual_fusables(&solid, fusable_band);
3127 if !fusables.is_empty() {
3128 eprintln!(
3129 "[oracle] {} residual fusable(s) after weld; sample {:?}",
3130 fusables.len(),
3131 fusables.first()
3132 );
3133 }
3134 }
3135 let candidates = scope.as_ref().map(|scope| {
3136 let candidates = soundness_candidates(
3137 &solid,
3138 scope,
3139 [operand_bounds(first), operand_bounds(second)],
3140 policy.sew_search,
3141 );
3142 diagnostics.count_n("passthrough.soundness_candidates", candidates.len() as u64);
3143 crate::soundness::census::profile_operation(&solid, &[first, second], Some(&scope.touched), "boolean");
3144 candidates
3145 });
3146 Ok((
3147 KernelOutcome {
3148 value: solid,
3149 diagnostics,
3150 },
3151 candidates,
3152 ))
3153}
3154