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
140
141pub fn without_perturbation<T>(action: impl FnOnce() -> T) -> T {
148 struct Restore(bool);
149 impl Drop for Restore {
150 fn drop(&mut self) {
151 WITHOUT_PERTURBATION.with(|cell| cell.set(self.0));
152 }
153 }
154 let _restore = Restore(WITHOUT_PERTURBATION.with(|cell| cell.replace(true)));
155 action()
156}
157
158fn touched_assembly(options: &BooleanOptions) -> bool {
160 match std::env::var("BREP_TOUCHED_ASSEMBLY").as_deref() {
161 Ok("0") => false,
162 Ok(_) => true,
163 Err(_) => options.touched_assembly,
164 }
165}
166
167fn disjoint_fast_path(options: &BooleanOptions) -> bool {
169 match std::env::var("BREP_DISJOINT_FAST_PATH").as_deref() {
170 Ok("0") => false,
171 Ok(_) => true,
172 Err(_) => options.disjoint_fast_path,
173 }
174}
175
176fn contact_fast_path(options: &BooleanOptions) -> bool {
178 match std::env::var("BREP_CONTACT_FAST_PATH").as_deref() {
179 Ok("0") => false,
180 Ok(_) => true,
181 Err(_) => options.contact_fast_path,
182 }
183}
184
185fn untouched_passthrough(options: &BooleanOptions) -> bool {
187 match std::env::var("BREP_UNTOUCHED_PASSTHROUGH").as_deref() {
188 Ok("0") => false,
189 Ok(_) => true,
190 Err(_) => options.untouched_passthrough,
191 }
192}
193
194fn default_tolerance() -> f64 {
195 1e-7
196}
197
198fn default_true() -> bool {
199 true
200}
201
202impl Default for BooleanOptions {
203 fn default() -> Self {
204 Self {
205 tolerance: default_tolerance(),
206 tolerances: None,
207 imprint: ImprintOptions::default(),
208 merge_coplanar_faces: true,
209 keep_unmerged_name_substrs: Vec::new(),
210 untouched_passthrough: true,
211 disjoint_fast_path: true,
212 contact_fast_path: true,
213 touched_assembly: false,
214 sector_classification: true,
215 sheet_trim: true,
216 keep_cells: false,
217 seam_reseat_later_references: None,
218 seam_rejoin_later_references: None,
219 }
220 }
221}
222
223mod select;
224mod sheet;
225mod cellular;
226pub mod sector;
227pub mod assemble;
228mod operand_state;
229mod rim;
230mod coincident;
231mod touch;
232pub(crate) mod reseat;
233mod ball_align;
234mod rejoin;
235mod window_retry;
236mod isotropic_chart;
237mod dedicated;
238pub mod closed_form;
239pub use dedicated::{register_dedicated_boolean, DedicatedBoolean};
240
241pub use rim::*;
242use select::*;
243use coincident::*;
244use touch::TouchCensus;
245pub use assemble::{
246 assemble_fragments, assemble_open_fragments, commit_nearby_edge_endpoints,
247 clear_candidate_memo, edge_interior_lies_on, finalize_assembled_solid, refresh_derived_genus,
248};
249use assemble::{assemble_fragments_scoped, AssemblyScope};
250#[allow(unused_imports)]
252pub use assemble::apply_assembly_heal_chain;
253
254
255struct WorkingScale {
260 factor: f64,
261 solids: Vec<BrepSolid>,
262 options: BooleanOptions,
263}
264
265thread_local! {
266 static ORIGINAL_WORKING_SCALE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
269}
270
271impl WorkingScale {
272 fn of(operands: &[&BrepSolid], options: &BooleanOptions) -> Result<Option<Self>, KernelRefusal> {
273 let Some(bounds) = crate::rescale::bounds_of(operands.iter().copied()) else {
274 return Ok(None);
275 };
276 let Some(factor) = crate::rescale::guard_factor(bounds).or_else(|| {
277 if ORIGINAL_WORKING_SCALE.with(|state| state.get()) { None }
278 else { crate::rescale::large_guard_factor(bounds) }
279 }) else {
280 return Ok(None);
281 };
282 crate::rescale::profile_fired("boolean", factor, bounds);
283 let solids = operands
284 .iter()
285 .map(|solid| crate::rescale::scale_operand(solid, factor, "boolean"))
286 .collect::<Result<Vec<_>, _>>()?;
287 let mut options = options.clone();
289 options.imprint.maximum_ssi_step = options.imprint.maximum_ssi_step.map(|step| step * factor);
290 Ok(Some(Self { factor, solids, options }))
291 }
292
293 fn run<T>(
296 &self,
297 original: impl FnOnce() -> Result<T, KernelRefusal>,
298 scaled: impl FnOnce() -> Result<T, KernelRefusal>,
299 ) -> Result<T, KernelRefusal> {
300 if self.factor >= 1.0 { return scaled(); }
301 match self.at_model_scale(original) {
302 Ok(value) => Ok(value),
303 Err(original) => scaled().or(Err(original)),
304 }
305 }
306
307 fn at_model_scale<T>(&self, original: impl FnOnce() -> T) -> T {
310 struct Restore(bool);
311 impl Drop for Restore {
312 fn drop(&mut self) { ORIGINAL_WORKING_SCALE.with(|state| state.set(self.0)); }
313 }
314 let _restore = Restore(ORIGINAL_WORKING_SCALE.with(|state| state.replace(true)));
315 original()
316 }
317
318 fn back(&self, solid: &BrepSolid) -> Result<BrepSolid, KernelRefusal> {
319 crate::rescale::scale_operand(solid, 1.0 / self.factor, "boolean")
320 }
321
322 fn refusal(&self, error: KernelRefusal) -> KernelRefusal {
323 crate::rescale::name_scale(error, self.factor)
324 }
325}
326
327pub fn boolean_operation(
328 first: &BrepSolid,
329 second: &BrepSolid,
330 operation: BooleanOperation,
331 options: &BooleanOptions,
332) -> Result<BrepSolid, KernelRefusal> {
333 if let Some(Ok(solid)) = dedicated::dedicated(first, second, operation) {
336 return Ok(solid);
337 }
338 if let Some(scaled) = WorkingScale::of(&[first, second], options)? {
339 let at_working_scale = || boolean_operation(&scaled.solids[0], &scaled.solids[1], operation, &scaled.options)
340 .map_err(|error| scaled.refusal(error))
341 .and_then(|solid| scaled.back(&solid));
342 if scaled.factor < 1.0
358 && switch!("BREP_LARGE_SCALE_BEFORE_LADDER", false)
359 && !WITHOUT_PERTURBATION.with(|cell| cell.get())
360 {
361 let exact = without_perturbation(|| {
362 scaled.at_model_scale(|| boolean_operation(first, second, operation, options)).or_else(|_| at_working_scale())
363 });
364 if let Ok(solid) = exact {
365 return Ok(solid);
366 }
367 }
368 return scaled.run(|| boolean_operation(first, second, operation, options), at_working_scale);
369 }
370 if isotropic_chart::active() {
373 return boolean_operation_unscaled(first, second, operation, options);
374 }
375 boolean_operation_unscaled(first, second, operation, options).or_else(|refused| {
376 isotropic_chart::suppressed(|| window_retry::retry(first, second, operation, options, refused, boolean_operation_unscaled))
379 })
380}
381
382fn boolean_operation_unscaled(
384 first: &BrepSolid,
385 second: &BrepSolid,
386 operation: BooleanOperation,
387 options: &BooleanOptions,
388) -> Result<BrepSolid, KernelRefusal> {
389 match boolean_operation_with_diagnostics(first, second, operation, options) {
390 Ok(outcome) => {
391 if below_tolerance_refusal_enabled()
394 && outcome.value.shells.iter().all(|shell| shell.faces.is_empty())
395 && !matches!(operation, BooleanOperation::Union)
396 {
397 if let Some(refusal) = below_tolerance_refusal(first, second, None) {
398 if let Some(answer) = below_tolerance_answer(first, second, operation) {
399 return Ok(answer);
400 }
401 if let Some(answer) = below_tolerance_rescaled(first, second, operation, options) {
402 return Ok(answer);
403 }
404 return Err(refusal);
405 }
406 }
407 if unresolved_merge_refusal_enabled() && !matches!(operation, BooleanOperation::Subtract) {
408 if let Some(refusal) = unresolved_merge_refusal(first, second) {
409 return Err(refusal);
410 }
411 }
412 if below_tolerance_slivers_enabled()
415 && !matches!(operation, BooleanOperation::Subtract)
416 && [first, second].iter().all(|solid| face_count(solid) <= SLIVER_ANSWER_FACES)
417 && near_coincident_planar_faces(first, second).is_some()
418 {
419 if let Some(answer) = below_tolerance_answer(first, second, operation) {
420 return Ok(answer);
421 }
422 }
423 Ok(outcome.value)
424 }
425 Err(error) => {
426 if below_tolerance_refusal_enabled() {
427 if let Some(refusal) = below_tolerance_refusal(first, second, Some(&error)) {
428 if let Some(answer) = below_tolerance_answer(first, second, operation) {
429 return Ok(answer);
430 }
431 if let Some(answer) = below_tolerance_rescaled(first, second, operation, options) {
432 return Ok(answer);
433 }
434 return Err(refusal);
435 }
436 }
437 if isotropic_chart::isotropic_chart_on() && !isotropic_chart::active() && !isotropic_chart::is_suppressed() {
446 let (a, b) = (isotropic_chart::isotropic(first), isotropic_chart::isotropic(second));
447 if a.is_some() || b.is_some() {
448 let (a, b) = (a.as_ref().unwrap_or(first), b.as_ref().unwrap_or(second));
449 match isotropic_chart::with_active(|| boolean_operation(a, b, operation, options)) {
450 Ok(result) => match isotropic_chart_identity(first, second, a, b, operation, options, &result) {
451 Ok(()) => return Ok(result),
452 Err(why) => {
453 if std::env::var("BREP_DEBUG_BOOL").is_ok() {
454 eprintln!("isotropic chart: the rescaled boolean is not admitted ({why}); on to the perturbation ladder");
455 }
456 }
457 },
458 Err(second_refusal) => {
459 if std::env::var("BREP_DEBUG_BOOL").is_ok() {
460 eprintln!("isotropic chart: the rescaled boolean refused too ({second_refusal}); on to the perturbation ladder");
461 }
462 }
463 }
464 }
465 }
466 if isotropic_chart::active() {
469 return Err(error);
470 }
471 if std::env::var("BREP_NO_PERTURB").as_deref() == Ok("1")
479 || !error.class.perturbation_eligible()
480 {
481 return Err(error);
482 }
483 if std::env::var("BREP_OPEN_OPERAND_GATE").as_deref() != Ok("0") {
505 if let Some((operand, open)) = [first, second]
506 .iter()
507 .enumerate()
508 .find_map(|(operand, solid)| {
509 let open = one_use_edges(solid);
510 (open > 0).then_some((operand, open))
511 })
512 {
513 return Err(error.with_message(|message| format!(
514 "{message}; operand {operand} is not a closed shell: {open} of its edges bound \
515 only one face, so no boolean of it encloses a solid and no perturbation \
516 can close it"
517 )));
518 }
519 }
520 if let Some((operand, face_id, deviation, weld)) =
521 planar_operand_off_its_plane(first, second, options)
522 {
523 return Err(error.with_message(|message| format!(
524 "{message}; operand {operand} face {face_id} is a plane whose straight \
525 boundary sits {deviation:.3e} off it (assembly weld {weld:.1e}), which \
526 no perturbation can reconcile — the body's planes must contain their \
527 boundary before it can take part in an exact boolean"
528 )));
529 }
530 if matches!(operation, BooleanOperation::Subtract)
545 && std::env::var("BREP_PINCH_GATE").as_deref() != Ok("0")
546 && subtract_pinches_at_internal_tangency(first, second, options.tolerance)
547 .unwrap_or(false)
548 {
549 if let Some(solid) = subtract_through_the_common_part(first, second, options) {
552 return Ok(solid);
553 }
554 return Err(error.with_message(|message| format!(
555 "{message}; internal tangency: the operands touch tangentially with \
556 co-directed normals, so the exact difference pinches to zero thickness \
557 (non-manifold, unrepresentable in a boundary model) — refusing rather \
558 than returning a perturbed sliver"
559 )));
560 }
561 if matches!(error.class, RefusalClass::TangentNodeSingularity)
577 && std::env::var("BREP_TANGENT_NODE_GATE").as_deref() != Ok("0")
578 {
579 return Err(error);
580 }
581 if matches!(operation, BooleanOperation::Union) {
585 if let Some(solid) = union_through_the_difference(first, second, options) {
586 return Ok(solid);
587 }
588 }
589 if WITHOUT_PERTURBATION.with(|cell| cell.get()) {
591 return Err(error);
592 }
593 match perturbation_retry(first, second, operation, options) {
594 Ok(solid) => Ok(solid),
595 Err(refused) if refused.is_empty() => Err(error),
596 Err(refused) => {
597 Err(error.with_message(|message| format!("{message}; {}", refused.join("; "))))
598 }
599 }
600 }
601 }
602}
603
604const PINCH_PROBE_STEPS: usize = 8;
609
610const PINCH_ANGULAR_TOLERANCE: f64 = 1e-4;
613
614const PINCH_SEPARATION_STEP: f64 = 1e-2;
618
619fn subtract_through_the_common_part(first: &BrepSolid, second: &BrepSolid, options: &BooleanOptions) -> Option<BrepSolid> {
637 if !switch!("BREP_PINCH_COMMON_RETRY", true) || !options.imprint.tangent_curve_imprint {
640 return None;
641 }
642 let common = boolean_operation_with_diagnostics(first, second, BooleanOperation::Intersect, options).ok()?.value;
643 if common.shells.iter().all(|shell| shell.faces.is_empty()) {
644 return None;
645 }
646 let cut = boolean_operation_with_diagnostics(first, &common, BooleanOperation::Subtract, options).ok()?.value;
647 if !cut.validate().is_empty() {
648 return None;
649 }
650 let volume = |solid: &BrepSolid| crate::solid_mass_properties(solid).ok().map(|mass| mass.volume);
651 let (whole, taken, left) = (volume(first)?, volume(&common)?, volume(&cut)?);
652 ((left - (whole - taken)).abs() <= 1e-9 * whole.abs().max(1.0)).then_some(cut)
653}
654
655fn union_through_the_difference(first: &BrepSolid, second: &BrepSolid, options: &BooleanOptions) -> Option<BrepSolid> {
668 if !switch!("BREP_TANGENT_UNION_DIFFERENCE_RETRY", true) || !options.imprint.tangent_curve_imprint {
669 return None;
670 }
671 let pinches = |a: &BrepSolid, b: &BrepSolid| subtract_pinches_at_internal_tangency(a, b, options.tolerance).unwrap_or(false);
672 if !pinches(first, second) && !pinches(second, first) {
673 return None;
674 }
675 let difference = match boolean_operation_with_diagnostics(first, second, BooleanOperation::Subtract, options) {
676 Ok(outcome) => outcome.value,
677 Err(_) => subtract_through_the_common_part(first, second, options)?,
678 };
679 if difference.shells.iter().all(|shell| shell.faces.is_empty()) || !difference.validate().is_empty() {
680 return None;
681 }
682 let union = boolean_operation_with_diagnostics(second, &difference, BooleanOperation::Union, options).ok()?.value;
683 if !union.validate().is_empty() {
684 return None;
685 }
686 let volume = |solid: &BrepSolid| crate::solid_mass_properties(solid).ok().map(|mass| mass.volume);
687 let (left, added, whole) = (volume(&difference)?, volume(second)?, volume(&union)?);
688 ((whole - (left + added)).abs() <= 1e-9 * whole.abs().max(1.0)).then_some(union)
689}
690
691pub fn subtract_pinches_at_internal_tangency(
713 first: &BrepSolid,
714 second: &BrepSolid,
715 tolerance: f64,
716) -> Result<bool, KernelRefusal> {
717 let contact = (tolerance * 100.0).max(1e-12);
720 let probes_a = first
721 .shells
722 .iter()
723 .flat_map(|shell| &shell.faces)
724 .map(PinchProbe::of)
725 .collect::<Result<Vec<_>, _>>()?;
726 let probes_b = second
727 .shells
728 .iter()
729 .flat_map(|shell| &shell.faces)
730 .map(PinchProbe::of)
731 .collect::<Result<Vec<_>, _>>()?;
732 for probe_a in &probes_a {
733 for probe_b in &probes_b {
734 let pad = 1e-2 * probe_a.extent().max(probe_b.extent());
741 if probe_a.separation(probe_b) > contact + pad {
742 continue;
743 }
744 if classify_surface_pair(
751 &probe_a.face.surface,
752 &probe_b.face.surface,
753 tolerance,
754 PINCH_ANGULAR_TOLERANCE,
755 ).or_refuse(KernelStage::Validate, "csg.boolean.mod")?
756 .relation
757 == SurfacePairRelation::Cosurface
758 {
759 continue;
760 }
761 if faces_touch_with_codirected_normals(probe_a, probe_b, contact)? {
762 return Ok(true);
763 }
764 }
765 }
766 Ok(false)
767}
768
769struct PinchProbe<'a> {
772 face: &'a FaceRecord,
773 samples: Vec<(f64, f64, Vec3)>,
775 minimum: [f64; 3],
776 maximum: [f64; 3],
777}
778
779impl<'a> PinchProbe<'a> {
780 fn of(face: &'a FaceRecord) -> Result<Self, KernelRefusal> {
781 let [u0, u1] = face.surface.domain_u().or_refuse(KernelStage::Validate, "domain_u")?;
782 let [v0, v1] = face.surface.domain_v().or_refuse(KernelStage::Validate, "domain_v")?;
783 let steps = PINCH_PROBE_STEPS as f64;
784 let mut samples = Vec::with_capacity((PINCH_PROBE_STEPS + 1).pow(2));
785 let mut minimum = [f64::INFINITY; 3];
786 let mut maximum = [f64::NEG_INFINITY; 3];
787 for i in 0..=PINCH_PROBE_STEPS {
788 let u = u0 + (u1 - u0) * i as f64 / steps;
789 for j in 0..=PINCH_PROBE_STEPS {
790 let v = v0 + (v1 - v0) * j as f64 / steps;
791 let Ok(point) = face.surface.evaluate(u, v) else {
792 continue;
793 };
794 for (axis, value) in [point.x, point.y, point.z].into_iter().enumerate() {
795 minimum[axis] = minimum[axis].min(value);
796 maximum[axis] = maximum[axis].max(value);
797 }
798 samples.push((u, v, point));
799 }
800 }
801 Ok(Self {
802 face,
803 samples,
804 minimum,
805 maximum,
806 })
807 }
808
809 fn extent(&self) -> f64 {
811 (0..3)
812 .map(|axis| self.maximum[axis] - self.minimum[axis])
813 .fold(0.0f64, f64::max)
814 }
815
816 fn separation(&self, other: &Self) -> f64 {
818 let mut gap: f64 = 0.0;
819 for axis in 0..3 {
820 gap = gap.max(self.minimum[axis] - other.maximum[axis]);
821 gap = gap.max(other.minimum[axis] - self.maximum[axis]);
822 }
823 gap
824 }
825}
826
827fn faces_touch_with_codirected_normals(
832 probe_a: &PinchProbe<'_>,
833 probe_b: &PinchProbe<'_>,
834 contact: f64,
835) -> Result<bool, KernelRefusal> {
836 for (probe, other) in [(probe_a, probe_b), (probe_b, probe_a)] {
837 let source = probe.face;
838 let target = other.face;
839 for &(u, v, point) in &probe.samples {
840 let projection = project_point_to_surface(&target.surface, point).or_refuse(KernelStage::Validate, "project_point_to_surface")?;
841 if projection.distance > contact {
842 continue;
843 }
844 let (Ok(source_normal), Ok(target_normal)) = (
847 source.surface.normal(u, v),
848 target.surface.normal(projection.u, projection.v),
849 ) else {
850 continue;
851 };
852 let source_outward = outward_normal(source_normal, source.same_sense);
853 let target_outward = outward_normal(target_normal, target.same_sense);
854 if source_outward.cross(target_outward).length() > PINCH_ANGULAR_TOLERANCE
855 || source_outward.dot(target_outward) <= 0.0
856 {
857 continue;
858 }
859 if parameter_point_in_face(source, Vec2 { x: u, y: v }, 1e-6).or_refuse(KernelStage::Validate, "parameter_point_in_face")?
860 == PolygonClass::Outside
861 || parameter_point_in_face(
862 target,
863 Vec2 {
864 x: projection.u,
865 y: projection.v,
866 },
867 1e-6,
868 ).or_refuse(KernelStage::Validate, "csg.boolean.mod")? == PolygonClass::Outside
869 {
870 continue;
871 }
872 if contact_separates_locally(source, target, u, v, contact)? {
873 return Ok(true);
874 }
875 }
876 }
877 Ok(false)
878}
879
880fn outward_normal(normal: Vec3, same_sense: bool) -> Vec3 {
881 if same_sense {
882 normal
883 } else {
884 normal.scale(-1.0)
885 }
886}
887
888fn contact_separates_locally(
894 source: &FaceRecord,
895 target: &FaceRecord,
896 u: f64,
897 v: f64,
898 contact: f64,
899) -> Result<bool, KernelRefusal> {
900 let [u0, u1] = source.surface.domain_u().or_refuse(KernelStage::Validate, "domain_u")?;
901 let [v0, v1] = source.surface.domain_v().or_refuse(KernelStage::Validate, "domain_v")?;
902 let step_u = (u1 - u0) * PINCH_SEPARATION_STEP;
903 let step_v = (v1 - v0) * PINCH_SEPARATION_STEP;
904 for (probe_u, probe_v) in [
905 ((u + step_u).min(u1), v),
906 ((u - step_u).max(u0), v),
907 (u, (v + step_v).min(v1)),
908 (u, (v - step_v).max(v0)),
909 ] {
910 if (probe_u - u).abs() < f64::EPSILON && (probe_v - v).abs() < f64::EPSILON {
911 continue;
912 }
913 let Ok(point) = source.surface.evaluate(probe_u, probe_v) else {
914 continue;
915 };
916 if project_point_to_surface(&target.surface, point).or_refuse(KernelStage::Validate, "project_point_to_surface")?.distance > contact * 10.0 {
919 return Ok(true);
920 }
921 }
922 Ok(false)
923}
924
925fn perturbation_retry(
979 first: &BrepSolid,
980 second: &BrepSolid,
981 operation: BooleanOperation,
982 options: &BooleanOptions,
983) -> Result<BrepSolid, Vec<String>> {
984 const DIRECTIONS: [[f64; 3]; 4] = [
995 [0.4034, 0.7973, 0.4491],
996 [0.7973, 0.4491, 0.4034],
997 [0.4491, 0.4034, 0.7973],
998 [0.5774, -0.5774, 0.5774],
999 ];
1000 const FRACTIONS: [f64; 5] = PERTURBATION_FRACTIONS;
1006
1007 let debug = std::env::var("BREP_DEBUG_BOOL").is_ok();
1008 let scale = crate::solid_tolerance::solid_scale(first)
1009 .max(crate::solid_tolerance::solid_scale(second))
1010 .max(1.0);
1011
1012 let _caller = crate::mass_caller("boolean.perturbation_rescue");
1016 let va = solid_signed_volume(first).ok().map(f64::abs);
1017 let vb = solid_signed_volume(second).ok().map(f64::abs);
1018 let hold_identity = std::env::var("BREP_PERTURB_IDENTITY").as_deref() != Ok("0");
1019 let hold_mirror = hold_identity && std::env::var("BREP_PERTURB_MIRROR").as_deref() != Ok("0");
1022 let early_exit = std::env::var("BREP_MIRROR_EARLY_EXIT").as_deref() != Ok("0");
1025 let mut trends = [MirrorTrend::default(); 4];
1026 let mut identity: Option<Option<InclusionExclusion>> = None;
1028 let mut refused = Vec::new();
1029 let ladder = std::env::var("BREP_DEBUG_PERTURB_LADDER").is_ok();
1033 let ladder_start = web_time::Instant::now();
1034 if ladder {
1035 let measured = inclusion_exclusion_volume(first, second, operation, options, va, vb, false);
1036 match &measured {
1037 Some(identity) => eprintln!(
1038 "[ladder] identity {} = {:.9} from the exact lane's {} ({:.9}); V(first) {:?} V(second) {:?}",
1039 identity.formula, identity.expected, identity.reading, identity.read, va, vb
1040 ),
1041 None => eprintln!("[ladder] no identity: no exact-lane boolean of these operands clears in either order"),
1042 }
1043 identity = Some(measured);
1044 }
1045 let rung_miss = |identity: &Option<Option<InclusionExclusion>>, candidate: &BrepSolid| -> String {
1046 let volume = body_volume(candidate);
1047 match (identity, volume) {
1048 (Some(Some(identity)), Some(volume)) => format!(
1049 "volume {volume:.9} miss {:+.3e} bar {:.3e}",
1050 volume - identity.expected,
1051 crate::VOLUME_DRIFT_ABS.max(crate::VOLUME_DRIFT_REL * identity.expected.abs())
1052 ),
1053 (_, Some(volume)) => format!("volume {volume:.9}"),
1054 _ => "no volume".to_string(),
1055 }
1056 };
1057
1058 for &fraction in &FRACTIONS {
1059 let magnitude = scale * fraction;
1060 for (direction, dir) in DIRECTIONS.iter().enumerate() {
1061 if trends[direction].closed {
1062 if ladder {
1063 eprintln!("[ladder] dir={dir:?} fraction={fraction:.1e} offset {magnitude:.3e}: not tried, its direction is closed");
1064 }
1065 continue;
1066 }
1067 let offset = [dir[0] * magnitude, dir[1] * magnitude, dir[2] * magnitude];
1068 let translate = match AffineTransform::new([
1069 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,
1073 ]) {
1074 Ok(transform) => transform,
1075 Err(_) => continue,
1076 };
1077 let moved = match crate::transform_brep(second, translate, false) {
1078 Ok(solid) => solid,
1079 Err(_) => continue,
1080 };
1081 let rung = format!("dir={dir:?} fraction={fraction:.1e} offset {magnitude:.3e}");
1082 let rung_start = web_time::Instant::now();
1083 let candidate =
1084 match boolean_operation_with_diagnostics(first, &moved, operation, options) {
1085 Ok(outcome) => outcome.value,
1086 Err(error) => {
1087 if ladder {
1088 eprintln!("[ladder] {rung}: exact lane refused {:?}", error.class);
1089 }
1090 continue;
1091 }
1092 };
1093 let built = rung_start.elapsed();
1094 if candidate.shells.is_empty() {
1096 if ladder {
1097 eprintln!("[ladder] {rung}: empty");
1098 }
1099 continue;
1100 }
1101 if let (Some(va), Some(vb)) = (va, vb) {
1106 if let Ok(vr) = solid_signed_volume(&candidate) {
1107 if !volume_within_csg_bounds(operation, va, vb, vr.abs()) {
1108 if ladder {
1109 eprintln!("[ladder] {rung}: outside the CSG bound, {}", rung_miss(&identity, &candidate));
1110 }
1111 continue;
1112 }
1113 }
1114 }
1115 let bounded = rung_start.elapsed();
1120 if hold_identity {
1122 let identity = identity.get_or_insert_with(|| {
1123 let identity =
1124 inclusion_exclusion_volume(first, second, operation, options, va, vb, false);
1125 if debug && identity.is_none() {
1126 eprintln!(
1127 "[perturb] no exact-lane boolean of these operands clears in either \
1128 order; no identity to hold"
1129 );
1130 }
1131 identity
1132 });
1133 if let Some(identity) = identity {
1134 let expected = identity.expected;
1135 let bar = crate::VOLUME_DRIFT_ABS.max(crate::VOLUME_DRIFT_REL * expected.abs());
1136 let volume = body_volume(&candidate);
1137 let miss = volume.map(|volume| (volume - expected).abs());
1138 if !miss.is_some_and(|miss| miss <= bar) {
1139 let sentence = format!(
1140 "perturbation rung dir={dir:?} fraction={fraction:.1e} \
1141 (offset {magnitude:.3e}) refused: its body reads {} against the \
1142 inclusion–exclusion identity {} = {expected:.9} (the exact lane's \
1143 {} reads {:.9}), a miss of {} beyond the volume drift bar {bar:.3e}",
1144 volume.map_or("no volume".to_string(), |volume| format!("{volume:.9}")),
1145 identity.formula,
1146 identity.reading,
1147 identity.read,
1148 miss.map_or("unmeasured".to_string(), |miss| format!("{miss:.3e}")),
1149 );
1150 if debug {
1151 eprintln!("[perturb] {sentence}");
1152 }
1153 if ladder {
1154 eprintln!(
1155 "[ladder] {rung}: refused by the identity, volume {} miss {} bar {bar:.3e}",
1156 volume.map_or("none".to_string(), |volume| format!("{volume:.9}")),
1157 volume.map_or("unmeasured".to_string(), |volume| format!("{:+.3e}", volume - expected)),
1158 );
1159 }
1160 refused.push(sentence);
1161 continue;
1162 }
1163 } else if hold_mirror {
1164 let mirror_start = web_time::Instant::now();
1167 let mirrored = AffineTransform::new([
1168 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,
1172 ])
1173 .ok()
1174 .and_then(|transform| crate::transform_brep(second, transform, false).ok());
1175 let mirror = mirrored.as_ref().and_then(|mirrored| {
1176 inclusion_exclusion_volume(first, mirrored, operation, options, va, vb, true)
1177 });
1178 let mirror_time = mirror_start.elapsed();
1179 let volume = body_volume(&candidate);
1180 let mut measured = None;
1181 let verdict = match (&mirror, volume) {
1182 (Some(mirror), Some(volume)) => {
1183 let bar = crate::VOLUME_DRIFT_ABS.max(crate::VOLUME_DRIFT_REL * mirror.expected.abs());
1184 let miss = 0.5 * (volume - mirror.expected).abs();
1185 measured = Some((0.5 * (volume - mirror.expected), bar));
1186 if ladder {
1187 eprintln!(
1188 "[ladder] {rung}: mirror at −offset reads {} = {:.9} (the mirrored {} {:.9}); body {volume:.9}, first-order translation error {:+.3e} bar {bar:.3e}",
1189 mirror.formula, mirror.expected, mirror.reading, mirror.read, 0.5 * (volume - mirror.expected)
1190 );
1191 }
1192 (miss > bar).then(|| format!(
1193 "perturbation rung dir={dir:?} fraction={fraction:.1e} \
1194 (offset {magnitude:.3e}) refused: no exact-lane boolean of the \
1195 operands clears, so the rung is held to its mirror: its body reads \
1196 {volume:.9} with the second operand moved +offset and {} = {:.9} \
1197 with it moved −offset (the mirrored {} reads {:.9}), a first-order \
1198 translation error of {miss:.3e} beyond the volume drift bar {bar:.3e}",
1199 mirror.formula, mirror.expected, mirror.reading, mirror.read
1200 ))
1201 }
1202 _ => Some(format!(
1203 "perturbation rung dir={dir:?} fraction={fraction:.1e} \
1204 (offset {magnitude:.3e}) refused: no exact-lane boolean of the operands \
1205 clears, and none clears with the second operand moved −offset either, \
1206 so nothing checks the rung's body{}",
1207 volume.map_or(String::new(), |volume| format!(" ({volume:.9})"))
1208 )),
1209 };
1210 match verdict {
1211 None => trends[direction].cleared(),
1212 Some(sentence) => {
1213 if debug {
1214 eprintln!("[perturb] {sentence}");
1215 }
1216 if ladder {
1217 eprintln!(
1218 "[ladder] {rung}: refused by its mirror (rung {:.0} ms: built {:.0}, bound {:.0}, mirror {:.0} ms; ladder {:.1} s)",
1219 rung_start.elapsed().as_secs_f64() * 1e3,
1220 built.as_secs_f64() * 1e3,
1221 (bounded - built).as_secs_f64() * 1e3,
1222 mirror_time.as_secs_f64() * 1e3,
1223 ladder_start.elapsed().as_secs_f64()
1224 );
1225 }
1226 refused.push(sentence);
1227 let closure = measured.and_then(|(error, bar)| {
1230 let earlier = trends[direction].refused(magnitude, error, early_exit)?;
1231 Some((earlier, error, bar))
1232 });
1233 if let Some(((earlier_offset, earlier_error), error, bar)) = closure {
1234 let closed = format!(
1235 "perturbation direction dir={dir:?} closed after offset {magnitude:.3e}: its \
1236 rungs' first-order translation errors read {earlier_error:+.3e} at offset \
1237 {earlier_offset:.3e} and {error:+.3e} at {magnitude:.3e}, one sign and \
1238 growing, so no larger offset along it comes back to the volume drift bar \
1239 {bar:.3e}"
1240 );
1241 if debug {
1242 eprintln!("[perturb] {closed}");
1243 }
1244 if ladder {
1245 eprintln!("[ladder] {closed}");
1246 }
1247 refused.push(closed);
1248 }
1249 continue;
1250 }
1251 }
1252 }
1253 }
1254 match crate::oracle::boolean_semantic_disagreement(
1258 first, second, operation, &candidate, 400,
1259 ) {
1260 Ok(report) if report.considered >= 30 && !report.is_flagged() => {
1261 if ladder {
1262 eprintln!(
1263 "[ladder] {rung}: accepted (oracle {} considered, rate {:.4}), {}",
1264 report.considered, report.disagreement_rate, rung_miss(&identity, &candidate)
1265 );
1266 }
1267 if debug {
1268 eprintln!(
1269 "[perturb] rescued {operation:?}: dir={dir:?} fraction={fraction:.1e} \
1270 magnitude={magnitude:.3e} offset={offset:?} \
1271 (oracle considered={} rate={:.4})",
1272 report.considered, report.disagreement_rate
1273 );
1274 }
1275 return Ok(candidate);
1276 }
1277 report => {
1278 if ladder {
1279 let verdict = match &report {
1280 Ok(report) => format!("oracle {} considered, rate {:.4}", report.considered, report.disagreement_rate),
1281 Err(error) => format!("oracle error {error:?}"),
1282 };
1283 eprintln!("[ladder] {rung}: refused by the oracle ({verdict}), {}", rung_miss(&identity, &candidate));
1284 }
1285 continue;
1286 }
1287 }
1288 }
1289 }
1290 if debug {
1291 eprintln!("[perturb] ladder exhausted for {operation:?}; no rung produced a clean result");
1292 }
1293 Err(refused)
1294}
1295
1296pub const PERTURBATION_FRACTIONS: [f64; 5] = [3e-5, 1e-4, 3e-4, 1e-3, 3e-3];
1299
1300#[derive(Clone, Copy, Default)]
1324pub struct MirrorTrend {
1325 last: Option<(f64, f64)>,
1327 pub closed: bool,
1328}
1329
1330impl MirrorTrend {
1331 pub fn refused(&mut self, offset: f64, error: f64, close: bool) -> Option<(f64, f64)> {
1336 let earlier = self
1337 .last
1338 .filter(|&(_, earlier)| earlier.signum() == error.signum() && error.abs() >= earlier.abs())
1339 .filter(|_| close);
1340 self.last = Some((offset, error));
1341 self.closed |= earlier.is_some();
1342 earlier
1343 }
1344
1345 pub fn cleared(&mut self) {
1347 self.last = None;
1348 }
1349}
1350
1351pub fn below_tolerance_refusal_enabled() -> bool {
1366 crate::switch!("BREP_BELOW_TOLERANCE_REFUSAL", true)
1367}
1368
1369pub fn below_tolerance_slivers_enabled() -> bool {
1386 crate::switch!("BREP_BELOW_TOLERANCE_SLIVERS", true)
1387}
1388
1389const SLIVER_ANSWER_FACES: usize = 64;
1392
1393fn face_count(solid: &BrepSolid) -> usize {
1394 solid.shells.iter().map(|shell| shell.faces.len()).sum()
1395}
1396
1397fn below_tolerance_answer(first: &BrepSolid, second: &BrepSolid, operation: BooleanOperation) -> Option<BrepSolid> {
1399 if !below_tolerance_slivers_enabled() || [first, second].iter().any(|solid| face_count(solid) > SLIVER_ANSWER_FACES) {
1400 return None;
1401 }
1402 if ![first, second].iter().all(|solid| closed_single_shell(solid)) {
1403 return None;
1404 }
1405 let inside = |x: &BrepSolid, y: &BrepSolid| difference_all_sliver(x, y);
1406 if matches!(operation, BooleanOperation::Subtract) {
1407 return inside(first, second).then(empty_solid);
1408 }
1409 let (first_in, second_in) = (inside(first, second), inside(second, first));
1410 let first_larger = || match (body_volume(first), body_volume(second)) {
1413 (Some(a), Some(b)) => a >= b,
1414 _ => true,
1415 };
1416 let outer_is_first = match (first_in, second_in) {
1417 (false, false) => return None,
1418 (true, false) => false,
1419 (false, true) => true,
1420 (true, true) => first_larger(),
1421 };
1422 let (outer, inner) = if outer_is_first { (first, second) } else { (second, first) };
1423 Some(match operation {
1424 BooleanOperation::Union => outer.clone(),
1425 _ => inner.clone(),
1426 })
1427}
1428
1429fn closed_single_shell(solid: &BrepSolid) -> bool {
1431 if !solid.kind.is_solid() || solid.shells.len() != 1 {
1432 return false;
1433 }
1434 let mut uses: HashMap<u64, usize> = HashMap::default();
1435 for coedge in solid.shells[0].faces.iter().flat_map(|face| &face.loops).flat_map(|lp| &lp.coedges) {
1436 *uses.entry(coedge.edge_id).or_default() += 1;
1437 }
1438 !uses.is_empty() && uses.values().all(|&count| count == 2) && solid.edges.iter().all(|edge| uses.contains_key(&edge.id))
1439}
1440
1441fn difference_all_sliver(first: &BrepSolid, second: &BrepSolid) -> bool {
1452 let Some(bounds) = difference_bounds(first, second) else {
1453 return false;
1454 };
1455 let Ok(properties) = crate::solid_mass_properties(first) else {
1456 return false;
1457 };
1458 bounds.out <= BELOW_TOLERANCE_BAND
1459 && bounds.upper.is_finite()
1460 && bounds.upper <= crate::tolerance::COINCIDENCE_DISTANCE_FLOOR * properties.surface_area
1461}
1462
1463struct DifferenceBounds {
1469 lower: f64,
1470 upper: f64,
1471 out: f64,
1473}
1474
1475fn difference_bounds(first: &BrepSolid, second: &BrepSolid) -> Option<DifferenceBounds> {
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 vertices_b: Vec<Vec3> = second.vertices.iter().map(|vertex| vertex.point).collect();
1479 let vertices_a: Vec<Vec3> = first.vertices.iter().map(|vertex| vertex.point).collect();
1480 let flat = 1e-9 * scale;
1481 let mut bounds = DifferenceBounds { lower: 0.0, upper: 0.0, out: 0.0 };
1482 for polygon in &polygons_b {
1483 let (origin, normal) = polygon_plane(polygon)?;
1484 if vertices_b.iter().any(|vertex| vertex.sub(origin).dot(normal) > flat) {
1486 return None;
1487 }
1488 let out = vertices_a.iter().map(|vertex| vertex.sub(origin).dot(normal)).fold(0.0f64, f64::max);
1489 bounds.out = bounds.out.max(out);
1490 if out <= 0.0 {
1491 continue;
1492 }
1493 let part: f64 = polygons_a.iter().map(|face| clipped_cone_volume(face, origin, normal)).sum();
1494 bounds.lower = bounds.lower.max(part);
1495 bounds.upper += part;
1496 }
1497 Some(bounds)
1498}
1499
1500pub fn below_tolerance_rescale_enabled() -> bool {
1510 crate::switch!("BREP_BELOW_TOLERANCE_RESCALE", false)
1511}
1512
1513fn below_tolerance_rescaled(first: &BrepSolid, second: &BrepSolid, operation: BooleanOperation, options: &BooleanOptions) -> Option<BrepSolid> {
1514 if !below_tolerance_rescale_enabled()
1515 || options.tolerances.is_some()
1516 || [first, second].iter().any(|solid| face_count(solid) > SLIVER_ANSWER_FACES || !closed_single_shell(solid))
1517 {
1518 return None;
1519 }
1520 let (volume_exact, area_exact) = convex_pair_measures(first, second, operation)?;
1521 let volume_slack = 1e-9 * body_volume(first)?.max(body_volume(second)?);
1522 let area_slack = 1e-9 * area_exact.max(1.0);
1523 for factor in [100.0, 1000.0] {
1524 let scaled = |solid: &BrepSolid| crate::rescale::scale_operand(solid, factor, "boolean").ok();
1525 let (Some(a), Some(b)) = (scaled(first), scaled(second)) else {
1526 continue;
1527 };
1528 let mut scaled_options = options.clone();
1529 scaled_options.imprint.maximum_ssi_step = scaled_options.imprint.maximum_ssi_step.map(|step| step * factor);
1530 let Ok(outcome) = boolean_operation_with_diagnostics(&a, &b, operation, &scaled_options) else {
1531 continue;
1532 };
1533 let Ok(answer) = crate::rescale::scale_operand(&outcome.value, 1.0 / factor, "boolean") else {
1534 continue;
1535 };
1536 let Ok(properties) = crate::solid_mass_properties(&answer) else {
1537 continue;
1538 };
1539 if (properties.volume.abs() - volume_exact).abs() <= volume_slack
1540 && (properties.surface_area - area_exact).abs() <= area_slack
1541 && !answer.validate().iter().any(|issue| issue.severity == "error")
1542 {
1543 return Some(answer);
1544 }
1545 }
1546 None
1547}
1548
1549fn convex_pair_measures(first: &BrepSolid, second: &BrepSolid, operation: BooleanOperation) -> Option<(f64, f64)> {
1555 let scale = crate::solid_tolerance::solid_scale(first).max(crate::solid_tolerance::solid_scale(second)).max(1.0);
1556 let (polygons_a, polygons_b) = (face_polygons(first, scale)?, face_polygons(second, scale)?);
1557 let (planes_a, planes_b) = (convex_planes(&polygons_a, scale)?, convex_planes(&polygons_b, scale)?);
1558 let zero = Vec3::new(0.0, 0.0, 0.0);
1559 let read = |polygons: &[Vec<Vec3>], planes: &[(Vec3, Vec3)]| {
1561 let (mut cone, mut area, mut inside_area) = (0.0, 0.0, 0.0);
1562 for polygon in polygons {
1563 area += vector_area(polygon, zero).length();
1564 let mut inside = polygon.clone();
1565 for &(origin, normal) in planes {
1566 inside = clip_polygon(&inside, origin, normal.scale(-1.0));
1567 if inside.len() < 3 {
1568 break;
1569 }
1570 }
1571 if inside.len() >= 3 {
1572 let vector = vector_area(&inside, zero);
1573 cone += inside[0].dot(vector) / 3.0;
1574 inside_area += vector.length();
1575 }
1576 }
1577 (cone, area, inside_area)
1578 };
1579 let (cone_a, area_a, inside_a) = read(&polygons_a, &planes_b);
1580 let (cone_b, area_b, inside_b) = read(&polygons_b, &planes_a);
1581 let (volume_a, volume_b) = (body_volume(first)?, body_volume(second)?);
1582 let common = cone_a + cone_b;
1583 Some(match operation {
1584 BooleanOperation::Intersect => (common, inside_a + inside_b),
1585 BooleanOperation::Union => (volume_a + volume_b - common, (area_a - inside_a) + (area_b - inside_b)),
1586 BooleanOperation::Subtract => (volume_a - common, (area_a - inside_a) + inside_b),
1587 })
1588}
1589
1590fn convex_planes(polygons: &[Vec<Vec3>], scale: f64) -> Option<Vec<(Vec3, Vec3)>> {
1593 let planes = polygons.iter().map(|polygon| polygon_plane(polygon)).collect::<Option<Vec<_>>>()?;
1594 let flat = 1e-9 * scale;
1595 let convex = planes.iter().all(|&(origin, normal)| polygons.iter().flatten().all(|vertex| vertex.sub(origin).dot(normal) <= flat));
1596 convex.then_some(planes)
1597}
1598
1599fn clip_polygon(polygon: &[Vec3], origin: Vec3, normal: Vec3) -> Vec<Vec3> {
1602 let side = |point: Vec3| point.sub(origin).dot(normal);
1603 let mut kept = Vec::with_capacity(polygon.len() + 2);
1604 for (index, &point) in polygon.iter().enumerate() {
1605 let next = polygon[(index + 1) % polygon.len()];
1606 let (here, there) = (side(point), side(next));
1607 if here >= 0.0 {
1608 kept.push(point);
1609 }
1610 if (here >= 0.0) != (there >= 0.0) {
1611 let t = here / (here - there);
1612 kept.push(point.add(next.sub(point).scale(t)));
1613 }
1614 }
1615 kept
1616}
1617
1618fn face_polygons(solid: &BrepSolid, scale: f64) -> Option<Vec<Vec<Vec3>>> {
1622 let vertex = |id: u64| solid.vertices.iter().find(|vertex| vertex.id == id).map(|vertex| vertex.point);
1623 let mut polygons = Vec::new();
1624 for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
1625 if !face.surface.is_affine().ok()? {
1626 return None;
1627 }
1628 for lp in &face.loops {
1629 let mut polygon = Vec::with_capacity(lp.coedges.len());
1630 for coedge in &lp.coedges {
1631 let edge = solid.edges.iter().find(|edge| edge.id == coedge.edge_id)?;
1632 let (start, end) = (vertex(edge.start_vertex_id)?, vertex(edge.end_vertex_id)?);
1633 let chord = end.sub(start);
1634 let length = chord.length();
1635 if edge.degenerate || length <= 1e-12 * scale {
1636 return None;
1637 }
1638 for control in &edge.curve.control_points {
1639 let offset = control.point().ok()?.sub(start);
1640 if offset.cross(chord).length() / length > 1e-9 * scale {
1641 return None;
1642 }
1643 }
1644 polygon.push(if coedge.forward { start } else { end });
1645 }
1646 polygons.push(polygon);
1647 }
1648 }
1649 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();
1651 if !(volume.abs() > 0.0) {
1652 return None;
1653 }
1654 if volume < 0.0 {
1655 for polygon in &mut polygons {
1656 polygon.reverse();
1657 }
1658 }
1659 Some(polygons)
1660}
1661
1662fn polygon_plane(polygon: &[Vec3]) -> Option<(Vec3, Vec3)> {
1664 let origin = *polygon.first()?;
1665 Some((origin, vector_area(polygon, origin).normalized().ok()?))
1666}
1667
1668fn vector_area(polygon: &[Vec3], origin: Vec3) -> Vec3 {
1669 let mut area = Vec3::new(0.0, 0.0, 0.0);
1670 for (index, point) in polygon.iter().enumerate() {
1671 let next = polygon[(index + 1) % polygon.len()];
1672 area = area.add(point.sub(origin).cross(next.sub(origin)));
1673 }
1674 area.scale(0.5)
1675}
1676
1677fn clipped_cone_volume(polygon: &[Vec3], origin: Vec3, normal: Vec3) -> f64 {
1683 let clipped: Vec<Vec3> = if normal.length() == 0.0 { polygon.to_vec() } else { clip_polygon(polygon, origin, normal) };
1684 if clipped.len() < 3 {
1685 return 0.0;
1686 }
1687 clipped[0].sub(origin).dot(vector_area(&clipped, origin)) / 3.0
1688}
1689
1690const BELOW_TOLERANCE_BAND: f64 = 10.0 * crate::tolerance::WELD_FLOOR;
1693
1694pub fn unresolved_merge_refusal_enabled() -> bool {
1704 crate::switch!("BREP_UNRESOLVED_MERGE_REFUSAL", false)
1705}
1706
1707pub fn sliver_shell_drop_enabled() -> bool {
1720 crate::switch!("BREP_SLIVER_SHELL_DROP", true)
1721}
1722
1723const SLIVER_SHELL_THICKNESS: f64 = 1e-12;
1727
1728pub fn sliver_shell_fast_on() -> bool {
1743 crate::switch!("BREP_SLIVER_SHELL_FAST", true)
1744}
1745
1746fn sliver_shell_fast_check_on() -> bool {
1747 crate::switch!("BREP_SLIVER_SHELL_FAST_CHECK", false)
1748}
1749
1750thread_local! {
1751 static SLIVER_FAST_CHECK: std::cell::Cell<(u64, u64, u64)> = const { std::cell::Cell::new((0, 0, 0)) };
1752}
1753
1754pub fn sliver_shell_fast_check_take() -> (u64, u64, u64) {
1757 SLIVER_FAST_CHECK.with(|cell| cell.replace((0, 0, 0)))
1758}
1759
1760fn sliver_fast_record(compared: u64, differed: u64, kept: u64) {
1761 SLIVER_FAST_CHECK.with(|cell| {
1762 let (a, b, c) = cell.get();
1763 cell.set((a + compared, b + differed, c + kept));
1764 });
1765}
1766
1767fn face_area_upper_bound(surface: &crate::NurbsSurface) -> Option<f64> {
1775 let net = &surface.control_points;
1776 let rows = net.len();
1777 let columns = net.first()?.len();
1778 if rows < 2 || columns < 2 || net.iter().any(|row| row.len() != columns) {
1779 return None;
1780 }
1781 let (p, q) = (surface.degree_u, surface.degree_v);
1782 let (us, vs) = (&surface.knots_u, &surface.knots_v);
1783 if us.len() != rows + p + 1 || vs.len() != columns + q + 1 {
1784 return None;
1785 }
1786 let mut w_min = f64::INFINITY;
1787 let mut w_max = 0.0f64;
1788 let mut point_max = 0.0f64;
1789 for c in net.iter().flatten() {
1790 if !(c.w > 0.0) {
1791 return None;
1792 }
1793 w_min = w_min.min(c.w);
1794 w_max = w_max.max(c.w);
1795 point_max = point_max.max((c.x * c.x + c.y * c.y + c.z * c.z).sqrt());
1796 }
1797 let hodograph = |along_u: bool| -> Option<(f64, f64)> {
1799 let (count, degree, knots) = if along_u { (rows, p, us) } else { (columns, q, vs) };
1800 let (mut dp, mut dw) = (0.0f64, 0.0f64);
1801 for i in 0..count - 1 {
1802 let span = knots[i + degree + 1] - knots[i + 1];
1803 if !(span > 0.0) {
1804 continue;
1805 }
1806 let scale = degree as f64 / span;
1807 let others = if along_u { columns } else { rows };
1808 for j in 0..others {
1809 let (a, b) = if along_u { (net[i][j], net[i + 1][j]) } else { (net[j][i], net[j][i + 1]) };
1810 let (x, y, z) = (b.x - a.x, b.y - a.y, b.z - a.z);
1811 dp = dp.max(scale * (x * x + y * y + z * z).sqrt());
1812 dw = dw.max(scale * (b.w - a.w).abs());
1813 }
1814 }
1815 Some((dp, dw))
1816 };
1817 let (pu, wu) = hodograph(true)?;
1818 let (pv, wv) = hodograph(false)?;
1819 let su = (pu * w_max + point_max * wu) / (w_min * w_min);
1820 let sv = (pv * w_max + point_max * wv) / (w_min * w_min);
1821 let extent_u = us[us.len() - 1] - us[0];
1822 let extent_v = vs[vs.len() - 1] - vs[0];
1823 let bound = su * sv * extent_u * extent_v;
1824 bound.is_finite().then_some(bound)
1825}
1826
1827pub fn trimmed_face_area_upper_bound(face: &crate::topology::FaceRecord) -> Option<f64> {
1835 let s = &face.surface;
1836 let (u0, u1) = (*s.knots_u.first()?, *s.knots_u.last()?);
1837 let (v0, v1) = (*s.knots_v.first()?, *s.knots_v.last()?);
1838 let (du, dv) = (1e-12 * (u1 - u0).abs(), 1e-12 * (v1 - v0).abs());
1840 if !(du > 0.0 && dv > 0.0) {
1841 return None;
1842 }
1843 for coedge in face.loops.iter().flat_map(|lp| &lp.coedges) {
1844 for c in &coedge.pcurve.control_points {
1845 if !(c.w > 0.0) {
1846 return None;
1847 }
1848 let (u, v) = (c.x / c.w, c.y / c.w);
1849 if !(u >= u0 - du && u <= u1 + du && v >= v0 - dv && v <= v1 + dv) {
1850 return None;
1851 }
1852 }
1853 }
1854 face_area_upper_bound(s).map(|bound| 2.0 * bound)
1855}
1856
1857fn drop_sliver_shells(solid: &mut BrepSolid) -> usize {
1860 if !sliver_shell_drop_enabled() || !solid.kind.is_solid() || solid.shells.len() < 2 {
1861 return 0;
1862 }
1863 let floor = SLIVER_SHELL_THICKNESS * crate::solid_tolerance::solid_scale(solid).max(1.0);
1864 let degenerate: std::collections::HashSet<u64> = solid.edges.iter().filter(|edge| edge.degenerate).map(|edge| edge.id).collect();
1865 let mut drop = vec![false; solid.shells.len()];
1866 for (index, shell) in solid.shells.iter().enumerate() {
1867 if shell.faces.is_empty() {
1868 continue;
1869 }
1870 let mut uses: HashMap<u64, usize> = HashMap::default();
1872 for coedge in shell.faces.iter().flat_map(|face| &face.loops).flat_map(|lp| &lp.coedges) {
1873 if !degenerate.contains(&coedge.edge_id) {
1874 *uses.entry(coedge.edge_id).or_default() += 1;
1875 }
1876 }
1877 if uses.is_empty() || uses.values().any(|&count| count != 2) {
1878 continue;
1879 }
1880 let alone = BrepSolid { shells: vec![shell.clone()], mass_properties_cache: Default::default(), ..solid.clone() };
1881 let (fast, check) = (sliver_shell_fast_on(), sliver_shell_fast_check_on());
1882 let kept_fast = (fast || check)
1883 && shell
1884 .faces
1885 .iter()
1886 .map(trimmed_face_area_upper_bound)
1887 .sum::<Option<f64>>()
1888 .map(|area| floor * area)
1889 .filter(|bar| bar.is_finite() && *bar > 0.0)
1890 .and_then(|bar| crate::solid_signed_volume_for_sign(&alone, bar).ok().map(|volume| volume > bar))
1891 .unwrap_or(false);
1892 if kept_fast && !check {
1893 sliver_fast_record(0, 0, 1);
1894 continue;
1895 }
1896 let Ok(mass) = crate::solid_mass_properties(&alone) else {
1897 continue;
1898 };
1899 let thickness = mass.volume.abs() / mass.surface_area.max(f64::MIN_POSITIVE);
1900 if env_read!("BREP_DEBUG_SLIVER_SHELL").is_some() {
1901 eprintln!(
1902 "sliver-shell: shell {index} of {}: volume {:.6e} area {:.6e} thickness {thickness:.3e}",
1903 solid.shells.len(),
1904 mass.volume,
1905 mass.surface_area
1906 );
1907 }
1908 drop[index] = thickness < floor;
1909 if check {
1910 sliver_fast_record(1, u64::from(kept_fast && drop[index]), u64::from(kept_fast));
1911 }
1912 }
1913 let dropped = drop.iter().filter(|&&d| d).count();
1914 if dropped == 0 || dropped == solid.shells.len() {
1915 return 0;
1916 }
1917 let mut index = 0;
1918 solid.shells.retain(|_| {
1919 let keep = !drop[index];
1920 index += 1;
1921 keep
1922 });
1923 let used_edges: std::collections::HashSet<u64> = solid
1924 .shells
1925 .iter()
1926 .flat_map(|shell| &shell.faces)
1927 .flat_map(|face| &face.loops)
1928 .flat_map(|lp| &lp.coedges)
1929 .map(|coedge| coedge.edge_id)
1930 .collect();
1931 solid.edges.retain(|edge| used_edges.contains(&edge.id));
1932 let used_vertices: std::collections::HashSet<u64> =
1933 solid.edges.iter().flat_map(|edge| [edge.start_vertex_id, edge.end_vertex_id]).collect();
1934 solid.vertices.retain(|vertex| used_vertices.contains(&vertex.id));
1935 solid.mass_properties_cache = Default::default();
1936 refresh_derived_genus(solid);
1938 dropped
1939}
1940
1941fn unresolved_merge_refusal(first: &BrepSolid, second: &BrepSolid) -> Option<KernelRefusal> {
1942 let (lower, upper) = (crate::tolerance::COINCIDENCE_DISTANCE_FLOOR, crate::tolerance::WELD_FLOOR);
1943 let (face_a, face_b, separation) = planar_faces_apart_within(first, second, lower, upper)?;
1944 Some(KernelRefusal::unsupported(
1945 KernelStage::Intersect,
1946 "below_modelling_tolerance",
1947 format!(
1948 "boolean: face {face_a} of the first operand and face {face_b} of the second are planes nearly on one \
1949 another, {separation:.3e} apart at most over their shared extent: farther than a coincidence \
1950 ({lower:.0e}) and closer than the kernel resolves ({upper:.0e}), so the step between them would be \
1951 welded away"
1952 ),
1953 ))
1954}
1955
1956fn below_tolerance_refusal(first: &BrepSolid, second: &BrepSolid, error: Option<&KernelRefusal>) -> Option<KernelRefusal> {
1957 let (face_a, face_b, separation) = near_coincident_planar_faces(first, second)?;
1958 let message = format!(
1959 "boolean: face {face_a} of the first operand and face {face_b} of the second are planes nearly on one \
1960 another, {separation:.3e} apart at most over their shared extent: the slivers between them are below the \
1961 modelling tolerance ({BELOW_TOLERANCE_BAND:.0e}), so the kernel cannot resolve them{}",
1962 error.map(|error| format!(" (the exact arrangement said: {})", error.message.chars().take(160).collect::<String>())).unwrap_or_default()
1963 );
1964 Some(KernelRefusal::unsupported(KernelStage::Intersect, "below_modelling_tolerance", message))
1965}
1966
1967fn near_coincident_planar_faces(first: &BrepSolid, second: &BrepSolid) -> Option<(u64, u64, f64)> {
1971 let scale = crate::solid_tolerance::solid_scale(first).max(crate::solid_tolerance::solid_scale(second)).max(1.0);
1972 planar_faces_apart_within(first, second, 1e-9 * scale, BELOW_TOLERANCE_BAND)
1973}
1974
1975fn planar_faces_apart_within(first: &BrepSolid, second: &BrepSolid, lower: f64, upper: f64) -> Option<(u64, u64, f64)> {
1979 struct Planar {
1980 id: u64,
1981 origin: Vec3,
1982 normal: Vec3,
1983 corners: Vec<Vec3>,
1984 bounds: crate::spatial::Aabb,
1985 }
1986 let read = |solid: &BrepSolid| -> Vec<Planar> {
1987 let at = |id: u64| solid.vertices.iter().find(|vertex| vertex.id == id).map(|vertex| vertex.point);
1988 solid
1989 .shells
1990 .iter()
1991 .flat_map(|shell| &shell.faces)
1992 .filter_map(|face| {
1993 if !face.surface.is_affine().ok()? {
1994 return None;
1995 }
1996 let origin = face.surface.control_points[0][0].point().ok()?;
1997 let a = face.surface.control_points[1][0].point().ok()?.sub(origin);
1998 let b = face.surface.control_points[0][1].point().ok()?.sub(origin);
1999 let normal = a.cross(b).normalized().ok()?;
2000 let corners: Vec<Vec3> = face
2001 .loops
2002 .iter()
2003 .flat_map(|lp| &lp.coedges)
2004 .filter_map(|coedge| solid.edges.iter().find(|edge| edge.id == coedge.edge_id))
2005 .flat_map(|edge| [at(edge.start_vertex_id), at(edge.end_vertex_id)])
2006 .flatten()
2007 .collect();
2008 if corners.is_empty() {
2009 return None;
2010 }
2011 let bounds = crate::spatial::Aabb::from_points(corners.clone());
2012 Some(Planar { id: face.id, origin, normal, corners, bounds })
2013 })
2014 .collect()
2015 };
2016 let (faces_a, faces_b) = (read(first), read(second));
2017 for a in &faces_a {
2018 for b in &faces_b {
2019 if a.normal.cross(b.normal).length() > 1e-3 {
2020 continue;
2021 }
2022 if !a.bounds.intersects(b.bounds, upper) {
2023 continue;
2024 }
2025 let separation = a
2026 .corners
2027 .iter()
2028 .map(|corner| corner.sub(b.origin).dot(b.normal).abs())
2029 .chain(b.corners.iter().map(|corner| corner.sub(a.origin).dot(a.normal).abs()))
2030 .fold(0.0f64, f64::max);
2031 if separation > lower && separation <= upper {
2032 return Some((a.id, b.id, separation));
2033 }
2034 }
2035 }
2036 None
2037}
2038
2039pub fn one_use_edges(solid: &BrepSolid) -> usize {
2040 let mut uses: HashMap<u64, usize> = HashMap::default();
2041 for coedge in solid
2042 .shells
2043 .iter()
2044 .flat_map(|shell| &shell.faces)
2045 .flat_map(|face| &face.loops)
2046 .flat_map(|loop_record| &loop_record.coedges)
2047 {
2048 *uses.entry(coedge.edge_id).or_default() += 1;
2049 }
2050 solid
2051 .edges
2052 .iter()
2053 .filter(|edge| !edge.degenerate && uses.get(&edge.id) == Some(&1))
2054 .count()
2055}
2056
2057fn body_volume(solid: &BrepSolid) -> Option<f64> {
2059 if solid.shells.is_empty() {
2060 return Some(0.0);
2061 }
2062 solid_signed_volume(solid).ok().map(f64::abs)
2063}
2064
2065struct InclusionExclusion {
2068 formula: &'static str,
2071 reading: &'static str,
2073 read: f64,
2075 expected: f64,
2077}
2078
2079fn isotropic_chart_identity(
2088 first: &BrepSolid,
2089 second: &BrepSolid,
2090 rescaled_first: &BrepSolid,
2091 rescaled_second: &BrepSolid,
2092 operation: BooleanOperation,
2093 options: &BooleanOptions,
2094 result: &BrepSolid,
2095) -> Result<(), String> {
2096 let _caller = crate::mass_caller("boolean.isotropic_chart_identity");
2097 let va = solid_signed_volume(first).ok().map(f64::abs);
2098 let vb = solid_signed_volume(second).ok().map(f64::abs);
2099 let volume = body_volume(result).ok_or("its body has no volume")?;
2100 if let (Some(va), Some(vb)) = (va, vb) {
2101 if !volume_within_csg_bounds(operation, va, vb, volume) {
2102 return Err(format!("volume {volume:.9} outside the CSG bound of {va:.9} and {vb:.9}"));
2103 }
2104 }
2105 let identity = inclusion_exclusion_volume(first, second, operation, options, va, vb, false)
2106 .or_else(|| isotropic_chart::with_active(|| inclusion_exclusion_volume(rescaled_first, rescaled_second, operation, options, va, vb, false)))
2107 .ok_or("no exact-lane boolean of the operands clears to read the inclusion-exclusion identity")?;
2108 let bar = crate::VOLUME_DRIFT_ABS.max(crate::VOLUME_DRIFT_REL * identity.expected.abs());
2109 if (volume - identity.expected).abs() > bar {
2110 return Err(format!(
2111 "volume {volume:.9} against the identity {} = {:.9} (the {} reads {:.9}), bar {bar:.3e}",
2112 identity.formula, identity.expected, identity.reading, identity.read
2113 ));
2114 }
2115 Ok(())
2116}
2117
2118fn inclusion_exclusion_volume(
2129 first: &BrepSolid,
2130 second: &BrepSolid,
2131 operation: BooleanOperation,
2132 options: &BooleanOptions,
2133 va: Option<f64>,
2134 vb: Option<f64>,
2135 own_first: bool,
2136) -> Option<InclusionExclusion> {
2137 use BooleanOperation::{Intersect, Subtract, Union};
2138 let (va, vb) = (va?, vb?);
2139 let own = match operation {
2140 Intersect => (Intersect, false, "first ∩ second"),
2141 Union => (Union, false, "first ∪ second"),
2142 Subtract => (Subtract, false, "first − second"),
2143 };
2144 let readings = [
2145 (Intersect, false, "first ∩ second"),
2146 (Intersect, true, "second ∩ first"),
2147 (Union, false, "first ∪ second"),
2148 (Union, true, "second ∪ first"),
2149 (Subtract, false, "first − second"),
2150 (Subtract, true, "second − first"),
2151 ];
2152 let own_reading = own_first.then_some(own);
2153 let leading = usize::from(own_first);
2154 for (index, (other, swapped, reading)) in own_reading.into_iter().chain(readings).enumerate() {
2155 if index >= leading && !swapped && std::mem::discriminant(&other) == std::mem::discriminant(&operation) {
2156 continue;
2157 }
2158 let (x, y) = if swapped { (second, first) } else { (first, second) };
2159 let Some(read) = boolean_operation_with_diagnostics(x, y, other, options)
2160 .ok()
2161 .and_then(|outcome| body_volume(&outcome.value))
2162 else {
2163 continue;
2164 };
2165 let intersection = match (other, swapped) {
2166 (Intersect, _) => read,
2167 (Union, _) => va + vb - read,
2168 (Subtract, false) => va - read,
2169 (Subtract, true) => vb - read,
2170 };
2171 let (formula, expected) = match operation {
2172 Intersect => ("V(first ∩ second)", intersection),
2173 Union => ("V(first) + V(second) − V(first ∩ second)", va + vb - intersection),
2174 Subtract => ("V(first) − V(first ∩ second)", va - intersection),
2175 };
2176 return Some(InclusionExclusion { formula, reading, read, expected });
2177 }
2178 None
2179}
2180
2181fn planar_operand_off_its_plane(
2190 first: &BrepSolid,
2191 second: &BrepSolid,
2192 options: &BooleanOptions,
2193) -> Option<(u8, u64, f64, f64)> {
2194 let policy = options
2195 .tolerances
2196 .clone()
2197 .unwrap_or_else(|| KernelTolerances::for_pair(first, second, options.tolerance));
2198 let weld = crate::tolerance::assembler_weld(policy.model);
2199 let mut worst: Option<(u8, u64, f64)> = None;
2200 for (operand, solid) in [(0u8, first), (1u8, second)] {
2201 let vertex_point = |id: u64| solid.vertices.iter().find(|v| v.id == id).map(|v| v.point);
2202 for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
2203 let Some(crate::AnalyticSurface::Plane {
2204 origin,
2205 u_dir,
2206 v_dir,
2207 ..
2208 }) = face.surface.analytic()
2209 else {
2210 continue;
2211 };
2212 let [loop_record] = face.loops.as_slice() else {
2213 continue;
2214 };
2215 let Ok(normal) = u_dir.cross(*v_dir).normalized() else {
2216 continue;
2217 };
2218 let mut off_plane = 0.0f64;
2219 let mut straight = true;
2220 for coedge in &loop_record.coedges {
2221 let Some(edge) = solid.edges.iter().find(|edge| edge.id == coedge.edge_id) else {
2222 straight = false;
2223 break;
2224 };
2225 let (Some(start), Some(end)) =
2226 (vertex_point(edge.start_vertex_id), vertex_point(edge.end_vertex_id))
2227 else {
2228 straight = false;
2229 break;
2230 };
2231 let chord = end.sub(start);
2232 let length = chord.length();
2233 if edge.degenerate || length <= weld {
2234 straight = false;
2235 break;
2236 }
2237 let direction = chord.scale(1.0 / length);
2238 for fraction in [0.25, 0.5, 0.75] {
2239 let Ok(point) = edge.curve.evaluate(edge.t0 + (edge.t1 - edge.t0) * fraction) else {
2240 straight = false;
2241 break;
2242 };
2243 let delta = point.sub(start);
2244 let along = delta.dot(direction);
2245 if delta.sub(direction.scale(along)).length() > weld
2246 || along < -weld
2247 || along > length + weld
2248 {
2249 straight = false;
2250 break;
2251 }
2252 }
2253 if !straight {
2254 break;
2255 }
2256 off_plane = off_plane.max(start.sub(*origin).dot(normal).abs());
2257 }
2258 if straight && off_plane > weld && worst.is_none_or(|(_, _, gap)| off_plane > gap) {
2259 worst = Some((operand, face.id, off_plane));
2260 }
2261 }
2262 }
2263 worst.map(|(operand, face_id, gap)| (operand, face_id, gap, weld))
2264}
2265
2266fn volume_within_csg_bounds(operation: BooleanOperation, va: f64, vb: f64, vr: f64) -> bool {
2269 let slack = 1e-2 * (va + vb).max(1.0);
2270 match operation {
2271 BooleanOperation::Union => vr >= va.max(vb) - slack && vr <= va + vb + slack,
2273 BooleanOperation::Subtract => vr <= va + slack && vr >= -slack,
2275 BooleanOperation::Intersect => vr <= va.min(vb) + slack && vr >= -slack,
2277 }
2278}
2279
2280fn reverse_fragment(fragment: &mut FaceFragmentRecord) -> Result<(), KernelRefusal> {
2307 fragment.same_sense = !fragment.same_sense;
2308 for loop_record in &mut fragment.loops {
2309 loop_record.coedges.reverse();
2310 for coedge in &mut loop_record.coedges {
2311 coedge.forward = !coedge.forward;
2312 coedge.pcurve = coedge.pcurve.reversed().or_refuse(KernelStage::Validate, "reversed")?;
2313 }
2314 }
2315 Ok(())
2316}
2317
2318fn build_nary_imprint(
2327 operands: &[BrepSolid],
2328 options: &ImprintOptions,
2329) -> Result<(ImprintResultRecord, Vec<(FaceKey, FaceKey)>), KernelRefusal> {
2330 let mut section_evidence = false;
2331 let mut cosurface: Vec<(FaceKey, FaceKey)> = Vec::new();
2332 let mut vertices: Vec<ImprintVertex> = Vec::new();
2333 let mut pieces: Vec<ImprintPieceRecord> = Vec::new();
2334 let mut by_face: HashMap<(u8, u64), Vec<u64>> = HashMap::default();
2335 let mut edge_splits: HashMap<(u8, u64), Vec<f64>> = HashMap::default();
2336 let mut next_vertex_id: u64 = 1;
2337 let mut next_piece_id: u64 = 1;
2338
2339 let profile = crate::profile::profile_enabled();
2341 let (mut empty_pairs, mut empty_ms, mut full_pairs, mut full_ms) = (0usize, 0.0f64, 0usize, 0.0f64);
2342 for i in 0..operands.len() {
2343 for j in (i + 1)..operands.len() {
2344 let pair_started = profile.then(web_time::Instant::now);
2345 let pair = build_imprints(&operands[i], &operands[j], options)?;
2346 if let Some(started) = pair_started {
2347 let ms = started.elapsed().as_secs_f64() * 1000.0;
2348 if pair.pieces.is_empty() && pair.vertices.is_empty() && pair.edge_splits.is_empty() {
2349 empty_pairs += 1;
2350 empty_ms += ms;
2351 } else {
2352 full_pairs += 1;
2353 full_ms += ms;
2354 }
2355 }
2356 let remap = |operand: u8| -> u8 {
2357 if operand == 0 {
2358 i as u8
2359 } else {
2360 j as u8
2361 }
2362 };
2363
2364 section_evidence = section_evidence || pair.section_evidence;
2365 for (first, second) in &pair.cosurface_pairs {
2366 let global = |key: &FaceKey| FaceKey { operand: remap(key.operand), face_id: key.face_id };
2367 cosurface.push((global(first), global(second)));
2368 }
2369 let mut vertex_map: HashMap<u64, u64> = HashMap::default();
2370 for vertex in &pair.vertices {
2371 let global = next_vertex_id;
2372 next_vertex_id += 1;
2373 vertex_map.insert(vertex.id, global);
2374 vertices.push(ImprintVertex {
2375 id: global,
2376 point: vertex.point,
2377 });
2378 }
2379
2380 let mut piece_map: HashMap<u64, u64> = HashMap::default();
2381 for piece in &pair.pieces {
2382 let global = next_piece_id;
2383 next_piece_id += 1;
2384 piece_map.insert(piece.id, global);
2385 let mut mapped = piece.clone();
2386 mapped.id = global;
2387 mapped.start_vertex_id = *vertex_map
2388 .get(&piece.start_vertex_id)
2389 .ok_or_else(|| KernelRefusal::internal(KernelStage::Intersect, "nary.imprint", "n-ary imprint: piece references unknown vertex"))?;
2390 mapped.end_vertex_id = *vertex_map
2391 .get(&piece.end_vertex_id)
2392 .ok_or_else(|| KernelRefusal::internal(KernelStage::Intersect, "nary.imprint", "n-ary imprint: piece references unknown vertex"))?;
2393 for pcurve in &mut mapped.pcurves {
2394 pcurve.operand = remap(pcurve.operand);
2395 }
2396 mapped.support_faces = [
2397 FaceKey {
2398 operand: remap(piece.support_faces[0].operand),
2399 face_id: piece.support_faces[0].face_id,
2400 },
2401 FaceKey {
2402 operand: remap(piece.support_faces[1].operand),
2403 face_id: piece.support_faces[1].face_id,
2404 },
2405 ];
2406 pieces.push(mapped);
2407 }
2408
2409 for entry in &pair.by_face {
2410 let list = by_face
2411 .entry((remap(entry.operand), entry.face_id))
2412 .or_default();
2413 for piece_id in &entry.piece_ids {
2414 let global = *piece_map.get(piece_id).ok_or_else(|| {
2415 KernelRefusal::internal(KernelStage::Intersect, "nary.imprint", "n-ary imprint: by_face references unknown piece")
2416 })?;
2417 list.push(global);
2418 }
2419 }
2420
2421 for split in &pair.edge_splits {
2422 edge_splits
2423 .entry((remap(split.operand), split.edge_id))
2424 .or_default()
2425 .extend(split.parameters.iter().copied());
2426 }
2427 }
2428 }
2429 if profile {
2430 profile_line!("boolean.nary.imprint_pairs empty={empty_pairs} empty_ms={empty_ms:.2} full={full_pairs} full_ms={full_ms:.2}");
2431 }
2432
2433 Ok((ImprintResultRecord {
2434 faces_in_unproved_pairs: None,
2435 vertices,
2436 pieces,
2437 tangent_nodes: Vec::new(),
2438 barrier_edges: Vec::new(),
2439 section_evidence,
2440 cosurface_pairs: Vec::new(),
2441 operand_sliver_regions: Vec::new(),
2442 tangent_sections: Vec::new(),
2443 by_face: by_face
2444 .into_iter()
2445 .map(|((operand, face_id), piece_ids)| FaceImprints {
2446 operand,
2447 face_id,
2448 piece_ids,
2449 })
2450 .collect(),
2451 edge_splits: edge_splits
2452 .into_iter()
2453 .map(|((operand, edge_id), parameters)| EdgeSplitRecord {
2454 operand,
2455 edge_id,
2456 parameters,
2457 })
2458 .collect(),
2459 }, cosurface))
2460}
2461
2462pub fn boolean_operation_nary(
2473 operands: &[BrepSolid],
2474 operation: BooleanOperation,
2475) -> Result<BrepSolid, KernelRefusal> {
2476 boolean_operation_nary_with_options(operands, operation, &BooleanOptions::default())
2477}
2478
2479pub fn boolean_operation_nary_with_options(
2485 operands: &[BrepSolid],
2486 operation: BooleanOperation,
2487 options: &BooleanOptions,
2488) -> Result<BrepSolid, KernelRefusal> {
2489 let most = nary_chunk();
2494 if operands.len() > most && nary_chunks_on() {
2495 let mut whole = boolean_operation_nary_with_options(&operands[..most], operation, options)?;
2496 for chunk in operands[most..].chunks(most - 1) {
2497 if let [only] = chunk {
2500 whole = boolean_operation(&whole, only, operation, options)?;
2501 continue;
2502 }
2503 let mut next = Vec::with_capacity(chunk.len() + 1);
2504 next.push(whole);
2505 next.extend_from_slice(chunk);
2506 whole = boolean_operation_nary_with_options(&next, operation, options)?;
2507 }
2508 return Ok(whole);
2509 }
2510 let arranged = boolean_operation_nary_arranged(operands, operation, options);
2511 match arranged {
2512 Err(error) if nary_sequential_fallback_enabled() && operands.len() > 2 && error.message.contains("boolean assembly") => {
2513 let mut whole = operands[0].clone();
2516 for operand in &operands[1..] {
2517 whole = match boolean_operation(&whole, operand, operation, options) {
2518 Ok(solid) => solid,
2519 Err(_) => return Err(error),
2520 };
2521 }
2522 Ok(whole)
2523 }
2524 other => other,
2525 }
2526}
2527
2528const NARY_MOST: usize = 255;
2537
2538fn nary_chunk() -> usize {
2541 NARY_MOST
2542}
2543
2544
2545fn nary_chunks_on() -> bool {
2548 crate::switch!("BREP_NARY_CHUNKS", true)
2549}
2550
2551fn nary_scoped_on() -> bool {
2564 crate::switch!("BREP_NARY_SCOPED", true)
2565}
2566
2567fn nary_sequential_fallback_enabled() -> bool {
2568 crate::switch!("BREP_NARY_SEQUENTIAL_FALLBACK", true)
2569}
2570
2571fn boolean_operation_nary_arranged(
2572 operands: &[BrepSolid],
2573 operation: BooleanOperation,
2574 options: &BooleanOptions,
2575) -> Result<BrepSolid, KernelRefusal> {
2576 if operands.len() > 1 {
2577 if let Some(scaled) = WorkingScale::of(&operands.iter().collect::<Vec<_>>(), options)? {
2578 return scaled.run(
2579 || boolean_operation_nary_with_options(operands, operation, options),
2580 || boolean_operation_nary_with_options(&scaled.solids, operation, &scaled.options)
2581 .map_err(|error| scaled.refusal(error))
2582 .and_then(|solid| scaled.back(&solid)),
2583 );
2584 }
2585 }
2586 if operands.is_empty() {
2587 return Err(KernelRefusal::input(KernelStage::Collect, "operands", "boolean_operation_nary: no operands provided"));
2588 }
2589 if operands.len() == 1 {
2590 return Ok(operands[0].clone());
2591 }
2592 if operands.len() > nary_chunk() {
2593 return Err(KernelRefusal::input(KernelStage::Collect, "operands", "boolean_operation_nary: at most 255 operands supported"));
2594 }
2595 if let Some(aligned) = ball_align::align_balls_nary(operands, operation, options.tolerance) {
2598 return boolean_operation_nary_with_options(&aligned, operation, options);
2599 }
2600 let debug = std::env::var("BREP_DEBUG_BOOL").is_ok();
2601
2602 let mut policy = KernelTolerances::for_solid(&operands[0], options.tolerance);
2606 for operand in &operands[1..] {
2607 let candidate = KernelTolerances::for_solid(operand, options.tolerance);
2608 if candidate.sew_search > policy.sew_search {
2609 policy = candidate;
2610 }
2611 }
2612 policy.check().or_input(KernelStage::Collect, "tolerances")?;
2613 let tolerance = policy.model;
2614
2615 let nary_clock = NaryClock::start();
2618 let mut healed = operands.to_vec();
2619 let refit_scopes: Option<Vec<std::collections::HashSet<u64>>> = (nary_scoped_on() && crate::switch!("BREP_NARY_SCOPED_REFIT", true)).then(|| {
2624 let bounds: Vec<Option<crate::Aabb>> = operands
2625 .iter()
2626 .map(|operand| crate::fragment::bounded_carriers(operand).then(|| operand_bounds(operand)))
2627 .collect();
2628 operands
2629 .iter()
2630 .enumerate()
2631 .map(|(index, operand)| {
2632 operand
2633 .shells
2634 .iter()
2635 .flat_map(|shell| &shell.faces)
2636 .filter(|face| {
2637 !bounds.iter().enumerate().filter(|(other, _)| *other != index).all(|(_, other)| {
2638 other.as_ref().is_some_and(|other| crate::fragment::face_separated(face, *other, policy.sew_search))
2639 })
2640 })
2641 .map(|face| face.id)
2642 .collect()
2643 })
2644 .collect()
2645 });
2646 for (index, operand) in healed.iter_mut().enumerate() {
2647 crate::heal::heal_operands(operand, &policy)?;
2648 nary_clock.lap("nary.heal.operands_ms");
2649 match &refit_scopes {
2652 Some(scopes) => crate::heal::with_refit_face_scope(scopes[index].clone(), || crate::heal::refit_inherited_trims_reused(operand, &policy))?,
2653 None => crate::heal::refit_inherited_trims_reused(operand, &policy)?,
2654 }
2655 nary_clock.lap("nary.heal.refit_ms");
2656 normalize_operand_band_seams(operand)?;
2659 nary_clock.lap("nary.heal.seams_ms");
2660 }
2661
2662 let mut imprint_options = options.imprint.clone();
2664 imprint_options.tolerance = tolerance;
2665 let (imprint, cosurface) = build_nary_imprint(&healed, &imprint_options)?;
2666 nary_clock.lap("nary.imprint_ms");
2667
2668 let mut split = Vec::with_capacity(healed.len());
2670 for (index, operand) in healed.iter().enumerate() {
2671 split.push(apply_edge_splits(operand, index as u8, &imprint)?);
2672 }
2673 let mut fragments = Vec::with_capacity(split.len());
2674 for (index, solid) in split.iter().enumerate() {
2675 fragments.push(fragment_solid(solid, index as u8, &imprint)?);
2676 }
2677 nary_clock.lap("nary.split_fragment_ms");
2678
2679 let selected = select_fragments_nary(&fragments, &healed, operation, tolerance, debug)?;
2681 nary_clock.lap("nary.select_ms");
2682
2683 let solids: HashMap<u8, &BrepSolid> = split
2685 .iter()
2686 .enumerate()
2687 .map(|(index, solid)| (index as u8, solid))
2688 .collect();
2689 let solid = if nary_scoped_on() {
2690 let prepared: Vec<&BrepSolid> = healed.iter().collect();
2694 let touch = touch::TouchCensus::build_all(&prepared, &imprint, &cosurface);
2695 assemble::assemble_fragments_inherited_scoped(selected, &solids, &imprint, tolerance, &touch)?
2696 } else {
2697 assemble_fragments(selected, &solids, &imprint, tolerance)?
2698 };
2699 nary_clock.lap("nary.assemble_ms");
2700 let solid = if options.merge_coplanar_faces
2701 && std::env::var("BREP_COPLANAR_MERGE").as_deref() != Ok("0")
2702 {
2703 let merged = merge_same_surface_faces_excluding(
2704 &solid,
2705 tolerance,
2706 &options.keep_unmerged_name_substrs,
2707 )?;
2708 let merged = merge_curve_continuation_edges(&merged, tolerance).map_err(|refusal| KernelRefusal { stage: KernelStage::Validate, ..refusal })?;
2709 rejoin::rejoin_unless_referenced(merged, options, tolerance)
2710 } else {
2711 solid
2712 };
2713 nary_clock.lap("nary.merge_ms");
2714 let validation = solid.validate_detailed(&policy);
2715 nary_clock.lap("nary.validate_ms");
2716 if !validation.issues.is_empty() {
2717 return Err(KernelRefusal::new(
2718 RefusalClass::InvalidResultTopology { issues: validation.issues.len() as u32 },
2719 KernelStage::Validate,
2720 format!(
2721 "boolean_operation_nary: invalid result: {:?}",
2722 validation.issues
2723 )));
2724 }
2725 if debug {
2726 if let Ok(report) =
2727 crate::oracle::boolean_semantic_disagreement_nary(&healed, operation, &solid, 300)
2728 {
2729 if report.is_flagged() {
2730 eprintln!(
2731 "[oracle] n-ary semantic disagreement rate {:.4} ({} of {} decidable points); sample {:?}",
2732 report.disagreement_rate,
2733 report.disagreements.len(),
2734 report.considered,
2735 report.sample_disagreement()
2736 );
2737 }
2738 }
2739 }
2740 Ok(solid)
2741}
2742
2743fn attribute_to_tangent_node(error: KernelRefusal, nodes: &[Vec3]) -> KernelRefusal {
2774 let Some(node) = nodes.first() else {
2775 return error;
2776 };
2777 if !error.class.perturbation_eligible()
2778 || matches!(error.class, RefusalClass::TangentNodeSingularity)
2779 {
2780 return error;
2781 }
2782 if std::env::var("BREP_DEBUG_BOOL").is_ok() {
2783 eprintln!(
2784 "boolean: tear downstream of the tangent node at ({:.6},{:.6},{:.6}) attributed to it; the stage read: {}",
2785 node.x, node.y, node.z, error.message
2786 );
2787 }
2788 KernelRefusal::new(
2789 RefusalClass::TangentNodeSingularity,
2790 error.stage,
2791 format!(
2792 "boolean: unsupported singular/tangent-node surface intersection \
2793 at the tangent node at ({:.6},{:.6},{:.6}): the section through it did not \
2794 assemble into a closed shell",
2795 node.x, node.y, node.z
2796 ),
2797 )
2798}
2799
2800pub fn attribute_to_tangent_section(
2822 error: KernelRefusal,
2823 sections: &[crate::imprint::TangentSectionRecord],
2824 origins: &[FaceKey],
2825) -> KernelRefusal {
2826 if sections.is_empty()
2827 || !error.class.perturbation_eligible()
2828 || matches!(error.class, RefusalClass::TangentNodeSingularity)
2829 {
2830 return error;
2831 }
2832 let named = refusal_result_faces(&error.message)
2833 .into_iter()
2834 .filter_map(|id| origins.get(id.checked_sub(1)? as usize).copied())
2835 .collect::<Vec<FaceKey>>();
2836 let involving = |fallback: bool| {
2840 sections.iter().find(|section| {
2841 section.grazing.is_empty() != fallback && named.iter().any(|face| section.faces.contains(face))
2842 })
2843 };
2844 let Some(section) = involving(false).or_else(|| involving(true)) else {
2845 return error;
2846 };
2847 let at = |point: Vec3| {
2850 let shown = |value: f64| if value.abs() < 5e-7 { 0.0 } else { value };
2851 format!("({:.6},{:.6},{:.6})", shown(point.x), shown(point.y), shown(point.z))
2852 };
2853 let pierces = (!section.grazing.is_empty()).then(|| {
2859 let shown = section.grazing.len().min(4);
2860 let mut listed = section.grazing[..shown]
2861 .iter()
2862 .map(|(point, tangency)| format!("{} at |tan·n| = {tangency:.4}", at(*point)))
2863 .collect::<Vec<_>>()
2864 .join(", ");
2865 if section.grazing.len() > shown {
2866 listed.push_str(&format!(" and {} more", section.grazing.len() - shown));
2867 }
2868 listed
2869 });
2870 let pierce_only = section.pierce_only();
2871 let shape = if let (true, Some(pierces)) = (pierce_only, pierces.as_deref()) {
2872 format!(
2873 "cross at a grazing angle: a trim edge pierces the other carrier inside both \
2874 trims at {pierces}, below the marcher's start gate, and no transverse section was \
2875 marched between the pierces — a near-tangent crossing born on a tangent contact \
2876 (a third-order singularity) the imprint does not build yet"
2877 )
2878 } else if section.planar {
2879 format!(
2880 "touch along a tangent curve from {} to {} (length {:.6}, {} stations{}) which the \
2881 imprint does not build yet",
2882 at(section.start),
2883 at(section.end),
2884 section.length,
2885 section.stations,
2886 if section.closed { ", closed" } else { "" }
2887 )
2888 } else {
2889 format!(
2890 "touch along a curve through {} with neither carrier planar, a curved/curved \
2891 tangent contact the lane does not trace yet",
2892 at(section.start)
2893 )
2894 };
2895 let shape = match (pierce_only, pierces) {
2896 (false, Some(pierces)) => format!(
2897 "{shape}; a trim edge also pierces the other carrier inside both trims at {pierces}, \
2898 below the marcher's start gate, with no transverse section marched"
2899 ),
2900 _ => shape,
2901 };
2902 let involved = named
2903 .iter()
2904 .filter(|face| section.faces.contains(face))
2905 .map(|face| format!("{}/{}", face.operand, face.face_id))
2906 .collect::<Vec<_>>()
2907 .join(", ");
2908 KernelRefusal::new(
2909 RefusalClass::TangentNodeSingularity,
2910 error.stage,
2911 format!(
2912 "boolean: unsupported tangent-curve surface intersection between faces {}/{} and {}/{}: \
2913 the carriers {shape}; the refusal names face(s) {involved} the contact involves; {}",
2914 section.first.operand, section.first.face_id, section.second.operand, section.second.face_id,
2915 error.message
2916 ),
2917 )
2918}
2919
2920pub fn refusal_result_faces(message: &str) -> Vec<u64> {
2925 let mut ids = Vec::new();
2926 let digits_after = |text: &str| -> Option<u64> {
2927 let end = text.find(|c: char| !c.is_ascii_digit()).unwrap_or(text.len());
2928 text[..end].parse().ok()
2929 };
2930 for (index, _) in message.match_indices("face ") {
2931 if let Some(id) = digits_after(&message[index + "face ".len()..]) {
2932 ids.push(id);
2933 }
2934 }
2935 if let Some(start) = message.find("on faces [") {
2936 let rest = &message[start + "on faces [".len()..];
2937 let list = &rest[..rest.find(']').unwrap_or(rest.len())];
2938 for entry in list.split(", ") {
2939 let entry = entry.trim_start();
2940 if let Some(id) = digits_after(entry) {
2941 if entry[id.to_string().len()..].starts_with(" '") {
2942 ids.push(id);
2943 }
2944 }
2945 }
2946 }
2947 ids.sort_unstable();
2948 ids.dedup();
2949 ids
2950}
2951
2952pub fn boolean_operation_with_diagnostics(
2953 first: &BrepSolid,
2954 second: &BrepSolid,
2955 operation: BooleanOperation,
2956 options: &BooleanOptions,
2957) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
2958 if let Some(scaled) = WorkingScale::of(&[first, second], options)? {
2959 return scaled.run(
2960 || boolean_operation_with_diagnostics(first, second, operation, options),
2961 || {
2962 let mut outcome = boolean_operation_with_diagnostics(&scaled.solids[0], &scaled.solids[1], operation, &scaled.options)
2963 .map_err(|error| scaled.refusal(error))?;
2964 outcome.value = scaled.back(&outcome.value)?;
2965 outcome.diagnostics.count_n("working_scale.fired", 1);
2966 outcome.diagnostics.measure_max("working_scale.factor", scaled.factor);
2967 Ok(outcome)
2968 },
2969 );
2970 }
2971 let _account = profile::Scope::new("boolean.other");
2972 let (first_aligned, second_aligned) = ball_align::align_balls(first, second, operation, options.tolerance);
2975 let (first, second) = (first_aligned.as_ref(), second_aligned.as_ref());
2976 let closed_inputs = matches!(std::env::var("BREP_CLOSED_OPERAND_INPUT").as_deref(), Err(_) | Ok("1") | Ok("on"));
2977 if let (true, Some(later)) = (reseat::seam_reseat_enabled(), &options.seam_reseat_later_references) {
2978 let started = Instant::now();
2979 let (first, second) = reseat::reseat_tangent_seams(first, second, later, options.tolerance);
2980 profile_stage("seam_prepare_ms", started.elapsed().as_secs_f64() * 1000.0);
2981 return boolean_operation_with_diagnostics_impl(&first, &second, operation, options, closed_inputs).map(without_sliver_shells);
2982 }
2983 let cylinders = reseat::seam_reseat_cylinders_mode();
2986 if reseat::seam_reseat_enabled() && cylinders != crate::env_read::Mode::Off {
2987 let kinds = reseat::ContactKinds { planes: false, cylinders: true };
2988 let volume = |result: &Result<KernelOutcome<BrepSolid>, KernelRefusal>| {
2989 result.as_ref().ok().and_then(|outcome| crate::solid_mass_properties(&outcome.value).ok()).map(|mass| mass.volume)
2990 };
2991 if reseat::seam_reseat_retry_enabled() {
2992 let plain = boolean_operation_with_diagnostics_impl(first, second, operation, options, closed_inputs).map(without_sliver_shells);
2998 if plain.is_ok() {
2999 return plain;
3000 }
3001 let (reseated_first, reseated_second) = reseat::reseat_tangent_seams_of(first, second, &[], options.tolerance, kinds);
3002 let moved = matches!(reseated_first, std::borrow::Cow::Owned(_)) || matches!(reseated_second, std::borrow::Cow::Owned(_));
3003 if !moved {
3004 return plain;
3005 }
3006 let reseated = crate::imprint::driver::with_tangent_cylinder_filter(|| {
3007 boolean_operation_with_diagnostics_impl(&reseated_first, &reseated_second, operation, options, closed_inputs).map(without_sliver_shells)
3008 });
3009 if cylinders == crate::env_read::Mode::Check {
3010 eprintln!(
3011 "boolean.seam_reseat_cylinders check: plain refused, reseated retry {} volume {:?}",
3012 if reseated.is_ok() { "built" } else { "refused" },
3013 volume(&reseated)
3014 );
3015 return plain;
3016 }
3017 return match reseated {
3018 Ok(mut outcome) => {
3019 outcome.diagnostics.count_n("seam_reseat_cylinders.retry_built", 1);
3020 Ok(outcome)
3021 }
3022 Err(_) => plain,
3023 };
3024 }
3025 let (reseated_first, reseated_second) = reseat::reseat_tangent_seams_of(first, second, &[], options.tolerance, kinds);
3026 let moved = matches!(reseated_first, std::borrow::Cow::Owned(_)) || matches!(reseated_second, std::borrow::Cow::Owned(_));
3027 if moved {
3028 let reseated = boolean_operation_with_diagnostics_impl(&reseated_first, &reseated_second, operation, options, closed_inputs).map(without_sliver_shells);
3029 if cylinders == crate::env_read::Mode::On {
3030 return reseated;
3031 }
3032 let plain = boolean_operation_with_diagnostics_impl(first, second, operation, options, closed_inputs).map(without_sliver_shells);
3033 eprintln!(
3034 "boolean.seam_reseat_cylinders check: plain {} volume {:?}, reseated {} volume {:?}",
3035 if plain.is_ok() { "built" } else { "refused" },
3036 volume(&plain),
3037 if reseated.is_ok() { "built" } else { "refused" },
3038 volume(&reseated)
3039 );
3040 return plain;
3041 }
3042 }
3043 boolean_operation_with_diagnostics_impl(first, second, operation, options, closed_inputs).map(without_sliver_shells)
3044}
3045
3046fn without_sliver_shells(mut outcome: KernelOutcome<BrepSolid>) -> KernelOutcome<BrepSolid> {
3048 let dropped = drop_sliver_shells(&mut outcome.value);
3049 if dropped > 0 {
3050 outcome.diagnostics.count_n("sliver_shell.dropped", dropped as u64);
3051 }
3052 outcome
3053}
3054
3055pub fn boolean_operation_with_diagnostics_impl(
3056 first: &BrepSolid,
3057 second: &BrepSolid,
3058 operation: BooleanOperation,
3059 options: &BooleanOptions,
3060 closed_inputs: bool,
3061) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
3062 let _coedge_memo = crate::topology::CoedgeMemoScope::open(true);
3065 if matches!(operation, BooleanOperation::Intersect)
3068 && [first, second].iter().any(|body| body.kind == crate::BodyKind::Sheet)
3069 && match std::env::var("BREP_SHEET_TRIM").as_deref() {
3070 Ok("1") => true,
3071 Ok("0") => false,
3072 _ => options.sheet_trim,
3073 }
3074 {
3075 return sheet::trim(first, second, options);
3076 }
3077 if matches!(operation, BooleanOperation::Union | BooleanOperation::Subtract) {
3086 if let Some(operand) = [first, second]
3087 .iter()
3088 .position(|solid| solid.kind == crate::BodyKind::Sheet)
3089 {
3090 return Err(KernelRefusal::input(
3091 KernelStage::Collect,
3092 "sheet_operand",
3093 format!(
3094 "boolean: operand {operand} is a Sheet, which encloses no solid; union and \
3095 subtract of a sheet are refused; Intersect trims a Sheet by a Solid"
3096 ),
3097 ));
3098 }
3099 }
3100 let mut outcome = boolean_operation_with_diagnostics_core(first, second, operation, options)?;
3106 let closure_started = closed_inputs.then(Instant::now);
3107 if closed_inputs {
3108 for (operand, solid) in [first, second].into_iter().enumerate() {
3109 let open = one_use_edges(solid);
3110 if open > 0 {
3111 return Err(KernelRefusal::input(KernelStage::Collect, "operand_closure", format!(
3112 "boolean: operand {operand} is not a closed shell: {open} of its edges bound only one face, so its inside is undefined"
3113 )));
3114 }
3115 }
3116 }
3117 if let Some(started) = closure_started {
3118 let ms = started.elapsed().as_secs_f64() * 1000.0;
3119 profile_stage("operand_closure_ms", ms);
3120 outcome.diagnostics.measure_max("timing.operand_closure_ms", ms);
3121 }
3122 Ok(outcome)
3123}
3124
3125fn boolean_operation_with_diagnostics_core(
3126 first: &BrepSolid, second: &BrepSolid, operation: BooleanOperation, options: &BooleanOptions,
3127) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
3128
3129 if let Some(offset) = crate::recentre::control_offset_at_entry() {
3132 return boolean_operation_with_diagnostics_at_offset(first, second, operation, options, offset);
3133 }
3134 let mut bounds = operand_bounds(first);
3137 bounds.include(operand_bounds(second));
3138 if let Some(offset) = crate::recentre::guard_offset(bounds) {
3139 crate::recentre::profile_fired("boolean", offset, bounds);
3140 let mut outcome = boolean_translated(first, second, operation, options, offset, crate::recentre::EntryKind::Guard)?;
3141 outcome.diagnostics.count_n("recentre.fired", 1);
3142 outcome.diagnostics.measure_max("recentre.distance", offset.length());
3143 return Ok(outcome);
3144 }
3145 let mut tangent_nodes = Vec::new();
3146 let (mut outcome, soundness_candidates) =
3147 closed_form::run(first, second, operation, options, &mut tangent_nodes, boolean_pipeline)
3148 .map_err(|error| attribute_to_tangent_node(error, &tangent_nodes))?;
3149 let stage_started = Instant::now();
3162 let accepted = match &soundness_candidates {
3163 Some(candidates) => crate::accept_sound_against_scoped(&[first, second], outcome.value, "boolean", candidates),
3166 None => crate::accept_sound_against(&[first, second], outcome.value, "boolean"),
3167 };
3168 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
3169 profile_stage("soundness_ms", stage_ms);
3170 outcome.diagnostics.measure_max("timing.soundness_ms", stage_ms);
3171 outcome.value = accepted?;
3172 Ok(outcome)
3173}
3174
3175pub fn boolean_operation_with_diagnostics_at_offset(
3179 first: &BrepSolid,
3180 second: &BrepSolid,
3181 operation: BooleanOperation,
3182 options: &BooleanOptions,
3183 offset: Vec3,
3184) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
3185 boolean_translated(first, second, operation, options, offset, crate::recentre::EntryKind::Control)
3186}
3187
3188fn boolean_translated(
3190 first: &BrepSolid,
3191 second: &BrepSolid,
3192 operation: BooleanOperation,
3193 options: &BooleanOptions,
3194 offset: Vec3,
3195 kind: crate::recentre::EntryKind,
3196) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
3197 let _entry = crate::recentre::TranslatedEntry::open(kind);
3198 let translate = |solid: &BrepSolid, offset: Vec3| {
3199 crate::recentre::translate_solid(solid, offset).map_err(|message| {
3200 KernelRefusal::internal(
3201 KernelStage::Collect,
3202 "translation_control",
3203 format!("boolean: the translation control could not move an operand: {message}"),
3204 )
3205 })
3206 };
3207 let moved_first = translate(first, offset)?;
3208 let moved_second = translate(second, offset)?;
3209 let outcome = boolean_operation_with_diagnostics(&moved_first, &moved_second, operation, options)?;
3210 let value = translate(&outcome.value, offset.scale(-1.0))?;
3211 Ok(KernelOutcome { value, diagnostics: outcome.diagnostics })
3212}
3213
3214struct NaryClock(Option<std::cell::Cell<web_time::Instant>>);
3217
3218impl NaryClock {
3219 fn start() -> Self {
3220 Self(crate::profile::profile_enabled().then(|| std::cell::Cell::new(web_time::Instant::now())))
3221 }
3222
3223 fn lap(&self, code: &str) {
3224 if let Some(cell) = &self.0 {
3225 let now = web_time::Instant::now();
3226 profile_stage(code, (now - cell.get()).as_secs_f64() * 1000.0);
3227 cell.set(now);
3228 }
3229 }
3230}
3231
3232fn profile_stage(code: &str, ms: f64) {
3236 let row = match code {
3237 "heal_ms" => Some("boolean.operand_prepare"),
3238 "imprint_ms" => Some("boolean.imprint"),
3239 "edge_split_ms" => Some("boolean.edge_split"),
3240 "fragment_ms" => Some("boolean.fragment"),
3241 "select_ms" => Some("boolean.select"),
3242 "assemble_ms" => Some("boolean.assemble"),
3243 "face_merge_ms" => Some("boolean.face_merge"),
3244 "soundness_ms" => Some("boolean.soundness"),
3245 "operand_closure_ms" => Some("boolean.operand_closure"),
3246 "seam_prepare_ms" => Some("boolean.seam_prepare"),
3247 "final_validate_ms" => Some("boolean.final_validate"),
3248 _ => None,
3249 };
3250 if let Some(row) = row { profile::record(row, ms); }
3251 if crate::profile::profile_enabled() {
3252 profile_line!("boolean.{code}={ms:.2}");
3253 }
3254}
3255
3256struct BooleanStageDump {
3261 directory: std::path::PathBuf,
3262 serial: usize,
3263}
3264
3265impl BooleanStageDump {
3266 fn open() -> Option<Self> {
3267 static SERIAL: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
3268 let directory = std::env::var("BREP_BOOLEAN_DUMP").ok().filter(|value| !value.is_empty())?;
3269 let serial = SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3270 Some(Self { directory: directory.into(), serial })
3271 }
3272
3273 fn write<T: Serialize + ?Sized>(&self, stage: &str, value: &T) {
3274 let path = self.directory.join(format!("{:03}-{stage}.json", self.serial));
3275 match serde_json::to_string(value) {
3276 Ok(text) => {
3277 if let Err(error) = std::fs::write(&path, text) {
3278 eprintln!("BREP_BOOLEAN_DUMP {}: {error}", path.display());
3279 }
3280 }
3281 Err(error) => eprintln!("BREP_BOOLEAN_DUMP {stage}: {error}"),
3282 }
3283 }
3284}
3285
3286pub fn boolean_policy(
3288 first: &BrepSolid,
3289 second: &BrepSolid,
3290 options: &BooleanOptions,
3291) -> Result<KernelTolerances, KernelRefusal> {
3292 let policy = options
3293 .tolerances
3294 .unwrap_or_else(|| KernelTolerances::for_pair(first, second, options.tolerance));
3295 policy.check().or_input(KernelStage::Collect, "tolerances")?;
3296 Ok(policy)
3297}
3298
3299fn refuse_oversized_projection_tables(first: &BrepSolid, second: &BrepSolid) -> Result<(), KernelRefusal> {
3312 let limit = crate::PROJECTION_TABLES_LIMIT;
3313 let mut largest: Option<(u64, &crate::NurbsSurface)> = None;
3314 let mut over = 0usize;
3315 for face in [first, second].into_iter().flat_map(|solid| solid.shells.iter()).flat_map(|shell| shell.faces.iter()) {
3316 let bytes = crate::projection_tables_bytes(&face.surface);
3317 over += usize::from(bytes > limit);
3318 if bytes >= limit / 16 && largest.is_none_or(|(most, _)| bytes > most) {
3319 largest = Some((bytes, &face.surface));
3320 }
3321 }
3322 let Some((most, surface)) = largest else { return Ok(()) };
3323 let spans = |knots: &[f64]| knots.windows(2).filter(|pair| pair[1] > pair[0]).count();
3324 let (spans_u, spans_v) = (spans(&surface.knots_u), spans(&surface.knots_v));
3325 if std::env::var_os("BREP_DEBUG_PROJECTION_TABLES").is_some() {
3326 eprintln!("boolean: largest projection tables {} MB (limit {} MB), a surface of {spans_u} x {spans_v} spans; {over} faces over the limit", most >> 20, limit >> 20);
3327 }
3328 if over == 0 {
3329 return Ok(());
3330 }
3331 Err(KernelRefusal::unsupported(
3332 KernelStage::Collect,
3333 "operand_surface_projection_tables",
3334 format!(
3335 "{over} operand faces lie on surfaces too finely divided to boolean: the largest, of {spans_u} x {spans_v} knot spans, takes about {} MB of projection tables (limit {} MB)",
3336 most >> 20,
3337 limit >> 20
3338 ),
3339 ))
3340}
3341
3342fn prepared_operands(
3345 first: &BrepSolid,
3346 second: &BrepSolid,
3347 policy: &KernelTolerances,
3348) -> Result<(BrepSolid, BrepSolid), KernelRefusal> {
3349 refuse_oversized_projection_tables(first, second)?;
3358 let stage_started = Instant::now();
3359 let mut first_owned = first.clone();
3360 let mut second_owned = second.clone();
3361 crate::heal::heal_operands(&mut first_owned, policy)?;
3362 crate::heal::heal_operands(&mut second_owned, policy)?;
3363 profile_stage("heal.operands_ms", stage_started.elapsed().as_secs_f64() * 1_000.0);
3364 let refit_started = Instant::now();
3368 crate::heal::refit_inherited_trims_reused(&mut first_owned, policy)?;
3369 crate::heal::refit_inherited_trims_reused(&mut second_owned, policy)?;
3370 profile_stage("heal.refit_ms", refit_started.elapsed().as_secs_f64() * 1_000.0);
3371 if crate::profile::profile_enabled() {
3372 let (hits, misses) = crate::reading_memo::counts();
3373 profile_line!("boolean.reading_memo hits={hits} misses={misses}");
3374 let (served, stored) = crate::heal::refit_memo_counts_served_stored();
3375 profile_line!("boolean.refit_memo served={served} stored={stored}");
3376 let (served, stored, mismatches) = crate::heal::claim_record_memo_counts();
3377 profile_line!("boolean.claim_record_memo served={served} stored={stored} check_mismatches={mismatches}");
3378 }
3379 profile_stage("heal_ms", stage_started.elapsed().as_secs_f64() * 1_000.0);
3380 normalize_operand_band_seams(&mut first_owned)?;
3385 normalize_operand_band_seams(&mut second_owned)?;
3386 Ok((first_owned, second_owned))
3387}
3388
3389fn boolean_imprint_options(options: &BooleanOptions, tolerance: f64) -> ImprintOptions {
3390 let mut imprint_options = options.imprint.clone();
3391 imprint_options.tolerance = tolerance;
3392 imprint_options
3393}
3394
3395pub fn boolean_split_operands(
3405 first: &BrepSolid,
3406 second: &BrepSolid,
3407 options: &BooleanOptions,
3408) -> Result<(BrepSolid, BrepSolid), KernelRefusal> {
3409 if let Some(scaled) = WorkingScale::of(&[first, second], options)? {
3410 return scaled.run(
3411 || boolean_split_operands(first, second, options),
3412 || {
3413 let (split_first, split_second) = boolean_split_operands(&scaled.solids[0], &scaled.solids[1], &scaled.options)
3414 .map_err(|error| scaled.refusal(error))?;
3415 Ok((scaled.back(&split_first)?, scaled.back(&split_second)?))
3416 },
3417 );
3418 }
3419 let policy = boolean_policy(first, second, options)?;
3420 let (first, second) = prepared_operands(first, second, &policy)?;
3421 let imprint = build_imprints(&first, &second, &boolean_imprint_options(options, policy.model))?;
3422 let (split_first, _) = apply_edge_splits_with_map(&first, 0, &imprint)?;
3423 let (split_second, _) = apply_edge_splits_with_map(&second, 1, &imprint)?;
3424 Ok((split_first, split_second))
3425}
3426
3427fn operand_bounds(solid: &BrepSolid) -> crate::Aabb {
3431 let mut bounds = crate::Aabb::from_points(solid.vertices.iter().map(|vertex| vertex.point));
3432 for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
3433 match crate::Aabb::from_surface_controls(&face.surface) {
3434 Ok(face_bounds) => bounds.include(face_bounds),
3435 Err(_) => {
3436 return crate::Aabb {
3437 minimum: Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY),
3438 maximum: Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY),
3439 }
3440 }
3441 }
3442 }
3443 bounds
3444}
3445
3446fn line_or_point_contact(first: &BrepSolid, second: &BrepSolid, bounds: [crate::Aabb; 2]) -> bool {
3452 apart_axes(bounds) >= 2 && plain_hull_solid(first) && plain_hull_solid(second)
3453}
3454
3455fn boxes_share_no_interior(first: &BrepSolid, second: &BrepSolid, bounds: [crate::Aabb; 2]) -> bool {
3458 apart_axes(bounds) >= 1 && plain_hull_solid(first) && plain_hull_solid(second)
3459}
3460
3461fn apart_axes([a, b]: [crate::Aabb; 2]) -> usize {
3463 let apart = |a_min: f64, a_max: f64, b_min: f64, b_max: f64| a_max <= b_min || b_max <= a_min;
3464 [
3465 apart(a.minimum.x, a.maximum.x, b.minimum.x, b.maximum.x),
3466 apart(a.minimum.y, a.maximum.y, b.minimum.y, b.maximum.y),
3467 apart(a.minimum.z, a.maximum.z, b.minimum.z, b.maximum.z),
3468 ]
3469 .into_iter()
3470 .filter(|&apart| apart)
3471 .count()
3472}
3473
3474fn plain_hull_solid(solid: &BrepSolid) -> bool {
3476 solid.kind == crate::BodyKind::Solid
3477 && solid.cells.is_empty()
3478 && solid.shells.iter().flat_map(|shell| &shell.faces).all(|face| {
3479 face.surface.control_points.iter().flatten().all(|control| control.w > 0.0 && control.w.is_finite())
3480 })
3481}
3482
3483fn scope_proved_apart_on() -> bool {
3487 switch!(live "BREP_SCOPE_PROVED_APART", true)
3488}
3489
3490fn soundness_candidates(
3505 solid: &BrepSolid,
3506 scope: &AssemblyScope,
3507 bounds: [crate::Aabb; 2],
3508 band: f64,
3509 unproved: Option<&HashSet<crate::imprint::FaceKey>>,
3510) -> HashSet<u64> {
3511 let mut candidates = HashSet::default();
3512 for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
3513 if scope.examined.contains(&face.id) {
3514 candidates.insert(face.id);
3515 continue;
3516 }
3517 let Some(&operand) = scope.operand_of.get(&face.id) else {
3518 candidates.insert(face.id);
3519 continue;
3520 };
3521 let other = bounds[usize::from(operand == 0)];
3522 match crate::Aabb::from_surface_controls(&face.surface) {
3523 Ok(face_bounds) if !face_bounds.intersects(other, band) => {}
3524 _ => {
3525 let proved_clear = unproved.is_some_and(|unproved| {
3526 scope.source_of.get(&face.id).is_some_and(|key| !unproved.contains(key))
3527 });
3528 if !proved_clear {
3529 candidates.insert(face.id);
3530 }
3531 }
3532 }
3533 }
3534 candidates
3535}
3536
3537
3538fn touching_empty_enabled() -> bool {
3546 switch!("BREP_TOUCHING_EMPTY", true)
3547}
3548
3549thread_local! {
3550 static TOUCHING_PROOF: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
3553}
3554
3555fn hair_deep_overlap(first: &BrepSolid, second: &BrepSolid, tolerance: f64) -> bool {
3562 use crate::AnalyticSurface as A;
3563 fn faces(solid: &BrepSolid) -> Vec<(&crate::AnalyticSurface, crate::spatial::Aabb, &crate::NurbsSurface, &crate::FaceRecord)> {
3564 solid
3565 .shells
3566 .iter()
3567 .flat_map(|shell| &shell.faces)
3568 .filter_map(|face| Some((face.surface.analytic()?, crate::Aabb::from_surface_controls(&face.surface).ok()?, &face.surface, face)))
3569 .collect()
3570 }
3571 let along = |surface: &crate::NurbsSurface, axis: Vec3| {
3573 surface.control_points.iter().flatten().filter_map(|control| control.point().ok()).fold((f64::INFINITY, f64::NEG_INFINITY), |(low, high), point| {
3574 let at = point.dot(axis);
3575 (low.min(at), high.max(at))
3576 })
3577 };
3578 let crossing = |distance: f64, ra: f64, rb: f64| {
3579 let outer = ra + rb - distance;
3580 let nested = distance - (ra - rb).abs();
3581 outer > tolerance && nested > tolerance
3582 };
3583 let boxes_overlap = |a: &crate::spatial::Aabb, b: &crate::spatial::Aabb| {
3584 (a.maximum.x.min(b.maximum.x) - a.minimum.x.max(b.minimum.x)) > tolerance
3585 && (a.maximum.y.min(b.maximum.y) - a.minimum.y.max(b.minimum.y)) > tolerance
3586 && (a.maximum.z.min(b.maximum.z) - a.minimum.z.max(b.minimum.z)) > tolerance
3587 };
3588 for (a, box_a, surface_a, face_a) in faces(first) {
3589 for (b, box_b, surface_b, face_b) in faces(second) {
3590 if !boxes_overlap(&box_a, &box_b) {
3591 continue;
3592 }
3593 match (a, b) {
3594 (A::RuledRevolution { frame: fa, rho0: a0, rho1: a1, .. }, A::RuledRevolution { frame: fb, rho0: b0, rho1: b1, .. })
3595 if (a0 - a1).abs() <= tolerance && (b0 - b1).abs() <= tolerance =>
3596 {
3597 let offset = fb.origin.sub(fa.origin);
3598 let normal = fa.axis.cross(fb.axis);
3599 if normal.length() <= 1e-12 {
3602 let (low_a, high_a) = along(surface_a, fa.axis);
3603 let (low_b, high_b) = along(surface_b, fa.axis);
3604 if high_a.min(high_b) - low_a.max(low_b) <= tolerance {
3605 continue;
3606 }
3607 }
3608 let apart = if normal.length() <= 1e-12 {
3609 offset.sub(fa.axis.scale(offset.dot(fa.axis))).length()
3610 } else {
3611 offset.dot(normal).abs() / normal.length()
3612 };
3613 if crossing(apart, a0.abs(), b0.abs()) {
3614 return true;
3615 }
3616 }
3617 (A::Sphere { frame: fa, radius: ra }, A::Sphere { frame: fb, radius: rb }) => {
3618 if crossing(fb.origin.sub(fa.origin).length(), *ra, *rb)
3623 && !circle_off_face(face_a, first, (fa.origin, *ra), (fb.origin, *rb), tolerance)
3624 && !circle_off_face(face_b, second, (fb.origin, *rb), (fa.origin, *ra), tolerance)
3625 {
3626 return true;
3627 }
3628 }
3629 _ => {}
3630 }
3631 }
3632 }
3633 false
3634}
3635
3636fn circle_off_face(face: &crate::FaceRecord, solid: &BrepSolid, own: (Vec3, f64), other: (Vec3, f64), tolerance: f64) -> bool {
3644 use crate::classification::{parameter_point_in_face, PolygonClass};
3645 let ((ca, ra), (cb, rb)) = (own, other);
3646 if face.loops.iter().all(|lp| lp.coedges.is_empty()) {
3647 return false;
3648 }
3649 fn clear(curve: &crate::NurbsCurve, depth: u32, centre: Vec3, radius: f64, tolerance: f64) -> bool {
3654 let points: Option<Vec<Vec3>> = curve.control_points.iter().map(|control| if control.w > 0.0 { control.point().ok() } else { None }).collect();
3655 let Some(points) = points else { return false };
3656 if points.iter().all(|point| point.sub(centre).length() < radius - tolerance) {
3657 return true;
3658 }
3659 let (mut low, mut high) = (Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY), Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY));
3660 for point in &points {
3661 low = Vec3::new(low.x.min(point.x), low.y.min(point.y), low.z.min(point.z));
3662 high = Vec3::new(high.x.max(point.x), high.y.max(point.y), high.z.max(point.z));
3663 }
3664 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));
3665 if near.sub(centre).length() > radius + tolerance {
3666 return true;
3667 }
3668 if depth == 0 {
3669 return false;
3670 }
3671 let Ok([t0, t1]) = curve.domain() else { return false };
3672 match curve.split(0.5 * (t0 + t1)) {
3673 Ok((left, right)) => clear(&left, depth - 1, centre, radius, tolerance) && clear(&right, depth - 1, centre, radius, tolerance),
3674 Err(_) => false,
3675 }
3676 }
3677 for coedge in face.loops.iter().flat_map(|lp| &lp.coedges) {
3678 let Some(edge) = solid.edges.iter().find(|edge| edge.id == coedge.edge_id) else { return false };
3679 let Ok([d0, d1]) = edge.curve.domain() else { return false };
3680 let mut span = edge.curve.clone();
3682 if edge.t1 < d1 {
3683 match span.split(edge.t1) {
3684 Ok((left, _)) => span = left,
3685 Err(_) => return false,
3686 }
3687 }
3688 if edge.t0 > d0 {
3689 match span.split(edge.t0) {
3690 Ok((_, right)) => span = right,
3691 Err(_) => return false,
3692 }
3693 }
3694 if !clear(&span, 10, cb, rb, tolerance) {
3695 return false;
3696 }
3697 }
3698 let axis = cb.sub(ca);
3699 let distance = axis.length();
3700 let Ok(n) = axis.normalized() else { return false };
3701 let along = (distance * distance + ra * ra - rb * rb) / (2.0 * distance);
3702 let across = ra * ra - along * along;
3703 let Ok(side) = n.perpendicular() else { return false };
3704 if !(across > 0.0) {
3705 return false;
3706 }
3707 let point = ca.add(n.scale(along)).add(side.scale(across.sqrt()));
3708 let Ok(projection) = crate::project_point_to_surface(&face.surface, point) else { return false };
3709 matches!(parameter_point_in_face(face, crate::Vec2 { x: projection.u, y: projection.v }, 1e-9), Ok(PolygonClass::Outside))
3710}
3711
3712
3713fn empty_solid() -> BrepSolid {
3715 BrepSolid {
3716 mass_properties_cache: Default::default(),
3717 cells: Default::default(),
3718 id: 0,
3719 vertices: Vec::new(),
3720 edges: Vec::new(),
3721 shells: Vec::new(),
3722 genus: 0,
3723 kind: crate::BodyKind::Solid,
3724 }
3725}
3726
3727fn concatenate_disjoint(first: &BrepSolid, second: &BrepSolid) -> BrepSolid {
3733 let mut vertices = Vec::new();
3734 let mut edges = Vec::new();
3735 let mut shells = Vec::new();
3736 let mut used_face_names = HashSet::<String>::default();
3737 let (mut next_face_id, mut next_loop_id, mut next_coedge_id) = (1u64, 1u64, 1u64);
3738 for operand in [first, second] {
3739 let vertex_base = vertices.len() as u64;
3740 let edge_base = edges.len() as u64;
3741 let mut vertex_ids: HashMap<u64, u64> = HashMap::default();
3742 for (index, vertex) in operand.vertices.iter().enumerate() {
3743 let id = vertex_base + index as u64 + 1;
3744 vertex_ids.insert(vertex.id, id);
3745 vertices.push(VertexRecord { id, point: vertex.point });
3746 }
3747 let mut edge_ids: HashMap<u64, u64> = HashMap::default();
3748 for (index, edge) in operand.edges.iter().enumerate() {
3749 let id = edge_base + index as u64 + 1;
3750 edge_ids.insert(edge.id, id);
3751 edges.push(EdgeRecord {
3752 id,
3753 curve: edge.curve.clone(),
3754 t0: edge.t0,
3755 t1: edge.t1,
3756 start_vertex_id: vertex_ids.get(&edge.start_vertex_id).copied().unwrap_or(edge.start_vertex_id),
3757 end_vertex_id: vertex_ids.get(&edge.end_vertex_id).copied().unwrap_or(edge.end_vertex_id),
3758 degenerate: edge.degenerate,
3759 name: edge.name.clone(),
3760 });
3761 }
3762 for shell in &operand.shells {
3763 let mut faces = Vec::with_capacity(shell.faces.len());
3764 for face in &shell.faces {
3765 let loops = face
3766 .loops
3767 .iter()
3768 .map(|loop_record| {
3769 let coedges = loop_record
3770 .coedges
3771 .iter()
3772 .map(|coedge| {
3773 let id = next_coedge_id;
3774 next_coedge_id += 1;
3775 CoedgeRecord {
3776 id,
3777 edge_id: edge_ids.get(&coedge.edge_id).copied().unwrap_or(coedge.edge_id),
3778 forward: coedge.forward,
3779 pcurve: coedge.pcurve.clone(),
3780 }
3781 })
3782 .collect();
3783 let id = next_loop_id;
3784 next_loop_id += 1;
3785 LoopRecord { id, coedges }
3786 })
3787 .collect();
3788 let name = face.name.clone().map(|base| {
3789 if used_face_names.insert(base.clone()) {
3790 base
3791 } else {
3792 let mut suffix = 1usize;
3793 loop {
3794 let candidate = format!("{base}_{suffix}");
3795 if used_face_names.insert(candidate.clone()) {
3796 break candidate;
3797 }
3798 suffix += 1;
3799 }
3800 }
3801 });
3802 faces.push(FaceRecord {
3803 id: next_face_id,
3804 surface: face.surface.clone(),
3805 same_sense: face.same_sense,
3806 loops,
3807 name,
3808 });
3809 next_face_id += 1;
3810 }
3811 shells.push(ShellRecord { id: shells.len() as u64 + 1, faces });
3812 }
3813 }
3814 BrepSolid {
3815 mass_properties_cache: Default::default(),
3816 cells: Default::default(),
3817 id: 1,
3818 vertices,
3819 edges,
3820 shells,
3821 genus: first.genus + second.genus,
3822 kind: crate::BodyKind::Solid,
3823 }
3824}
3825
3826fn boolean_pipeline(
3829 first: &BrepSolid,
3830 second: &BrepSolid,
3831 operation: BooleanOperation,
3832 options: &BooleanOptions,
3833 tangent_nodes: &mut Vec<Vec3>,
3834) -> Result<(KernelOutcome<BrepSolid>, Option<HashSet<u64>>), KernelRefusal> {
3835 let _work = crate::imprint::work_profile::Scope::open("boolean");
3836 let replaced_operands = operand_state::replace_operands(first, second, operation, options);
3837 let (first, second) = match &replaced_operands {
3838 Some((first, second)) => (first, second),
3839 None => (first, second),
3840 };
3841 let policy = boolean_policy(first, second, options)?;
3842 let tolerance = policy.model;
3843 let bounds = [operand_bounds(first), operand_bounds(second)];
3858 let disjoint = disjoint_fast_path(options) && !bounds[0].intersects(bounds[1], policy.sew_search);
3859 let contact = !disjoint
3860 && contact_fast_path(options)
3861 && options.seam_reseat_later_references.is_some()
3862 && line_or_point_contact(first, second, bounds);
3863 let contact = contact
3868 || (!disjoint
3869 && matches!(operation, BooleanOperation::Intersect)
3870 && contact_fast_path(options)
3871 && boxes_share_no_interior(first, second, bounds));
3872 if disjoint || contact {
3873 let operation_started = Instant::now();
3874 let mut diagnostics = KernelDiagnostics::default();
3875 diagnostics.count_n(
3876 "collect.faces",
3877 first.shells.iter().chain(&second.shells).map(|shell| shell.faces.len() as u64).sum(),
3878 );
3879 diagnostics.count(if contact { "boolean.contact_fast_path" } else { "boolean.disjoint_fast_path" });
3880 diagnostics.measure_max("tolerance.model", policy.model);
3881 diagnostics.measure_max("tolerance.sew_search", policy.sew_search);
3882 let value = match operation {
3883 BooleanOperation::Union => concatenate_disjoint(first, second),
3884 BooleanOperation::Subtract => first.clone(),
3885 BooleanOperation::Intersect => {
3886 diagnostics.event(
3887 DiagnosticSeverity::Info,
3888 KernelStage::Select,
3889 "boolean.empty_result",
3890 format!("{operation:?} of witnessed-non-overlapping operands is empty"),
3891 );
3892 empty_solid()
3893 }
3894 };
3895 let stage_ms = operation_started.elapsed().as_secs_f64() * 1_000.0;
3896 profile_stage("disjoint_fast_path_ms", stage_ms);
3897 diagnostics.measure_max("timing.total_ms", stage_ms);
3898 return Ok((KernelOutcome { value, diagnostics }, Some(HashSet::default())));
3899 }
3900 let heal_started = Instant::now();
3901 let (first_owned, second_owned) = prepared_operands(first, second, &policy)?;
3902 let heal_ms = heal_started.elapsed().as_secs_f64() * 1_000.0;
3903 let first = &first_owned;
3904 let second = &second_owned;
3905
3906 let mut diagnostics = KernelDiagnostics::default();
3907 diagnostics.measure_max("timing.heal_ms", heal_ms);
3910 let fit_scope = crate::PcurveFitScope::open();
3915 let polyline_scope = crate::PolylineFitScope::open();
3919 let operation_started = Instant::now();
3920 diagnostics.count_n(
3921 "collect.faces",
3922 first
3923 .shells
3924 .iter()
3925 .chain(&second.shells)
3926 .map(|shell| shell.faces.len() as u64)
3927 .sum(),
3928 );
3929 diagnostics.measure_max("tolerance.model", policy.model);
3930 diagnostics.measure_max("tolerance.sew_search", policy.sew_search);
3931
3932 let imprint_options = boolean_imprint_options(options, tolerance);
3933 let stage_started = Instant::now();
3934 let imprint = build_imprints(first, second, &imprint_options)?;
3935 tangent_nodes.extend_from_slice(&imprint.tangent_nodes);
3936 if std::env::var("BREP_DEBUG_BOOL").is_ok() {
3937 for piece in &imprint.pieces {
3938 let start = piece.curve.evaluate(piece.t0);
3939 let end = piece.curve.evaluate(piece.t1);
3940 eprintln!(
3941 "piece {} supports={:?} t=[{:.6},{:.6}] start={:?} end={:?}",
3942 piece.id, piece.support_faces, piece.t0, piece.t1, start, end
3943 );
3944 }
3945 for entry in &imprint.by_face {
3946 eprintln!(
3947 "by_face operand={} face={} pieces={:?}",
3948 entry.operand, entry.face_id, entry.piece_ids
3949 );
3950 }
3951 for split in &imprint.edge_splits {
3952 eprintln!(
3953 "edge_split operand={} edge={} params={:?}",
3954 split.operand, split.edge_id, split.parameters
3955 );
3956 }
3957 }
3958 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
3959 profile_stage("imprint_ms", stage_ms);
3960 diagnostics.measure_max("timing.imprint_ms", stage_ms);
3961 diagnostics.count_n("intersect.pieces", imprint.pieces.len() as u64);
3962 diagnostics.count_n("intersect.vertices", imprint.vertices.len() as u64);
3963 diagnostics.count_n("intersect.edge_splits", imprint.edge_splits.len() as u64);
3964 let (march_swap_rescues, clip_swap_rescues) = crate::imprint::take_rescue_firings();
3965 diagnostics.count_n("intersect.march_swap_rescue", march_swap_rescues);
3966 diagnostics.count_n("intersect.clip_swap_rescue", clip_swap_rescues);
3967 let touch = TouchCensus::build([first, second], &imprint);
3968 touch.report(&mut diagnostics);
3969 let stage_started = Instant::now();
3970 let (split_first, split_map_first) = apply_edge_splits_with_map(first, 0, &imprint)?;
3971 let (split_second, split_map_second) = apply_edge_splits_with_map(second, 1, &imprint)?;
3972 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
3973 profile_stage("edge_split_ms", stage_ms);
3974 diagnostics.measure_max("timing.edge_split_ms", stage_ms);
3975 let stage_started = Instant::now();
3976 crate::classification::classify_profile_begin();
3977 let fragments_a = crate::fragment::fragment_solid_against(&split_first, 0, &imprint, crate::fragment::bounded_carriers(second).then_some((bounds[1], policy.sew_search)))?;
3978 let fragments_b = crate::fragment::fragment_solid_against(&split_second, 1, &imprint, crate::fragment::bounded_carriers(first).then_some((bounds[0], policy.sew_search)))?;
3979 crate::classification::classify_profile_report("fragment");
3980 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
3981 profile_stage("fragment_ms", stage_ms);
3982 diagnostics.measure_max("timing.fragment_ms", stage_ms);
3983 diagnostics.count_n(
3984 "fragment.candidates",
3985 (fragments_a.len() + fragments_b.len()) as u64,
3986 );
3987 touch.report_fragments(&[&fragments_a, &fragments_b], &mut diagnostics);
3988 let a_surface_samples: Vec<Vec3> = fragments_a
3993 .iter()
3994 .flat_map(|fragment| {
3995 std::iter::once(fragment.test_point).chain(fragment.extra_test_points.iter().copied())
3996 })
3997 .collect();
3998 let b_surface_samples: Vec<Vec3> = fragments_b
3999 .iter()
4000 .flat_map(|fragment| {
4001 std::iter::once(fragment.test_point).chain(fragment.extra_test_points.iter().copied())
4002 })
4003 .collect();
4004 let stage_started = Instant::now();
4005 let mut barrier_edges: HashSet<(u8, u64)> = imprint
4006 .pieces
4007 .iter()
4008 .filter_map(|piece| piece.shared_edge.map(|(operand, edge_id, _)| (operand, edge_id)))
4009 .collect();
4010 barrier_edges.extend(imprint.barrier_edges.iter().copied());
4011 for (operand, split_map) in [(0u8, &split_map_first), (1u8, &split_map_second)] {
4017 let minted: Vec<(u8, u64)> = barrier_edges
4018 .iter()
4019 .filter(|(barrier_operand, _)| *barrier_operand == operand)
4020 .filter_map(|(_, edge_id)| split_map.get(edge_id))
4021 .flat_map(|sub_ids| sub_ids.iter().map(|sub_id| (operand, *sub_id)))
4022 .collect();
4023 barrier_edges.extend(minted);
4024 }
4025 crate::classification::classify_profile_begin();
4026 let coincident = coincident_pairs(
4027 &fragments_a,
4028 &fragments_b,
4029 first,
4030 second,
4031 &imprint.cosurface_pairs,
4032 tolerance,
4033 )?;
4034 let sector_mode = sector::sector_mode(options);
4035 let mut select_census = sector::SelectCensus::default();
4036 let mut selected = select_fragments(
4037 fragments_a,
4038 fragments_b,
4039 first,
4040 second,
4041 operation,
4042 tolerance,
4043 &barrier_edges,
4044 &imprint,
4045 &coincident,
4046 sector_mode,
4047 &mut select_census,
4048 )?;
4049 let resewn = resew_coincident_rims(
4050 &mut selected,
4051 [&split_first, &split_second],
4052 [first, second],
4053 &imprint.cosurface_pairs,
4054 operation,
4055 tolerance,
4056 )?;
4057 diagnostics.count_n("select.coincident_pairs", coincident.len() as u64);
4058 diagnostics.count_n("select.rims_resewn", resewn as u64);
4059 crate::classification::classify_profile_report("select");
4060 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
4061 profile_stage("select_ms", stage_ms);
4062 diagnostics.measure_max("timing.select_ms", stage_ms);
4063 diagnostics.count_n("select.fragments", selected.len() as u64);
4064 diagnostics.count_n("select.sector_eligible", select_census.eligible);
4066 diagnostics.count_n("select.sector_primary", select_census.sector_primary);
4067 diagnostics.count_n("select.sector_fallback", select_census.sector_fallback);
4068 diagnostics.count_n("select.sector_disagree", select_census.disagree);
4069 diagnostics.count_n("select.ray_casts", select_census.ray_casts);
4070 diagnostics.count_n("select.on_votes", select_census.on_votes);
4071 diagnostics.count_n("select.overturns", select_census.overturns);
4072 if sector_mode != sector::SectorMode::Off || std::env::var_os("BREP_SECTOR_CENSUS").is_some() {
4073 sector::sector_census_line(|| {
4074 format!(
4075 "selection mode={sector_mode:?} select_ms={stage_ms:.3} selected={} eligible={} primary={} fallback={} disagree={} ray_casts={} on_votes={} overturns={}",
4076 selected.len(),
4077 select_census.eligible,
4078 select_census.sector_primary,
4079 select_census.sector_fallback,
4080 select_census.disagree,
4081 select_census.ray_casts,
4082 select_census.on_votes,
4083 select_census.overturns
4084 )
4085 });
4086 }
4087 if selected.is_empty()
4109 && !imprint.section_evidence
4110 && std::env::var("BREP_EMPTY_BOOLEAN").as_deref() != Ok("0")
4111 {
4112 let strictly_inside = |samples: &[Vec3], other: &BrepSolid| -> Result<bool, KernelRefusal> {
4113 for &sample in samples {
4114 if classify_point(sample, other, tolerance).or_refuse(KernelStage::Validate, "classify_point")?.class == PointClass::In {
4115 return Ok(true);
4116 }
4117 }
4118 Ok(false)
4119 };
4120 let outside_witness = |samples: &[Vec3], other: &BrepSolid| -> Result<bool, KernelRefusal> {
4121 for &sample in samples {
4122 if classify_point(sample, other, tolerance).or_refuse(KernelStage::Validate, "classify_point")?.class == PointClass::Out {
4123 return Ok(true);
4124 }
4125 }
4126 Ok(false)
4127 };
4128 let legitimate = match operation {
4129 BooleanOperation::Intersect => {
4130 !strictly_inside(&a_surface_samples, second)?
4131 && !strictly_inside(&b_surface_samples, first)?
4132 }
4133 BooleanOperation::Subtract => !outside_witness(&a_surface_samples, second)?,
4134 BooleanOperation::Union => false,
4135 };
4136 if legitimate {
4137 diagnostics.event(
4138 DiagnosticSeverity::Info,
4139 KernelStage::Select,
4140 "boolean.empty_result",
4141 format!("{operation:?} of witnessed-non-overlapping operands is empty"),
4142 );
4143 fit_scope.close().report_into(&mut diagnostics);
4144 polyline_scope.close().report_into(&mut diagnostics);
4145 diagnostics.measure_max(
4146 "timing.total_ms",
4147 operation_started.elapsed().as_secs_f64() * 1_000.0,
4148 );
4149 return Ok((
4150 KernelOutcome {
4151 value: empty_solid(),
4152 diagnostics,
4153 },
4154 None,
4155 ));
4156 }
4157 }
4158 if selected.is_empty()
4167 && imprint.section_evidence
4168 && !matches!(operation, BooleanOperation::Union)
4169 && touching_empty_enabled()
4170 && !TOUCHING_PROOF.with(std::cell::Cell::get)
4171 {
4172 let strict = |samples: &[Vec3], other: &BrepSolid, class: PointClass| -> Result<bool, KernelRefusal> {
4173 for &sample in samples {
4174 if classify_point(sample, other, tolerance).or_refuse(KernelStage::Validate, "classify_point")?.class == class {
4175 return Ok(true);
4176 }
4177 }
4178 Ok(false)
4179 };
4180 let witnessed = match operation {
4181 BooleanOperation::Intersect => {
4182 !strict(&a_surface_samples, second, PointClass::In)? && !strict(&b_surface_samples, first, PointClass::In)?
4183 }
4184 BooleanOperation::Subtract => !strict(&a_surface_samples, second, PointClass::Out)?,
4185 BooleanOperation::Union => false,
4186 };
4187 let overlap_free = !hair_deep_overlap(first, second, tolerance);
4193 if witnessed && overlap_free {
4194 TOUCHING_PROOF.with(|flag| flag.set(true));
4195 let proof = inclusion_exclusion_volume(first, second, operation, options, body_volume(first), body_volume(second), false);
4196 TOUCHING_PROOF.with(|flag| flag.set(false));
4197 let volume = |solid: &BrepSolid| body_volume(solid).unwrap_or(f64::INFINITY);
4202 let band = 1e-9 * volume(first).max(volume(second));
4203 if let Some(proof) = proof.filter(|proof| proof.expected.is_finite() && proof.expected.abs() <= band) {
4204 diagnostics.event(
4205 DiagnosticSeverity::Info,
4206 KernelStage::Select,
4207 "boolean.empty_touching",
4208 format!(
4209 "{operation:?} of touching operands is empty: {} reads {:.3e} by {} (band {band:.3e})",
4210 proof.formula, proof.expected, proof.reading
4211 ),
4212 );
4213 fit_scope.close().report_into(&mut diagnostics);
4214 polyline_scope.close().report_into(&mut diagnostics);
4215 diagnostics.measure_max("timing.total_ms", operation_started.elapsed().as_secs_f64() * 1_000.0);
4216 return Ok((KernelOutcome { value: empty_solid(), diagnostics }, None));
4217 }
4218 }
4219 }
4220 let solids = [(0, &split_first), (1, &split_second)]
4221 .into_iter()
4222 .collect::<HashMap<_, _>>();
4223 let dump = BooleanStageDump::open();
4224 if let Some(dump) = &dump {
4225 dump.write("first", &split_first);
4226 dump.write("second", &split_second);
4227 dump.write("selected", &selected);
4228 }
4229 let stage_started = Instant::now();
4230 let assembled_origins: Vec<FaceKey> = if imprint.tangent_sections.is_empty() {
4234 Vec::new()
4235 } else {
4236 selected
4237 .iter()
4238 .map(|fragment| FaceKey { operand: fragment.operand, face_id: fragment.source_face_id })
4239 .collect()
4240 };
4241 let attributable: Vec<crate::imprint::TangentSectionRecord> = imprint
4248 .tangent_sections
4249 .iter()
4250 .filter(|section| imprint.tangent_nodes.is_empty() || section.grazing.is_empty())
4251 .cloned()
4252 .collect();
4253 let attribute = |error: KernelRefusal| {
4254 attribute_to_tangent_section(error, &attributable, &assembled_origins)
4255 };
4256 let cellular_result = matches!(operation, BooleanOperation::Union)
4257 && cellular::enabled(options)
4258 && cellular::complete_contact(first, second, &selected, tolerance);
4259 let (solid, scope) = if cellular_result {
4260 (assemble::assemble_cellular_fragments(selected, &solids, &imprint, tolerance)
4261 .map_err(attribute)?, None)
4262 } else if untouched_passthrough(options) {
4263 assemble_fragments_scoped(selected, &solids, &imprint, tolerance, &touch, touched_assembly(options))
4264 .map_err(attribute)?
4265 } else {
4266 (assemble_fragments(selected, &solids, &imprint, tolerance).map_err(attribute)?, None)
4267 };
4268 if let Some(scope) = &scope {
4269 diagnostics.count_n("passthrough.faces_examined", scope.examined.len() as u64);
4270 }
4271 if let Some(dump) = &dump {
4272 dump.write("assembled", &solid);
4273 }
4274 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
4275 profile_stage("assemble_ms", stage_ms);
4276 diagnostics.measure_max("timing.assemble_ms", stage_ms);
4277 let stage_started = Instant::now();
4278 let declines_before = crate::face_merge::declines_served();
4279 let area_checks_before = crate::face_merge::boundary_area_checks();
4280 if std::env::var("BREP_DEBUG_PREMERGE_VALIDATE").is_ok() {
4281 let issues = solid.validate();
4282 eprintln!(
4283 "pre-merge validation: {} issue(s){}",
4284 issues.len(),
4285 issues
4286 .first()
4287 .map(|issue| format!(" — first: {}", issue.message))
4288 .unwrap_or_default()
4289 );
4290 }
4291 let solid = if solid.kind != crate::BodyKind::Cellular && options.merge_coplanar_faces
4292 && std::env::var("BREP_COPLANAR_MERGE").as_deref() != Ok("0")
4293 {
4294 let merged = match &scope {
4295 Some(scope) => merge_same_surface_faces_scoped(
4299 &solid,
4300 tolerance,
4301 &options.keep_unmerged_name_substrs,
4302 &scope.examined,
4303 )?,
4304 None => merge_same_surface_faces_excluding(
4305 &solid,
4306 tolerance,
4307 &options.keep_unmerged_name_substrs,
4308 )?,
4309 };
4310 let merged = merge_curve_continuation_edges(&merged, tolerance).map_err(|refusal| KernelRefusal { stage: KernelStage::Validate, ..refusal })?;
4315 rejoin::rejoin_unless_referenced(merged, options, tolerance)
4316 } else {
4317 solid
4318 };
4319 if let Some(dump) = &dump {
4320 dump.write("merged", &solid);
4321 }
4322 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
4323 profile_stage("face_merge_ms", stage_ms);
4324 if crate::profile::profile_enabled() {
4325 profile_line!("boolean.merge_declines served={}", crate::face_merge::declines_served() - declines_before);
4326 let area_checks = crate::face_merge::boundary_area_checks();
4327 if area_checks != area_checks_before {
4328 profile_line!("boolean.merge_area_checks boundary={} integrated={}", area_checks.0 - area_checks_before.0, area_checks.1 - area_checks_before.1);
4329 }
4330 }
4331 diagnostics.measure_max("timing.face_merge_ms", stage_ms);
4332 let validation_started = Instant::now();
4333 let validation = solid.validate_detailed_scoped(&policy, scope.as_ref().map(|scope| &scope.examined));
4334 profile_stage("final_validate_ms", validation_started.elapsed().as_secs_f64() * 1000.0);
4335 diagnostics.count_n("validate.issues", validation.issues.len() as u64);
4336 diagnostics.count_n(
4337 "validate.wire_warnings",
4338 validation.wire_warnings.len() as u64,
4339 );
4340 diagnostics.measure_max("validate.max_pcurve_error", validation.max_pcurve_error);
4341 for warning in &validation.wire_warnings {
4342 diagnostics.event(
4343 DiagnosticSeverity::Warning,
4344 KernelStage::Validate,
4345 "validate.uv_wire",
4346 warning.message.clone(),
4347 );
4348 }
4349 for issue in &validation.issues {
4350 diagnostics.event(
4351 DiagnosticSeverity::Error,
4352 KernelStage::Validate,
4353 "validate.brep",
4354 issue.message.clone(),
4355 );
4356 }
4357 fit_scope.close().report_into(&mut diagnostics);
4358 polyline_scope.close().report_into(&mut diagnostics);
4359 diagnostics.measure_max(
4360 "timing.total_ms",
4361 operation_started.elapsed().as_secs_f64() * 1_000.0,
4362 );
4363 if !validation.issues.is_empty() {
4364 return Err(KernelRefusal::new(
4365 RefusalClass::InvalidResultTopology { issues: validation.issues.len() as u32 },
4366 KernelStage::Validate,
4367 format!(
4368 "boolean_operation: invalid result: {:?}",
4369 validation.issues
4370 )));
4371 }
4372 if std::env::var("BREP_DEBUG_BOOL").is_ok() {
4378 if let Ok(report) =
4379 crate::oracle::boolean_semantic_disagreement(first, second, operation, &solid, 200)
4380 {
4381 if report.is_flagged() {
4382 eprintln!(
4383 "[oracle] semantic disagreement rate {:.4} ({} of {} decidable points); sample {:?}",
4384 report.disagreement_rate,
4385 report.disagreements.len(),
4386 report.considered,
4387 report.sample_disagreement()
4388 );
4389 }
4390 }
4391 let fusable_band = crate::tolerance::assembler_weld(policy.model);
4392 let fusables = crate::oracle::boolean_residual_fusables(&solid, fusable_band);
4393 if !fusables.is_empty() {
4394 eprintln!(
4395 "[oracle] {} residual fusable(s) after weld; sample {:?}",
4396 fusables.len(),
4397 fusables.first()
4398 );
4399 }
4400 }
4401 let candidates = scope.as_ref().map(|scope| {
4402 let unproved = (scope_proved_apart_on() && plain_hull_solid(first) && plain_hull_solid(second))
4403 .then(|| imprint.faces_in_unproved_pairs.as_ref())
4404 .flatten()
4405 .map(|faces| faces.iter().copied().collect::<HashSet<_>>());
4406 let candidates = soundness_candidates(
4407 &solid,
4408 scope,
4409 [operand_bounds(first), operand_bounds(second)],
4410 policy.sew_search,
4411 unproved.as_ref(),
4412 );
4413 diagnostics.count_n("passthrough.soundness_candidates", candidates.len() as u64);
4414 crate::soundness::census::profile_operation(&solid, &[first, second], Some(&scope.touched), "boolean");
4415 candidates
4416 });
4417 Ok((
4418 KernelOutcome {
4419 value: solid,
4420 diagnostics,
4421 },
4422 candidates,
4423 ))
4424}
4425
4426