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
136thread_local! {
137 static WITHOUT_PERTURBATION: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
138}
139
140pub fn without_perturbation<T>(action: impl FnOnce() -> T) -> T {
147 struct Restore(bool);
148 impl Drop for Restore {
149 fn drop(&mut self) {
150 WITHOUT_PERTURBATION.with(|cell| cell.set(self.0));
151 }
152 }
153 let _restore = Restore(WITHOUT_PERTURBATION.with(|cell| cell.replace(true)));
154 action()
155}
156
157fn touched_assembly(options: &BooleanOptions) -> bool {
159 match std::env::var("BREP_TOUCHED_ASSEMBLY").as_deref() {
160 Ok("0") => false,
161 Ok(_) => true,
162 Err(_) => options.touched_assembly,
163 }
164}
165
166fn disjoint_fast_path(options: &BooleanOptions) -> bool {
168 match std::env::var("BREP_DISJOINT_FAST_PATH").as_deref() {
169 Ok("0") => false,
170 Ok(_) => true,
171 Err(_) => options.disjoint_fast_path,
172 }
173}
174
175fn contact_fast_path(options: &BooleanOptions) -> bool {
177 match std::env::var("BREP_CONTACT_FAST_PATH").as_deref() {
178 Ok("0") => false,
179 Ok(_) => true,
180 Err(_) => options.contact_fast_path,
181 }
182}
183
184fn untouched_passthrough(options: &BooleanOptions) -> bool {
186 match std::env::var("BREP_UNTOUCHED_PASSTHROUGH").as_deref() {
187 Ok("0") => false,
188 Ok(_) => true,
189 Err(_) => options.untouched_passthrough,
190 }
191}
192
193fn default_tolerance() -> f64 {
194 1e-7
195}
196
197fn default_true() -> bool {
198 true
199}
200
201impl Default for BooleanOptions {
202 fn default() -> Self {
203 Self {
204 tolerance: default_tolerance(),
205 tolerances: None,
206 imprint: ImprintOptions::default(),
207 merge_coplanar_faces: true,
208 keep_unmerged_name_substrs: Vec::new(),
209 untouched_passthrough: true,
210 disjoint_fast_path: true,
211 contact_fast_path: true,
212 touched_assembly: false,
213 sector_classification: true,
214 sheet_trim: true,
215 keep_cells: false,
216 seam_reseat_later_references: None,
217 seam_rejoin_later_references: None,
218 }
219 }
220}
221
222mod select;
223mod sheet;
224mod cellular;
225pub mod sector;
226pub mod assemble;
227mod operand_state;
228mod rim;
229mod coincident;
230mod touch;
231pub(crate) mod reseat;
232mod ball_align;
233mod rejoin;
234mod window_retry;
235
236pub use rim::*;
237use select::*;
238use coincident::*;
239use touch::TouchCensus;
240pub use assemble::{
241 assemble_fragments, assemble_open_fragments, commit_nearby_edge_endpoints,
242 clear_candidate_memo, edge_interior_lies_on, finalize_assembled_solid, refresh_derived_genus,
243};
244use assemble::{assemble_fragments_scoped, AssemblyScope};
245#[allow(unused_imports)]
247pub use assemble::apply_assembly_heal_chain;
248
249
250struct WorkingScale {
255 factor: f64,
256 solids: Vec<BrepSolid>,
257 options: BooleanOptions,
258}
259
260thread_local! {
261 static ORIGINAL_WORKING_SCALE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
264}
265
266impl WorkingScale {
267 fn of(operands: &[&BrepSolid], options: &BooleanOptions) -> Result<Option<Self>, KernelRefusal> {
268 let Some(bounds) = crate::rescale::bounds_of(operands.iter().copied()) else {
269 return Ok(None);
270 };
271 let Some(factor) = crate::rescale::guard_factor(bounds).or_else(|| {
272 if ORIGINAL_WORKING_SCALE.with(|state| state.get()) { None }
273 else { crate::rescale::large_guard_factor(bounds) }
274 }) else {
275 return Ok(None);
276 };
277 crate::rescale::profile_fired("boolean", factor, bounds);
278 let solids = operands
279 .iter()
280 .map(|solid| crate::rescale::scale_operand(solid, factor, "boolean"))
281 .collect::<Result<Vec<_>, _>>()?;
282 let mut options = options.clone();
284 options.imprint.maximum_ssi_step = options.imprint.maximum_ssi_step.map(|step| step * factor);
285 Ok(Some(Self { factor, solids, options }))
286 }
287
288 fn run<T>(
291 &self,
292 original: impl FnOnce() -> Result<T, KernelRefusal>,
293 scaled: impl FnOnce() -> Result<T, KernelRefusal>,
294 ) -> Result<T, KernelRefusal> {
295 if self.factor >= 1.0 { return scaled(); }
296 struct Restore(bool);
297 impl Drop for Restore {
298 fn drop(&mut self) { ORIGINAL_WORKING_SCALE.with(|state| state.set(self.0)); }
299 }
300 let answer = {
301 let _restore = Restore(ORIGINAL_WORKING_SCALE.with(|state| state.replace(true)));
302 original()
303 };
304 match answer {
305 Ok(value) => Ok(value),
306 Err(original) => scaled().or(Err(original)),
307 }
308 }
309
310 fn back(&self, solid: &BrepSolid) -> Result<BrepSolid, KernelRefusal> {
311 crate::rescale::scale_operand(solid, 1.0 / self.factor, "boolean")
312 }
313
314 fn refusal(&self, error: KernelRefusal) -> KernelRefusal {
315 crate::rescale::name_scale(error, self.factor)
316 }
317}
318
319pub fn boolean_operation(
320 first: &BrepSolid,
321 second: &BrepSolid,
322 operation: BooleanOperation,
323 options: &BooleanOptions,
324) -> Result<BrepSolid, KernelRefusal> {
325 if let Some(scaled) = WorkingScale::of(&[first, second], options)? {
326 return scaled.run(
327 || boolean_operation(first, second, operation, options),
328 || boolean_operation(&scaled.solids[0], &scaled.solids[1], operation, &scaled.options)
329 .map_err(|error| scaled.refusal(error))
330 .and_then(|solid| scaled.back(&solid)),
331 );
332 }
333 boolean_operation_unscaled(first, second, operation, options)
334 .or_else(|refused| window_retry::retry(first, second, operation, options, refused, boolean_operation_unscaled))
335}
336
337fn boolean_operation_unscaled(
339 first: &BrepSolid,
340 second: &BrepSolid,
341 operation: BooleanOperation,
342 options: &BooleanOptions,
343) -> Result<BrepSolid, KernelRefusal> {
344 match boolean_operation_with_diagnostics(first, second, operation, options) {
345 Ok(outcome) => {
346 if below_tolerance_refusal_enabled()
349 && outcome.value.shells.iter().all(|shell| shell.faces.is_empty())
350 && !matches!(operation, BooleanOperation::Union)
351 {
352 if let Some(refusal) = below_tolerance_refusal(first, second, None) {
353 if let Some(answer) = below_tolerance_answer(first, second, operation) {
354 return Ok(answer);
355 }
356 if let Some(answer) = below_tolerance_rescaled(first, second, operation, options) {
357 return Ok(answer);
358 }
359 return Err(refusal);
360 }
361 }
362 if unresolved_merge_refusal_enabled() && !matches!(operation, BooleanOperation::Subtract) {
363 if let Some(refusal) = unresolved_merge_refusal(first, second) {
364 return Err(refusal);
365 }
366 }
367 if below_tolerance_slivers_enabled()
370 && !matches!(operation, BooleanOperation::Subtract)
371 && [first, second].iter().all(|solid| face_count(solid) <= SLIVER_ANSWER_FACES)
372 && near_coincident_planar_faces(first, second).is_some()
373 {
374 if let Some(answer) = below_tolerance_answer(first, second, operation) {
375 return Ok(answer);
376 }
377 }
378 Ok(outcome.value)
379 }
380 Err(error) => {
381 if below_tolerance_refusal_enabled() {
382 if let Some(refusal) = below_tolerance_refusal(first, second, Some(&error)) {
383 if let Some(answer) = below_tolerance_answer(first, second, operation) {
384 return Ok(answer);
385 }
386 if let Some(answer) = below_tolerance_rescaled(first, second, operation, options) {
387 return Ok(answer);
388 }
389 return Err(refusal);
390 }
391 }
392 if std::env::var("BREP_NO_PERTURB").as_deref() == Ok("1")
400 || !error.class.perturbation_eligible()
401 {
402 return Err(error);
403 }
404 if std::env::var("BREP_OPEN_OPERAND_GATE").as_deref() != Ok("0") {
426 if let Some((operand, open)) = [first, second]
427 .iter()
428 .enumerate()
429 .find_map(|(operand, solid)| {
430 let open = one_use_edges(solid);
431 (open > 0).then_some((operand, open))
432 })
433 {
434 return Err(error.with_message(|message| format!(
435 "{message}; operand {operand} is not a closed shell: {open} of its edges bound \
436 only one face, so no boolean of it encloses a solid and no perturbation \
437 can close it"
438 )));
439 }
440 }
441 if let Some((operand, face_id, deviation, weld)) =
442 planar_operand_off_its_plane(first, second, options)
443 {
444 return Err(error.with_message(|message| format!(
445 "{message}; operand {operand} face {face_id} is a plane whose straight \
446 boundary sits {deviation:.3e} off it (assembly weld {weld:.1e}), which \
447 no perturbation can reconcile — the body's planes must contain their \
448 boundary before it can take part in an exact boolean"
449 )));
450 }
451 if matches!(operation, BooleanOperation::Subtract)
466 && std::env::var("BREP_PINCH_GATE").as_deref() != Ok("0")
467 && subtract_pinches_at_internal_tangency(first, second, options.tolerance)
468 .unwrap_or(false)
469 {
470 if let Some(solid) = subtract_through_the_common_part(first, second, options) {
473 return Ok(solid);
474 }
475 return Err(error.with_message(|message| format!(
476 "{message}; internal tangency: the operands touch tangentially with \
477 co-directed normals, so the exact difference pinches to zero thickness \
478 (non-manifold, unrepresentable in a boundary model) — refusing rather \
479 than returning a perturbed sliver"
480 )));
481 }
482 if matches!(error.class, RefusalClass::TangentNodeSingularity)
498 && std::env::var("BREP_TANGENT_NODE_GATE").as_deref() != Ok("0")
499 {
500 return Err(error);
501 }
502 if matches!(operation, BooleanOperation::Union) {
506 if let Some(solid) = union_through_the_difference(first, second, options) {
507 return Ok(solid);
508 }
509 }
510 if WITHOUT_PERTURBATION.with(|cell| cell.get()) {
512 return Err(error);
513 }
514 match perturbation_retry(first, second, operation, options) {
515 Ok(solid) => Ok(solid),
516 Err(refused) if refused.is_empty() => Err(error),
517 Err(refused) => {
518 Err(error.with_message(|message| format!("{message}; {}", refused.join("; "))))
519 }
520 }
521 }
522 }
523}
524
525const PINCH_PROBE_STEPS: usize = 8;
530
531const PINCH_ANGULAR_TOLERANCE: f64 = 1e-4;
534
535const PINCH_SEPARATION_STEP: f64 = 1e-2;
539
540fn subtract_through_the_common_part(first: &BrepSolid, second: &BrepSolid, options: &BooleanOptions) -> Option<BrepSolid> {
558 if !switch!("BREP_PINCH_COMMON_RETRY", true) || !options.imprint.tangent_curve_imprint {
561 return None;
562 }
563 let common = boolean_operation_with_diagnostics(first, second, BooleanOperation::Intersect, options).ok()?.value;
564 if common.shells.iter().all(|shell| shell.faces.is_empty()) {
565 return None;
566 }
567 let cut = boolean_operation_with_diagnostics(first, &common, BooleanOperation::Subtract, options).ok()?.value;
568 if !cut.validate().is_empty() {
569 return None;
570 }
571 let volume = |solid: &BrepSolid| crate::solid_mass_properties(solid).ok().map(|mass| mass.volume);
572 let (whole, taken, left) = (volume(first)?, volume(&common)?, volume(&cut)?);
573 ((left - (whole - taken)).abs() <= 1e-9 * whole.abs().max(1.0)).then_some(cut)
574}
575
576fn union_through_the_difference(first: &BrepSolid, second: &BrepSolid, options: &BooleanOptions) -> Option<BrepSolid> {
589 if !switch!("BREP_TANGENT_UNION_DIFFERENCE_RETRY", true) || !options.imprint.tangent_curve_imprint {
590 return None;
591 }
592 let pinches = |a: &BrepSolid, b: &BrepSolid| subtract_pinches_at_internal_tangency(a, b, options.tolerance).unwrap_or(false);
593 if !pinches(first, second) && !pinches(second, first) {
594 return None;
595 }
596 let difference = match boolean_operation_with_diagnostics(first, second, BooleanOperation::Subtract, options) {
597 Ok(outcome) => outcome.value,
598 Err(_) => subtract_through_the_common_part(first, second, options)?,
599 };
600 if difference.shells.iter().all(|shell| shell.faces.is_empty()) || !difference.validate().is_empty() {
601 return None;
602 }
603 let union = boolean_operation_with_diagnostics(second, &difference, BooleanOperation::Union, options).ok()?.value;
604 if !union.validate().is_empty() {
605 return None;
606 }
607 let volume = |solid: &BrepSolid| crate::solid_mass_properties(solid).ok().map(|mass| mass.volume);
608 let (left, added, whole) = (volume(&difference)?, volume(second)?, volume(&union)?);
609 ((whole - (left + added)).abs() <= 1e-9 * whole.abs().max(1.0)).then_some(union)
610}
611
612pub fn subtract_pinches_at_internal_tangency(
634 first: &BrepSolid,
635 second: &BrepSolid,
636 tolerance: f64,
637) -> Result<bool, KernelRefusal> {
638 let contact = (tolerance * 100.0).max(1e-12);
641 let probes_a = first
642 .shells
643 .iter()
644 .flat_map(|shell| &shell.faces)
645 .map(PinchProbe::of)
646 .collect::<Result<Vec<_>, _>>()?;
647 let probes_b = second
648 .shells
649 .iter()
650 .flat_map(|shell| &shell.faces)
651 .map(PinchProbe::of)
652 .collect::<Result<Vec<_>, _>>()?;
653 for probe_a in &probes_a {
654 for probe_b in &probes_b {
655 let pad = 1e-2 * probe_a.extent().max(probe_b.extent());
662 if probe_a.separation(probe_b) > contact + pad {
663 continue;
664 }
665 if classify_surface_pair(
672 &probe_a.face.surface,
673 &probe_b.face.surface,
674 tolerance,
675 PINCH_ANGULAR_TOLERANCE,
676 ).or_refuse(KernelStage::Validate, "csg.boolean.mod")?
677 .relation
678 == SurfacePairRelation::Cosurface
679 {
680 continue;
681 }
682 if faces_touch_with_codirected_normals(probe_a, probe_b, contact)? {
683 return Ok(true);
684 }
685 }
686 }
687 Ok(false)
688}
689
690struct PinchProbe<'a> {
693 face: &'a FaceRecord,
694 samples: Vec<(f64, f64, Vec3)>,
696 minimum: [f64; 3],
697 maximum: [f64; 3],
698}
699
700impl<'a> PinchProbe<'a> {
701 fn of(face: &'a FaceRecord) -> Result<Self, KernelRefusal> {
702 let [u0, u1] = face.surface.domain_u().or_refuse(KernelStage::Validate, "domain_u")?;
703 let [v0, v1] = face.surface.domain_v().or_refuse(KernelStage::Validate, "domain_v")?;
704 let steps = PINCH_PROBE_STEPS as f64;
705 let mut samples = Vec::with_capacity((PINCH_PROBE_STEPS + 1).pow(2));
706 let mut minimum = [f64::INFINITY; 3];
707 let mut maximum = [f64::NEG_INFINITY; 3];
708 for i in 0..=PINCH_PROBE_STEPS {
709 let u = u0 + (u1 - u0) * i as f64 / steps;
710 for j in 0..=PINCH_PROBE_STEPS {
711 let v = v0 + (v1 - v0) * j as f64 / steps;
712 let Ok(point) = face.surface.evaluate(u, v) else {
713 continue;
714 };
715 for (axis, value) in [point.x, point.y, point.z].into_iter().enumerate() {
716 minimum[axis] = minimum[axis].min(value);
717 maximum[axis] = maximum[axis].max(value);
718 }
719 samples.push((u, v, point));
720 }
721 }
722 Ok(Self {
723 face,
724 samples,
725 minimum,
726 maximum,
727 })
728 }
729
730 fn extent(&self) -> f64 {
732 (0..3)
733 .map(|axis| self.maximum[axis] - self.minimum[axis])
734 .fold(0.0f64, f64::max)
735 }
736
737 fn separation(&self, other: &Self) -> f64 {
739 let mut gap: f64 = 0.0;
740 for axis in 0..3 {
741 gap = gap.max(self.minimum[axis] - other.maximum[axis]);
742 gap = gap.max(other.minimum[axis] - self.maximum[axis]);
743 }
744 gap
745 }
746}
747
748fn faces_touch_with_codirected_normals(
753 probe_a: &PinchProbe<'_>,
754 probe_b: &PinchProbe<'_>,
755 contact: f64,
756) -> Result<bool, KernelRefusal> {
757 for (probe, other) in [(probe_a, probe_b), (probe_b, probe_a)] {
758 let source = probe.face;
759 let target = other.face;
760 for &(u, v, point) in &probe.samples {
761 let projection = project_point_to_surface(&target.surface, point).or_refuse(KernelStage::Validate, "project_point_to_surface")?;
762 if projection.distance > contact {
763 continue;
764 }
765 let (Ok(source_normal), Ok(target_normal)) = (
768 source.surface.normal(u, v),
769 target.surface.normal(projection.u, projection.v),
770 ) else {
771 continue;
772 };
773 let source_outward = outward_normal(source_normal, source.same_sense);
774 let target_outward = outward_normal(target_normal, target.same_sense);
775 if source_outward.cross(target_outward).length() > PINCH_ANGULAR_TOLERANCE
776 || source_outward.dot(target_outward) <= 0.0
777 {
778 continue;
779 }
780 if parameter_point_in_face(source, Vec2 { x: u, y: v }, 1e-6).or_refuse(KernelStage::Validate, "parameter_point_in_face")?
781 == PolygonClass::Outside
782 || parameter_point_in_face(
783 target,
784 Vec2 {
785 x: projection.u,
786 y: projection.v,
787 },
788 1e-6,
789 ).or_refuse(KernelStage::Validate, "csg.boolean.mod")? == PolygonClass::Outside
790 {
791 continue;
792 }
793 if contact_separates_locally(source, target, u, v, contact)? {
794 return Ok(true);
795 }
796 }
797 }
798 Ok(false)
799}
800
801fn outward_normal(normal: Vec3, same_sense: bool) -> Vec3 {
802 if same_sense {
803 normal
804 } else {
805 normal.scale(-1.0)
806 }
807}
808
809fn contact_separates_locally(
815 source: &FaceRecord,
816 target: &FaceRecord,
817 u: f64,
818 v: f64,
819 contact: f64,
820) -> Result<bool, KernelRefusal> {
821 let [u0, u1] = source.surface.domain_u().or_refuse(KernelStage::Validate, "domain_u")?;
822 let [v0, v1] = source.surface.domain_v().or_refuse(KernelStage::Validate, "domain_v")?;
823 let step_u = (u1 - u0) * PINCH_SEPARATION_STEP;
824 let step_v = (v1 - v0) * PINCH_SEPARATION_STEP;
825 for (probe_u, probe_v) in [
826 ((u + step_u).min(u1), v),
827 ((u - step_u).max(u0), v),
828 (u, (v + step_v).min(v1)),
829 (u, (v - step_v).max(v0)),
830 ] {
831 if (probe_u - u).abs() < f64::EPSILON && (probe_v - v).abs() < f64::EPSILON {
832 continue;
833 }
834 let Ok(point) = source.surface.evaluate(probe_u, probe_v) else {
835 continue;
836 };
837 if project_point_to_surface(&target.surface, point).or_refuse(KernelStage::Validate, "project_point_to_surface")?.distance > contact * 10.0 {
840 return Ok(true);
841 }
842 }
843 Ok(false)
844}
845
846fn perturbation_retry(
900 first: &BrepSolid,
901 second: &BrepSolid,
902 operation: BooleanOperation,
903 options: &BooleanOptions,
904) -> Result<BrepSolid, Vec<String>> {
905 const DIRECTIONS: [[f64; 3]; 4] = [
916 [0.4034, 0.7973, 0.4491],
917 [0.7973, 0.4491, 0.4034],
918 [0.4491, 0.4034, 0.7973],
919 [0.5774, -0.5774, 0.5774],
920 ];
921 const FRACTIONS: [f64; 5] = PERTURBATION_FRACTIONS;
927
928 let debug = std::env::var("BREP_DEBUG_BOOL").is_ok();
929 let scale = crate::solid_tolerance::solid_scale(first)
930 .max(crate::solid_tolerance::solid_scale(second))
931 .max(1.0);
932
933 let _caller = crate::mass_caller("boolean.perturbation_rescue");
937 let va = solid_signed_volume(first).ok().map(f64::abs);
938 let vb = solid_signed_volume(second).ok().map(f64::abs);
939 let hold_identity = std::env::var("BREP_PERTURB_IDENTITY").as_deref() != Ok("0");
940 let hold_mirror = hold_identity && std::env::var("BREP_PERTURB_MIRROR").as_deref() != Ok("0");
943 let early_exit = std::env::var("BREP_MIRROR_EARLY_EXIT").as_deref() != Ok("0");
946 let mut trends = [MirrorTrend::default(); 4];
947 let mut identity: Option<Option<InclusionExclusion>> = None;
949 let mut refused = Vec::new();
950 let ladder = std::env::var("BREP_DEBUG_PERTURB_LADDER").is_ok();
954 let ladder_start = web_time::Instant::now();
955 if ladder {
956 let measured = inclusion_exclusion_volume(first, second, operation, options, va, vb, false);
957 match &measured {
958 Some(identity) => eprintln!(
959 "[ladder] identity {} = {:.9} from the exact lane's {} ({:.9}); V(first) {:?} V(second) {:?}",
960 identity.formula, identity.expected, identity.reading, identity.read, va, vb
961 ),
962 None => eprintln!("[ladder] no identity: no exact-lane boolean of these operands clears in either order"),
963 }
964 identity = Some(measured);
965 }
966 let rung_miss = |identity: &Option<Option<InclusionExclusion>>, candidate: &BrepSolid| -> String {
967 let volume = body_volume(candidate);
968 match (identity, volume) {
969 (Some(Some(identity)), Some(volume)) => format!(
970 "volume {volume:.9} miss {:+.3e} bar {:.3e}",
971 volume - identity.expected,
972 crate::VOLUME_DRIFT_ABS.max(crate::VOLUME_DRIFT_REL * identity.expected.abs())
973 ),
974 (_, Some(volume)) => format!("volume {volume:.9}"),
975 _ => "no volume".to_string(),
976 }
977 };
978
979 for &fraction in &FRACTIONS {
980 let magnitude = scale * fraction;
981 for (direction, dir) in DIRECTIONS.iter().enumerate() {
982 if trends[direction].closed {
983 if ladder {
984 eprintln!("[ladder] dir={dir:?} fraction={fraction:.1e} offset {magnitude:.3e}: not tried, its direction is closed");
985 }
986 continue;
987 }
988 let offset = [dir[0] * magnitude, dir[1] * magnitude, dir[2] * magnitude];
989 let translate = match AffineTransform::new([
990 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,
994 ]) {
995 Ok(transform) => transform,
996 Err(_) => continue,
997 };
998 let moved = match crate::transform_brep(second, translate, false) {
999 Ok(solid) => solid,
1000 Err(_) => continue,
1001 };
1002 let rung = format!("dir={dir:?} fraction={fraction:.1e} offset {magnitude:.3e}");
1003 let rung_start = web_time::Instant::now();
1004 let candidate =
1005 match boolean_operation_with_diagnostics(first, &moved, operation, options) {
1006 Ok(outcome) => outcome.value,
1007 Err(error) => {
1008 if ladder {
1009 eprintln!("[ladder] {rung}: exact lane refused {:?}", error.class);
1010 }
1011 continue;
1012 }
1013 };
1014 let built = rung_start.elapsed();
1015 if candidate.shells.is_empty() {
1017 if ladder {
1018 eprintln!("[ladder] {rung}: empty");
1019 }
1020 continue;
1021 }
1022 if let (Some(va), Some(vb)) = (va, vb) {
1027 if let Ok(vr) = solid_signed_volume(&candidate) {
1028 if !volume_within_csg_bounds(operation, va, vb, vr.abs()) {
1029 if ladder {
1030 eprintln!("[ladder] {rung}: outside the CSG bound, {}", rung_miss(&identity, &candidate));
1031 }
1032 continue;
1033 }
1034 }
1035 }
1036 let bounded = rung_start.elapsed();
1041 if hold_identity {
1043 let identity = identity.get_or_insert_with(|| {
1044 let identity =
1045 inclusion_exclusion_volume(first, second, operation, options, va, vb, false);
1046 if debug && identity.is_none() {
1047 eprintln!(
1048 "[perturb] no exact-lane boolean of these operands clears in either \
1049 order; no identity to hold"
1050 );
1051 }
1052 identity
1053 });
1054 if let Some(identity) = identity {
1055 let expected = identity.expected;
1056 let bar = crate::VOLUME_DRIFT_ABS.max(crate::VOLUME_DRIFT_REL * expected.abs());
1057 let volume = body_volume(&candidate);
1058 let miss = volume.map(|volume| (volume - expected).abs());
1059 if !miss.is_some_and(|miss| miss <= bar) {
1060 let sentence = format!(
1061 "perturbation rung dir={dir:?} fraction={fraction:.1e} \
1062 (offset {magnitude:.3e}) refused: its body reads {} against the \
1063 inclusion–exclusion identity {} = {expected:.9} (the exact lane's \
1064 {} reads {:.9}), a miss of {} beyond the volume drift bar {bar:.3e}",
1065 volume.map_or("no volume".to_string(), |volume| format!("{volume:.9}")),
1066 identity.formula,
1067 identity.reading,
1068 identity.read,
1069 miss.map_or("unmeasured".to_string(), |miss| format!("{miss:.3e}")),
1070 );
1071 if debug {
1072 eprintln!("[perturb] {sentence}");
1073 }
1074 if ladder {
1075 eprintln!(
1076 "[ladder] {rung}: refused by the identity, volume {} miss {} bar {bar:.3e}",
1077 volume.map_or("none".to_string(), |volume| format!("{volume:.9}")),
1078 volume.map_or("unmeasured".to_string(), |volume| format!("{:+.3e}", volume - expected)),
1079 );
1080 }
1081 refused.push(sentence);
1082 continue;
1083 }
1084 } else if hold_mirror {
1085 let mirror_start = web_time::Instant::now();
1088 let mirrored = AffineTransform::new([
1089 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,
1093 ])
1094 .ok()
1095 .and_then(|transform| crate::transform_brep(second, transform, false).ok());
1096 let mirror = mirrored.as_ref().and_then(|mirrored| {
1097 inclusion_exclusion_volume(first, mirrored, operation, options, va, vb, true)
1098 });
1099 let mirror_time = mirror_start.elapsed();
1100 let volume = body_volume(&candidate);
1101 let mut measured = None;
1102 let verdict = match (&mirror, volume) {
1103 (Some(mirror), Some(volume)) => {
1104 let bar = crate::VOLUME_DRIFT_ABS.max(crate::VOLUME_DRIFT_REL * mirror.expected.abs());
1105 let miss = 0.5 * (volume - mirror.expected).abs();
1106 measured = Some((0.5 * (volume - mirror.expected), bar));
1107 if ladder {
1108 eprintln!(
1109 "[ladder] {rung}: mirror at −offset reads {} = {:.9} (the mirrored {} {:.9}); body {volume:.9}, first-order translation error {:+.3e} bar {bar:.3e}",
1110 mirror.formula, mirror.expected, mirror.reading, mirror.read, 0.5 * (volume - mirror.expected)
1111 );
1112 }
1113 (miss > bar).then(|| format!(
1114 "perturbation rung dir={dir:?} fraction={fraction:.1e} \
1115 (offset {magnitude:.3e}) refused: no exact-lane boolean of the \
1116 operands clears, so the rung is held to its mirror: its body reads \
1117 {volume:.9} with the second operand moved +offset and {} = {:.9} \
1118 with it moved −offset (the mirrored {} reads {:.9}), a first-order \
1119 translation error of {miss:.3e} beyond the volume drift bar {bar:.3e}",
1120 mirror.formula, mirror.expected, mirror.reading, mirror.read
1121 ))
1122 }
1123 _ => Some(format!(
1124 "perturbation rung dir={dir:?} fraction={fraction:.1e} \
1125 (offset {magnitude:.3e}) refused: no exact-lane boolean of the operands \
1126 clears, and none clears with the second operand moved −offset either, \
1127 so nothing checks the rung's body{}",
1128 volume.map_or(String::new(), |volume| format!(" ({volume:.9})"))
1129 )),
1130 };
1131 match verdict {
1132 None => trends[direction].cleared(),
1133 Some(sentence) => {
1134 if debug {
1135 eprintln!("[perturb] {sentence}");
1136 }
1137 if ladder {
1138 eprintln!(
1139 "[ladder] {rung}: refused by its mirror (rung {:.0} ms: built {:.0}, bound {:.0}, mirror {:.0} ms; ladder {:.1} s)",
1140 rung_start.elapsed().as_secs_f64() * 1e3,
1141 built.as_secs_f64() * 1e3,
1142 (bounded - built).as_secs_f64() * 1e3,
1143 mirror_time.as_secs_f64() * 1e3,
1144 ladder_start.elapsed().as_secs_f64()
1145 );
1146 }
1147 refused.push(sentence);
1148 let closure = measured.and_then(|(error, bar)| {
1151 let earlier = trends[direction].refused(magnitude, error, early_exit)?;
1152 Some((earlier, error, bar))
1153 });
1154 if let Some(((earlier_offset, earlier_error), error, bar)) = closure {
1155 let closed = format!(
1156 "perturbation direction dir={dir:?} closed after offset {magnitude:.3e}: its \
1157 rungs' first-order translation errors read {earlier_error:+.3e} at offset \
1158 {earlier_offset:.3e} and {error:+.3e} at {magnitude:.3e}, one sign and \
1159 growing, so no larger offset along it comes back to the volume drift bar \
1160 {bar:.3e}"
1161 );
1162 if debug {
1163 eprintln!("[perturb] {closed}");
1164 }
1165 if ladder {
1166 eprintln!("[ladder] {closed}");
1167 }
1168 refused.push(closed);
1169 }
1170 continue;
1171 }
1172 }
1173 }
1174 }
1175 match crate::oracle::boolean_semantic_disagreement(
1179 first, second, operation, &candidate, 400,
1180 ) {
1181 Ok(report) if report.considered >= 30 && !report.is_flagged() => {
1182 if ladder {
1183 eprintln!(
1184 "[ladder] {rung}: accepted (oracle {} considered, rate {:.4}), {}",
1185 report.considered, report.disagreement_rate, rung_miss(&identity, &candidate)
1186 );
1187 }
1188 if debug {
1189 eprintln!(
1190 "[perturb] rescued {operation:?}: dir={dir:?} fraction={fraction:.1e} \
1191 magnitude={magnitude:.3e} offset={offset:?} \
1192 (oracle considered={} rate={:.4})",
1193 report.considered, report.disagreement_rate
1194 );
1195 }
1196 return Ok(candidate);
1197 }
1198 report => {
1199 if ladder {
1200 let verdict = match &report {
1201 Ok(report) => format!("oracle {} considered, rate {:.4}", report.considered, report.disagreement_rate),
1202 Err(error) => format!("oracle error {error:?}"),
1203 };
1204 eprintln!("[ladder] {rung}: refused by the oracle ({verdict}), {}", rung_miss(&identity, &candidate));
1205 }
1206 continue;
1207 }
1208 }
1209 }
1210 }
1211 if debug {
1212 eprintln!("[perturb] ladder exhausted for {operation:?}; no rung produced a clean result");
1213 }
1214 Err(refused)
1215}
1216
1217pub const PERTURBATION_FRACTIONS: [f64; 5] = [3e-5, 1e-4, 3e-4, 1e-3, 3e-3];
1220
1221#[derive(Clone, Copy, Default)]
1245pub struct MirrorTrend {
1246 last: Option<(f64, f64)>,
1248 pub closed: bool,
1249}
1250
1251impl MirrorTrend {
1252 pub fn refused(&mut self, offset: f64, error: f64, close: bool) -> Option<(f64, f64)> {
1257 let earlier = self
1258 .last
1259 .filter(|&(_, earlier)| earlier.signum() == error.signum() && error.abs() >= earlier.abs())
1260 .filter(|_| close);
1261 self.last = Some((offset, error));
1262 self.closed |= earlier.is_some();
1263 earlier
1264 }
1265
1266 pub fn cleared(&mut self) {
1268 self.last = None;
1269 }
1270}
1271
1272pub fn below_tolerance_refusal_enabled() -> bool {
1287 crate::switch!("BREP_BELOW_TOLERANCE_REFUSAL", true)
1288}
1289
1290pub fn below_tolerance_slivers_enabled() -> bool {
1307 crate::switch!("BREP_BELOW_TOLERANCE_SLIVERS", true)
1308}
1309
1310const SLIVER_ANSWER_FACES: usize = 64;
1313
1314fn face_count(solid: &BrepSolid) -> usize {
1315 solid.shells.iter().map(|shell| shell.faces.len()).sum()
1316}
1317
1318fn below_tolerance_answer(first: &BrepSolid, second: &BrepSolid, operation: BooleanOperation) -> Option<BrepSolid> {
1320 if !below_tolerance_slivers_enabled() || [first, second].iter().any(|solid| face_count(solid) > SLIVER_ANSWER_FACES) {
1321 return None;
1322 }
1323 if ![first, second].iter().all(|solid| closed_single_shell(solid)) {
1324 return None;
1325 }
1326 let inside = |x: &BrepSolid, y: &BrepSolid| difference_all_sliver(x, y);
1327 if matches!(operation, BooleanOperation::Subtract) {
1328 return inside(first, second).then(empty_solid);
1329 }
1330 let (first_in, second_in) = (inside(first, second), inside(second, first));
1331 let first_larger = || match (body_volume(first), body_volume(second)) {
1334 (Some(a), Some(b)) => a >= b,
1335 _ => true,
1336 };
1337 let outer_is_first = match (first_in, second_in) {
1338 (false, false) => return None,
1339 (true, false) => false,
1340 (false, true) => true,
1341 (true, true) => first_larger(),
1342 };
1343 let (outer, inner) = if outer_is_first { (first, second) } else { (second, first) };
1344 Some(match operation {
1345 BooleanOperation::Union => outer.clone(),
1346 _ => inner.clone(),
1347 })
1348}
1349
1350fn closed_single_shell(solid: &BrepSolid) -> bool {
1352 if !solid.kind.is_solid() || solid.shells.len() != 1 {
1353 return false;
1354 }
1355 let mut uses: HashMap<u64, usize> = HashMap::default();
1356 for coedge in solid.shells[0].faces.iter().flat_map(|face| &face.loops).flat_map(|lp| &lp.coedges) {
1357 *uses.entry(coedge.edge_id).or_default() += 1;
1358 }
1359 !uses.is_empty() && uses.values().all(|&count| count == 2) && solid.edges.iter().all(|edge| uses.contains_key(&edge.id))
1360}
1361
1362fn difference_all_sliver(first: &BrepSolid, second: &BrepSolid) -> bool {
1373 let Some(bounds) = difference_bounds(first, second) else {
1374 return false;
1375 };
1376 let Ok(properties) = crate::solid_mass_properties(first) else {
1377 return false;
1378 };
1379 bounds.out <= BELOW_TOLERANCE_BAND
1380 && bounds.upper.is_finite()
1381 && bounds.upper <= crate::tolerance::COINCIDENCE_DISTANCE_FLOOR * properties.surface_area
1382}
1383
1384struct DifferenceBounds {
1390 lower: f64,
1391 upper: f64,
1392 out: f64,
1394}
1395
1396fn difference_bounds(first: &BrepSolid, second: &BrepSolid) -> Option<DifferenceBounds> {
1397 let scale = crate::solid_tolerance::solid_scale(first).max(crate::solid_tolerance::solid_scale(second)).max(1.0);
1398 let (polygons_a, polygons_b) = (face_polygons(first, scale)?, face_polygons(second, scale)?);
1399 let vertices_b: Vec<Vec3> = second.vertices.iter().map(|vertex| vertex.point).collect();
1400 let vertices_a: Vec<Vec3> = first.vertices.iter().map(|vertex| vertex.point).collect();
1401 let flat = 1e-9 * scale;
1402 let mut bounds = DifferenceBounds { lower: 0.0, upper: 0.0, out: 0.0 };
1403 for polygon in &polygons_b {
1404 let (origin, normal) = polygon_plane(polygon)?;
1405 if vertices_b.iter().any(|vertex| vertex.sub(origin).dot(normal) > flat) {
1407 return None;
1408 }
1409 let out = vertices_a.iter().map(|vertex| vertex.sub(origin).dot(normal)).fold(0.0f64, f64::max);
1410 bounds.out = bounds.out.max(out);
1411 if out <= 0.0 {
1412 continue;
1413 }
1414 let part: f64 = polygons_a.iter().map(|face| clipped_cone_volume(face, origin, normal)).sum();
1415 bounds.lower = bounds.lower.max(part);
1416 bounds.upper += part;
1417 }
1418 Some(bounds)
1419}
1420
1421pub fn below_tolerance_rescale_enabled() -> bool {
1431 crate::switch!("BREP_BELOW_TOLERANCE_RESCALE", false)
1432}
1433
1434fn below_tolerance_rescaled(first: &BrepSolid, second: &BrepSolid, operation: BooleanOperation, options: &BooleanOptions) -> Option<BrepSolid> {
1435 if !below_tolerance_rescale_enabled()
1436 || options.tolerances.is_some()
1437 || [first, second].iter().any(|solid| face_count(solid) > SLIVER_ANSWER_FACES || !closed_single_shell(solid))
1438 {
1439 return None;
1440 }
1441 let (volume_exact, area_exact) = convex_pair_measures(first, second, operation)?;
1442 let volume_slack = 1e-9 * body_volume(first)?.max(body_volume(second)?);
1443 let area_slack = 1e-9 * area_exact.max(1.0);
1444 for factor in [100.0, 1000.0] {
1445 let scaled = |solid: &BrepSolid| crate::rescale::scale_operand(solid, factor, "boolean").ok();
1446 let (Some(a), Some(b)) = (scaled(first), scaled(second)) else {
1447 continue;
1448 };
1449 let mut scaled_options = options.clone();
1450 scaled_options.imprint.maximum_ssi_step = scaled_options.imprint.maximum_ssi_step.map(|step| step * factor);
1451 let Ok(outcome) = boolean_operation_with_diagnostics(&a, &b, operation, &scaled_options) else {
1452 continue;
1453 };
1454 let Ok(answer) = crate::rescale::scale_operand(&outcome.value, 1.0 / factor, "boolean") else {
1455 continue;
1456 };
1457 let Ok(properties) = crate::solid_mass_properties(&answer) else {
1458 continue;
1459 };
1460 if (properties.volume.abs() - volume_exact).abs() <= volume_slack
1461 && (properties.surface_area - area_exact).abs() <= area_slack
1462 && !answer.validate().iter().any(|issue| issue.severity == "error")
1463 {
1464 return Some(answer);
1465 }
1466 }
1467 None
1468}
1469
1470fn convex_pair_measures(first: &BrepSolid, second: &BrepSolid, operation: BooleanOperation) -> Option<(f64, f64)> {
1476 let scale = crate::solid_tolerance::solid_scale(first).max(crate::solid_tolerance::solid_scale(second)).max(1.0);
1477 let (polygons_a, polygons_b) = (face_polygons(first, scale)?, face_polygons(second, scale)?);
1478 let (planes_a, planes_b) = (convex_planes(&polygons_a, scale)?, convex_planes(&polygons_b, scale)?);
1479 let zero = Vec3::new(0.0, 0.0, 0.0);
1480 let read = |polygons: &[Vec<Vec3>], planes: &[(Vec3, Vec3)]| {
1482 let (mut cone, mut area, mut inside_area) = (0.0, 0.0, 0.0);
1483 for polygon in polygons {
1484 area += vector_area(polygon, zero).length();
1485 let mut inside = polygon.clone();
1486 for &(origin, normal) in planes {
1487 inside = clip_polygon(&inside, origin, normal.scale(-1.0));
1488 if inside.len() < 3 {
1489 break;
1490 }
1491 }
1492 if inside.len() >= 3 {
1493 let vector = vector_area(&inside, zero);
1494 cone += inside[0].dot(vector) / 3.0;
1495 inside_area += vector.length();
1496 }
1497 }
1498 (cone, area, inside_area)
1499 };
1500 let (cone_a, area_a, inside_a) = read(&polygons_a, &planes_b);
1501 let (cone_b, area_b, inside_b) = read(&polygons_b, &planes_a);
1502 let (volume_a, volume_b) = (body_volume(first)?, body_volume(second)?);
1503 let common = cone_a + cone_b;
1504 Some(match operation {
1505 BooleanOperation::Intersect => (common, inside_a + inside_b),
1506 BooleanOperation::Union => (volume_a + volume_b - common, (area_a - inside_a) + (area_b - inside_b)),
1507 BooleanOperation::Subtract => (volume_a - common, (area_a - inside_a) + inside_b),
1508 })
1509}
1510
1511fn convex_planes(polygons: &[Vec<Vec3>], scale: f64) -> Option<Vec<(Vec3, Vec3)>> {
1514 let planes = polygons.iter().map(|polygon| polygon_plane(polygon)).collect::<Option<Vec<_>>>()?;
1515 let flat = 1e-9 * scale;
1516 let convex = planes.iter().all(|&(origin, normal)| polygons.iter().flatten().all(|vertex| vertex.sub(origin).dot(normal) <= flat));
1517 convex.then_some(planes)
1518}
1519
1520fn clip_polygon(polygon: &[Vec3], origin: Vec3, normal: Vec3) -> Vec<Vec3> {
1523 let side = |point: Vec3| point.sub(origin).dot(normal);
1524 let mut kept = Vec::with_capacity(polygon.len() + 2);
1525 for (index, &point) in polygon.iter().enumerate() {
1526 let next = polygon[(index + 1) % polygon.len()];
1527 let (here, there) = (side(point), side(next));
1528 if here >= 0.0 {
1529 kept.push(point);
1530 }
1531 if (here >= 0.0) != (there >= 0.0) {
1532 let t = here / (here - there);
1533 kept.push(point.add(next.sub(point).scale(t)));
1534 }
1535 }
1536 kept
1537}
1538
1539fn face_polygons(solid: &BrepSolid, scale: f64) -> Option<Vec<Vec<Vec3>>> {
1543 let vertex = |id: u64| solid.vertices.iter().find(|vertex| vertex.id == id).map(|vertex| vertex.point);
1544 let mut polygons = Vec::new();
1545 for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
1546 if !face.surface.is_affine().ok()? {
1547 return None;
1548 }
1549 for lp in &face.loops {
1550 let mut polygon = Vec::with_capacity(lp.coedges.len());
1551 for coedge in &lp.coedges {
1552 let edge = solid.edges.iter().find(|edge| edge.id == coedge.edge_id)?;
1553 let (start, end) = (vertex(edge.start_vertex_id)?, vertex(edge.end_vertex_id)?);
1554 let chord = end.sub(start);
1555 let length = chord.length();
1556 if edge.degenerate || length <= 1e-12 * scale {
1557 return None;
1558 }
1559 for control in &edge.curve.control_points {
1560 let offset = control.point().ok()?.sub(start);
1561 if offset.cross(chord).length() / length > 1e-9 * scale {
1562 return None;
1563 }
1564 }
1565 polygon.push(if coedge.forward { start } else { end });
1566 }
1567 polygons.push(polygon);
1568 }
1569 }
1570 let volume: f64 = polygons.iter().map(|polygon| clipped_cone_volume(polygon, Vec3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 0.0))).sum();
1572 if !(volume.abs() > 0.0) {
1573 return None;
1574 }
1575 if volume < 0.0 {
1576 for polygon in &mut polygons {
1577 polygon.reverse();
1578 }
1579 }
1580 Some(polygons)
1581}
1582
1583fn polygon_plane(polygon: &[Vec3]) -> Option<(Vec3, Vec3)> {
1585 let origin = *polygon.first()?;
1586 Some((origin, vector_area(polygon, origin).normalized().ok()?))
1587}
1588
1589fn vector_area(polygon: &[Vec3], origin: Vec3) -> Vec3 {
1590 let mut area = Vec3::new(0.0, 0.0, 0.0);
1591 for (index, point) in polygon.iter().enumerate() {
1592 let next = polygon[(index + 1) % polygon.len()];
1593 area = area.add(point.sub(origin).cross(next.sub(origin)));
1594 }
1595 area.scale(0.5)
1596}
1597
1598fn clipped_cone_volume(polygon: &[Vec3], origin: Vec3, normal: Vec3) -> f64 {
1604 let clipped: Vec<Vec3> = if normal.length() == 0.0 { polygon.to_vec() } else { clip_polygon(polygon, origin, normal) };
1605 if clipped.len() < 3 {
1606 return 0.0;
1607 }
1608 clipped[0].sub(origin).dot(vector_area(&clipped, origin)) / 3.0
1609}
1610
1611const BELOW_TOLERANCE_BAND: f64 = 10.0 * crate::tolerance::WELD_FLOOR;
1614
1615pub fn unresolved_merge_refusal_enabled() -> bool {
1625 crate::switch!("BREP_UNRESOLVED_MERGE_REFUSAL", false)
1626}
1627
1628pub fn sliver_shell_drop_enabled() -> bool {
1641 crate::switch!("BREP_SLIVER_SHELL_DROP", true)
1642}
1643
1644const SLIVER_SHELL_THICKNESS: f64 = 1e-12;
1648
1649pub fn sliver_shell_fast_on() -> bool {
1664 crate::switch!("BREP_SLIVER_SHELL_FAST", true)
1665}
1666
1667fn sliver_shell_fast_check_on() -> bool {
1668 crate::switch!("BREP_SLIVER_SHELL_FAST_CHECK", false)
1669}
1670
1671thread_local! {
1672 static SLIVER_FAST_CHECK: std::cell::Cell<(u64, u64, u64)> = const { std::cell::Cell::new((0, 0, 0)) };
1673}
1674
1675pub fn sliver_shell_fast_check_take() -> (u64, u64, u64) {
1678 SLIVER_FAST_CHECK.with(|cell| cell.replace((0, 0, 0)))
1679}
1680
1681fn sliver_fast_record(compared: u64, differed: u64, kept: u64) {
1682 SLIVER_FAST_CHECK.with(|cell| {
1683 let (a, b, c) = cell.get();
1684 cell.set((a + compared, b + differed, c + kept));
1685 });
1686}
1687
1688fn face_area_upper_bound(surface: &crate::NurbsSurface) -> Option<f64> {
1696 let net = &surface.control_points;
1697 let rows = net.len();
1698 let columns = net.first()?.len();
1699 if rows < 2 || columns < 2 || net.iter().any(|row| row.len() != columns) {
1700 return None;
1701 }
1702 let (p, q) = (surface.degree_u, surface.degree_v);
1703 let (us, vs) = (&surface.knots_u, &surface.knots_v);
1704 if us.len() != rows + p + 1 || vs.len() != columns + q + 1 {
1705 return None;
1706 }
1707 let mut w_min = f64::INFINITY;
1708 let mut w_max = 0.0f64;
1709 let mut point_max = 0.0f64;
1710 for c in net.iter().flatten() {
1711 if !(c.w > 0.0) {
1712 return None;
1713 }
1714 w_min = w_min.min(c.w);
1715 w_max = w_max.max(c.w);
1716 point_max = point_max.max((c.x * c.x + c.y * c.y + c.z * c.z).sqrt());
1717 }
1718 let hodograph = |along_u: bool| -> Option<(f64, f64)> {
1720 let (count, degree, knots) = if along_u { (rows, p, us) } else { (columns, q, vs) };
1721 let (mut dp, mut dw) = (0.0f64, 0.0f64);
1722 for i in 0..count - 1 {
1723 let span = knots[i + degree + 1] - knots[i + 1];
1724 if !(span > 0.0) {
1725 continue;
1726 }
1727 let scale = degree as f64 / span;
1728 let others = if along_u { columns } else { rows };
1729 for j in 0..others {
1730 let (a, b) = if along_u { (net[i][j], net[i + 1][j]) } else { (net[j][i], net[j][i + 1]) };
1731 let (x, y, z) = (b.x - a.x, b.y - a.y, b.z - a.z);
1732 dp = dp.max(scale * (x * x + y * y + z * z).sqrt());
1733 dw = dw.max(scale * (b.w - a.w).abs());
1734 }
1735 }
1736 Some((dp, dw))
1737 };
1738 let (pu, wu) = hodograph(true)?;
1739 let (pv, wv) = hodograph(false)?;
1740 let su = (pu * w_max + point_max * wu) / (w_min * w_min);
1741 let sv = (pv * w_max + point_max * wv) / (w_min * w_min);
1742 let extent_u = us[us.len() - 1] - us[0];
1743 let extent_v = vs[vs.len() - 1] - vs[0];
1744 let bound = su * sv * extent_u * extent_v;
1745 bound.is_finite().then_some(bound)
1746}
1747
1748pub fn trimmed_face_area_upper_bound(face: &crate::topology::FaceRecord) -> Option<f64> {
1756 let s = &face.surface;
1757 let (u0, u1) = (*s.knots_u.first()?, *s.knots_u.last()?);
1758 let (v0, v1) = (*s.knots_v.first()?, *s.knots_v.last()?);
1759 let (du, dv) = (1e-12 * (u1 - u0).abs(), 1e-12 * (v1 - v0).abs());
1761 if !(du > 0.0 && dv > 0.0) {
1762 return None;
1763 }
1764 for coedge in face.loops.iter().flat_map(|lp| &lp.coedges) {
1765 for c in &coedge.pcurve.control_points {
1766 if !(c.w > 0.0) {
1767 return None;
1768 }
1769 let (u, v) = (c.x / c.w, c.y / c.w);
1770 if !(u >= u0 - du && u <= u1 + du && v >= v0 - dv && v <= v1 + dv) {
1771 return None;
1772 }
1773 }
1774 }
1775 face_area_upper_bound(s).map(|bound| 2.0 * bound)
1776}
1777
1778fn drop_sliver_shells(solid: &mut BrepSolid) -> usize {
1781 if !sliver_shell_drop_enabled() || !solid.kind.is_solid() || solid.shells.len() < 2 {
1782 return 0;
1783 }
1784 let floor = SLIVER_SHELL_THICKNESS * crate::solid_tolerance::solid_scale(solid).max(1.0);
1785 let degenerate: std::collections::HashSet<u64> = solid.edges.iter().filter(|edge| edge.degenerate).map(|edge| edge.id).collect();
1786 let mut drop = vec![false; solid.shells.len()];
1787 for (index, shell) in solid.shells.iter().enumerate() {
1788 if shell.faces.is_empty() {
1789 continue;
1790 }
1791 let mut uses: HashMap<u64, usize> = HashMap::default();
1793 for coedge in shell.faces.iter().flat_map(|face| &face.loops).flat_map(|lp| &lp.coedges) {
1794 if !degenerate.contains(&coedge.edge_id) {
1795 *uses.entry(coedge.edge_id).or_default() += 1;
1796 }
1797 }
1798 if uses.is_empty() || uses.values().any(|&count| count != 2) {
1799 continue;
1800 }
1801 let alone = BrepSolid { shells: vec![shell.clone()], mass_properties_cache: Default::default(), ..solid.clone() };
1802 let (fast, check) = (sliver_shell_fast_on(), sliver_shell_fast_check_on());
1803 let kept_fast = (fast || check)
1804 && shell
1805 .faces
1806 .iter()
1807 .map(trimmed_face_area_upper_bound)
1808 .sum::<Option<f64>>()
1809 .map(|area| floor * area)
1810 .filter(|bar| bar.is_finite() && *bar > 0.0)
1811 .and_then(|bar| crate::solid_signed_volume_for_sign(&alone, bar).ok().map(|volume| volume > bar))
1812 .unwrap_or(false);
1813 if kept_fast && !check {
1814 sliver_fast_record(0, 0, 1);
1815 continue;
1816 }
1817 let Ok(mass) = crate::solid_mass_properties(&alone) else {
1818 continue;
1819 };
1820 let thickness = mass.volume.abs() / mass.surface_area.max(f64::MIN_POSITIVE);
1821 if env_read!("BREP_DEBUG_SLIVER_SHELL").is_some() {
1822 eprintln!(
1823 "sliver-shell: shell {index} of {}: volume {:.6e} area {:.6e} thickness {thickness:.3e}",
1824 solid.shells.len(),
1825 mass.volume,
1826 mass.surface_area
1827 );
1828 }
1829 drop[index] = thickness < floor;
1830 if check {
1831 sliver_fast_record(1, u64::from(kept_fast && drop[index]), u64::from(kept_fast));
1832 }
1833 }
1834 let dropped = drop.iter().filter(|&&d| d).count();
1835 if dropped == 0 || dropped == solid.shells.len() {
1836 return 0;
1837 }
1838 let mut index = 0;
1839 solid.shells.retain(|_| {
1840 let keep = !drop[index];
1841 index += 1;
1842 keep
1843 });
1844 let used_edges: std::collections::HashSet<u64> = solid
1845 .shells
1846 .iter()
1847 .flat_map(|shell| &shell.faces)
1848 .flat_map(|face| &face.loops)
1849 .flat_map(|lp| &lp.coedges)
1850 .map(|coedge| coedge.edge_id)
1851 .collect();
1852 solid.edges.retain(|edge| used_edges.contains(&edge.id));
1853 let used_vertices: std::collections::HashSet<u64> =
1854 solid.edges.iter().flat_map(|edge| [edge.start_vertex_id, edge.end_vertex_id]).collect();
1855 solid.vertices.retain(|vertex| used_vertices.contains(&vertex.id));
1856 solid.mass_properties_cache = Default::default();
1857 refresh_derived_genus(solid);
1859 dropped
1860}
1861
1862fn unresolved_merge_refusal(first: &BrepSolid, second: &BrepSolid) -> Option<KernelRefusal> {
1863 let (lower, upper) = (crate::tolerance::COINCIDENCE_DISTANCE_FLOOR, crate::tolerance::WELD_FLOOR);
1864 let (face_a, face_b, separation) = planar_faces_apart_within(first, second, lower, upper)?;
1865 Some(KernelRefusal::unsupported(
1866 KernelStage::Intersect,
1867 "below_modelling_tolerance",
1868 format!(
1869 "boolean: face {face_a} of the first operand and face {face_b} of the second are planes nearly on one \
1870 another, {separation:.3e} apart at most over their shared extent: farther than a coincidence \
1871 ({lower:.0e}) and closer than the kernel resolves ({upper:.0e}), so the step between them would be \
1872 welded away"
1873 ),
1874 ))
1875}
1876
1877fn below_tolerance_refusal(first: &BrepSolid, second: &BrepSolid, error: Option<&KernelRefusal>) -> Option<KernelRefusal> {
1878 let (face_a, face_b, separation) = near_coincident_planar_faces(first, second)?;
1879 let message = format!(
1880 "boolean: face {face_a} of the first operand and face {face_b} of the second are planes nearly on one \
1881 another, {separation:.3e} apart at most over their shared extent: the slivers between them are below the \
1882 modelling tolerance ({BELOW_TOLERANCE_BAND:.0e}), so the kernel cannot resolve them{}",
1883 error.map(|error| format!(" (the exact arrangement said: {})", error.message.chars().take(160).collect::<String>())).unwrap_or_default()
1884 );
1885 Some(KernelRefusal::unsupported(KernelStage::Intersect, "below_modelling_tolerance", message))
1886}
1887
1888fn near_coincident_planar_faces(first: &BrepSolid, second: &BrepSolid) -> Option<(u64, u64, f64)> {
1892 let scale = crate::solid_tolerance::solid_scale(first).max(crate::solid_tolerance::solid_scale(second)).max(1.0);
1893 planar_faces_apart_within(first, second, 1e-9 * scale, BELOW_TOLERANCE_BAND)
1894}
1895
1896fn planar_faces_apart_within(first: &BrepSolid, second: &BrepSolid, lower: f64, upper: f64) -> Option<(u64, u64, f64)> {
1900 struct Planar {
1901 id: u64,
1902 origin: Vec3,
1903 normal: Vec3,
1904 corners: Vec<Vec3>,
1905 bounds: crate::spatial::Aabb,
1906 }
1907 let read = |solid: &BrepSolid| -> Vec<Planar> {
1908 let at = |id: u64| solid.vertices.iter().find(|vertex| vertex.id == id).map(|vertex| vertex.point);
1909 solid
1910 .shells
1911 .iter()
1912 .flat_map(|shell| &shell.faces)
1913 .filter_map(|face| {
1914 if !face.surface.is_affine().ok()? {
1915 return None;
1916 }
1917 let origin = face.surface.control_points[0][0].point().ok()?;
1918 let a = face.surface.control_points[1][0].point().ok()?.sub(origin);
1919 let b = face.surface.control_points[0][1].point().ok()?.sub(origin);
1920 let normal = a.cross(b).normalized().ok()?;
1921 let corners: Vec<Vec3> = face
1922 .loops
1923 .iter()
1924 .flat_map(|lp| &lp.coedges)
1925 .filter_map(|coedge| solid.edges.iter().find(|edge| edge.id == coedge.edge_id))
1926 .flat_map(|edge| [at(edge.start_vertex_id), at(edge.end_vertex_id)])
1927 .flatten()
1928 .collect();
1929 if corners.is_empty() {
1930 return None;
1931 }
1932 let bounds = crate::spatial::Aabb::from_points(corners.clone());
1933 Some(Planar { id: face.id, origin, normal, corners, bounds })
1934 })
1935 .collect()
1936 };
1937 let (faces_a, faces_b) = (read(first), read(second));
1938 for a in &faces_a {
1939 for b in &faces_b {
1940 if a.normal.cross(b.normal).length() > 1e-3 {
1941 continue;
1942 }
1943 if !a.bounds.intersects(b.bounds, upper) {
1944 continue;
1945 }
1946 let separation = a
1947 .corners
1948 .iter()
1949 .map(|corner| corner.sub(b.origin).dot(b.normal).abs())
1950 .chain(b.corners.iter().map(|corner| corner.sub(a.origin).dot(a.normal).abs()))
1951 .fold(0.0f64, f64::max);
1952 if separation > lower && separation <= upper {
1953 return Some((a.id, b.id, separation));
1954 }
1955 }
1956 }
1957 None
1958}
1959
1960pub fn one_use_edges(solid: &BrepSolid) -> usize {
1961 let mut uses: HashMap<u64, usize> = HashMap::default();
1962 for coedge in solid
1963 .shells
1964 .iter()
1965 .flat_map(|shell| &shell.faces)
1966 .flat_map(|face| &face.loops)
1967 .flat_map(|loop_record| &loop_record.coedges)
1968 {
1969 *uses.entry(coedge.edge_id).or_default() += 1;
1970 }
1971 solid
1972 .edges
1973 .iter()
1974 .filter(|edge| !edge.degenerate && uses.get(&edge.id) == Some(&1))
1975 .count()
1976}
1977
1978fn body_volume(solid: &BrepSolid) -> Option<f64> {
1980 if solid.shells.is_empty() {
1981 return Some(0.0);
1982 }
1983 solid_signed_volume(solid).ok().map(f64::abs)
1984}
1985
1986struct InclusionExclusion {
1989 formula: &'static str,
1992 reading: &'static str,
1994 read: f64,
1996 expected: f64,
1998}
1999
2000fn inclusion_exclusion_volume(
2011 first: &BrepSolid,
2012 second: &BrepSolid,
2013 operation: BooleanOperation,
2014 options: &BooleanOptions,
2015 va: Option<f64>,
2016 vb: Option<f64>,
2017 own_first: bool,
2018) -> Option<InclusionExclusion> {
2019 use BooleanOperation::{Intersect, Subtract, Union};
2020 let (va, vb) = (va?, vb?);
2021 let own = match operation {
2022 Intersect => (Intersect, false, "first ∩ second"),
2023 Union => (Union, false, "first ∪ second"),
2024 Subtract => (Subtract, false, "first − second"),
2025 };
2026 let readings = [
2027 (Intersect, false, "first ∩ second"),
2028 (Intersect, true, "second ∩ first"),
2029 (Union, false, "first ∪ second"),
2030 (Union, true, "second ∪ first"),
2031 (Subtract, false, "first − second"),
2032 (Subtract, true, "second − first"),
2033 ];
2034 let own_reading = own_first.then_some(own);
2035 let leading = usize::from(own_first);
2036 for (index, (other, swapped, reading)) in own_reading.into_iter().chain(readings).enumerate() {
2037 if index >= leading && !swapped && std::mem::discriminant(&other) == std::mem::discriminant(&operation) {
2038 continue;
2039 }
2040 let (x, y) = if swapped { (second, first) } else { (first, second) };
2041 let Some(read) = boolean_operation_with_diagnostics(x, y, other, options)
2042 .ok()
2043 .and_then(|outcome| body_volume(&outcome.value))
2044 else {
2045 continue;
2046 };
2047 let intersection = match (other, swapped) {
2048 (Intersect, _) => read,
2049 (Union, _) => va + vb - read,
2050 (Subtract, false) => va - read,
2051 (Subtract, true) => vb - read,
2052 };
2053 let (formula, expected) = match operation {
2054 Intersect => ("V(first ∩ second)", intersection),
2055 Union => ("V(first) + V(second) − V(first ∩ second)", va + vb - intersection),
2056 Subtract => ("V(first) − V(first ∩ second)", va - intersection),
2057 };
2058 return Some(InclusionExclusion { formula, reading, read, expected });
2059 }
2060 None
2061}
2062
2063fn planar_operand_off_its_plane(
2072 first: &BrepSolid,
2073 second: &BrepSolid,
2074 options: &BooleanOptions,
2075) -> Option<(u8, u64, f64, f64)> {
2076 let policy = options
2077 .tolerances
2078 .clone()
2079 .unwrap_or_else(|| KernelTolerances::for_pair(first, second, options.tolerance));
2080 let weld = crate::tolerance::assembler_weld(policy.model);
2081 let mut worst: Option<(u8, u64, f64)> = None;
2082 for (operand, solid) in [(0u8, first), (1u8, second)] {
2083 let vertex_point = |id: u64| solid.vertices.iter().find(|v| v.id == id).map(|v| v.point);
2084 for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
2085 let Some(crate::AnalyticSurface::Plane {
2086 origin,
2087 u_dir,
2088 v_dir,
2089 ..
2090 }) = face.surface.analytic()
2091 else {
2092 continue;
2093 };
2094 let [loop_record] = face.loops.as_slice() else {
2095 continue;
2096 };
2097 let Ok(normal) = u_dir.cross(*v_dir).normalized() else {
2098 continue;
2099 };
2100 let mut off_plane = 0.0f64;
2101 let mut straight = true;
2102 for coedge in &loop_record.coedges {
2103 let Some(edge) = solid.edges.iter().find(|edge| edge.id == coedge.edge_id) else {
2104 straight = false;
2105 break;
2106 };
2107 let (Some(start), Some(end)) =
2108 (vertex_point(edge.start_vertex_id), vertex_point(edge.end_vertex_id))
2109 else {
2110 straight = false;
2111 break;
2112 };
2113 let chord = end.sub(start);
2114 let length = chord.length();
2115 if edge.degenerate || length <= weld {
2116 straight = false;
2117 break;
2118 }
2119 let direction = chord.scale(1.0 / length);
2120 for fraction in [0.25, 0.5, 0.75] {
2121 let Ok(point) = edge.curve.evaluate(edge.t0 + (edge.t1 - edge.t0) * fraction) else {
2122 straight = false;
2123 break;
2124 };
2125 let delta = point.sub(start);
2126 let along = delta.dot(direction);
2127 if delta.sub(direction.scale(along)).length() > weld
2128 || along < -weld
2129 || along > length + weld
2130 {
2131 straight = false;
2132 break;
2133 }
2134 }
2135 if !straight {
2136 break;
2137 }
2138 off_plane = off_plane.max(start.sub(*origin).dot(normal).abs());
2139 }
2140 if straight && off_plane > weld && worst.is_none_or(|(_, _, gap)| off_plane > gap) {
2141 worst = Some((operand, face.id, off_plane));
2142 }
2143 }
2144 }
2145 worst.map(|(operand, face_id, gap)| (operand, face_id, gap, weld))
2146}
2147
2148fn volume_within_csg_bounds(operation: BooleanOperation, va: f64, vb: f64, vr: f64) -> bool {
2151 let slack = 1e-2 * (va + vb).max(1.0);
2152 match operation {
2153 BooleanOperation::Union => vr >= va.max(vb) - slack && vr <= va + vb + slack,
2155 BooleanOperation::Subtract => vr <= va + slack && vr >= -slack,
2157 BooleanOperation::Intersect => vr <= va.min(vb) + slack && vr >= -slack,
2159 }
2160}
2161
2162fn reverse_fragment(fragment: &mut FaceFragmentRecord) -> Result<(), KernelRefusal> {
2189 fragment.same_sense = !fragment.same_sense;
2190 for loop_record in &mut fragment.loops {
2191 loop_record.coedges.reverse();
2192 for coedge in &mut loop_record.coedges {
2193 coedge.forward = !coedge.forward;
2194 coedge.pcurve = coedge.pcurve.reversed().or_refuse(KernelStage::Validate, "reversed")?;
2195 }
2196 }
2197 Ok(())
2198}
2199
2200fn build_nary_imprint(
2207 operands: &[BrepSolid],
2208 options: &ImprintOptions,
2209) -> Result<ImprintResultRecord, KernelRefusal> {
2210 let mut section_evidence = false;
2211 let mut vertices: Vec<ImprintVertex> = Vec::new();
2212 let mut pieces: Vec<ImprintPieceRecord> = Vec::new();
2213 let mut by_face: HashMap<(u8, u64), Vec<u64>> = HashMap::default();
2214 let mut edge_splits: HashMap<(u8, u64), Vec<f64>> = HashMap::default();
2215 let mut next_vertex_id: u64 = 1;
2216 let mut next_piece_id: u64 = 1;
2217
2218 for i in 0..operands.len() {
2219 for j in (i + 1)..operands.len() {
2220 let pair = build_imprints(&operands[i], &operands[j], options)?;
2221 let remap = |operand: u8| -> u8 {
2222 if operand == 0 {
2223 i as u8
2224 } else {
2225 j as u8
2226 }
2227 };
2228
2229 section_evidence = section_evidence || pair.section_evidence;
2230 let mut vertex_map: HashMap<u64, u64> = HashMap::default();
2231 for vertex in &pair.vertices {
2232 let global = next_vertex_id;
2233 next_vertex_id += 1;
2234 vertex_map.insert(vertex.id, global);
2235 vertices.push(ImprintVertex {
2236 id: global,
2237 point: vertex.point,
2238 });
2239 }
2240
2241 let mut piece_map: HashMap<u64, u64> = HashMap::default();
2242 for piece in &pair.pieces {
2243 let global = next_piece_id;
2244 next_piece_id += 1;
2245 piece_map.insert(piece.id, global);
2246 let mut mapped = piece.clone();
2247 mapped.id = global;
2248 mapped.start_vertex_id = *vertex_map
2249 .get(&piece.start_vertex_id)
2250 .ok_or_else(|| KernelRefusal::internal(KernelStage::Intersect, "nary.imprint", "n-ary imprint: piece references unknown vertex"))?;
2251 mapped.end_vertex_id = *vertex_map
2252 .get(&piece.end_vertex_id)
2253 .ok_or_else(|| KernelRefusal::internal(KernelStage::Intersect, "nary.imprint", "n-ary imprint: piece references unknown vertex"))?;
2254 for pcurve in &mut mapped.pcurves {
2255 pcurve.operand = remap(pcurve.operand);
2256 }
2257 mapped.support_faces = [
2258 FaceKey {
2259 operand: remap(piece.support_faces[0].operand),
2260 face_id: piece.support_faces[0].face_id,
2261 },
2262 FaceKey {
2263 operand: remap(piece.support_faces[1].operand),
2264 face_id: piece.support_faces[1].face_id,
2265 },
2266 ];
2267 pieces.push(mapped);
2268 }
2269
2270 for entry in &pair.by_face {
2271 let list = by_face
2272 .entry((remap(entry.operand), entry.face_id))
2273 .or_default();
2274 for piece_id in &entry.piece_ids {
2275 let global = *piece_map.get(piece_id).ok_or_else(|| {
2276 KernelRefusal::internal(KernelStage::Intersect, "nary.imprint", "n-ary imprint: by_face references unknown piece")
2277 })?;
2278 list.push(global);
2279 }
2280 }
2281
2282 for split in &pair.edge_splits {
2283 edge_splits
2284 .entry((remap(split.operand), split.edge_id))
2285 .or_default()
2286 .extend(split.parameters.iter().copied());
2287 }
2288 }
2289 }
2290
2291 Ok(ImprintResultRecord {
2292 faces_in_unproved_pairs: None,
2293 vertices,
2294 pieces,
2295 tangent_nodes: Vec::new(),
2296 barrier_edges: Vec::new(),
2297 section_evidence,
2298 cosurface_pairs: Vec::new(),
2299 operand_sliver_regions: Vec::new(),
2300 tangent_sections: Vec::new(),
2301 by_face: by_face
2302 .into_iter()
2303 .map(|((operand, face_id), piece_ids)| FaceImprints {
2304 operand,
2305 face_id,
2306 piece_ids,
2307 })
2308 .collect(),
2309 edge_splits: edge_splits
2310 .into_iter()
2311 .map(|((operand, edge_id), parameters)| EdgeSplitRecord {
2312 operand,
2313 edge_id,
2314 parameters,
2315 })
2316 .collect(),
2317 })
2318}
2319
2320pub fn boolean_operation_nary(
2331 operands: &[BrepSolid],
2332 operation: BooleanOperation,
2333) -> Result<BrepSolid, KernelRefusal> {
2334 boolean_operation_nary_with_options(operands, operation, &BooleanOptions::default())
2335}
2336
2337pub fn boolean_operation_nary_with_options(
2343 operands: &[BrepSolid],
2344 operation: BooleanOperation,
2345 options: &BooleanOptions,
2346) -> Result<BrepSolid, KernelRefusal> {
2347 let most = nary_chunk();
2352 if operands.len() > most && nary_chunks_on() {
2353 let mut whole = boolean_operation_nary_with_options(&operands[..most], operation, options)?;
2354 for chunk in operands[most..].chunks(most - 1) {
2355 if let [only] = chunk {
2358 whole = boolean_operation(&whole, only, operation, options)?;
2359 continue;
2360 }
2361 let mut next = Vec::with_capacity(chunk.len() + 1);
2362 next.push(whole);
2363 next.extend_from_slice(chunk);
2364 whole = boolean_operation_nary_with_options(&next, operation, options)?;
2365 }
2366 return Ok(whole);
2367 }
2368 let arranged = boolean_operation_nary_arranged(operands, operation, options);
2369 match arranged {
2370 Err(error) if nary_sequential_fallback_enabled() && operands.len() > 2 && error.message.contains("boolean assembly") => {
2371 let mut whole = operands[0].clone();
2374 for operand in &operands[1..] {
2375 whole = match boolean_operation(&whole, operand, operation, options) {
2376 Ok(solid) => solid,
2377 Err(_) => return Err(error),
2378 };
2379 }
2380 Ok(whole)
2381 }
2382 other => other,
2383 }
2384}
2385
2386const NARY_MOST: usize = 255;
2395
2396fn nary_chunk() -> usize {
2399 NARY_MOST
2400}
2401
2402
2403fn nary_chunks_on() -> bool {
2406 crate::switch!("BREP_NARY_CHUNKS", true)
2407}
2408
2409fn nary_sequential_fallback_enabled() -> bool {
2410 crate::switch!("BREP_NARY_SEQUENTIAL_FALLBACK", true)
2411}
2412
2413fn boolean_operation_nary_arranged(
2414 operands: &[BrepSolid],
2415 operation: BooleanOperation,
2416 options: &BooleanOptions,
2417) -> Result<BrepSolid, KernelRefusal> {
2418 if operands.len() > 1 {
2419 if let Some(scaled) = WorkingScale::of(&operands.iter().collect::<Vec<_>>(), options)? {
2420 return scaled.run(
2421 || boolean_operation_nary_with_options(operands, operation, options),
2422 || boolean_operation_nary_with_options(&scaled.solids, operation, &scaled.options)
2423 .map_err(|error| scaled.refusal(error))
2424 .and_then(|solid| scaled.back(&solid)),
2425 );
2426 }
2427 }
2428 if operands.is_empty() {
2429 return Err(KernelRefusal::input(KernelStage::Collect, "operands", "boolean_operation_nary: no operands provided"));
2430 }
2431 if operands.len() == 1 {
2432 return Ok(operands[0].clone());
2433 }
2434 if operands.len() > nary_chunk() {
2435 return Err(KernelRefusal::input(KernelStage::Collect, "operands", "boolean_operation_nary: at most 255 operands supported"));
2436 }
2437 if let Some(aligned) = ball_align::align_balls_nary(operands, operation, options.tolerance) {
2440 return boolean_operation_nary_with_options(&aligned, operation, options);
2441 }
2442 let debug = std::env::var("BREP_DEBUG_BOOL").is_ok();
2443
2444 let mut policy = KernelTolerances::for_solid(&operands[0], options.tolerance);
2448 for operand in &operands[1..] {
2449 let candidate = KernelTolerances::for_solid(operand, options.tolerance);
2450 if candidate.sew_search > policy.sew_search {
2451 policy = candidate;
2452 }
2453 }
2454 policy.check().or_input(KernelStage::Collect, "tolerances")?;
2455 let tolerance = policy.model;
2456
2457 let mut healed = operands.to_vec();
2460 for operand in &mut healed {
2461 crate::heal::heal_operands(operand, &policy)?;
2462 crate::heal::refit_inherited_trims_reused(operand, &policy)?;
2465 normalize_operand_band_seams(operand)?;
2468 }
2469
2470 let mut imprint_options = options.imprint.clone();
2472 imprint_options.tolerance = tolerance;
2473 let imprint = build_nary_imprint(&healed, &imprint_options)?;
2474
2475 let mut split = Vec::with_capacity(healed.len());
2477 for (index, operand) in healed.iter().enumerate() {
2478 split.push(apply_edge_splits(operand, index as u8, &imprint)?);
2479 }
2480 let mut fragments = Vec::with_capacity(split.len());
2481 for (index, solid) in split.iter().enumerate() {
2482 fragments.push(fragment_solid(solid, index as u8, &imprint)?);
2483 }
2484
2485 let selected = select_fragments_nary(&fragments, &healed, operation, tolerance, debug)?;
2487
2488 let solids: HashMap<u8, &BrepSolid> = split
2490 .iter()
2491 .enumerate()
2492 .map(|(index, solid)| (index as u8, solid))
2493 .collect();
2494 let solid = assemble_fragments(selected, &solids, &imprint, tolerance)?;
2495 let solid = if options.merge_coplanar_faces
2496 && std::env::var("BREP_COPLANAR_MERGE").as_deref() != Ok("0")
2497 {
2498 let merged = merge_same_surface_faces_excluding(
2499 &solid,
2500 tolerance,
2501 &options.keep_unmerged_name_substrs,
2502 )?;
2503 let merged = merge_curve_continuation_edges(&merged, tolerance).map_err(|refusal| KernelRefusal { stage: KernelStage::Validate, ..refusal })?;
2504 rejoin::rejoin_unless_referenced(merged, options, tolerance)
2505 } else {
2506 solid
2507 };
2508 let validation = solid.validate_detailed(&policy);
2509 if !validation.issues.is_empty() {
2510 return Err(KernelRefusal::new(
2511 RefusalClass::InvalidResultTopology { issues: validation.issues.len() as u32 },
2512 KernelStage::Validate,
2513 format!(
2514 "boolean_operation_nary: invalid result: {:?}",
2515 validation.issues
2516 )));
2517 }
2518 if debug {
2519 if let Ok(report) =
2520 crate::oracle::boolean_semantic_disagreement_nary(&healed, operation, &solid, 300)
2521 {
2522 if report.is_flagged() {
2523 eprintln!(
2524 "[oracle] n-ary semantic disagreement rate {:.4} ({} of {} decidable points); sample {:?}",
2525 report.disagreement_rate,
2526 report.disagreements.len(),
2527 report.considered,
2528 report.sample_disagreement()
2529 );
2530 }
2531 }
2532 }
2533 Ok(solid)
2534}
2535
2536fn attribute_to_tangent_node(error: KernelRefusal, nodes: &[Vec3]) -> KernelRefusal {
2567 let Some(node) = nodes.first() else {
2568 return error;
2569 };
2570 if !error.class.perturbation_eligible()
2571 || matches!(error.class, RefusalClass::TangentNodeSingularity)
2572 {
2573 return error;
2574 }
2575 if std::env::var("BREP_DEBUG_BOOL").is_ok() {
2576 eprintln!(
2577 "boolean: tear downstream of the tangent node at ({:.6},{:.6},{:.6}) attributed to it; the stage read: {}",
2578 node.x, node.y, node.z, error.message
2579 );
2580 }
2581 KernelRefusal::new(
2582 RefusalClass::TangentNodeSingularity,
2583 error.stage,
2584 format!(
2585 "boolean: unsupported singular/tangent-node surface intersection \
2586 at the tangent node at ({:.6},{:.6},{:.6}): the section through it did not \
2587 assemble into a closed shell",
2588 node.x, node.y, node.z
2589 ),
2590 )
2591}
2592
2593pub fn attribute_to_tangent_section(
2615 error: KernelRefusal,
2616 sections: &[crate::imprint::TangentSectionRecord],
2617 origins: &[FaceKey],
2618) -> KernelRefusal {
2619 if sections.is_empty()
2620 || !error.class.perturbation_eligible()
2621 || matches!(error.class, RefusalClass::TangentNodeSingularity)
2622 {
2623 return error;
2624 }
2625 let named = refusal_result_faces(&error.message)
2626 .into_iter()
2627 .filter_map(|id| origins.get(id.checked_sub(1)? as usize).copied())
2628 .collect::<Vec<FaceKey>>();
2629 let involving = |fallback: bool| {
2633 sections.iter().find(|section| {
2634 section.grazing.is_empty() != fallback && named.iter().any(|face| section.faces.contains(face))
2635 })
2636 };
2637 let Some(section) = involving(false).or_else(|| involving(true)) else {
2638 return error;
2639 };
2640 let at = |point: Vec3| {
2643 let shown = |value: f64| if value.abs() < 5e-7 { 0.0 } else { value };
2644 format!("({:.6},{:.6},{:.6})", shown(point.x), shown(point.y), shown(point.z))
2645 };
2646 let pierces = (!section.grazing.is_empty()).then(|| {
2652 let shown = section.grazing.len().min(4);
2653 let mut listed = section.grazing[..shown]
2654 .iter()
2655 .map(|(point, tangency)| format!("{} at |tan·n| = {tangency:.4}", at(*point)))
2656 .collect::<Vec<_>>()
2657 .join(", ");
2658 if section.grazing.len() > shown {
2659 listed.push_str(&format!(" and {} more", section.grazing.len() - shown));
2660 }
2661 listed
2662 });
2663 let pierce_only = section.pierce_only();
2664 let shape = if let (true, Some(pierces)) = (pierce_only, pierces.as_deref()) {
2665 format!(
2666 "cross at a grazing angle: a trim edge pierces the other carrier inside both \
2667 trims at {pierces}, below the marcher's start gate, and no transverse section was \
2668 marched between the pierces — a near-tangent crossing born on a tangent contact \
2669 (a third-order singularity) the imprint does not build yet"
2670 )
2671 } else if section.planar {
2672 format!(
2673 "touch along a tangent curve from {} to {} (length {:.6}, {} stations{}) which the \
2674 imprint does not build yet",
2675 at(section.start),
2676 at(section.end),
2677 section.length,
2678 section.stations,
2679 if section.closed { ", closed" } else { "" }
2680 )
2681 } else {
2682 format!(
2683 "touch along a curve through {} with neither carrier planar, a curved/curved \
2684 tangent contact the lane does not trace yet",
2685 at(section.start)
2686 )
2687 };
2688 let shape = match (pierce_only, pierces) {
2689 (false, Some(pierces)) => format!(
2690 "{shape}; a trim edge also pierces the other carrier inside both trims at {pierces}, \
2691 below the marcher's start gate, with no transverse section marched"
2692 ),
2693 _ => shape,
2694 };
2695 let involved = named
2696 .iter()
2697 .filter(|face| section.faces.contains(face))
2698 .map(|face| format!("{}/{}", face.operand, face.face_id))
2699 .collect::<Vec<_>>()
2700 .join(", ");
2701 KernelRefusal::new(
2702 RefusalClass::TangentNodeSingularity,
2703 error.stage,
2704 format!(
2705 "boolean: unsupported tangent-curve surface intersection between faces {}/{} and {}/{}: \
2706 the carriers {shape}; the refusal names face(s) {involved} the contact involves; {}",
2707 section.first.operand, section.first.face_id, section.second.operand, section.second.face_id,
2708 error.message
2709 ),
2710 )
2711}
2712
2713pub fn refusal_result_faces(message: &str) -> Vec<u64> {
2718 let mut ids = Vec::new();
2719 let digits_after = |text: &str| -> Option<u64> {
2720 let end = text.find(|c: char| !c.is_ascii_digit()).unwrap_or(text.len());
2721 text[..end].parse().ok()
2722 };
2723 for (index, _) in message.match_indices("face ") {
2724 if let Some(id) = digits_after(&message[index + "face ".len()..]) {
2725 ids.push(id);
2726 }
2727 }
2728 if let Some(start) = message.find("on faces [") {
2729 let rest = &message[start + "on faces [".len()..];
2730 let list = &rest[..rest.find(']').unwrap_or(rest.len())];
2731 for entry in list.split(", ") {
2732 let entry = entry.trim_start();
2733 if let Some(id) = digits_after(entry) {
2734 if entry[id.to_string().len()..].starts_with(" '") {
2735 ids.push(id);
2736 }
2737 }
2738 }
2739 }
2740 ids.sort_unstable();
2741 ids.dedup();
2742 ids
2743}
2744
2745pub fn boolean_operation_with_diagnostics(
2746 first: &BrepSolid,
2747 second: &BrepSolid,
2748 operation: BooleanOperation,
2749 options: &BooleanOptions,
2750) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
2751 if let Some(scaled) = WorkingScale::of(&[first, second], options)? {
2752 return scaled.run(
2753 || boolean_operation_with_diagnostics(first, second, operation, options),
2754 || {
2755 let mut outcome = boolean_operation_with_diagnostics(&scaled.solids[0], &scaled.solids[1], operation, &scaled.options)
2756 .map_err(|error| scaled.refusal(error))?;
2757 outcome.value = scaled.back(&outcome.value)?;
2758 outcome.diagnostics.count_n("working_scale.fired", 1);
2759 outcome.diagnostics.measure_max("working_scale.factor", scaled.factor);
2760 Ok(outcome)
2761 },
2762 );
2763 }
2764 let _account = profile::Scope::new("boolean.other");
2765 let (first_aligned, second_aligned) = ball_align::align_balls(first, second, operation, options.tolerance);
2768 let (first, second) = (first_aligned.as_ref(), second_aligned.as_ref());
2769 let closed_inputs = matches!(std::env::var("BREP_CLOSED_OPERAND_INPUT").as_deref(), Err(_) | Ok("1") | Ok("on"));
2770 if let (true, Some(later)) = (reseat::seam_reseat_enabled(), &options.seam_reseat_later_references) {
2771 let started = Instant::now();
2772 let (first, second) = reseat::reseat_tangent_seams(first, second, later, options.tolerance);
2773 profile_stage("seam_prepare_ms", started.elapsed().as_secs_f64() * 1000.0);
2774 return boolean_operation_with_diagnostics_impl(&first, &second, operation, options, closed_inputs).map(without_sliver_shells);
2775 }
2776 let cylinders = reseat::seam_reseat_cylinders_mode();
2779 if reseat::seam_reseat_enabled() && cylinders != crate::env_read::Mode::Off {
2780 let kinds = reseat::ContactKinds { planes: false, cylinders: true };
2781 let volume = |result: &Result<KernelOutcome<BrepSolid>, KernelRefusal>| {
2782 result.as_ref().ok().and_then(|outcome| crate::solid_mass_properties(&outcome.value).ok()).map(|mass| mass.volume)
2783 };
2784 if reseat::seam_reseat_retry_enabled() {
2785 let plain = boolean_operation_with_diagnostics_impl(first, second, operation, options, closed_inputs).map(without_sliver_shells);
2791 if plain.is_ok() {
2792 return plain;
2793 }
2794 let (reseated_first, reseated_second) = reseat::reseat_tangent_seams_of(first, second, &[], options.tolerance, kinds);
2795 let moved = matches!(reseated_first, std::borrow::Cow::Owned(_)) || matches!(reseated_second, std::borrow::Cow::Owned(_));
2796 if !moved {
2797 return plain;
2798 }
2799 let reseated = crate::imprint::driver::with_tangent_cylinder_filter(|| {
2800 boolean_operation_with_diagnostics_impl(&reseated_first, &reseated_second, operation, options, closed_inputs).map(without_sliver_shells)
2801 });
2802 if cylinders == crate::env_read::Mode::Check {
2803 eprintln!(
2804 "boolean.seam_reseat_cylinders check: plain refused, reseated retry {} volume {:?}",
2805 if reseated.is_ok() { "built" } else { "refused" },
2806 volume(&reseated)
2807 );
2808 return plain;
2809 }
2810 return match reseated {
2811 Ok(mut outcome) => {
2812 outcome.diagnostics.count_n("seam_reseat_cylinders.retry_built", 1);
2813 Ok(outcome)
2814 }
2815 Err(_) => plain,
2816 };
2817 }
2818 let (reseated_first, reseated_second) = reseat::reseat_tangent_seams_of(first, second, &[], options.tolerance, kinds);
2819 let moved = matches!(reseated_first, std::borrow::Cow::Owned(_)) || matches!(reseated_second, std::borrow::Cow::Owned(_));
2820 if moved {
2821 let reseated = boolean_operation_with_diagnostics_impl(&reseated_first, &reseated_second, operation, options, closed_inputs).map(without_sliver_shells);
2822 if cylinders == crate::env_read::Mode::On {
2823 return reseated;
2824 }
2825 let plain = boolean_operation_with_diagnostics_impl(first, second, operation, options, closed_inputs).map(without_sliver_shells);
2826 eprintln!(
2827 "boolean.seam_reseat_cylinders check: plain {} volume {:?}, reseated {} volume {:?}",
2828 if plain.is_ok() { "built" } else { "refused" },
2829 volume(&plain),
2830 if reseated.is_ok() { "built" } else { "refused" },
2831 volume(&reseated)
2832 );
2833 return plain;
2834 }
2835 }
2836 boolean_operation_with_diagnostics_impl(first, second, operation, options, closed_inputs).map(without_sliver_shells)
2837}
2838
2839fn without_sliver_shells(mut outcome: KernelOutcome<BrepSolid>) -> KernelOutcome<BrepSolid> {
2841 let dropped = drop_sliver_shells(&mut outcome.value);
2842 if dropped > 0 {
2843 outcome.diagnostics.count_n("sliver_shell.dropped", dropped as u64);
2844 }
2845 outcome
2846}
2847
2848pub fn boolean_operation_with_diagnostics_impl(
2849 first: &BrepSolid,
2850 second: &BrepSolid,
2851 operation: BooleanOperation,
2852 options: &BooleanOptions,
2853 closed_inputs: bool,
2854) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
2855 let _coedge_memo = crate::topology::CoedgeMemoScope::open(true);
2858 if matches!(operation, BooleanOperation::Intersect)
2861 && [first, second].iter().any(|body| body.kind == crate::BodyKind::Sheet)
2862 && match std::env::var("BREP_SHEET_TRIM").as_deref() {
2863 Ok("1") => true,
2864 Ok("0") => false,
2865 _ => options.sheet_trim,
2866 }
2867 {
2868 return sheet::trim(first, second, options);
2869 }
2870 if matches!(operation, BooleanOperation::Union | BooleanOperation::Subtract) {
2879 if let Some(operand) = [first, second]
2880 .iter()
2881 .position(|solid| solid.kind == crate::BodyKind::Sheet)
2882 {
2883 return Err(KernelRefusal::input(
2884 KernelStage::Collect,
2885 "sheet_operand",
2886 format!(
2887 "boolean: operand {operand} is a Sheet, which encloses no solid; union and \
2888 subtract of a sheet are refused; Intersect trims a Sheet by a Solid"
2889 ),
2890 ));
2891 }
2892 }
2893 let mut outcome = boolean_operation_with_diagnostics_core(first, second, operation, options)?;
2899 let closure_started = closed_inputs.then(Instant::now);
2900 if closed_inputs {
2901 for (operand, solid) in [first, second].into_iter().enumerate() {
2902 let open = one_use_edges(solid);
2903 if open > 0 {
2904 return Err(KernelRefusal::input(KernelStage::Collect, "operand_closure", format!(
2905 "boolean: operand {operand} is not a closed shell: {open} of its edges bound only one face, so its inside is undefined"
2906 )));
2907 }
2908 }
2909 }
2910 if let Some(started) = closure_started {
2911 let ms = started.elapsed().as_secs_f64() * 1000.0;
2912 profile_stage("operand_closure_ms", ms);
2913 outcome.diagnostics.measure_max("timing.operand_closure_ms", ms);
2914 }
2915 Ok(outcome)
2916}
2917
2918fn boolean_operation_with_diagnostics_core(
2919 first: &BrepSolid, second: &BrepSolid, operation: BooleanOperation, options: &BooleanOptions,
2920) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
2921
2922 if let Some(offset) = crate::recentre::control_offset_at_entry() {
2925 return boolean_operation_with_diagnostics_at_offset(first, second, operation, options, offset);
2926 }
2927 let mut bounds = operand_bounds(first);
2930 bounds.include(operand_bounds(second));
2931 if let Some(offset) = crate::recentre::guard_offset(bounds) {
2932 crate::recentre::profile_fired("boolean", offset, bounds);
2933 let mut outcome = boolean_translated(first, second, operation, options, offset, crate::recentre::EntryKind::Guard)?;
2934 outcome.diagnostics.count_n("recentre.fired", 1);
2935 outcome.diagnostics.measure_max("recentre.distance", offset.length());
2936 return Ok(outcome);
2937 }
2938 let mut tangent_nodes = Vec::new();
2939 let (mut outcome, soundness_candidates) =
2940 boolean_pipeline(first, second, operation, options, &mut tangent_nodes)
2941 .map_err(|error| attribute_to_tangent_node(error, &tangent_nodes))?;
2942 let stage_started = Instant::now();
2955 let accepted = match &soundness_candidates {
2956 Some(candidates) => crate::accept_sound_against_scoped(&[first, second], outcome.value, "boolean", candidates),
2959 None => crate::accept_sound_against(&[first, second], outcome.value, "boolean"),
2960 };
2961 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
2962 profile_stage("soundness_ms", stage_ms);
2963 outcome.diagnostics.measure_max("timing.soundness_ms", stage_ms);
2964 outcome.value = accepted?;
2965 Ok(outcome)
2966}
2967
2968pub fn boolean_operation_with_diagnostics_at_offset(
2972 first: &BrepSolid,
2973 second: &BrepSolid,
2974 operation: BooleanOperation,
2975 options: &BooleanOptions,
2976 offset: Vec3,
2977) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
2978 boolean_translated(first, second, operation, options, offset, crate::recentre::EntryKind::Control)
2979}
2980
2981fn boolean_translated(
2983 first: &BrepSolid,
2984 second: &BrepSolid,
2985 operation: BooleanOperation,
2986 options: &BooleanOptions,
2987 offset: Vec3,
2988 kind: crate::recentre::EntryKind,
2989) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
2990 let _entry = crate::recentre::TranslatedEntry::open(kind);
2991 let translate = |solid: &BrepSolid, offset: Vec3| {
2992 crate::recentre::translate_solid(solid, offset).map_err(|message| {
2993 KernelRefusal::internal(
2994 KernelStage::Collect,
2995 "translation_control",
2996 format!("boolean: the translation control could not move an operand: {message}"),
2997 )
2998 })
2999 };
3000 let moved_first = translate(first, offset)?;
3001 let moved_second = translate(second, offset)?;
3002 let outcome = boolean_operation_with_diagnostics(&moved_first, &moved_second, operation, options)?;
3003 let value = translate(&outcome.value, offset.scale(-1.0))?;
3004 Ok(KernelOutcome { value, diagnostics: outcome.diagnostics })
3005}
3006
3007fn profile_stage(code: &str, ms: f64) {
3011 let row = match code {
3012 "heal_ms" => Some("boolean.operand_prepare"),
3013 "imprint_ms" => Some("boolean.imprint"),
3014 "edge_split_ms" => Some("boolean.edge_split"),
3015 "fragment_ms" => Some("boolean.fragment"),
3016 "select_ms" => Some("boolean.select"),
3017 "assemble_ms" => Some("boolean.assemble"),
3018 "face_merge_ms" => Some("boolean.face_merge"),
3019 "soundness_ms" => Some("boolean.soundness"),
3020 "operand_closure_ms" => Some("boolean.operand_closure"),
3021 "seam_prepare_ms" => Some("boolean.seam_prepare"),
3022 "final_validate_ms" => Some("boolean.final_validate"),
3023 _ => None,
3024 };
3025 if let Some(row) = row { profile::record(row, ms); }
3026 if crate::profile::profile_enabled() {
3027 profile_line!("boolean.{code}={ms:.2}");
3028 }
3029}
3030
3031struct BooleanStageDump {
3036 directory: std::path::PathBuf,
3037 serial: usize,
3038}
3039
3040impl BooleanStageDump {
3041 fn open() -> Option<Self> {
3042 static SERIAL: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
3043 let directory = std::env::var("BREP_BOOLEAN_DUMP").ok().filter(|value| !value.is_empty())?;
3044 let serial = SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3045 Some(Self { directory: directory.into(), serial })
3046 }
3047
3048 fn write<T: Serialize + ?Sized>(&self, stage: &str, value: &T) {
3049 let path = self.directory.join(format!("{:03}-{stage}.json", self.serial));
3050 match serde_json::to_string(value) {
3051 Ok(text) => {
3052 if let Err(error) = std::fs::write(&path, text) {
3053 eprintln!("BREP_BOOLEAN_DUMP {}: {error}", path.display());
3054 }
3055 }
3056 Err(error) => eprintln!("BREP_BOOLEAN_DUMP {stage}: {error}"),
3057 }
3058 }
3059}
3060
3061pub fn boolean_policy(
3063 first: &BrepSolid,
3064 second: &BrepSolid,
3065 options: &BooleanOptions,
3066) -> Result<KernelTolerances, KernelRefusal> {
3067 let policy = options
3068 .tolerances
3069 .unwrap_or_else(|| KernelTolerances::for_pair(first, second, options.tolerance));
3070 policy.check().or_input(KernelStage::Collect, "tolerances")?;
3071 Ok(policy)
3072}
3073
3074fn prepared_operands(
3077 first: &BrepSolid,
3078 second: &BrepSolid,
3079 policy: &KernelTolerances,
3080) -> Result<(BrepSolid, BrepSolid), KernelRefusal> {
3081 let stage_started = Instant::now();
3090 let mut first_owned = first.clone();
3091 let mut second_owned = second.clone();
3092 crate::heal::heal_operands(&mut first_owned, policy)?;
3093 crate::heal::heal_operands(&mut second_owned, policy)?;
3094 profile_stage("heal.operands_ms", stage_started.elapsed().as_secs_f64() * 1_000.0);
3095 let refit_started = Instant::now();
3099 crate::heal::refit_inherited_trims_reused(&mut first_owned, policy)?;
3100 crate::heal::refit_inherited_trims_reused(&mut second_owned, policy)?;
3101 profile_stage("heal.refit_ms", refit_started.elapsed().as_secs_f64() * 1_000.0);
3102 if crate::profile::profile_enabled() {
3103 let (hits, misses) = crate::reading_memo::counts();
3104 profile_line!("boolean.reading_memo hits={hits} misses={misses}");
3105 let (served, stored) = crate::heal::refit_memo_counts_served_stored();
3106 profile_line!("boolean.refit_memo served={served} stored={stored}");
3107 let (served, stored, mismatches) = crate::heal::claim_record_memo_counts();
3108 profile_line!("boolean.claim_record_memo served={served} stored={stored} check_mismatches={mismatches}");
3109 }
3110 profile_stage("heal_ms", stage_started.elapsed().as_secs_f64() * 1_000.0);
3111 normalize_operand_band_seams(&mut first_owned)?;
3116 normalize_operand_band_seams(&mut second_owned)?;
3117 Ok((first_owned, second_owned))
3118}
3119
3120fn boolean_imprint_options(options: &BooleanOptions, tolerance: f64) -> ImprintOptions {
3121 let mut imprint_options = options.imprint.clone();
3122 imprint_options.tolerance = tolerance;
3123 imprint_options
3124}
3125
3126pub fn boolean_split_operands(
3136 first: &BrepSolid,
3137 second: &BrepSolid,
3138 options: &BooleanOptions,
3139) -> Result<(BrepSolid, BrepSolid), KernelRefusal> {
3140 if let Some(scaled) = WorkingScale::of(&[first, second], options)? {
3141 return scaled.run(
3142 || boolean_split_operands(first, second, options),
3143 || {
3144 let (split_first, split_second) = boolean_split_operands(&scaled.solids[0], &scaled.solids[1], &scaled.options)
3145 .map_err(|error| scaled.refusal(error))?;
3146 Ok((scaled.back(&split_first)?, scaled.back(&split_second)?))
3147 },
3148 );
3149 }
3150 let policy = boolean_policy(first, second, options)?;
3151 let (first, second) = prepared_operands(first, second, &policy)?;
3152 let imprint = build_imprints(&first, &second, &boolean_imprint_options(options, policy.model))?;
3153 let (split_first, _) = apply_edge_splits_with_map(&first, 0, &imprint)?;
3154 let (split_second, _) = apply_edge_splits_with_map(&second, 1, &imprint)?;
3155 Ok((split_first, split_second))
3156}
3157
3158fn operand_bounds(solid: &BrepSolid) -> crate::Aabb {
3162 let mut bounds = crate::Aabb::from_points(solid.vertices.iter().map(|vertex| vertex.point));
3163 for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
3164 match crate::Aabb::from_surface_controls(&face.surface) {
3165 Ok(face_bounds) => bounds.include(face_bounds),
3166 Err(_) => {
3167 return crate::Aabb {
3168 minimum: Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY),
3169 maximum: Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY),
3170 }
3171 }
3172 }
3173 }
3174 bounds
3175}
3176
3177fn line_or_point_contact(first: &BrepSolid, second: &BrepSolid, bounds: [crate::Aabb; 2]) -> bool {
3183 apart_axes(bounds) >= 2 && plain_hull_solid(first) && plain_hull_solid(second)
3184}
3185
3186fn boxes_share_no_interior(first: &BrepSolid, second: &BrepSolid, bounds: [crate::Aabb; 2]) -> bool {
3189 apart_axes(bounds) >= 1 && plain_hull_solid(first) && plain_hull_solid(second)
3190}
3191
3192fn apart_axes([a, b]: [crate::Aabb; 2]) -> usize {
3194 let apart = |a_min: f64, a_max: f64, b_min: f64, b_max: f64| a_max <= b_min || b_max <= a_min;
3195 [
3196 apart(a.minimum.x, a.maximum.x, b.minimum.x, b.maximum.x),
3197 apart(a.minimum.y, a.maximum.y, b.minimum.y, b.maximum.y),
3198 apart(a.minimum.z, a.maximum.z, b.minimum.z, b.maximum.z),
3199 ]
3200 .into_iter()
3201 .filter(|&apart| apart)
3202 .count()
3203}
3204
3205fn plain_hull_solid(solid: &BrepSolid) -> bool {
3207 solid.kind == crate::BodyKind::Solid
3208 && solid.cells.is_empty()
3209 && solid.shells.iter().flat_map(|shell| &shell.faces).all(|face| {
3210 face.surface.control_points.iter().flatten().all(|control| control.w > 0.0 && control.w.is_finite())
3211 })
3212}
3213
3214fn scope_proved_apart_on() -> bool {
3218 switch!(live "BREP_SCOPE_PROVED_APART", true)
3219}
3220
3221fn soundness_candidates(
3236 solid: &BrepSolid,
3237 scope: &AssemblyScope,
3238 bounds: [crate::Aabb; 2],
3239 band: f64,
3240 unproved: Option<&HashSet<crate::imprint::FaceKey>>,
3241) -> HashSet<u64> {
3242 let mut candidates = HashSet::default();
3243 for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
3244 if scope.examined.contains(&face.id) {
3245 candidates.insert(face.id);
3246 continue;
3247 }
3248 let Some(&operand) = scope.operand_of.get(&face.id) else {
3249 candidates.insert(face.id);
3250 continue;
3251 };
3252 let other = bounds[usize::from(operand == 0)];
3253 match crate::Aabb::from_surface_controls(&face.surface) {
3254 Ok(face_bounds) if !face_bounds.intersects(other, band) => {}
3255 _ => {
3256 let proved_clear = unproved.is_some_and(|unproved| {
3257 scope.source_of.get(&face.id).is_some_and(|key| !unproved.contains(key))
3258 });
3259 if !proved_clear {
3260 candidates.insert(face.id);
3261 }
3262 }
3263 }
3264 }
3265 candidates
3266}
3267
3268
3269fn touching_empty_enabled() -> bool {
3277 switch!("BREP_TOUCHING_EMPTY", true)
3278}
3279
3280thread_local! {
3281 static TOUCHING_PROOF: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
3284}
3285
3286fn hair_deep_overlap(first: &BrepSolid, second: &BrepSolid, tolerance: f64) -> bool {
3293 use crate::AnalyticSurface as A;
3294 fn faces(solid: &BrepSolid) -> Vec<(&crate::AnalyticSurface, crate::spatial::Aabb, &crate::NurbsSurface, &crate::FaceRecord)> {
3295 solid
3296 .shells
3297 .iter()
3298 .flat_map(|shell| &shell.faces)
3299 .filter_map(|face| Some((face.surface.analytic()?, crate::Aabb::from_surface_controls(&face.surface).ok()?, &face.surface, face)))
3300 .collect()
3301 }
3302 let along = |surface: &crate::NurbsSurface, axis: Vec3| {
3304 surface.control_points.iter().flatten().filter_map(|control| control.point().ok()).fold((f64::INFINITY, f64::NEG_INFINITY), |(low, high), point| {
3305 let at = point.dot(axis);
3306 (low.min(at), high.max(at))
3307 })
3308 };
3309 let crossing = |distance: f64, ra: f64, rb: f64| {
3310 let outer = ra + rb - distance;
3311 let nested = distance - (ra - rb).abs();
3312 outer > tolerance && nested > tolerance
3313 };
3314 let boxes_overlap = |a: &crate::spatial::Aabb, b: &crate::spatial::Aabb| {
3315 (a.maximum.x.min(b.maximum.x) - a.minimum.x.max(b.minimum.x)) > tolerance
3316 && (a.maximum.y.min(b.maximum.y) - a.minimum.y.max(b.minimum.y)) > tolerance
3317 && (a.maximum.z.min(b.maximum.z) - a.minimum.z.max(b.minimum.z)) > tolerance
3318 };
3319 for (a, box_a, surface_a, face_a) in faces(first) {
3320 for (b, box_b, surface_b, face_b) in faces(second) {
3321 if !boxes_overlap(&box_a, &box_b) {
3322 continue;
3323 }
3324 match (a, b) {
3325 (A::RuledRevolution { frame: fa, rho0: a0, rho1: a1, .. }, A::RuledRevolution { frame: fb, rho0: b0, rho1: b1, .. })
3326 if (a0 - a1).abs() <= tolerance && (b0 - b1).abs() <= tolerance =>
3327 {
3328 let offset = fb.origin.sub(fa.origin);
3329 let normal = fa.axis.cross(fb.axis);
3330 if normal.length() <= 1e-12 {
3333 let (low_a, high_a) = along(surface_a, fa.axis);
3334 let (low_b, high_b) = along(surface_b, fa.axis);
3335 if high_a.min(high_b) - low_a.max(low_b) <= tolerance {
3336 continue;
3337 }
3338 }
3339 let apart = if normal.length() <= 1e-12 {
3340 offset.sub(fa.axis.scale(offset.dot(fa.axis))).length()
3341 } else {
3342 offset.dot(normal).abs() / normal.length()
3343 };
3344 if crossing(apart, a0.abs(), b0.abs()) {
3345 return true;
3346 }
3347 }
3348 (A::Sphere { frame: fa, radius: ra }, A::Sphere { frame: fb, radius: rb }) => {
3349 if crossing(fb.origin.sub(fa.origin).length(), *ra, *rb)
3354 && !circle_off_face(face_a, first, (fa.origin, *ra), (fb.origin, *rb), tolerance)
3355 && !circle_off_face(face_b, second, (fb.origin, *rb), (fa.origin, *ra), tolerance)
3356 {
3357 return true;
3358 }
3359 }
3360 _ => {}
3361 }
3362 }
3363 }
3364 false
3365}
3366
3367fn circle_off_face(face: &crate::FaceRecord, solid: &BrepSolid, own: (Vec3, f64), other: (Vec3, f64), tolerance: f64) -> bool {
3375 use crate::classification::{parameter_point_in_face, PolygonClass};
3376 let ((ca, ra), (cb, rb)) = (own, other);
3377 if face.loops.iter().all(|lp| lp.coedges.is_empty()) {
3378 return false;
3379 }
3380 fn clear(curve: &crate::NurbsCurve, depth: u32, centre: Vec3, radius: f64, tolerance: f64) -> bool {
3385 let points: Option<Vec<Vec3>> = curve.control_points.iter().map(|control| if control.w > 0.0 { control.point().ok() } else { None }).collect();
3386 let Some(points) = points else { return false };
3387 if points.iter().all(|point| point.sub(centre).length() < radius - tolerance) {
3388 return true;
3389 }
3390 let (mut low, mut high) = (Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY), Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY));
3391 for point in &points {
3392 low = Vec3::new(low.x.min(point.x), low.y.min(point.y), low.z.min(point.z));
3393 high = Vec3::new(high.x.max(point.x), high.y.max(point.y), high.z.max(point.z));
3394 }
3395 let near = Vec3::new(centre.x.clamp(low.x, high.x), centre.y.clamp(low.y, high.y), centre.z.clamp(low.z, high.z));
3396 if near.sub(centre).length() > radius + tolerance {
3397 return true;
3398 }
3399 if depth == 0 {
3400 return false;
3401 }
3402 let Ok([t0, t1]) = curve.domain() else { return false };
3403 match curve.split(0.5 * (t0 + t1)) {
3404 Ok((left, right)) => clear(&left, depth - 1, centre, radius, tolerance) && clear(&right, depth - 1, centre, radius, tolerance),
3405 Err(_) => false,
3406 }
3407 }
3408 for coedge in face.loops.iter().flat_map(|lp| &lp.coedges) {
3409 let Some(edge) = solid.edges.iter().find(|edge| edge.id == coedge.edge_id) else { return false };
3410 let Ok([d0, d1]) = edge.curve.domain() else { return false };
3411 let mut span = edge.curve.clone();
3413 if edge.t1 < d1 {
3414 match span.split(edge.t1) {
3415 Ok((left, _)) => span = left,
3416 Err(_) => return false,
3417 }
3418 }
3419 if edge.t0 > d0 {
3420 match span.split(edge.t0) {
3421 Ok((_, right)) => span = right,
3422 Err(_) => return false,
3423 }
3424 }
3425 if !clear(&span, 10, cb, rb, tolerance) {
3426 return false;
3427 }
3428 }
3429 let axis = cb.sub(ca);
3430 let distance = axis.length();
3431 let Ok(n) = axis.normalized() else { return false };
3432 let along = (distance * distance + ra * ra - rb * rb) / (2.0 * distance);
3433 let across = ra * ra - along * along;
3434 let Ok(side) = n.perpendicular() else { return false };
3435 if !(across > 0.0) {
3436 return false;
3437 }
3438 let point = ca.add(n.scale(along)).add(side.scale(across.sqrt()));
3439 let Ok(projection) = crate::project_point_to_surface(&face.surface, point) else { return false };
3440 matches!(parameter_point_in_face(face, crate::Vec2 { x: projection.u, y: projection.v }, 1e-9), Ok(PolygonClass::Outside))
3441}
3442
3443
3444fn empty_solid() -> BrepSolid {
3446 BrepSolid {
3447 mass_properties_cache: Default::default(),
3448 cells: Default::default(),
3449 id: 0,
3450 vertices: Vec::new(),
3451 edges: Vec::new(),
3452 shells: Vec::new(),
3453 genus: 0,
3454 kind: crate::BodyKind::Solid,
3455 }
3456}
3457
3458fn concatenate_disjoint(first: &BrepSolid, second: &BrepSolid) -> BrepSolid {
3464 let mut vertices = Vec::new();
3465 let mut edges = Vec::new();
3466 let mut shells = Vec::new();
3467 let mut used_face_names = HashSet::<String>::default();
3468 let (mut next_face_id, mut next_loop_id, mut next_coedge_id) = (1u64, 1u64, 1u64);
3469 for operand in [first, second] {
3470 let vertex_base = vertices.len() as u64;
3471 let edge_base = edges.len() as u64;
3472 let mut vertex_ids: HashMap<u64, u64> = HashMap::default();
3473 for (index, vertex) in operand.vertices.iter().enumerate() {
3474 let id = vertex_base + index as u64 + 1;
3475 vertex_ids.insert(vertex.id, id);
3476 vertices.push(VertexRecord { id, point: vertex.point });
3477 }
3478 let mut edge_ids: HashMap<u64, u64> = HashMap::default();
3479 for (index, edge) in operand.edges.iter().enumerate() {
3480 let id = edge_base + index as u64 + 1;
3481 edge_ids.insert(edge.id, id);
3482 edges.push(EdgeRecord {
3483 id,
3484 curve: edge.curve.clone(),
3485 t0: edge.t0,
3486 t1: edge.t1,
3487 start_vertex_id: vertex_ids.get(&edge.start_vertex_id).copied().unwrap_or(edge.start_vertex_id),
3488 end_vertex_id: vertex_ids.get(&edge.end_vertex_id).copied().unwrap_or(edge.end_vertex_id),
3489 degenerate: edge.degenerate,
3490 name: edge.name.clone(),
3491 });
3492 }
3493 for shell in &operand.shells {
3494 let mut faces = Vec::with_capacity(shell.faces.len());
3495 for face in &shell.faces {
3496 let loops = face
3497 .loops
3498 .iter()
3499 .map(|loop_record| {
3500 let coedges = loop_record
3501 .coedges
3502 .iter()
3503 .map(|coedge| {
3504 let id = next_coedge_id;
3505 next_coedge_id += 1;
3506 CoedgeRecord {
3507 id,
3508 edge_id: edge_ids.get(&coedge.edge_id).copied().unwrap_or(coedge.edge_id),
3509 forward: coedge.forward,
3510 pcurve: coedge.pcurve.clone(),
3511 }
3512 })
3513 .collect();
3514 let id = next_loop_id;
3515 next_loop_id += 1;
3516 LoopRecord { id, coedges }
3517 })
3518 .collect();
3519 let name = face.name.clone().map(|base| {
3520 if used_face_names.insert(base.clone()) {
3521 base
3522 } else {
3523 let mut suffix = 1usize;
3524 loop {
3525 let candidate = format!("{base}_{suffix}");
3526 if used_face_names.insert(candidate.clone()) {
3527 break candidate;
3528 }
3529 suffix += 1;
3530 }
3531 }
3532 });
3533 faces.push(FaceRecord {
3534 id: next_face_id,
3535 surface: face.surface.clone(),
3536 same_sense: face.same_sense,
3537 loops,
3538 name,
3539 });
3540 next_face_id += 1;
3541 }
3542 shells.push(ShellRecord { id: shells.len() as u64 + 1, faces });
3543 }
3544 }
3545 BrepSolid {
3546 mass_properties_cache: Default::default(),
3547 cells: Default::default(),
3548 id: 1,
3549 vertices,
3550 edges,
3551 shells,
3552 genus: first.genus + second.genus,
3553 kind: crate::BodyKind::Solid,
3554 }
3555}
3556
3557fn boolean_pipeline(
3560 first: &BrepSolid,
3561 second: &BrepSolid,
3562 operation: BooleanOperation,
3563 options: &BooleanOptions,
3564 tangent_nodes: &mut Vec<Vec3>,
3565) -> Result<(KernelOutcome<BrepSolid>, Option<HashSet<u64>>), KernelRefusal> {
3566 let _work = crate::imprint::work_profile::Scope::open("boolean");
3567 let replaced_operands = operand_state::replace_operands(first, second, operation, options);
3568 let (first, second) = match &replaced_operands {
3569 Some((first, second)) => (first, second),
3570 None => (first, second),
3571 };
3572 let policy = boolean_policy(first, second, options)?;
3573 let tolerance = policy.model;
3574 let bounds = [operand_bounds(first), operand_bounds(second)];
3589 let disjoint = disjoint_fast_path(options) && !bounds[0].intersects(bounds[1], policy.sew_search);
3590 let contact = !disjoint
3591 && contact_fast_path(options)
3592 && options.seam_reseat_later_references.is_some()
3593 && line_or_point_contact(first, second, bounds);
3594 let contact = contact
3599 || (!disjoint
3600 && matches!(operation, BooleanOperation::Intersect)
3601 && contact_fast_path(options)
3602 && boxes_share_no_interior(first, second, bounds));
3603 if disjoint || contact {
3604 let operation_started = Instant::now();
3605 let mut diagnostics = KernelDiagnostics::default();
3606 diagnostics.count_n(
3607 "collect.faces",
3608 first.shells.iter().chain(&second.shells).map(|shell| shell.faces.len() as u64).sum(),
3609 );
3610 diagnostics.count(if contact { "boolean.contact_fast_path" } else { "boolean.disjoint_fast_path" });
3611 diagnostics.measure_max("tolerance.model", policy.model);
3612 diagnostics.measure_max("tolerance.sew_search", policy.sew_search);
3613 let value = match operation {
3614 BooleanOperation::Union => concatenate_disjoint(first, second),
3615 BooleanOperation::Subtract => first.clone(),
3616 BooleanOperation::Intersect => {
3617 diagnostics.event(
3618 DiagnosticSeverity::Info,
3619 KernelStage::Select,
3620 "boolean.empty_result",
3621 format!("{operation:?} of witnessed-non-overlapping operands is empty"),
3622 );
3623 empty_solid()
3624 }
3625 };
3626 let stage_ms = operation_started.elapsed().as_secs_f64() * 1_000.0;
3627 profile_stage("disjoint_fast_path_ms", stage_ms);
3628 diagnostics.measure_max("timing.total_ms", stage_ms);
3629 return Ok((KernelOutcome { value, diagnostics }, Some(HashSet::default())));
3630 }
3631 let heal_started = Instant::now();
3632 let (first_owned, second_owned) = prepared_operands(first, second, &policy)?;
3633 let heal_ms = heal_started.elapsed().as_secs_f64() * 1_000.0;
3634 let first = &first_owned;
3635 let second = &second_owned;
3636
3637 let mut diagnostics = KernelDiagnostics::default();
3638 diagnostics.measure_max("timing.heal_ms", heal_ms);
3641 let fit_scope = crate::PcurveFitScope::open();
3646 let polyline_scope = crate::PolylineFitScope::open();
3650 let operation_started = Instant::now();
3651 diagnostics.count_n(
3652 "collect.faces",
3653 first
3654 .shells
3655 .iter()
3656 .chain(&second.shells)
3657 .map(|shell| shell.faces.len() as u64)
3658 .sum(),
3659 );
3660 diagnostics.measure_max("tolerance.model", policy.model);
3661 diagnostics.measure_max("tolerance.sew_search", policy.sew_search);
3662
3663 let imprint_options = boolean_imprint_options(options, tolerance);
3664 let stage_started = Instant::now();
3665 let imprint = build_imprints(first, second, &imprint_options)?;
3666 tangent_nodes.extend_from_slice(&imprint.tangent_nodes);
3667 if std::env::var("BREP_DEBUG_BOOL").is_ok() {
3668 for piece in &imprint.pieces {
3669 let start = piece.curve.evaluate(piece.t0);
3670 let end = piece.curve.evaluate(piece.t1);
3671 eprintln!(
3672 "piece {} supports={:?} t=[{:.6},{:.6}] start={:?} end={:?}",
3673 piece.id, piece.support_faces, piece.t0, piece.t1, start, end
3674 );
3675 }
3676 for entry in &imprint.by_face {
3677 eprintln!(
3678 "by_face operand={} face={} pieces={:?}",
3679 entry.operand, entry.face_id, entry.piece_ids
3680 );
3681 }
3682 for split in &imprint.edge_splits {
3683 eprintln!(
3684 "edge_split operand={} edge={} params={:?}",
3685 split.operand, split.edge_id, split.parameters
3686 );
3687 }
3688 }
3689 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
3690 profile_stage("imprint_ms", stage_ms);
3691 diagnostics.measure_max("timing.imprint_ms", stage_ms);
3692 diagnostics.count_n("intersect.pieces", imprint.pieces.len() as u64);
3693 diagnostics.count_n("intersect.vertices", imprint.vertices.len() as u64);
3694 diagnostics.count_n("intersect.edge_splits", imprint.edge_splits.len() as u64);
3695 let (march_swap_rescues, clip_swap_rescues) = crate::imprint::take_rescue_firings();
3696 diagnostics.count_n("intersect.march_swap_rescue", march_swap_rescues);
3697 diagnostics.count_n("intersect.clip_swap_rescue", clip_swap_rescues);
3698 let touch = TouchCensus::build([first, second], &imprint);
3699 touch.report(&mut diagnostics);
3700 let stage_started = Instant::now();
3701 let (split_first, split_map_first) = apply_edge_splits_with_map(first, 0, &imprint)?;
3702 let (split_second, split_map_second) = apply_edge_splits_with_map(second, 1, &imprint)?;
3703 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
3704 profile_stage("edge_split_ms", stage_ms);
3705 diagnostics.measure_max("timing.edge_split_ms", stage_ms);
3706 let stage_started = Instant::now();
3707 crate::classification::classify_profile_begin();
3708 let fragments_a = crate::fragment::fragment_solid_against(&split_first, 0, &imprint, crate::fragment::bounded_carriers(second).then_some((bounds[1], policy.sew_search)))?;
3709 let fragments_b = crate::fragment::fragment_solid_against(&split_second, 1, &imprint, crate::fragment::bounded_carriers(first).then_some((bounds[0], policy.sew_search)))?;
3710 crate::classification::classify_profile_report("fragment");
3711 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
3712 profile_stage("fragment_ms", stage_ms);
3713 diagnostics.measure_max("timing.fragment_ms", stage_ms);
3714 diagnostics.count_n(
3715 "fragment.candidates",
3716 (fragments_a.len() + fragments_b.len()) as u64,
3717 );
3718 touch.report_fragments(&[&fragments_a, &fragments_b], &mut diagnostics);
3719 let a_surface_samples: Vec<Vec3> = fragments_a
3724 .iter()
3725 .flat_map(|fragment| {
3726 std::iter::once(fragment.test_point).chain(fragment.extra_test_points.iter().copied())
3727 })
3728 .collect();
3729 let b_surface_samples: Vec<Vec3> = fragments_b
3730 .iter()
3731 .flat_map(|fragment| {
3732 std::iter::once(fragment.test_point).chain(fragment.extra_test_points.iter().copied())
3733 })
3734 .collect();
3735 let stage_started = Instant::now();
3736 let mut barrier_edges: HashSet<(u8, u64)> = imprint
3737 .pieces
3738 .iter()
3739 .filter_map(|piece| piece.shared_edge.map(|(operand, edge_id, _)| (operand, edge_id)))
3740 .collect();
3741 barrier_edges.extend(imprint.barrier_edges.iter().copied());
3742 for (operand, split_map) in [(0u8, &split_map_first), (1u8, &split_map_second)] {
3748 let minted: Vec<(u8, u64)> = barrier_edges
3749 .iter()
3750 .filter(|(barrier_operand, _)| *barrier_operand == operand)
3751 .filter_map(|(_, edge_id)| split_map.get(edge_id))
3752 .flat_map(|sub_ids| sub_ids.iter().map(|sub_id| (operand, *sub_id)))
3753 .collect();
3754 barrier_edges.extend(minted);
3755 }
3756 crate::classification::classify_profile_begin();
3757 let coincident = coincident_pairs(
3758 &fragments_a,
3759 &fragments_b,
3760 first,
3761 second,
3762 &imprint.cosurface_pairs,
3763 tolerance,
3764 )?;
3765 let sector_mode = sector::sector_mode(options);
3766 let mut select_census = sector::SelectCensus::default();
3767 let mut selected = select_fragments(
3768 fragments_a,
3769 fragments_b,
3770 first,
3771 second,
3772 operation,
3773 tolerance,
3774 &barrier_edges,
3775 &imprint,
3776 &coincident,
3777 sector_mode,
3778 &mut select_census,
3779 )?;
3780 let resewn = resew_coincident_rims(
3781 &mut selected,
3782 [&split_first, &split_second],
3783 [first, second],
3784 &imprint.cosurface_pairs,
3785 operation,
3786 tolerance,
3787 )?;
3788 diagnostics.count_n("select.coincident_pairs", coincident.len() as u64);
3789 diagnostics.count_n("select.rims_resewn", resewn as u64);
3790 crate::classification::classify_profile_report("select");
3791 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
3792 profile_stage("select_ms", stage_ms);
3793 diagnostics.measure_max("timing.select_ms", stage_ms);
3794 diagnostics.count_n("select.fragments", selected.len() as u64);
3795 diagnostics.count_n("select.sector_eligible", select_census.eligible);
3797 diagnostics.count_n("select.sector_primary", select_census.sector_primary);
3798 diagnostics.count_n("select.sector_fallback", select_census.sector_fallback);
3799 diagnostics.count_n("select.sector_disagree", select_census.disagree);
3800 diagnostics.count_n("select.ray_casts", select_census.ray_casts);
3801 diagnostics.count_n("select.on_votes", select_census.on_votes);
3802 diagnostics.count_n("select.overturns", select_census.overturns);
3803 if sector_mode != sector::SectorMode::Off || std::env::var_os("BREP_SECTOR_CENSUS").is_some() {
3804 sector::sector_census_line(|| {
3805 format!(
3806 "selection mode={sector_mode:?} select_ms={stage_ms:.3} selected={} eligible={} primary={} fallback={} disagree={} ray_casts={} on_votes={} overturns={}",
3807 selected.len(),
3808 select_census.eligible,
3809 select_census.sector_primary,
3810 select_census.sector_fallback,
3811 select_census.disagree,
3812 select_census.ray_casts,
3813 select_census.on_votes,
3814 select_census.overturns
3815 )
3816 });
3817 }
3818 if selected.is_empty()
3840 && !imprint.section_evidence
3841 && std::env::var("BREP_EMPTY_BOOLEAN").as_deref() != Ok("0")
3842 {
3843 let strictly_inside = |samples: &[Vec3], other: &BrepSolid| -> Result<bool, KernelRefusal> {
3844 for &sample in samples {
3845 if classify_point(sample, other, tolerance).or_refuse(KernelStage::Validate, "classify_point")?.class == PointClass::In {
3846 return Ok(true);
3847 }
3848 }
3849 Ok(false)
3850 };
3851 let outside_witness = |samples: &[Vec3], other: &BrepSolid| -> Result<bool, KernelRefusal> {
3852 for &sample in samples {
3853 if classify_point(sample, other, tolerance).or_refuse(KernelStage::Validate, "classify_point")?.class == PointClass::Out {
3854 return Ok(true);
3855 }
3856 }
3857 Ok(false)
3858 };
3859 let legitimate = match operation {
3860 BooleanOperation::Intersect => {
3861 !strictly_inside(&a_surface_samples, second)?
3862 && !strictly_inside(&b_surface_samples, first)?
3863 }
3864 BooleanOperation::Subtract => !outside_witness(&a_surface_samples, second)?,
3865 BooleanOperation::Union => false,
3866 };
3867 if legitimate {
3868 diagnostics.event(
3869 DiagnosticSeverity::Info,
3870 KernelStage::Select,
3871 "boolean.empty_result",
3872 format!("{operation:?} of witnessed-non-overlapping operands is empty"),
3873 );
3874 fit_scope.close().report_into(&mut diagnostics);
3875 polyline_scope.close().report_into(&mut diagnostics);
3876 diagnostics.measure_max(
3877 "timing.total_ms",
3878 operation_started.elapsed().as_secs_f64() * 1_000.0,
3879 );
3880 return Ok((
3881 KernelOutcome {
3882 value: empty_solid(),
3883 diagnostics,
3884 },
3885 None,
3886 ));
3887 }
3888 }
3889 if selected.is_empty()
3898 && imprint.section_evidence
3899 && !matches!(operation, BooleanOperation::Union)
3900 && touching_empty_enabled()
3901 && !TOUCHING_PROOF.with(std::cell::Cell::get)
3902 {
3903 let strict = |samples: &[Vec3], other: &BrepSolid, class: PointClass| -> Result<bool, KernelRefusal> {
3904 for &sample in samples {
3905 if classify_point(sample, other, tolerance).or_refuse(KernelStage::Validate, "classify_point")?.class == class {
3906 return Ok(true);
3907 }
3908 }
3909 Ok(false)
3910 };
3911 let witnessed = match operation {
3912 BooleanOperation::Intersect => {
3913 !strict(&a_surface_samples, second, PointClass::In)? && !strict(&b_surface_samples, first, PointClass::In)?
3914 }
3915 BooleanOperation::Subtract => !strict(&a_surface_samples, second, PointClass::Out)?,
3916 BooleanOperation::Union => false,
3917 };
3918 let overlap_free = !hair_deep_overlap(first, second, tolerance);
3924 if witnessed && overlap_free {
3925 TOUCHING_PROOF.with(|flag| flag.set(true));
3926 let proof = inclusion_exclusion_volume(first, second, operation, options, body_volume(first), body_volume(second), false);
3927 TOUCHING_PROOF.with(|flag| flag.set(false));
3928 let volume = |solid: &BrepSolid| body_volume(solid).unwrap_or(f64::INFINITY);
3933 let band = 1e-9 * volume(first).max(volume(second));
3934 if let Some(proof) = proof.filter(|proof| proof.expected.is_finite() && proof.expected.abs() <= band) {
3935 diagnostics.event(
3936 DiagnosticSeverity::Info,
3937 KernelStage::Select,
3938 "boolean.empty_touching",
3939 format!(
3940 "{operation:?} of touching operands is empty: {} reads {:.3e} by {} (band {band:.3e})",
3941 proof.formula, proof.expected, proof.reading
3942 ),
3943 );
3944 fit_scope.close().report_into(&mut diagnostics);
3945 polyline_scope.close().report_into(&mut diagnostics);
3946 diagnostics.measure_max("timing.total_ms", operation_started.elapsed().as_secs_f64() * 1_000.0);
3947 return Ok((KernelOutcome { value: empty_solid(), diagnostics }, None));
3948 }
3949 }
3950 }
3951 let solids = [(0, &split_first), (1, &split_second)]
3952 .into_iter()
3953 .collect::<HashMap<_, _>>();
3954 let dump = BooleanStageDump::open();
3955 if let Some(dump) = &dump {
3956 dump.write("first", &split_first);
3957 dump.write("second", &split_second);
3958 dump.write("selected", &selected);
3959 }
3960 let stage_started = Instant::now();
3961 let assembled_origins: Vec<FaceKey> = if imprint.tangent_sections.is_empty() {
3965 Vec::new()
3966 } else {
3967 selected
3968 .iter()
3969 .map(|fragment| FaceKey { operand: fragment.operand, face_id: fragment.source_face_id })
3970 .collect()
3971 };
3972 let attributable: Vec<crate::imprint::TangentSectionRecord> = imprint
3979 .tangent_sections
3980 .iter()
3981 .filter(|section| imprint.tangent_nodes.is_empty() || section.grazing.is_empty())
3982 .cloned()
3983 .collect();
3984 let attribute = |error: KernelRefusal| {
3985 attribute_to_tangent_section(error, &attributable, &assembled_origins)
3986 };
3987 let cellular_result = matches!(operation, BooleanOperation::Union)
3988 && cellular::enabled(options)
3989 && cellular::complete_contact(first, second, &selected, tolerance);
3990 let (solid, scope) = if cellular_result {
3991 (assemble::assemble_cellular_fragments(selected, &solids, &imprint, tolerance)
3992 .map_err(attribute)?, None)
3993 } else if untouched_passthrough(options) {
3994 assemble_fragments_scoped(selected, &solids, &imprint, tolerance, &touch, touched_assembly(options))
3995 .map_err(attribute)?
3996 } else {
3997 (assemble_fragments(selected, &solids, &imprint, tolerance).map_err(attribute)?, None)
3998 };
3999 if let Some(scope) = &scope {
4000 diagnostics.count_n("passthrough.faces_examined", scope.examined.len() as u64);
4001 }
4002 if let Some(dump) = &dump {
4003 dump.write("assembled", &solid);
4004 }
4005 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
4006 profile_stage("assemble_ms", stage_ms);
4007 diagnostics.measure_max("timing.assemble_ms", stage_ms);
4008 let stage_started = Instant::now();
4009 let declines_before = crate::face_merge::declines_served();
4010 let area_checks_before = crate::face_merge::boundary_area_checks();
4011 if std::env::var("BREP_DEBUG_PREMERGE_VALIDATE").is_ok() {
4012 let issues = solid.validate();
4013 eprintln!(
4014 "pre-merge validation: {} issue(s){}",
4015 issues.len(),
4016 issues
4017 .first()
4018 .map(|issue| format!(" — first: {}", issue.message))
4019 .unwrap_or_default()
4020 );
4021 }
4022 let solid = if solid.kind != crate::BodyKind::Cellular && options.merge_coplanar_faces
4023 && std::env::var("BREP_COPLANAR_MERGE").as_deref() != Ok("0")
4024 {
4025 let merged = match &scope {
4026 Some(scope) => merge_same_surface_faces_scoped(
4030 &solid,
4031 tolerance,
4032 &options.keep_unmerged_name_substrs,
4033 &scope.examined,
4034 )?,
4035 None => merge_same_surface_faces_excluding(
4036 &solid,
4037 tolerance,
4038 &options.keep_unmerged_name_substrs,
4039 )?,
4040 };
4041 let merged = merge_curve_continuation_edges(&merged, tolerance).map_err(|refusal| KernelRefusal { stage: KernelStage::Validate, ..refusal })?;
4046 rejoin::rejoin_unless_referenced(merged, options, tolerance)
4047 } else {
4048 solid
4049 };
4050 if let Some(dump) = &dump {
4051 dump.write("merged", &solid);
4052 }
4053 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
4054 profile_stage("face_merge_ms", stage_ms);
4055 if crate::profile::profile_enabled() {
4056 profile_line!("boolean.merge_declines served={}", crate::face_merge::declines_served() - declines_before);
4057 let area_checks = crate::face_merge::boundary_area_checks();
4058 if area_checks != area_checks_before {
4059 profile_line!("boolean.merge_area_checks boundary={} integrated={}", area_checks.0 - area_checks_before.0, area_checks.1 - area_checks_before.1);
4060 }
4061 }
4062 diagnostics.measure_max("timing.face_merge_ms", stage_ms);
4063 let validation_started = Instant::now();
4064 let validation = solid.validate_detailed_scoped(&policy, scope.as_ref().map(|scope| &scope.examined));
4065 profile_stage("final_validate_ms", validation_started.elapsed().as_secs_f64() * 1000.0);
4066 diagnostics.count_n("validate.issues", validation.issues.len() as u64);
4067 diagnostics.count_n(
4068 "validate.wire_warnings",
4069 validation.wire_warnings.len() as u64,
4070 );
4071 diagnostics.measure_max("validate.max_pcurve_error", validation.max_pcurve_error);
4072 for warning in &validation.wire_warnings {
4073 diagnostics.event(
4074 DiagnosticSeverity::Warning,
4075 KernelStage::Validate,
4076 "validate.uv_wire",
4077 warning.message.clone(),
4078 );
4079 }
4080 for issue in &validation.issues {
4081 diagnostics.event(
4082 DiagnosticSeverity::Error,
4083 KernelStage::Validate,
4084 "validate.brep",
4085 issue.message.clone(),
4086 );
4087 }
4088 fit_scope.close().report_into(&mut diagnostics);
4089 polyline_scope.close().report_into(&mut diagnostics);
4090 diagnostics.measure_max(
4091 "timing.total_ms",
4092 operation_started.elapsed().as_secs_f64() * 1_000.0,
4093 );
4094 if !validation.issues.is_empty() {
4095 return Err(KernelRefusal::new(
4096 RefusalClass::InvalidResultTopology { issues: validation.issues.len() as u32 },
4097 KernelStage::Validate,
4098 format!(
4099 "boolean_operation: invalid result: {:?}",
4100 validation.issues
4101 )));
4102 }
4103 if std::env::var("BREP_DEBUG_BOOL").is_ok() {
4109 if let Ok(report) =
4110 crate::oracle::boolean_semantic_disagreement(first, second, operation, &solid, 200)
4111 {
4112 if report.is_flagged() {
4113 eprintln!(
4114 "[oracle] semantic disagreement rate {:.4} ({} of {} decidable points); sample {:?}",
4115 report.disagreement_rate,
4116 report.disagreements.len(),
4117 report.considered,
4118 report.sample_disagreement()
4119 );
4120 }
4121 }
4122 let fusable_band = crate::tolerance::assembler_weld(policy.model);
4123 let fusables = crate::oracle::boolean_residual_fusables(&solid, fusable_band);
4124 if !fusables.is_empty() {
4125 eprintln!(
4126 "[oracle] {} residual fusable(s) after weld; sample {:?}",
4127 fusables.len(),
4128 fusables.first()
4129 );
4130 }
4131 }
4132 let candidates = scope.as_ref().map(|scope| {
4133 let unproved = (scope_proved_apart_on() && plain_hull_solid(first) && plain_hull_solid(second))
4134 .then(|| imprint.faces_in_unproved_pairs.as_ref())
4135 .flatten()
4136 .map(|faces| faces.iter().copied().collect::<HashSet<_>>());
4137 let candidates = soundness_candidates(
4138 &solid,
4139 scope,
4140 [operand_bounds(first), operand_bounds(second)],
4141 policy.sew_search,
4142 unproved.as_ref(),
4143 );
4144 diagnostics.count_n("passthrough.soundness_candidates", candidates.len() as u64);
4145 crate::soundness::census::profile_operation(&solid, &[first, second], Some(&scope.touched), "boolean");
4146 candidates
4147 });
4148 Ok((
4149 KernelOutcome {
4150 value: solid,
4151 diagnostics,
4152 },
4153 candidates,
4154 ))
4155}
4156
4157