1pub mod profile;
2pub use crate::arrangement::Vec2;
3use crate::classification::{classify_point, parameter_point_in_face, PolygonClass};
4pub use crate::fragment::{FaceFragmentRecord, FragmentEdgeSource};
5pub use crate::imprint::{
6 EdgeSplitRecord, FaceImprints, FaceKey, ImprintOptions, ImprintPieceRecord,
7 ImprintResultRecord, ImprintVertex,
8};
9use crate::tolerance::{assembler_weld, commit_weld};
10pub use crate::topology::{
11 adaptive_coedge_error, BrepSolid, CoedgeRecord, EdgeRecord, FaceRecord, LoopRecord,
12 ShellRecord, VertexRecord,
13};
14pub use crate::{
15 KernelRefusal, OrRefuse, RefusalClass,
16 apply_edge_splits, apply_edge_splits_with_map, build_imprints, build_pcurve_on_surface,
17 build_pcurve_on_surface_range, classify_surface_pair,
18 fragment_solid, interpolate_curve, merge_curve_continuation_edges,
19 merge_same_surface_faces_excluding, merge_same_surface_faces_scoped,
20 project_point_to_curve, project_point_to_surface, solid_signed_volume, solid_signed_volume_for_sign, AffineTransform,
21 DiagnosticSeverity, KernelDiagnostics, KernelOutcome, KernelStage, KernelTolerances, NurbsCurve,
22 PointClass, SolidClassifier, SurfacePairRelation, Vec3,
23};
24pub use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
25use serde::{Deserialize, Serialize};
26pub use web_time::Instant;
27
28thread_local! {
29 pub static CONFORMANCE_REPAIRS: std::cell::Cell<u64> =
35 const { std::cell::Cell::new(0) };
36}
37
38#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
39#[serde(rename_all = "lowercase")]
40pub enum BooleanOperation {
41 Union,
42 Intersect,
43 Subtract,
44}
45
46#[derive(Clone, Debug, Deserialize)]
47pub struct BooleanOptions {
48 #[serde(default = "default_tolerance")]
49 pub tolerance: f64,
50 #[serde(default)]
53 pub tolerances: Option<KernelTolerances>,
54 #[serde(default)]
55 pub imprint: ImprintOptions,
56 #[serde(default = "default_true")]
59 pub merge_coplanar_faces: bool,
60 #[serde(default)]
70 pub keep_unmerged_name_substrs: Vec<String>,
71 #[serde(default = "default_true")]
75 pub untouched_passthrough: bool,
76 #[serde(default = "default_true")]
80 pub disjoint_fast_path: bool,
81 #[serde(default = "default_true")]
91 pub contact_fast_path: bool,
92 #[serde(default)]
100 pub touched_assembly: bool,
101 #[serde(default = "default_true")]
109 pub sector_classification: bool,
110 #[serde(default = "default_true")]
114 pub sheet_trim: bool,
115 #[serde(default)]
119 pub keep_cells: bool,
120 #[serde(default)]
125 pub seam_reseat_later_references: Option<Vec<String>>,
126 #[serde(default)]
133 pub seam_rejoin_later_references: Option<Vec<String>>,
134}
135
136thread_local! {
137 static WITHOUT_PERTURBATION: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
138}
139
140pub fn without_perturbation<T>(action: impl FnOnce() -> T) -> T {
147 struct Restore(bool);
148 impl Drop for Restore {
149 fn drop(&mut self) {
150 WITHOUT_PERTURBATION.with(|cell| cell.set(self.0));
151 }
152 }
153 let _restore = Restore(WITHOUT_PERTURBATION.with(|cell| cell.replace(true)));
154 action()
155}
156
157fn touched_assembly(options: &BooleanOptions) -> bool {
159 match std::env::var("BREP_TOUCHED_ASSEMBLY").as_deref() {
160 Ok("0") => false,
161 Ok(_) => true,
162 Err(_) => options.touched_assembly,
163 }
164}
165
166fn disjoint_fast_path(options: &BooleanOptions) -> bool {
168 match std::env::var("BREP_DISJOINT_FAST_PATH").as_deref() {
169 Ok("0") => false,
170 Ok(_) => true,
171 Err(_) => options.disjoint_fast_path,
172 }
173}
174
175fn contact_fast_path(options: &BooleanOptions) -> bool {
177 match std::env::var("BREP_CONTACT_FAST_PATH").as_deref() {
178 Ok("0") => false,
179 Ok(_) => true,
180 Err(_) => options.contact_fast_path,
181 }
182}
183
184fn untouched_passthrough(options: &BooleanOptions) -> bool {
186 match std::env::var("BREP_UNTOUCHED_PASSTHROUGH").as_deref() {
187 Ok("0") => false,
188 Ok(_) => true,
189 Err(_) => options.untouched_passthrough,
190 }
191}
192
193fn default_tolerance() -> f64 {
194 1e-7
195}
196
197fn default_true() -> bool {
198 true
199}
200
201impl Default for BooleanOptions {
202 fn default() -> Self {
203 Self {
204 tolerance: default_tolerance(),
205 tolerances: None,
206 imprint: ImprintOptions::default(),
207 merge_coplanar_faces: true,
208 keep_unmerged_name_substrs: Vec::new(),
209 untouched_passthrough: true,
210 disjoint_fast_path: true,
211 contact_fast_path: true,
212 touched_assembly: false,
213 sector_classification: true,
214 sheet_trim: true,
215 keep_cells: false,
216 seam_reseat_later_references: None,
217 seam_rejoin_later_references: None,
218 }
219 }
220}
221
222mod select;
223mod sheet;
224mod cellular;
225pub mod sector;
226pub mod assemble;
227mod operand_state;
228mod rim;
229mod coincident;
230mod touch;
231pub(crate) mod reseat;
232mod ball_align;
233mod rejoin;
234mod window_retry;
235mod isotropic_chart;
236mod dedicated;
237pub use dedicated::{register_dedicated_boolean, DedicatedBoolean};
238
239pub use rim::*;
240use select::*;
241use coincident::*;
242use touch::TouchCensus;
243pub use assemble::{
244 assemble_fragments, assemble_open_fragments, commit_nearby_edge_endpoints,
245 clear_candidate_memo, edge_interior_lies_on, finalize_assembled_solid, refresh_derived_genus,
246};
247use assemble::{assemble_fragments_scoped, AssemblyScope};
248#[allow(unused_imports)]
250pub use assemble::apply_assembly_heal_chain;
251
252
253struct WorkingScale {
258 factor: f64,
259 solids: Vec<BrepSolid>,
260 options: BooleanOptions,
261}
262
263thread_local! {
264 static ORIGINAL_WORKING_SCALE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
267}
268
269impl WorkingScale {
270 fn of(operands: &[&BrepSolid], options: &BooleanOptions) -> Result<Option<Self>, KernelRefusal> {
271 let Some(bounds) = crate::rescale::bounds_of(operands.iter().copied()) else {
272 return Ok(None);
273 };
274 let Some(factor) = crate::rescale::guard_factor(bounds).or_else(|| {
275 if ORIGINAL_WORKING_SCALE.with(|state| state.get()) { None }
276 else { crate::rescale::large_guard_factor(bounds) }
277 }) else {
278 return Ok(None);
279 };
280 crate::rescale::profile_fired("boolean", factor, bounds);
281 let solids = operands
282 .iter()
283 .map(|solid| crate::rescale::scale_operand(solid, factor, "boolean"))
284 .collect::<Result<Vec<_>, _>>()?;
285 let mut options = options.clone();
287 options.imprint.maximum_ssi_step = options.imprint.maximum_ssi_step.map(|step| step * factor);
288 Ok(Some(Self { factor, solids, options }))
289 }
290
291 fn run<T>(
294 &self,
295 original: impl FnOnce() -> Result<T, KernelRefusal>,
296 scaled: impl FnOnce() -> Result<T, KernelRefusal>,
297 ) -> Result<T, KernelRefusal> {
298 if self.factor >= 1.0 { return scaled(); }
299 struct Restore(bool);
300 impl Drop for Restore {
301 fn drop(&mut self) { ORIGINAL_WORKING_SCALE.with(|state| state.set(self.0)); }
302 }
303 let answer = {
304 let _restore = Restore(ORIGINAL_WORKING_SCALE.with(|state| state.replace(true)));
305 original()
306 };
307 match answer {
308 Ok(value) => Ok(value),
309 Err(original) => scaled().or(Err(original)),
310 }
311 }
312
313 fn back(&self, solid: &BrepSolid) -> Result<BrepSolid, KernelRefusal> {
314 crate::rescale::scale_operand(solid, 1.0 / self.factor, "boolean")
315 }
316
317 fn refusal(&self, error: KernelRefusal) -> KernelRefusal {
318 crate::rescale::name_scale(error, self.factor)
319 }
320}
321
322pub fn boolean_operation(
323 first: &BrepSolid,
324 second: &BrepSolid,
325 operation: BooleanOperation,
326 options: &BooleanOptions,
327) -> Result<BrepSolid, KernelRefusal> {
328 if let Some(Ok(solid)) = dedicated::dedicated(first, second, operation) {
331 return Ok(solid);
332 }
333 if let Some(scaled) = WorkingScale::of(&[first, second], options)? {
334 return scaled.run(
335 || boolean_operation(first, second, operation, options),
336 || boolean_operation(&scaled.solids[0], &scaled.solids[1], operation, &scaled.options)
337 .map_err(|error| scaled.refusal(error))
338 .and_then(|solid| scaled.back(&solid)),
339 );
340 }
341 if isotropic_chart::active() {
344 return boolean_operation_unscaled(first, second, operation, options);
345 }
346 boolean_operation_unscaled(first, second, operation, options).or_else(|refused| {
347 isotropic_chart::suppressed(|| window_retry::retry(first, second, operation, options, refused, boolean_operation_unscaled))
350 })
351}
352
353fn boolean_operation_unscaled(
355 first: &BrepSolid,
356 second: &BrepSolid,
357 operation: BooleanOperation,
358 options: &BooleanOptions,
359) -> Result<BrepSolid, KernelRefusal> {
360 match boolean_operation_with_diagnostics(first, second, operation, options) {
361 Ok(outcome) => {
362 if below_tolerance_refusal_enabled()
365 && outcome.value.shells.iter().all(|shell| shell.faces.is_empty())
366 && !matches!(operation, BooleanOperation::Union)
367 {
368 if let Some(refusal) = below_tolerance_refusal(first, second, None) {
369 if let Some(answer) = below_tolerance_answer(first, second, operation) {
370 return Ok(answer);
371 }
372 if let Some(answer) = below_tolerance_rescaled(first, second, operation, options) {
373 return Ok(answer);
374 }
375 return Err(refusal);
376 }
377 }
378 if unresolved_merge_refusal_enabled() && !matches!(operation, BooleanOperation::Subtract) {
379 if let Some(refusal) = unresolved_merge_refusal(first, second) {
380 return Err(refusal);
381 }
382 }
383 if below_tolerance_slivers_enabled()
386 && !matches!(operation, BooleanOperation::Subtract)
387 && [first, second].iter().all(|solid| face_count(solid) <= SLIVER_ANSWER_FACES)
388 && near_coincident_planar_faces(first, second).is_some()
389 {
390 if let Some(answer) = below_tolerance_answer(first, second, operation) {
391 return Ok(answer);
392 }
393 }
394 Ok(outcome.value)
395 }
396 Err(error) => {
397 if below_tolerance_refusal_enabled() {
398 if let Some(refusal) = below_tolerance_refusal(first, second, Some(&error)) {
399 if let Some(answer) = below_tolerance_answer(first, second, operation) {
400 return Ok(answer);
401 }
402 if let Some(answer) = below_tolerance_rescaled(first, second, operation, options) {
403 return Ok(answer);
404 }
405 return Err(refusal);
406 }
407 }
408 if isotropic_chart::isotropic_chart_on() && !isotropic_chart::active() && !isotropic_chart::is_suppressed() {
417 let (a, b) = (isotropic_chart::isotropic(first), isotropic_chart::isotropic(second));
418 if a.is_some() || b.is_some() {
419 let (a, b) = (a.as_ref().unwrap_or(first), b.as_ref().unwrap_or(second));
420 match isotropic_chart::with_active(|| boolean_operation(a, b, operation, options)) {
421 Ok(result) => match isotropic_chart_identity(first, second, a, b, operation, options, &result) {
422 Ok(()) => return Ok(result),
423 Err(why) => {
424 if std::env::var("BREP_DEBUG_BOOL").is_ok() {
425 eprintln!("isotropic chart: the rescaled boolean is not admitted ({why}); on to the perturbation ladder");
426 }
427 }
428 },
429 Err(second_refusal) => {
430 if std::env::var("BREP_DEBUG_BOOL").is_ok() {
431 eprintln!("isotropic chart: the rescaled boolean refused too ({second_refusal}); on to the perturbation ladder");
432 }
433 }
434 }
435 }
436 }
437 if isotropic_chart::active() {
440 return Err(error);
441 }
442 if std::env::var("BREP_NO_PERTURB").as_deref() == Ok("1")
450 || !error.class.perturbation_eligible()
451 {
452 return Err(error);
453 }
454 if std::env::var("BREP_OPEN_OPERAND_GATE").as_deref() != Ok("0") {
476 if let Some((operand, open)) = [first, second]
477 .iter()
478 .enumerate()
479 .find_map(|(operand, solid)| {
480 let open = one_use_edges(solid);
481 (open > 0).then_some((operand, open))
482 })
483 {
484 return Err(error.with_message(|message| format!(
485 "{message}; operand {operand} is not a closed shell: {open} of its edges bound \
486 only one face, so no boolean of it encloses a solid and no perturbation \
487 can close it"
488 )));
489 }
490 }
491 if let Some((operand, face_id, deviation, weld)) =
492 planar_operand_off_its_plane(first, second, options)
493 {
494 return Err(error.with_message(|message| format!(
495 "{message}; operand {operand} face {face_id} is a plane whose straight \
496 boundary sits {deviation:.3e} off it (assembly weld {weld:.1e}), which \
497 no perturbation can reconcile — the body's planes must contain their \
498 boundary before it can take part in an exact boolean"
499 )));
500 }
501 if matches!(operation, BooleanOperation::Subtract)
516 && std::env::var("BREP_PINCH_GATE").as_deref() != Ok("0")
517 && subtract_pinches_at_internal_tangency(first, second, options.tolerance)
518 .unwrap_or(false)
519 {
520 if let Some(solid) = subtract_through_the_common_part(first, second, options) {
523 return Ok(solid);
524 }
525 return Err(error.with_message(|message| format!(
526 "{message}; internal tangency: the operands touch tangentially with \
527 co-directed normals, so the exact difference pinches to zero thickness \
528 (non-manifold, unrepresentable in a boundary model) — refusing rather \
529 than returning a perturbed sliver"
530 )));
531 }
532 if matches!(error.class, RefusalClass::TangentNodeSingularity)
548 && std::env::var("BREP_TANGENT_NODE_GATE").as_deref() != Ok("0")
549 {
550 return Err(error);
551 }
552 if matches!(operation, BooleanOperation::Union) {
556 if let Some(solid) = union_through_the_difference(first, second, options) {
557 return Ok(solid);
558 }
559 }
560 if WITHOUT_PERTURBATION.with(|cell| cell.get()) {
562 return Err(error);
563 }
564 match perturbation_retry(first, second, operation, options) {
565 Ok(solid) => Ok(solid),
566 Err(refused) if refused.is_empty() => Err(error),
567 Err(refused) => {
568 Err(error.with_message(|message| format!("{message}; {}", refused.join("; "))))
569 }
570 }
571 }
572 }
573}
574
575const PINCH_PROBE_STEPS: usize = 8;
580
581const PINCH_ANGULAR_TOLERANCE: f64 = 1e-4;
584
585const PINCH_SEPARATION_STEP: f64 = 1e-2;
589
590fn subtract_through_the_common_part(first: &BrepSolid, second: &BrepSolid, options: &BooleanOptions) -> Option<BrepSolid> {
608 if !switch!("BREP_PINCH_COMMON_RETRY", true) || !options.imprint.tangent_curve_imprint {
611 return None;
612 }
613 let common = boolean_operation_with_diagnostics(first, second, BooleanOperation::Intersect, options).ok()?.value;
614 if common.shells.iter().all(|shell| shell.faces.is_empty()) {
615 return None;
616 }
617 let cut = boolean_operation_with_diagnostics(first, &common, BooleanOperation::Subtract, options).ok()?.value;
618 if !cut.validate().is_empty() {
619 return None;
620 }
621 let volume = |solid: &BrepSolid| crate::solid_mass_properties(solid).ok().map(|mass| mass.volume);
622 let (whole, taken, left) = (volume(first)?, volume(&common)?, volume(&cut)?);
623 ((left - (whole - taken)).abs() <= 1e-9 * whole.abs().max(1.0)).then_some(cut)
624}
625
626fn union_through_the_difference(first: &BrepSolid, second: &BrepSolid, options: &BooleanOptions) -> Option<BrepSolid> {
639 if !switch!("BREP_TANGENT_UNION_DIFFERENCE_RETRY", true) || !options.imprint.tangent_curve_imprint {
640 return None;
641 }
642 let pinches = |a: &BrepSolid, b: &BrepSolid| subtract_pinches_at_internal_tangency(a, b, options.tolerance).unwrap_or(false);
643 if !pinches(first, second) && !pinches(second, first) {
644 return None;
645 }
646 let difference = match boolean_operation_with_diagnostics(first, second, BooleanOperation::Subtract, options) {
647 Ok(outcome) => outcome.value,
648 Err(_) => subtract_through_the_common_part(first, second, options)?,
649 };
650 if difference.shells.iter().all(|shell| shell.faces.is_empty()) || !difference.validate().is_empty() {
651 return None;
652 }
653 let union = boolean_operation_with_diagnostics(second, &difference, BooleanOperation::Union, options).ok()?.value;
654 if !union.validate().is_empty() {
655 return None;
656 }
657 let volume = |solid: &BrepSolid| crate::solid_mass_properties(solid).ok().map(|mass| mass.volume);
658 let (left, added, whole) = (volume(&difference)?, volume(second)?, volume(&union)?);
659 ((whole - (left + added)).abs() <= 1e-9 * whole.abs().max(1.0)).then_some(union)
660}
661
662pub fn subtract_pinches_at_internal_tangency(
684 first: &BrepSolid,
685 second: &BrepSolid,
686 tolerance: f64,
687) -> Result<bool, KernelRefusal> {
688 let contact = (tolerance * 100.0).max(1e-12);
691 let probes_a = first
692 .shells
693 .iter()
694 .flat_map(|shell| &shell.faces)
695 .map(PinchProbe::of)
696 .collect::<Result<Vec<_>, _>>()?;
697 let probes_b = second
698 .shells
699 .iter()
700 .flat_map(|shell| &shell.faces)
701 .map(PinchProbe::of)
702 .collect::<Result<Vec<_>, _>>()?;
703 for probe_a in &probes_a {
704 for probe_b in &probes_b {
705 let pad = 1e-2 * probe_a.extent().max(probe_b.extent());
712 if probe_a.separation(probe_b) > contact + pad {
713 continue;
714 }
715 if classify_surface_pair(
722 &probe_a.face.surface,
723 &probe_b.face.surface,
724 tolerance,
725 PINCH_ANGULAR_TOLERANCE,
726 ).or_refuse(KernelStage::Validate, "csg.boolean.mod")?
727 .relation
728 == SurfacePairRelation::Cosurface
729 {
730 continue;
731 }
732 if faces_touch_with_codirected_normals(probe_a, probe_b, contact)? {
733 return Ok(true);
734 }
735 }
736 }
737 Ok(false)
738}
739
740struct PinchProbe<'a> {
743 face: &'a FaceRecord,
744 samples: Vec<(f64, f64, Vec3)>,
746 minimum: [f64; 3],
747 maximum: [f64; 3],
748}
749
750impl<'a> PinchProbe<'a> {
751 fn of(face: &'a FaceRecord) -> Result<Self, KernelRefusal> {
752 let [u0, u1] = face.surface.domain_u().or_refuse(KernelStage::Validate, "domain_u")?;
753 let [v0, v1] = face.surface.domain_v().or_refuse(KernelStage::Validate, "domain_v")?;
754 let steps = PINCH_PROBE_STEPS as f64;
755 let mut samples = Vec::with_capacity((PINCH_PROBE_STEPS + 1).pow(2));
756 let mut minimum = [f64::INFINITY; 3];
757 let mut maximum = [f64::NEG_INFINITY; 3];
758 for i in 0..=PINCH_PROBE_STEPS {
759 let u = u0 + (u1 - u0) * i as f64 / steps;
760 for j in 0..=PINCH_PROBE_STEPS {
761 let v = v0 + (v1 - v0) * j as f64 / steps;
762 let Ok(point) = face.surface.evaluate(u, v) else {
763 continue;
764 };
765 for (axis, value) in [point.x, point.y, point.z].into_iter().enumerate() {
766 minimum[axis] = minimum[axis].min(value);
767 maximum[axis] = maximum[axis].max(value);
768 }
769 samples.push((u, v, point));
770 }
771 }
772 Ok(Self {
773 face,
774 samples,
775 minimum,
776 maximum,
777 })
778 }
779
780 fn extent(&self) -> f64 {
782 (0..3)
783 .map(|axis| self.maximum[axis] - self.minimum[axis])
784 .fold(0.0f64, f64::max)
785 }
786
787 fn separation(&self, other: &Self) -> f64 {
789 let mut gap: f64 = 0.0;
790 for axis in 0..3 {
791 gap = gap.max(self.minimum[axis] - other.maximum[axis]);
792 gap = gap.max(other.minimum[axis] - self.maximum[axis]);
793 }
794 gap
795 }
796}
797
798fn faces_touch_with_codirected_normals(
803 probe_a: &PinchProbe<'_>,
804 probe_b: &PinchProbe<'_>,
805 contact: f64,
806) -> Result<bool, KernelRefusal> {
807 for (probe, other) in [(probe_a, probe_b), (probe_b, probe_a)] {
808 let source = probe.face;
809 let target = other.face;
810 for &(u, v, point) in &probe.samples {
811 let projection = project_point_to_surface(&target.surface, point).or_refuse(KernelStage::Validate, "project_point_to_surface")?;
812 if projection.distance > contact {
813 continue;
814 }
815 let (Ok(source_normal), Ok(target_normal)) = (
818 source.surface.normal(u, v),
819 target.surface.normal(projection.u, projection.v),
820 ) else {
821 continue;
822 };
823 let source_outward = outward_normal(source_normal, source.same_sense);
824 let target_outward = outward_normal(target_normal, target.same_sense);
825 if source_outward.cross(target_outward).length() > PINCH_ANGULAR_TOLERANCE
826 || source_outward.dot(target_outward) <= 0.0
827 {
828 continue;
829 }
830 if parameter_point_in_face(source, Vec2 { x: u, y: v }, 1e-6).or_refuse(KernelStage::Validate, "parameter_point_in_face")?
831 == PolygonClass::Outside
832 || parameter_point_in_face(
833 target,
834 Vec2 {
835 x: projection.u,
836 y: projection.v,
837 },
838 1e-6,
839 ).or_refuse(KernelStage::Validate, "csg.boolean.mod")? == PolygonClass::Outside
840 {
841 continue;
842 }
843 if contact_separates_locally(source, target, u, v, contact)? {
844 return Ok(true);
845 }
846 }
847 }
848 Ok(false)
849}
850
851fn outward_normal(normal: Vec3, same_sense: bool) -> Vec3 {
852 if same_sense {
853 normal
854 } else {
855 normal.scale(-1.0)
856 }
857}
858
859fn contact_separates_locally(
865 source: &FaceRecord,
866 target: &FaceRecord,
867 u: f64,
868 v: f64,
869 contact: f64,
870) -> Result<bool, KernelRefusal> {
871 let [u0, u1] = source.surface.domain_u().or_refuse(KernelStage::Validate, "domain_u")?;
872 let [v0, v1] = source.surface.domain_v().or_refuse(KernelStage::Validate, "domain_v")?;
873 let step_u = (u1 - u0) * PINCH_SEPARATION_STEP;
874 let step_v = (v1 - v0) * PINCH_SEPARATION_STEP;
875 for (probe_u, probe_v) in [
876 ((u + step_u).min(u1), v),
877 ((u - step_u).max(u0), v),
878 (u, (v + step_v).min(v1)),
879 (u, (v - step_v).max(v0)),
880 ] {
881 if (probe_u - u).abs() < f64::EPSILON && (probe_v - v).abs() < f64::EPSILON {
882 continue;
883 }
884 let Ok(point) = source.surface.evaluate(probe_u, probe_v) else {
885 continue;
886 };
887 if project_point_to_surface(&target.surface, point).or_refuse(KernelStage::Validate, "project_point_to_surface")?.distance > contact * 10.0 {
890 return Ok(true);
891 }
892 }
893 Ok(false)
894}
895
896fn perturbation_retry(
950 first: &BrepSolid,
951 second: &BrepSolid,
952 operation: BooleanOperation,
953 options: &BooleanOptions,
954) -> Result<BrepSolid, Vec<String>> {
955 const DIRECTIONS: [[f64; 3]; 4] = [
966 [0.4034, 0.7973, 0.4491],
967 [0.7973, 0.4491, 0.4034],
968 [0.4491, 0.4034, 0.7973],
969 [0.5774, -0.5774, 0.5774],
970 ];
971 const FRACTIONS: [f64; 5] = PERTURBATION_FRACTIONS;
977
978 let debug = std::env::var("BREP_DEBUG_BOOL").is_ok();
979 let scale = crate::solid_tolerance::solid_scale(first)
980 .max(crate::solid_tolerance::solid_scale(second))
981 .max(1.0);
982
983 let _caller = crate::mass_caller("boolean.perturbation_rescue");
987 let va = solid_signed_volume(first).ok().map(f64::abs);
988 let vb = solid_signed_volume(second).ok().map(f64::abs);
989 let hold_identity = std::env::var("BREP_PERTURB_IDENTITY").as_deref() != Ok("0");
990 let hold_mirror = hold_identity && std::env::var("BREP_PERTURB_MIRROR").as_deref() != Ok("0");
993 let early_exit = std::env::var("BREP_MIRROR_EARLY_EXIT").as_deref() != Ok("0");
996 let mut trends = [MirrorTrend::default(); 4];
997 let mut identity: Option<Option<InclusionExclusion>> = None;
999 let mut refused = Vec::new();
1000 let ladder = std::env::var("BREP_DEBUG_PERTURB_LADDER").is_ok();
1004 let ladder_start = web_time::Instant::now();
1005 if ladder {
1006 let measured = inclusion_exclusion_volume(first, second, operation, options, va, vb, false);
1007 match &measured {
1008 Some(identity) => eprintln!(
1009 "[ladder] identity {} = {:.9} from the exact lane's {} ({:.9}); V(first) {:?} V(second) {:?}",
1010 identity.formula, identity.expected, identity.reading, identity.read, va, vb
1011 ),
1012 None => eprintln!("[ladder] no identity: no exact-lane boolean of these operands clears in either order"),
1013 }
1014 identity = Some(measured);
1015 }
1016 let rung_miss = |identity: &Option<Option<InclusionExclusion>>, candidate: &BrepSolid| -> String {
1017 let volume = body_volume(candidate);
1018 match (identity, volume) {
1019 (Some(Some(identity)), Some(volume)) => format!(
1020 "volume {volume:.9} miss {:+.3e} bar {:.3e}",
1021 volume - identity.expected,
1022 crate::VOLUME_DRIFT_ABS.max(crate::VOLUME_DRIFT_REL * identity.expected.abs())
1023 ),
1024 (_, Some(volume)) => format!("volume {volume:.9}"),
1025 _ => "no volume".to_string(),
1026 }
1027 };
1028
1029 for &fraction in &FRACTIONS {
1030 let magnitude = scale * fraction;
1031 for (direction, dir) in DIRECTIONS.iter().enumerate() {
1032 if trends[direction].closed {
1033 if ladder {
1034 eprintln!("[ladder] dir={dir:?} fraction={fraction:.1e} offset {magnitude:.3e}: not tried, its direction is closed");
1035 }
1036 continue;
1037 }
1038 let offset = [dir[0] * magnitude, dir[1] * magnitude, dir[2] * magnitude];
1039 let translate = match AffineTransform::new([
1040 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,
1044 ]) {
1045 Ok(transform) => transform,
1046 Err(_) => continue,
1047 };
1048 let moved = match crate::transform_brep(second, translate, false) {
1049 Ok(solid) => solid,
1050 Err(_) => continue,
1051 };
1052 let rung = format!("dir={dir:?} fraction={fraction:.1e} offset {magnitude:.3e}");
1053 let rung_start = web_time::Instant::now();
1054 let candidate =
1055 match boolean_operation_with_diagnostics(first, &moved, operation, options) {
1056 Ok(outcome) => outcome.value,
1057 Err(error) => {
1058 if ladder {
1059 eprintln!("[ladder] {rung}: exact lane refused {:?}", error.class);
1060 }
1061 continue;
1062 }
1063 };
1064 let built = rung_start.elapsed();
1065 if candidate.shells.is_empty() {
1067 if ladder {
1068 eprintln!("[ladder] {rung}: empty");
1069 }
1070 continue;
1071 }
1072 if let (Some(va), Some(vb)) = (va, vb) {
1077 if let Ok(vr) = solid_signed_volume(&candidate) {
1078 if !volume_within_csg_bounds(operation, va, vb, vr.abs()) {
1079 if ladder {
1080 eprintln!("[ladder] {rung}: outside the CSG bound, {}", rung_miss(&identity, &candidate));
1081 }
1082 continue;
1083 }
1084 }
1085 }
1086 let bounded = rung_start.elapsed();
1091 if hold_identity {
1093 let identity = identity.get_or_insert_with(|| {
1094 let identity =
1095 inclusion_exclusion_volume(first, second, operation, options, va, vb, false);
1096 if debug && identity.is_none() {
1097 eprintln!(
1098 "[perturb] no exact-lane boolean of these operands clears in either \
1099 order; no identity to hold"
1100 );
1101 }
1102 identity
1103 });
1104 if let Some(identity) = identity {
1105 let expected = identity.expected;
1106 let bar = crate::VOLUME_DRIFT_ABS.max(crate::VOLUME_DRIFT_REL * expected.abs());
1107 let volume = body_volume(&candidate);
1108 let miss = volume.map(|volume| (volume - expected).abs());
1109 if !miss.is_some_and(|miss| miss <= bar) {
1110 let sentence = format!(
1111 "perturbation rung dir={dir:?} fraction={fraction:.1e} \
1112 (offset {magnitude:.3e}) refused: its body reads {} against the \
1113 inclusion–exclusion identity {} = {expected:.9} (the exact lane's \
1114 {} reads {:.9}), a miss of {} beyond the volume drift bar {bar:.3e}",
1115 volume.map_or("no volume".to_string(), |volume| format!("{volume:.9}")),
1116 identity.formula,
1117 identity.reading,
1118 identity.read,
1119 miss.map_or("unmeasured".to_string(), |miss| format!("{miss:.3e}")),
1120 );
1121 if debug {
1122 eprintln!("[perturb] {sentence}");
1123 }
1124 if ladder {
1125 eprintln!(
1126 "[ladder] {rung}: refused by the identity, volume {} miss {} bar {bar:.3e}",
1127 volume.map_or("none".to_string(), |volume| format!("{volume:.9}")),
1128 volume.map_or("unmeasured".to_string(), |volume| format!("{:+.3e}", volume - expected)),
1129 );
1130 }
1131 refused.push(sentence);
1132 continue;
1133 }
1134 } else if hold_mirror {
1135 let mirror_start = web_time::Instant::now();
1138 let mirrored = AffineTransform::new([
1139 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,
1143 ])
1144 .ok()
1145 .and_then(|transform| crate::transform_brep(second, transform, false).ok());
1146 let mirror = mirrored.as_ref().and_then(|mirrored| {
1147 inclusion_exclusion_volume(first, mirrored, operation, options, va, vb, true)
1148 });
1149 let mirror_time = mirror_start.elapsed();
1150 let volume = body_volume(&candidate);
1151 let mut measured = None;
1152 let verdict = match (&mirror, volume) {
1153 (Some(mirror), Some(volume)) => {
1154 let bar = crate::VOLUME_DRIFT_ABS.max(crate::VOLUME_DRIFT_REL * mirror.expected.abs());
1155 let miss = 0.5 * (volume - mirror.expected).abs();
1156 measured = Some((0.5 * (volume - mirror.expected), bar));
1157 if ladder {
1158 eprintln!(
1159 "[ladder] {rung}: mirror at −offset reads {} = {:.9} (the mirrored {} {:.9}); body {volume:.9}, first-order translation error {:+.3e} bar {bar:.3e}",
1160 mirror.formula, mirror.expected, mirror.reading, mirror.read, 0.5 * (volume - mirror.expected)
1161 );
1162 }
1163 (miss > bar).then(|| format!(
1164 "perturbation rung dir={dir:?} fraction={fraction:.1e} \
1165 (offset {magnitude:.3e}) refused: no exact-lane boolean of the \
1166 operands clears, so the rung is held to its mirror: its body reads \
1167 {volume:.9} with the second operand moved +offset and {} = {:.9} \
1168 with it moved −offset (the mirrored {} reads {:.9}), a first-order \
1169 translation error of {miss:.3e} beyond the volume drift bar {bar:.3e}",
1170 mirror.formula, mirror.expected, mirror.reading, mirror.read
1171 ))
1172 }
1173 _ => Some(format!(
1174 "perturbation rung dir={dir:?} fraction={fraction:.1e} \
1175 (offset {magnitude:.3e}) refused: no exact-lane boolean of the operands \
1176 clears, and none clears with the second operand moved −offset either, \
1177 so nothing checks the rung's body{}",
1178 volume.map_or(String::new(), |volume| format!(" ({volume:.9})"))
1179 )),
1180 };
1181 match verdict {
1182 None => trends[direction].cleared(),
1183 Some(sentence) => {
1184 if debug {
1185 eprintln!("[perturb] {sentence}");
1186 }
1187 if ladder {
1188 eprintln!(
1189 "[ladder] {rung}: refused by its mirror (rung {:.0} ms: built {:.0}, bound {:.0}, mirror {:.0} ms; ladder {:.1} s)",
1190 rung_start.elapsed().as_secs_f64() * 1e3,
1191 built.as_secs_f64() * 1e3,
1192 (bounded - built).as_secs_f64() * 1e3,
1193 mirror_time.as_secs_f64() * 1e3,
1194 ladder_start.elapsed().as_secs_f64()
1195 );
1196 }
1197 refused.push(sentence);
1198 let closure = measured.and_then(|(error, bar)| {
1201 let earlier = trends[direction].refused(magnitude, error, early_exit)?;
1202 Some((earlier, error, bar))
1203 });
1204 if let Some(((earlier_offset, earlier_error), error, bar)) = closure {
1205 let closed = format!(
1206 "perturbation direction dir={dir:?} closed after offset {magnitude:.3e}: its \
1207 rungs' first-order translation errors read {earlier_error:+.3e} at offset \
1208 {earlier_offset:.3e} and {error:+.3e} at {magnitude:.3e}, one sign and \
1209 growing, so no larger offset along it comes back to the volume drift bar \
1210 {bar:.3e}"
1211 );
1212 if debug {
1213 eprintln!("[perturb] {closed}");
1214 }
1215 if ladder {
1216 eprintln!("[ladder] {closed}");
1217 }
1218 refused.push(closed);
1219 }
1220 continue;
1221 }
1222 }
1223 }
1224 }
1225 match crate::oracle::boolean_semantic_disagreement(
1229 first, second, operation, &candidate, 400,
1230 ) {
1231 Ok(report) if report.considered >= 30 && !report.is_flagged() => {
1232 if ladder {
1233 eprintln!(
1234 "[ladder] {rung}: accepted (oracle {} considered, rate {:.4}), {}",
1235 report.considered, report.disagreement_rate, rung_miss(&identity, &candidate)
1236 );
1237 }
1238 if debug {
1239 eprintln!(
1240 "[perturb] rescued {operation:?}: dir={dir:?} fraction={fraction:.1e} \
1241 magnitude={magnitude:.3e} offset={offset:?} \
1242 (oracle considered={} rate={:.4})",
1243 report.considered, report.disagreement_rate
1244 );
1245 }
1246 return Ok(candidate);
1247 }
1248 report => {
1249 if ladder {
1250 let verdict = match &report {
1251 Ok(report) => format!("oracle {} considered, rate {:.4}", report.considered, report.disagreement_rate),
1252 Err(error) => format!("oracle error {error:?}"),
1253 };
1254 eprintln!("[ladder] {rung}: refused by the oracle ({verdict}), {}", rung_miss(&identity, &candidate));
1255 }
1256 continue;
1257 }
1258 }
1259 }
1260 }
1261 if debug {
1262 eprintln!("[perturb] ladder exhausted for {operation:?}; no rung produced a clean result");
1263 }
1264 Err(refused)
1265}
1266
1267pub const PERTURBATION_FRACTIONS: [f64; 5] = [3e-5, 1e-4, 3e-4, 1e-3, 3e-3];
1270
1271#[derive(Clone, Copy, Default)]
1295pub struct MirrorTrend {
1296 last: Option<(f64, f64)>,
1298 pub closed: bool,
1299}
1300
1301impl MirrorTrend {
1302 pub fn refused(&mut self, offset: f64, error: f64, close: bool) -> Option<(f64, f64)> {
1307 let earlier = self
1308 .last
1309 .filter(|&(_, earlier)| earlier.signum() == error.signum() && error.abs() >= earlier.abs())
1310 .filter(|_| close);
1311 self.last = Some((offset, error));
1312 self.closed |= earlier.is_some();
1313 earlier
1314 }
1315
1316 pub fn cleared(&mut self) {
1318 self.last = None;
1319 }
1320}
1321
1322pub fn below_tolerance_refusal_enabled() -> bool {
1337 crate::switch!("BREP_BELOW_TOLERANCE_REFUSAL", true)
1338}
1339
1340pub fn below_tolerance_slivers_enabled() -> bool {
1357 crate::switch!("BREP_BELOW_TOLERANCE_SLIVERS", true)
1358}
1359
1360const SLIVER_ANSWER_FACES: usize = 64;
1363
1364fn face_count(solid: &BrepSolid) -> usize {
1365 solid.shells.iter().map(|shell| shell.faces.len()).sum()
1366}
1367
1368fn below_tolerance_answer(first: &BrepSolid, second: &BrepSolid, operation: BooleanOperation) -> Option<BrepSolid> {
1370 if !below_tolerance_slivers_enabled() || [first, second].iter().any(|solid| face_count(solid) > SLIVER_ANSWER_FACES) {
1371 return None;
1372 }
1373 if ![first, second].iter().all(|solid| closed_single_shell(solid)) {
1374 return None;
1375 }
1376 let inside = |x: &BrepSolid, y: &BrepSolid| difference_all_sliver(x, y);
1377 if matches!(operation, BooleanOperation::Subtract) {
1378 return inside(first, second).then(empty_solid);
1379 }
1380 let (first_in, second_in) = (inside(first, second), inside(second, first));
1381 let first_larger = || match (body_volume(first), body_volume(second)) {
1384 (Some(a), Some(b)) => a >= b,
1385 _ => true,
1386 };
1387 let outer_is_first = match (first_in, second_in) {
1388 (false, false) => return None,
1389 (true, false) => false,
1390 (false, true) => true,
1391 (true, true) => first_larger(),
1392 };
1393 let (outer, inner) = if outer_is_first { (first, second) } else { (second, first) };
1394 Some(match operation {
1395 BooleanOperation::Union => outer.clone(),
1396 _ => inner.clone(),
1397 })
1398}
1399
1400fn closed_single_shell(solid: &BrepSolid) -> bool {
1402 if !solid.kind.is_solid() || solid.shells.len() != 1 {
1403 return false;
1404 }
1405 let mut uses: HashMap<u64, usize> = HashMap::default();
1406 for coedge in solid.shells[0].faces.iter().flat_map(|face| &face.loops).flat_map(|lp| &lp.coedges) {
1407 *uses.entry(coedge.edge_id).or_default() += 1;
1408 }
1409 !uses.is_empty() && uses.values().all(|&count| count == 2) && solid.edges.iter().all(|edge| uses.contains_key(&edge.id))
1410}
1411
1412fn difference_all_sliver(first: &BrepSolid, second: &BrepSolid) -> bool {
1423 let Some(bounds) = difference_bounds(first, second) else {
1424 return false;
1425 };
1426 let Ok(properties) = crate::solid_mass_properties(first) else {
1427 return false;
1428 };
1429 bounds.out <= BELOW_TOLERANCE_BAND
1430 && bounds.upper.is_finite()
1431 && bounds.upper <= crate::tolerance::COINCIDENCE_DISTANCE_FLOOR * properties.surface_area
1432}
1433
1434struct DifferenceBounds {
1440 lower: f64,
1441 upper: f64,
1442 out: f64,
1444}
1445
1446fn difference_bounds(first: &BrepSolid, second: &BrepSolid) -> Option<DifferenceBounds> {
1447 let scale = crate::solid_tolerance::solid_scale(first).max(crate::solid_tolerance::solid_scale(second)).max(1.0);
1448 let (polygons_a, polygons_b) = (face_polygons(first, scale)?, face_polygons(second, scale)?);
1449 let vertices_b: Vec<Vec3> = second.vertices.iter().map(|vertex| vertex.point).collect();
1450 let vertices_a: Vec<Vec3> = first.vertices.iter().map(|vertex| vertex.point).collect();
1451 let flat = 1e-9 * scale;
1452 let mut bounds = DifferenceBounds { lower: 0.0, upper: 0.0, out: 0.0 };
1453 for polygon in &polygons_b {
1454 let (origin, normal) = polygon_plane(polygon)?;
1455 if vertices_b.iter().any(|vertex| vertex.sub(origin).dot(normal) > flat) {
1457 return None;
1458 }
1459 let out = vertices_a.iter().map(|vertex| vertex.sub(origin).dot(normal)).fold(0.0f64, f64::max);
1460 bounds.out = bounds.out.max(out);
1461 if out <= 0.0 {
1462 continue;
1463 }
1464 let part: f64 = polygons_a.iter().map(|face| clipped_cone_volume(face, origin, normal)).sum();
1465 bounds.lower = bounds.lower.max(part);
1466 bounds.upper += part;
1467 }
1468 Some(bounds)
1469}
1470
1471pub fn below_tolerance_rescale_enabled() -> bool {
1481 crate::switch!("BREP_BELOW_TOLERANCE_RESCALE", false)
1482}
1483
1484fn below_tolerance_rescaled(first: &BrepSolid, second: &BrepSolid, operation: BooleanOperation, options: &BooleanOptions) -> Option<BrepSolid> {
1485 if !below_tolerance_rescale_enabled()
1486 || options.tolerances.is_some()
1487 || [first, second].iter().any(|solid| face_count(solid) > SLIVER_ANSWER_FACES || !closed_single_shell(solid))
1488 {
1489 return None;
1490 }
1491 let (volume_exact, area_exact) = convex_pair_measures(first, second, operation)?;
1492 let volume_slack = 1e-9 * body_volume(first)?.max(body_volume(second)?);
1493 let area_slack = 1e-9 * area_exact.max(1.0);
1494 for factor in [100.0, 1000.0] {
1495 let scaled = |solid: &BrepSolid| crate::rescale::scale_operand(solid, factor, "boolean").ok();
1496 let (Some(a), Some(b)) = (scaled(first), scaled(second)) else {
1497 continue;
1498 };
1499 let mut scaled_options = options.clone();
1500 scaled_options.imprint.maximum_ssi_step = scaled_options.imprint.maximum_ssi_step.map(|step| step * factor);
1501 let Ok(outcome) = boolean_operation_with_diagnostics(&a, &b, operation, &scaled_options) else {
1502 continue;
1503 };
1504 let Ok(answer) = crate::rescale::scale_operand(&outcome.value, 1.0 / factor, "boolean") else {
1505 continue;
1506 };
1507 let Ok(properties) = crate::solid_mass_properties(&answer) else {
1508 continue;
1509 };
1510 if (properties.volume.abs() - volume_exact).abs() <= volume_slack
1511 && (properties.surface_area - area_exact).abs() <= area_slack
1512 && !answer.validate().iter().any(|issue| issue.severity == "error")
1513 {
1514 return Some(answer);
1515 }
1516 }
1517 None
1518}
1519
1520fn convex_pair_measures(first: &BrepSolid, second: &BrepSolid, operation: BooleanOperation) -> Option<(f64, f64)> {
1526 let scale = crate::solid_tolerance::solid_scale(first).max(crate::solid_tolerance::solid_scale(second)).max(1.0);
1527 let (polygons_a, polygons_b) = (face_polygons(first, scale)?, face_polygons(second, scale)?);
1528 let (planes_a, planes_b) = (convex_planes(&polygons_a, scale)?, convex_planes(&polygons_b, scale)?);
1529 let zero = Vec3::new(0.0, 0.0, 0.0);
1530 let read = |polygons: &[Vec<Vec3>], planes: &[(Vec3, Vec3)]| {
1532 let (mut cone, mut area, mut inside_area) = (0.0, 0.0, 0.0);
1533 for polygon in polygons {
1534 area += vector_area(polygon, zero).length();
1535 let mut inside = polygon.clone();
1536 for &(origin, normal) in planes {
1537 inside = clip_polygon(&inside, origin, normal.scale(-1.0));
1538 if inside.len() < 3 {
1539 break;
1540 }
1541 }
1542 if inside.len() >= 3 {
1543 let vector = vector_area(&inside, zero);
1544 cone += inside[0].dot(vector) / 3.0;
1545 inside_area += vector.length();
1546 }
1547 }
1548 (cone, area, inside_area)
1549 };
1550 let (cone_a, area_a, inside_a) = read(&polygons_a, &planes_b);
1551 let (cone_b, area_b, inside_b) = read(&polygons_b, &planes_a);
1552 let (volume_a, volume_b) = (body_volume(first)?, body_volume(second)?);
1553 let common = cone_a + cone_b;
1554 Some(match operation {
1555 BooleanOperation::Intersect => (common, inside_a + inside_b),
1556 BooleanOperation::Union => (volume_a + volume_b - common, (area_a - inside_a) + (area_b - inside_b)),
1557 BooleanOperation::Subtract => (volume_a - common, (area_a - inside_a) + inside_b),
1558 })
1559}
1560
1561fn convex_planes(polygons: &[Vec<Vec3>], scale: f64) -> Option<Vec<(Vec3, Vec3)>> {
1564 let planes = polygons.iter().map(|polygon| polygon_plane(polygon)).collect::<Option<Vec<_>>>()?;
1565 let flat = 1e-9 * scale;
1566 let convex = planes.iter().all(|&(origin, normal)| polygons.iter().flatten().all(|vertex| vertex.sub(origin).dot(normal) <= flat));
1567 convex.then_some(planes)
1568}
1569
1570fn clip_polygon(polygon: &[Vec3], origin: Vec3, normal: Vec3) -> Vec<Vec3> {
1573 let side = |point: Vec3| point.sub(origin).dot(normal);
1574 let mut kept = Vec::with_capacity(polygon.len() + 2);
1575 for (index, &point) in polygon.iter().enumerate() {
1576 let next = polygon[(index + 1) % polygon.len()];
1577 let (here, there) = (side(point), side(next));
1578 if here >= 0.0 {
1579 kept.push(point);
1580 }
1581 if (here >= 0.0) != (there >= 0.0) {
1582 let t = here / (here - there);
1583 kept.push(point.add(next.sub(point).scale(t)));
1584 }
1585 }
1586 kept
1587}
1588
1589fn face_polygons(solid: &BrepSolid, scale: f64) -> Option<Vec<Vec<Vec3>>> {
1593 let vertex = |id: u64| solid.vertices.iter().find(|vertex| vertex.id == id).map(|vertex| vertex.point);
1594 let mut polygons = Vec::new();
1595 for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
1596 if !face.surface.is_affine().ok()? {
1597 return None;
1598 }
1599 for lp in &face.loops {
1600 let mut polygon = Vec::with_capacity(lp.coedges.len());
1601 for coedge in &lp.coedges {
1602 let edge = solid.edges.iter().find(|edge| edge.id == coedge.edge_id)?;
1603 let (start, end) = (vertex(edge.start_vertex_id)?, vertex(edge.end_vertex_id)?);
1604 let chord = end.sub(start);
1605 let length = chord.length();
1606 if edge.degenerate || length <= 1e-12 * scale {
1607 return None;
1608 }
1609 for control in &edge.curve.control_points {
1610 let offset = control.point().ok()?.sub(start);
1611 if offset.cross(chord).length() / length > 1e-9 * scale {
1612 return None;
1613 }
1614 }
1615 polygon.push(if coedge.forward { start } else { end });
1616 }
1617 polygons.push(polygon);
1618 }
1619 }
1620 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();
1622 if !(volume.abs() > 0.0) {
1623 return None;
1624 }
1625 if volume < 0.0 {
1626 for polygon in &mut polygons {
1627 polygon.reverse();
1628 }
1629 }
1630 Some(polygons)
1631}
1632
1633fn polygon_plane(polygon: &[Vec3]) -> Option<(Vec3, Vec3)> {
1635 let origin = *polygon.first()?;
1636 Some((origin, vector_area(polygon, origin).normalized().ok()?))
1637}
1638
1639fn vector_area(polygon: &[Vec3], origin: Vec3) -> Vec3 {
1640 let mut area = Vec3::new(0.0, 0.0, 0.0);
1641 for (index, point) in polygon.iter().enumerate() {
1642 let next = polygon[(index + 1) % polygon.len()];
1643 area = area.add(point.sub(origin).cross(next.sub(origin)));
1644 }
1645 area.scale(0.5)
1646}
1647
1648fn clipped_cone_volume(polygon: &[Vec3], origin: Vec3, normal: Vec3) -> f64 {
1654 let clipped: Vec<Vec3> = if normal.length() == 0.0 { polygon.to_vec() } else { clip_polygon(polygon, origin, normal) };
1655 if clipped.len() < 3 {
1656 return 0.0;
1657 }
1658 clipped[0].sub(origin).dot(vector_area(&clipped, origin)) / 3.0
1659}
1660
1661const BELOW_TOLERANCE_BAND: f64 = 10.0 * crate::tolerance::WELD_FLOOR;
1664
1665pub fn unresolved_merge_refusal_enabled() -> bool {
1675 crate::switch!("BREP_UNRESOLVED_MERGE_REFUSAL", false)
1676}
1677
1678pub fn sliver_shell_drop_enabled() -> bool {
1691 crate::switch!("BREP_SLIVER_SHELL_DROP", true)
1692}
1693
1694const SLIVER_SHELL_THICKNESS: f64 = 1e-12;
1698
1699pub fn sliver_shell_fast_on() -> bool {
1714 crate::switch!("BREP_SLIVER_SHELL_FAST", true)
1715}
1716
1717fn sliver_shell_fast_check_on() -> bool {
1718 crate::switch!("BREP_SLIVER_SHELL_FAST_CHECK", false)
1719}
1720
1721thread_local! {
1722 static SLIVER_FAST_CHECK: std::cell::Cell<(u64, u64, u64)> = const { std::cell::Cell::new((0, 0, 0)) };
1723}
1724
1725pub fn sliver_shell_fast_check_take() -> (u64, u64, u64) {
1728 SLIVER_FAST_CHECK.with(|cell| cell.replace((0, 0, 0)))
1729}
1730
1731fn sliver_fast_record(compared: u64, differed: u64, kept: u64) {
1732 SLIVER_FAST_CHECK.with(|cell| {
1733 let (a, b, c) = cell.get();
1734 cell.set((a + compared, b + differed, c + kept));
1735 });
1736}
1737
1738fn face_area_upper_bound(surface: &crate::NurbsSurface) -> Option<f64> {
1746 let net = &surface.control_points;
1747 let rows = net.len();
1748 let columns = net.first()?.len();
1749 if rows < 2 || columns < 2 || net.iter().any(|row| row.len() != columns) {
1750 return None;
1751 }
1752 let (p, q) = (surface.degree_u, surface.degree_v);
1753 let (us, vs) = (&surface.knots_u, &surface.knots_v);
1754 if us.len() != rows + p + 1 || vs.len() != columns + q + 1 {
1755 return None;
1756 }
1757 let mut w_min = f64::INFINITY;
1758 let mut w_max = 0.0f64;
1759 let mut point_max = 0.0f64;
1760 for c in net.iter().flatten() {
1761 if !(c.w > 0.0) {
1762 return None;
1763 }
1764 w_min = w_min.min(c.w);
1765 w_max = w_max.max(c.w);
1766 point_max = point_max.max((c.x * c.x + c.y * c.y + c.z * c.z).sqrt());
1767 }
1768 let hodograph = |along_u: bool| -> Option<(f64, f64)> {
1770 let (count, degree, knots) = if along_u { (rows, p, us) } else { (columns, q, vs) };
1771 let (mut dp, mut dw) = (0.0f64, 0.0f64);
1772 for i in 0..count - 1 {
1773 let span = knots[i + degree + 1] - knots[i + 1];
1774 if !(span > 0.0) {
1775 continue;
1776 }
1777 let scale = degree as f64 / span;
1778 let others = if along_u { columns } else { rows };
1779 for j in 0..others {
1780 let (a, b) = if along_u { (net[i][j], net[i + 1][j]) } else { (net[j][i], net[j][i + 1]) };
1781 let (x, y, z) = (b.x - a.x, b.y - a.y, b.z - a.z);
1782 dp = dp.max(scale * (x * x + y * y + z * z).sqrt());
1783 dw = dw.max(scale * (b.w - a.w).abs());
1784 }
1785 }
1786 Some((dp, dw))
1787 };
1788 let (pu, wu) = hodograph(true)?;
1789 let (pv, wv) = hodograph(false)?;
1790 let su = (pu * w_max + point_max * wu) / (w_min * w_min);
1791 let sv = (pv * w_max + point_max * wv) / (w_min * w_min);
1792 let extent_u = us[us.len() - 1] - us[0];
1793 let extent_v = vs[vs.len() - 1] - vs[0];
1794 let bound = su * sv * extent_u * extent_v;
1795 bound.is_finite().then_some(bound)
1796}
1797
1798pub fn trimmed_face_area_upper_bound(face: &crate::topology::FaceRecord) -> Option<f64> {
1806 let s = &face.surface;
1807 let (u0, u1) = (*s.knots_u.first()?, *s.knots_u.last()?);
1808 let (v0, v1) = (*s.knots_v.first()?, *s.knots_v.last()?);
1809 let (du, dv) = (1e-12 * (u1 - u0).abs(), 1e-12 * (v1 - v0).abs());
1811 if !(du > 0.0 && dv > 0.0) {
1812 return None;
1813 }
1814 for coedge in face.loops.iter().flat_map(|lp| &lp.coedges) {
1815 for c in &coedge.pcurve.control_points {
1816 if !(c.w > 0.0) {
1817 return None;
1818 }
1819 let (u, v) = (c.x / c.w, c.y / c.w);
1820 if !(u >= u0 - du && u <= u1 + du && v >= v0 - dv && v <= v1 + dv) {
1821 return None;
1822 }
1823 }
1824 }
1825 face_area_upper_bound(s).map(|bound| 2.0 * bound)
1826}
1827
1828fn drop_sliver_shells(solid: &mut BrepSolid) -> usize {
1831 if !sliver_shell_drop_enabled() || !solid.kind.is_solid() || solid.shells.len() < 2 {
1832 return 0;
1833 }
1834 let floor = SLIVER_SHELL_THICKNESS * crate::solid_tolerance::solid_scale(solid).max(1.0);
1835 let degenerate: std::collections::HashSet<u64> = solid.edges.iter().filter(|edge| edge.degenerate).map(|edge| edge.id).collect();
1836 let mut drop = vec![false; solid.shells.len()];
1837 for (index, shell) in solid.shells.iter().enumerate() {
1838 if shell.faces.is_empty() {
1839 continue;
1840 }
1841 let mut uses: HashMap<u64, usize> = HashMap::default();
1843 for coedge in shell.faces.iter().flat_map(|face| &face.loops).flat_map(|lp| &lp.coedges) {
1844 if !degenerate.contains(&coedge.edge_id) {
1845 *uses.entry(coedge.edge_id).or_default() += 1;
1846 }
1847 }
1848 if uses.is_empty() || uses.values().any(|&count| count != 2) {
1849 continue;
1850 }
1851 let alone = BrepSolid { shells: vec![shell.clone()], mass_properties_cache: Default::default(), ..solid.clone() };
1852 let (fast, check) = (sliver_shell_fast_on(), sliver_shell_fast_check_on());
1853 let kept_fast = (fast || check)
1854 && shell
1855 .faces
1856 .iter()
1857 .map(trimmed_face_area_upper_bound)
1858 .sum::<Option<f64>>()
1859 .map(|area| floor * area)
1860 .filter(|bar| bar.is_finite() && *bar > 0.0)
1861 .and_then(|bar| crate::solid_signed_volume_for_sign(&alone, bar).ok().map(|volume| volume > bar))
1862 .unwrap_or(false);
1863 if kept_fast && !check {
1864 sliver_fast_record(0, 0, 1);
1865 continue;
1866 }
1867 let Ok(mass) = crate::solid_mass_properties(&alone) else {
1868 continue;
1869 };
1870 let thickness = mass.volume.abs() / mass.surface_area.max(f64::MIN_POSITIVE);
1871 if env_read!("BREP_DEBUG_SLIVER_SHELL").is_some() {
1872 eprintln!(
1873 "sliver-shell: shell {index} of {}: volume {:.6e} area {:.6e} thickness {thickness:.3e}",
1874 solid.shells.len(),
1875 mass.volume,
1876 mass.surface_area
1877 );
1878 }
1879 drop[index] = thickness < floor;
1880 if check {
1881 sliver_fast_record(1, u64::from(kept_fast && drop[index]), u64::from(kept_fast));
1882 }
1883 }
1884 let dropped = drop.iter().filter(|&&d| d).count();
1885 if dropped == 0 || dropped == solid.shells.len() {
1886 return 0;
1887 }
1888 let mut index = 0;
1889 solid.shells.retain(|_| {
1890 let keep = !drop[index];
1891 index += 1;
1892 keep
1893 });
1894 let used_edges: std::collections::HashSet<u64> = solid
1895 .shells
1896 .iter()
1897 .flat_map(|shell| &shell.faces)
1898 .flat_map(|face| &face.loops)
1899 .flat_map(|lp| &lp.coedges)
1900 .map(|coedge| coedge.edge_id)
1901 .collect();
1902 solid.edges.retain(|edge| used_edges.contains(&edge.id));
1903 let used_vertices: std::collections::HashSet<u64> =
1904 solid.edges.iter().flat_map(|edge| [edge.start_vertex_id, edge.end_vertex_id]).collect();
1905 solid.vertices.retain(|vertex| used_vertices.contains(&vertex.id));
1906 solid.mass_properties_cache = Default::default();
1907 refresh_derived_genus(solid);
1909 dropped
1910}
1911
1912fn unresolved_merge_refusal(first: &BrepSolid, second: &BrepSolid) -> Option<KernelRefusal> {
1913 let (lower, upper) = (crate::tolerance::COINCIDENCE_DISTANCE_FLOOR, crate::tolerance::WELD_FLOOR);
1914 let (face_a, face_b, separation) = planar_faces_apart_within(first, second, lower, upper)?;
1915 Some(KernelRefusal::unsupported(
1916 KernelStage::Intersect,
1917 "below_modelling_tolerance",
1918 format!(
1919 "boolean: face {face_a} of the first operand and face {face_b} of the second are planes nearly on one \
1920 another, {separation:.3e} apart at most over their shared extent: farther than a coincidence \
1921 ({lower:.0e}) and closer than the kernel resolves ({upper:.0e}), so the step between them would be \
1922 welded away"
1923 ),
1924 ))
1925}
1926
1927fn below_tolerance_refusal(first: &BrepSolid, second: &BrepSolid, error: Option<&KernelRefusal>) -> Option<KernelRefusal> {
1928 let (face_a, face_b, separation) = near_coincident_planar_faces(first, second)?;
1929 let message = format!(
1930 "boolean: face {face_a} of the first operand and face {face_b} of the second are planes nearly on one \
1931 another, {separation:.3e} apart at most over their shared extent: the slivers between them are below the \
1932 modelling tolerance ({BELOW_TOLERANCE_BAND:.0e}), so the kernel cannot resolve them{}",
1933 error.map(|error| format!(" (the exact arrangement said: {})", error.message.chars().take(160).collect::<String>())).unwrap_or_default()
1934 );
1935 Some(KernelRefusal::unsupported(KernelStage::Intersect, "below_modelling_tolerance", message))
1936}
1937
1938fn near_coincident_planar_faces(first: &BrepSolid, second: &BrepSolid) -> Option<(u64, u64, f64)> {
1942 let scale = crate::solid_tolerance::solid_scale(first).max(crate::solid_tolerance::solid_scale(second)).max(1.0);
1943 planar_faces_apart_within(first, second, 1e-9 * scale, BELOW_TOLERANCE_BAND)
1944}
1945
1946fn planar_faces_apart_within(first: &BrepSolid, second: &BrepSolid, lower: f64, upper: f64) -> Option<(u64, u64, f64)> {
1950 struct Planar {
1951 id: u64,
1952 origin: Vec3,
1953 normal: Vec3,
1954 corners: Vec<Vec3>,
1955 bounds: crate::spatial::Aabb,
1956 }
1957 let read = |solid: &BrepSolid| -> Vec<Planar> {
1958 let at = |id: u64| solid.vertices.iter().find(|vertex| vertex.id == id).map(|vertex| vertex.point);
1959 solid
1960 .shells
1961 .iter()
1962 .flat_map(|shell| &shell.faces)
1963 .filter_map(|face| {
1964 if !face.surface.is_affine().ok()? {
1965 return None;
1966 }
1967 let origin = face.surface.control_points[0][0].point().ok()?;
1968 let a = face.surface.control_points[1][0].point().ok()?.sub(origin);
1969 let b = face.surface.control_points[0][1].point().ok()?.sub(origin);
1970 let normal = a.cross(b).normalized().ok()?;
1971 let corners: Vec<Vec3> = face
1972 .loops
1973 .iter()
1974 .flat_map(|lp| &lp.coedges)
1975 .filter_map(|coedge| solid.edges.iter().find(|edge| edge.id == coedge.edge_id))
1976 .flat_map(|edge| [at(edge.start_vertex_id), at(edge.end_vertex_id)])
1977 .flatten()
1978 .collect();
1979 if corners.is_empty() {
1980 return None;
1981 }
1982 let bounds = crate::spatial::Aabb::from_points(corners.clone());
1983 Some(Planar { id: face.id, origin, normal, corners, bounds })
1984 })
1985 .collect()
1986 };
1987 let (faces_a, faces_b) = (read(first), read(second));
1988 for a in &faces_a {
1989 for b in &faces_b {
1990 if a.normal.cross(b.normal).length() > 1e-3 {
1991 continue;
1992 }
1993 if !a.bounds.intersects(b.bounds, upper) {
1994 continue;
1995 }
1996 let separation = a
1997 .corners
1998 .iter()
1999 .map(|corner| corner.sub(b.origin).dot(b.normal).abs())
2000 .chain(b.corners.iter().map(|corner| corner.sub(a.origin).dot(a.normal).abs()))
2001 .fold(0.0f64, f64::max);
2002 if separation > lower && separation <= upper {
2003 return Some((a.id, b.id, separation));
2004 }
2005 }
2006 }
2007 None
2008}
2009
2010pub fn one_use_edges(solid: &BrepSolid) -> usize {
2011 let mut uses: HashMap<u64, usize> = HashMap::default();
2012 for coedge in solid
2013 .shells
2014 .iter()
2015 .flat_map(|shell| &shell.faces)
2016 .flat_map(|face| &face.loops)
2017 .flat_map(|loop_record| &loop_record.coedges)
2018 {
2019 *uses.entry(coedge.edge_id).or_default() += 1;
2020 }
2021 solid
2022 .edges
2023 .iter()
2024 .filter(|edge| !edge.degenerate && uses.get(&edge.id) == Some(&1))
2025 .count()
2026}
2027
2028fn body_volume(solid: &BrepSolid) -> Option<f64> {
2030 if solid.shells.is_empty() {
2031 return Some(0.0);
2032 }
2033 solid_signed_volume(solid).ok().map(f64::abs)
2034}
2035
2036struct InclusionExclusion {
2039 formula: &'static str,
2042 reading: &'static str,
2044 read: f64,
2046 expected: f64,
2048}
2049
2050fn isotropic_chart_identity(
2059 first: &BrepSolid,
2060 second: &BrepSolid,
2061 rescaled_first: &BrepSolid,
2062 rescaled_second: &BrepSolid,
2063 operation: BooleanOperation,
2064 options: &BooleanOptions,
2065 result: &BrepSolid,
2066) -> Result<(), String> {
2067 let _caller = crate::mass_caller("boolean.isotropic_chart_identity");
2068 let va = solid_signed_volume(first).ok().map(f64::abs);
2069 let vb = solid_signed_volume(second).ok().map(f64::abs);
2070 let volume = body_volume(result).ok_or("its body has no volume")?;
2071 if let (Some(va), Some(vb)) = (va, vb) {
2072 if !volume_within_csg_bounds(operation, va, vb, volume) {
2073 return Err(format!("volume {volume:.9} outside the CSG bound of {va:.9} and {vb:.9}"));
2074 }
2075 }
2076 let identity = inclusion_exclusion_volume(first, second, operation, options, va, vb, false)
2077 .or_else(|| isotropic_chart::with_active(|| inclusion_exclusion_volume(rescaled_first, rescaled_second, operation, options, va, vb, false)))
2078 .ok_or("no exact-lane boolean of the operands clears to read the inclusion-exclusion identity")?;
2079 let bar = crate::VOLUME_DRIFT_ABS.max(crate::VOLUME_DRIFT_REL * identity.expected.abs());
2080 if (volume - identity.expected).abs() > bar {
2081 return Err(format!(
2082 "volume {volume:.9} against the identity {} = {:.9} (the {} reads {:.9}), bar {bar:.3e}",
2083 identity.formula, identity.expected, identity.reading, identity.read
2084 ));
2085 }
2086 Ok(())
2087}
2088
2089fn inclusion_exclusion_volume(
2100 first: &BrepSolid,
2101 second: &BrepSolid,
2102 operation: BooleanOperation,
2103 options: &BooleanOptions,
2104 va: Option<f64>,
2105 vb: Option<f64>,
2106 own_first: bool,
2107) -> Option<InclusionExclusion> {
2108 use BooleanOperation::{Intersect, Subtract, Union};
2109 let (va, vb) = (va?, vb?);
2110 let own = match operation {
2111 Intersect => (Intersect, false, "first ∩ second"),
2112 Union => (Union, false, "first ∪ second"),
2113 Subtract => (Subtract, false, "first − second"),
2114 };
2115 let readings = [
2116 (Intersect, false, "first ∩ second"),
2117 (Intersect, true, "second ∩ first"),
2118 (Union, false, "first ∪ second"),
2119 (Union, true, "second ∪ first"),
2120 (Subtract, false, "first − second"),
2121 (Subtract, true, "second − first"),
2122 ];
2123 let own_reading = own_first.then_some(own);
2124 let leading = usize::from(own_first);
2125 for (index, (other, swapped, reading)) in own_reading.into_iter().chain(readings).enumerate() {
2126 if index >= leading && !swapped && std::mem::discriminant(&other) == std::mem::discriminant(&operation) {
2127 continue;
2128 }
2129 let (x, y) = if swapped { (second, first) } else { (first, second) };
2130 let Some(read) = boolean_operation_with_diagnostics(x, y, other, options)
2131 .ok()
2132 .and_then(|outcome| body_volume(&outcome.value))
2133 else {
2134 continue;
2135 };
2136 let intersection = match (other, swapped) {
2137 (Intersect, _) => read,
2138 (Union, _) => va + vb - read,
2139 (Subtract, false) => va - read,
2140 (Subtract, true) => vb - read,
2141 };
2142 let (formula, expected) = match operation {
2143 Intersect => ("V(first ∩ second)", intersection),
2144 Union => ("V(first) + V(second) − V(first ∩ second)", va + vb - intersection),
2145 Subtract => ("V(first) − V(first ∩ second)", va - intersection),
2146 };
2147 return Some(InclusionExclusion { formula, reading, read, expected });
2148 }
2149 None
2150}
2151
2152fn planar_operand_off_its_plane(
2161 first: &BrepSolid,
2162 second: &BrepSolid,
2163 options: &BooleanOptions,
2164) -> Option<(u8, u64, f64, f64)> {
2165 let policy = options
2166 .tolerances
2167 .clone()
2168 .unwrap_or_else(|| KernelTolerances::for_pair(first, second, options.tolerance));
2169 let weld = crate::tolerance::assembler_weld(policy.model);
2170 let mut worst: Option<(u8, u64, f64)> = None;
2171 for (operand, solid) in [(0u8, first), (1u8, second)] {
2172 let vertex_point = |id: u64| solid.vertices.iter().find(|v| v.id == id).map(|v| v.point);
2173 for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
2174 let Some(crate::AnalyticSurface::Plane {
2175 origin,
2176 u_dir,
2177 v_dir,
2178 ..
2179 }) = face.surface.analytic()
2180 else {
2181 continue;
2182 };
2183 let [loop_record] = face.loops.as_slice() else {
2184 continue;
2185 };
2186 let Ok(normal) = u_dir.cross(*v_dir).normalized() else {
2187 continue;
2188 };
2189 let mut off_plane = 0.0f64;
2190 let mut straight = true;
2191 for coedge in &loop_record.coedges {
2192 let Some(edge) = solid.edges.iter().find(|edge| edge.id == coedge.edge_id) else {
2193 straight = false;
2194 break;
2195 };
2196 let (Some(start), Some(end)) =
2197 (vertex_point(edge.start_vertex_id), vertex_point(edge.end_vertex_id))
2198 else {
2199 straight = false;
2200 break;
2201 };
2202 let chord = end.sub(start);
2203 let length = chord.length();
2204 if edge.degenerate || length <= weld {
2205 straight = false;
2206 break;
2207 }
2208 let direction = chord.scale(1.0 / length);
2209 for fraction in [0.25, 0.5, 0.75] {
2210 let Ok(point) = edge.curve.evaluate(edge.t0 + (edge.t1 - edge.t0) * fraction) else {
2211 straight = false;
2212 break;
2213 };
2214 let delta = point.sub(start);
2215 let along = delta.dot(direction);
2216 if delta.sub(direction.scale(along)).length() > weld
2217 || along < -weld
2218 || along > length + weld
2219 {
2220 straight = false;
2221 break;
2222 }
2223 }
2224 if !straight {
2225 break;
2226 }
2227 off_plane = off_plane.max(start.sub(*origin).dot(normal).abs());
2228 }
2229 if straight && off_plane > weld && worst.is_none_or(|(_, _, gap)| off_plane > gap) {
2230 worst = Some((operand, face.id, off_plane));
2231 }
2232 }
2233 }
2234 worst.map(|(operand, face_id, gap)| (operand, face_id, gap, weld))
2235}
2236
2237fn volume_within_csg_bounds(operation: BooleanOperation, va: f64, vb: f64, vr: f64) -> bool {
2240 let slack = 1e-2 * (va + vb).max(1.0);
2241 match operation {
2242 BooleanOperation::Union => vr >= va.max(vb) - slack && vr <= va + vb + slack,
2244 BooleanOperation::Subtract => vr <= va + slack && vr >= -slack,
2246 BooleanOperation::Intersect => vr <= va.min(vb) + slack && vr >= -slack,
2248 }
2249}
2250
2251fn reverse_fragment(fragment: &mut FaceFragmentRecord) -> Result<(), KernelRefusal> {
2278 fragment.same_sense = !fragment.same_sense;
2279 for loop_record in &mut fragment.loops {
2280 loop_record.coedges.reverse();
2281 for coedge in &mut loop_record.coedges {
2282 coedge.forward = !coedge.forward;
2283 coedge.pcurve = coedge.pcurve.reversed().or_refuse(KernelStage::Validate, "reversed")?;
2284 }
2285 }
2286 Ok(())
2287}
2288
2289fn build_nary_imprint(
2298 operands: &[BrepSolid],
2299 options: &ImprintOptions,
2300) -> Result<(ImprintResultRecord, Vec<(FaceKey, FaceKey)>), KernelRefusal> {
2301 let mut section_evidence = false;
2302 let mut cosurface: Vec<(FaceKey, FaceKey)> = Vec::new();
2303 let mut vertices: Vec<ImprintVertex> = Vec::new();
2304 let mut pieces: Vec<ImprintPieceRecord> = Vec::new();
2305 let mut by_face: HashMap<(u8, u64), Vec<u64>> = HashMap::default();
2306 let mut edge_splits: HashMap<(u8, u64), Vec<f64>> = HashMap::default();
2307 let mut next_vertex_id: u64 = 1;
2308 let mut next_piece_id: u64 = 1;
2309
2310 let profile = crate::profile::profile_enabled();
2312 let (mut empty_pairs, mut empty_ms, mut full_pairs, mut full_ms) = (0usize, 0.0f64, 0usize, 0.0f64);
2313 for i in 0..operands.len() {
2314 for j in (i + 1)..operands.len() {
2315 let pair_started = profile.then(web_time::Instant::now);
2316 let pair = build_imprints(&operands[i], &operands[j], options)?;
2317 if let Some(started) = pair_started {
2318 let ms = started.elapsed().as_secs_f64() * 1000.0;
2319 if pair.pieces.is_empty() && pair.vertices.is_empty() && pair.edge_splits.is_empty() {
2320 empty_pairs += 1;
2321 empty_ms += ms;
2322 } else {
2323 full_pairs += 1;
2324 full_ms += ms;
2325 }
2326 }
2327 let remap = |operand: u8| -> u8 {
2328 if operand == 0 {
2329 i as u8
2330 } else {
2331 j as u8
2332 }
2333 };
2334
2335 section_evidence = section_evidence || pair.section_evidence;
2336 for (first, second) in &pair.cosurface_pairs {
2337 let global = |key: &FaceKey| FaceKey { operand: remap(key.operand), face_id: key.face_id };
2338 cosurface.push((global(first), global(second)));
2339 }
2340 let mut vertex_map: HashMap<u64, u64> = HashMap::default();
2341 for vertex in &pair.vertices {
2342 let global = next_vertex_id;
2343 next_vertex_id += 1;
2344 vertex_map.insert(vertex.id, global);
2345 vertices.push(ImprintVertex {
2346 id: global,
2347 point: vertex.point,
2348 });
2349 }
2350
2351 let mut piece_map: HashMap<u64, u64> = HashMap::default();
2352 for piece in &pair.pieces {
2353 let global = next_piece_id;
2354 next_piece_id += 1;
2355 piece_map.insert(piece.id, global);
2356 let mut mapped = piece.clone();
2357 mapped.id = global;
2358 mapped.start_vertex_id = *vertex_map
2359 .get(&piece.start_vertex_id)
2360 .ok_or_else(|| KernelRefusal::internal(KernelStage::Intersect, "nary.imprint", "n-ary imprint: piece references unknown vertex"))?;
2361 mapped.end_vertex_id = *vertex_map
2362 .get(&piece.end_vertex_id)
2363 .ok_or_else(|| KernelRefusal::internal(KernelStage::Intersect, "nary.imprint", "n-ary imprint: piece references unknown vertex"))?;
2364 for pcurve in &mut mapped.pcurves {
2365 pcurve.operand = remap(pcurve.operand);
2366 }
2367 mapped.support_faces = [
2368 FaceKey {
2369 operand: remap(piece.support_faces[0].operand),
2370 face_id: piece.support_faces[0].face_id,
2371 },
2372 FaceKey {
2373 operand: remap(piece.support_faces[1].operand),
2374 face_id: piece.support_faces[1].face_id,
2375 },
2376 ];
2377 pieces.push(mapped);
2378 }
2379
2380 for entry in &pair.by_face {
2381 let list = by_face
2382 .entry((remap(entry.operand), entry.face_id))
2383 .or_default();
2384 for piece_id in &entry.piece_ids {
2385 let global = *piece_map.get(piece_id).ok_or_else(|| {
2386 KernelRefusal::internal(KernelStage::Intersect, "nary.imprint", "n-ary imprint: by_face references unknown piece")
2387 })?;
2388 list.push(global);
2389 }
2390 }
2391
2392 for split in &pair.edge_splits {
2393 edge_splits
2394 .entry((remap(split.operand), split.edge_id))
2395 .or_default()
2396 .extend(split.parameters.iter().copied());
2397 }
2398 }
2399 }
2400 if profile {
2401 profile_line!("boolean.nary.imprint_pairs empty={empty_pairs} empty_ms={empty_ms:.2} full={full_pairs} full_ms={full_ms:.2}");
2402 }
2403
2404 Ok((ImprintResultRecord {
2405 faces_in_unproved_pairs: None,
2406 vertices,
2407 pieces,
2408 tangent_nodes: Vec::new(),
2409 barrier_edges: Vec::new(),
2410 section_evidence,
2411 cosurface_pairs: Vec::new(),
2412 operand_sliver_regions: Vec::new(),
2413 tangent_sections: Vec::new(),
2414 by_face: by_face
2415 .into_iter()
2416 .map(|((operand, face_id), piece_ids)| FaceImprints {
2417 operand,
2418 face_id,
2419 piece_ids,
2420 })
2421 .collect(),
2422 edge_splits: edge_splits
2423 .into_iter()
2424 .map(|((operand, edge_id), parameters)| EdgeSplitRecord {
2425 operand,
2426 edge_id,
2427 parameters,
2428 })
2429 .collect(),
2430 }, cosurface))
2431}
2432
2433pub fn boolean_operation_nary(
2444 operands: &[BrepSolid],
2445 operation: BooleanOperation,
2446) -> Result<BrepSolid, KernelRefusal> {
2447 boolean_operation_nary_with_options(operands, operation, &BooleanOptions::default())
2448}
2449
2450pub fn boolean_operation_nary_with_options(
2456 operands: &[BrepSolid],
2457 operation: BooleanOperation,
2458 options: &BooleanOptions,
2459) -> Result<BrepSolid, KernelRefusal> {
2460 let most = nary_chunk();
2465 if operands.len() > most && nary_chunks_on() {
2466 let mut whole = boolean_operation_nary_with_options(&operands[..most], operation, options)?;
2467 for chunk in operands[most..].chunks(most - 1) {
2468 if let [only] = chunk {
2471 whole = boolean_operation(&whole, only, operation, options)?;
2472 continue;
2473 }
2474 let mut next = Vec::with_capacity(chunk.len() + 1);
2475 next.push(whole);
2476 next.extend_from_slice(chunk);
2477 whole = boolean_operation_nary_with_options(&next, operation, options)?;
2478 }
2479 return Ok(whole);
2480 }
2481 let arranged = boolean_operation_nary_arranged(operands, operation, options);
2482 match arranged {
2483 Err(error) if nary_sequential_fallback_enabled() && operands.len() > 2 && error.message.contains("boolean assembly") => {
2484 let mut whole = operands[0].clone();
2487 for operand in &operands[1..] {
2488 whole = match boolean_operation(&whole, operand, operation, options) {
2489 Ok(solid) => solid,
2490 Err(_) => return Err(error),
2491 };
2492 }
2493 Ok(whole)
2494 }
2495 other => other,
2496 }
2497}
2498
2499const NARY_MOST: usize = 255;
2508
2509fn nary_chunk() -> usize {
2512 NARY_MOST
2513}
2514
2515
2516fn nary_chunks_on() -> bool {
2519 crate::switch!("BREP_NARY_CHUNKS", true)
2520}
2521
2522fn nary_scoped_on() -> bool {
2535 crate::switch!("BREP_NARY_SCOPED", true)
2536}
2537
2538fn nary_sequential_fallback_enabled() -> bool {
2539 crate::switch!("BREP_NARY_SEQUENTIAL_FALLBACK", true)
2540}
2541
2542fn boolean_operation_nary_arranged(
2543 operands: &[BrepSolid],
2544 operation: BooleanOperation,
2545 options: &BooleanOptions,
2546) -> Result<BrepSolid, KernelRefusal> {
2547 if operands.len() > 1 {
2548 if let Some(scaled) = WorkingScale::of(&operands.iter().collect::<Vec<_>>(), options)? {
2549 return scaled.run(
2550 || boolean_operation_nary_with_options(operands, operation, options),
2551 || boolean_operation_nary_with_options(&scaled.solids, operation, &scaled.options)
2552 .map_err(|error| scaled.refusal(error))
2553 .and_then(|solid| scaled.back(&solid)),
2554 );
2555 }
2556 }
2557 if operands.is_empty() {
2558 return Err(KernelRefusal::input(KernelStage::Collect, "operands", "boolean_operation_nary: no operands provided"));
2559 }
2560 if operands.len() == 1 {
2561 return Ok(operands[0].clone());
2562 }
2563 if operands.len() > nary_chunk() {
2564 return Err(KernelRefusal::input(KernelStage::Collect, "operands", "boolean_operation_nary: at most 255 operands supported"));
2565 }
2566 if let Some(aligned) = ball_align::align_balls_nary(operands, operation, options.tolerance) {
2569 return boolean_operation_nary_with_options(&aligned, operation, options);
2570 }
2571 let debug = std::env::var("BREP_DEBUG_BOOL").is_ok();
2572
2573 let mut policy = KernelTolerances::for_solid(&operands[0], options.tolerance);
2577 for operand in &operands[1..] {
2578 let candidate = KernelTolerances::for_solid(operand, options.tolerance);
2579 if candidate.sew_search > policy.sew_search {
2580 policy = candidate;
2581 }
2582 }
2583 policy.check().or_input(KernelStage::Collect, "tolerances")?;
2584 let tolerance = policy.model;
2585
2586 let nary_clock = NaryClock::start();
2589 let mut healed = operands.to_vec();
2590 let refit_scopes: Option<Vec<std::collections::HashSet<u64>>> = (nary_scoped_on() && crate::switch!("BREP_NARY_SCOPED_REFIT", true)).then(|| {
2595 let bounds: Vec<Option<crate::Aabb>> = operands
2596 .iter()
2597 .map(|operand| crate::fragment::bounded_carriers(operand).then(|| operand_bounds(operand)))
2598 .collect();
2599 operands
2600 .iter()
2601 .enumerate()
2602 .map(|(index, operand)| {
2603 operand
2604 .shells
2605 .iter()
2606 .flat_map(|shell| &shell.faces)
2607 .filter(|face| {
2608 !bounds.iter().enumerate().filter(|(other, _)| *other != index).all(|(_, other)| {
2609 other.as_ref().is_some_and(|other| crate::fragment::face_separated(face, *other, policy.sew_search))
2610 })
2611 })
2612 .map(|face| face.id)
2613 .collect()
2614 })
2615 .collect()
2616 });
2617 for (index, operand) in healed.iter_mut().enumerate() {
2618 crate::heal::heal_operands(operand, &policy)?;
2619 nary_clock.lap("nary.heal.operands_ms");
2620 match &refit_scopes {
2623 Some(scopes) => crate::heal::with_refit_face_scope(scopes[index].clone(), || crate::heal::refit_inherited_trims_reused(operand, &policy))?,
2624 None => crate::heal::refit_inherited_trims_reused(operand, &policy)?,
2625 }
2626 nary_clock.lap("nary.heal.refit_ms");
2627 normalize_operand_band_seams(operand)?;
2630 nary_clock.lap("nary.heal.seams_ms");
2631 }
2632
2633 let mut imprint_options = options.imprint.clone();
2635 imprint_options.tolerance = tolerance;
2636 let (imprint, cosurface) = build_nary_imprint(&healed, &imprint_options)?;
2637 nary_clock.lap("nary.imprint_ms");
2638
2639 let mut split = Vec::with_capacity(healed.len());
2641 for (index, operand) in healed.iter().enumerate() {
2642 split.push(apply_edge_splits(operand, index as u8, &imprint)?);
2643 }
2644 let mut fragments = Vec::with_capacity(split.len());
2645 for (index, solid) in split.iter().enumerate() {
2646 fragments.push(fragment_solid(solid, index as u8, &imprint)?);
2647 }
2648 nary_clock.lap("nary.split_fragment_ms");
2649
2650 let selected = select_fragments_nary(&fragments, &healed, operation, tolerance, debug)?;
2652 nary_clock.lap("nary.select_ms");
2653
2654 let solids: HashMap<u8, &BrepSolid> = split
2656 .iter()
2657 .enumerate()
2658 .map(|(index, solid)| (index as u8, solid))
2659 .collect();
2660 let solid = if nary_scoped_on() {
2661 let prepared: Vec<&BrepSolid> = healed.iter().collect();
2665 let touch = touch::TouchCensus::build_all(&prepared, &imprint, &cosurface);
2666 assemble::assemble_fragments_inherited_scoped(selected, &solids, &imprint, tolerance, &touch)?
2667 } else {
2668 assemble_fragments(selected, &solids, &imprint, tolerance)?
2669 };
2670 nary_clock.lap("nary.assemble_ms");
2671 let solid = if options.merge_coplanar_faces
2672 && std::env::var("BREP_COPLANAR_MERGE").as_deref() != Ok("0")
2673 {
2674 let merged = merge_same_surface_faces_excluding(
2675 &solid,
2676 tolerance,
2677 &options.keep_unmerged_name_substrs,
2678 )?;
2679 let merged = merge_curve_continuation_edges(&merged, tolerance).map_err(|refusal| KernelRefusal { stage: KernelStage::Validate, ..refusal })?;
2680 rejoin::rejoin_unless_referenced(merged, options, tolerance)
2681 } else {
2682 solid
2683 };
2684 nary_clock.lap("nary.merge_ms");
2685 let validation = solid.validate_detailed(&policy);
2686 nary_clock.lap("nary.validate_ms");
2687 if !validation.issues.is_empty() {
2688 return Err(KernelRefusal::new(
2689 RefusalClass::InvalidResultTopology { issues: validation.issues.len() as u32 },
2690 KernelStage::Validate,
2691 format!(
2692 "boolean_operation_nary: invalid result: {:?}",
2693 validation.issues
2694 )));
2695 }
2696 if debug {
2697 if let Ok(report) =
2698 crate::oracle::boolean_semantic_disagreement_nary(&healed, operation, &solid, 300)
2699 {
2700 if report.is_flagged() {
2701 eprintln!(
2702 "[oracle] n-ary semantic disagreement rate {:.4} ({} of {} decidable points); sample {:?}",
2703 report.disagreement_rate,
2704 report.disagreements.len(),
2705 report.considered,
2706 report.sample_disagreement()
2707 );
2708 }
2709 }
2710 }
2711 Ok(solid)
2712}
2713
2714fn attribute_to_tangent_node(error: KernelRefusal, nodes: &[Vec3]) -> KernelRefusal {
2745 let Some(node) = nodes.first() else {
2746 return error;
2747 };
2748 if !error.class.perturbation_eligible()
2749 || matches!(error.class, RefusalClass::TangentNodeSingularity)
2750 {
2751 return error;
2752 }
2753 if std::env::var("BREP_DEBUG_BOOL").is_ok() {
2754 eprintln!(
2755 "boolean: tear downstream of the tangent node at ({:.6},{:.6},{:.6}) attributed to it; the stage read: {}",
2756 node.x, node.y, node.z, error.message
2757 );
2758 }
2759 KernelRefusal::new(
2760 RefusalClass::TangentNodeSingularity,
2761 error.stage,
2762 format!(
2763 "boolean: unsupported singular/tangent-node surface intersection \
2764 at the tangent node at ({:.6},{:.6},{:.6}): the section through it did not \
2765 assemble into a closed shell",
2766 node.x, node.y, node.z
2767 ),
2768 )
2769}
2770
2771pub fn attribute_to_tangent_section(
2793 error: KernelRefusal,
2794 sections: &[crate::imprint::TangentSectionRecord],
2795 origins: &[FaceKey],
2796) -> KernelRefusal {
2797 if sections.is_empty()
2798 || !error.class.perturbation_eligible()
2799 || matches!(error.class, RefusalClass::TangentNodeSingularity)
2800 {
2801 return error;
2802 }
2803 let named = refusal_result_faces(&error.message)
2804 .into_iter()
2805 .filter_map(|id| origins.get(id.checked_sub(1)? as usize).copied())
2806 .collect::<Vec<FaceKey>>();
2807 let involving = |fallback: bool| {
2811 sections.iter().find(|section| {
2812 section.grazing.is_empty() != fallback && named.iter().any(|face| section.faces.contains(face))
2813 })
2814 };
2815 let Some(section) = involving(false).or_else(|| involving(true)) else {
2816 return error;
2817 };
2818 let at = |point: Vec3| {
2821 let shown = |value: f64| if value.abs() < 5e-7 { 0.0 } else { value };
2822 format!("({:.6},{:.6},{:.6})", shown(point.x), shown(point.y), shown(point.z))
2823 };
2824 let pierces = (!section.grazing.is_empty()).then(|| {
2830 let shown = section.grazing.len().min(4);
2831 let mut listed = section.grazing[..shown]
2832 .iter()
2833 .map(|(point, tangency)| format!("{} at |tan·n| = {tangency:.4}", at(*point)))
2834 .collect::<Vec<_>>()
2835 .join(", ");
2836 if section.grazing.len() > shown {
2837 listed.push_str(&format!(" and {} more", section.grazing.len() - shown));
2838 }
2839 listed
2840 });
2841 let pierce_only = section.pierce_only();
2842 let shape = if let (true, Some(pierces)) = (pierce_only, pierces.as_deref()) {
2843 format!(
2844 "cross at a grazing angle: a trim edge pierces the other carrier inside both \
2845 trims at {pierces}, below the marcher's start gate, and no transverse section was \
2846 marched between the pierces — a near-tangent crossing born on a tangent contact \
2847 (a third-order singularity) the imprint does not build yet"
2848 )
2849 } else if section.planar {
2850 format!(
2851 "touch along a tangent curve from {} to {} (length {:.6}, {} stations{}) which the \
2852 imprint does not build yet",
2853 at(section.start),
2854 at(section.end),
2855 section.length,
2856 section.stations,
2857 if section.closed { ", closed" } else { "" }
2858 )
2859 } else {
2860 format!(
2861 "touch along a curve through {} with neither carrier planar, a curved/curved \
2862 tangent contact the lane does not trace yet",
2863 at(section.start)
2864 )
2865 };
2866 let shape = match (pierce_only, pierces) {
2867 (false, Some(pierces)) => format!(
2868 "{shape}; a trim edge also pierces the other carrier inside both trims at {pierces}, \
2869 below the marcher's start gate, with no transverse section marched"
2870 ),
2871 _ => shape,
2872 };
2873 let involved = named
2874 .iter()
2875 .filter(|face| section.faces.contains(face))
2876 .map(|face| format!("{}/{}", face.operand, face.face_id))
2877 .collect::<Vec<_>>()
2878 .join(", ");
2879 KernelRefusal::new(
2880 RefusalClass::TangentNodeSingularity,
2881 error.stage,
2882 format!(
2883 "boolean: unsupported tangent-curve surface intersection between faces {}/{} and {}/{}: \
2884 the carriers {shape}; the refusal names face(s) {involved} the contact involves; {}",
2885 section.first.operand, section.first.face_id, section.second.operand, section.second.face_id,
2886 error.message
2887 ),
2888 )
2889}
2890
2891pub fn refusal_result_faces(message: &str) -> Vec<u64> {
2896 let mut ids = Vec::new();
2897 let digits_after = |text: &str| -> Option<u64> {
2898 let end = text.find(|c: char| !c.is_ascii_digit()).unwrap_or(text.len());
2899 text[..end].parse().ok()
2900 };
2901 for (index, _) in message.match_indices("face ") {
2902 if let Some(id) = digits_after(&message[index + "face ".len()..]) {
2903 ids.push(id);
2904 }
2905 }
2906 if let Some(start) = message.find("on faces [") {
2907 let rest = &message[start + "on faces [".len()..];
2908 let list = &rest[..rest.find(']').unwrap_or(rest.len())];
2909 for entry in list.split(", ") {
2910 let entry = entry.trim_start();
2911 if let Some(id) = digits_after(entry) {
2912 if entry[id.to_string().len()..].starts_with(" '") {
2913 ids.push(id);
2914 }
2915 }
2916 }
2917 }
2918 ids.sort_unstable();
2919 ids.dedup();
2920 ids
2921}
2922
2923pub fn boolean_operation_with_diagnostics(
2924 first: &BrepSolid,
2925 second: &BrepSolid,
2926 operation: BooleanOperation,
2927 options: &BooleanOptions,
2928) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
2929 if let Some(scaled) = WorkingScale::of(&[first, second], options)? {
2930 return scaled.run(
2931 || boolean_operation_with_diagnostics(first, second, operation, options),
2932 || {
2933 let mut outcome = boolean_operation_with_diagnostics(&scaled.solids[0], &scaled.solids[1], operation, &scaled.options)
2934 .map_err(|error| scaled.refusal(error))?;
2935 outcome.value = scaled.back(&outcome.value)?;
2936 outcome.diagnostics.count_n("working_scale.fired", 1);
2937 outcome.diagnostics.measure_max("working_scale.factor", scaled.factor);
2938 Ok(outcome)
2939 },
2940 );
2941 }
2942 let _account = profile::Scope::new("boolean.other");
2943 let (first_aligned, second_aligned) = ball_align::align_balls(first, second, operation, options.tolerance);
2946 let (first, second) = (first_aligned.as_ref(), second_aligned.as_ref());
2947 let closed_inputs = matches!(std::env::var("BREP_CLOSED_OPERAND_INPUT").as_deref(), Err(_) | Ok("1") | Ok("on"));
2948 if let (true, Some(later)) = (reseat::seam_reseat_enabled(), &options.seam_reseat_later_references) {
2949 let started = Instant::now();
2950 let (first, second) = reseat::reseat_tangent_seams(first, second, later, options.tolerance);
2951 profile_stage("seam_prepare_ms", started.elapsed().as_secs_f64() * 1000.0);
2952 return boolean_operation_with_diagnostics_impl(&first, &second, operation, options, closed_inputs).map(without_sliver_shells);
2953 }
2954 let cylinders = reseat::seam_reseat_cylinders_mode();
2957 if reseat::seam_reseat_enabled() && cylinders != crate::env_read::Mode::Off {
2958 let kinds = reseat::ContactKinds { planes: false, cylinders: true };
2959 let volume = |result: &Result<KernelOutcome<BrepSolid>, KernelRefusal>| {
2960 result.as_ref().ok().and_then(|outcome| crate::solid_mass_properties(&outcome.value).ok()).map(|mass| mass.volume)
2961 };
2962 if reseat::seam_reseat_retry_enabled() {
2963 let plain = boolean_operation_with_diagnostics_impl(first, second, operation, options, closed_inputs).map(without_sliver_shells);
2969 if plain.is_ok() {
2970 return plain;
2971 }
2972 let (reseated_first, reseated_second) = reseat::reseat_tangent_seams_of(first, second, &[], options.tolerance, kinds);
2973 let moved = matches!(reseated_first, std::borrow::Cow::Owned(_)) || matches!(reseated_second, std::borrow::Cow::Owned(_));
2974 if !moved {
2975 return plain;
2976 }
2977 let reseated = crate::imprint::driver::with_tangent_cylinder_filter(|| {
2978 boolean_operation_with_diagnostics_impl(&reseated_first, &reseated_second, operation, options, closed_inputs).map(without_sliver_shells)
2979 });
2980 if cylinders == crate::env_read::Mode::Check {
2981 eprintln!(
2982 "boolean.seam_reseat_cylinders check: plain refused, reseated retry {} volume {:?}",
2983 if reseated.is_ok() { "built" } else { "refused" },
2984 volume(&reseated)
2985 );
2986 return plain;
2987 }
2988 return match reseated {
2989 Ok(mut outcome) => {
2990 outcome.diagnostics.count_n("seam_reseat_cylinders.retry_built", 1);
2991 Ok(outcome)
2992 }
2993 Err(_) => plain,
2994 };
2995 }
2996 let (reseated_first, reseated_second) = reseat::reseat_tangent_seams_of(first, second, &[], options.tolerance, kinds);
2997 let moved = matches!(reseated_first, std::borrow::Cow::Owned(_)) || matches!(reseated_second, std::borrow::Cow::Owned(_));
2998 if moved {
2999 let reseated = boolean_operation_with_diagnostics_impl(&reseated_first, &reseated_second, operation, options, closed_inputs).map(without_sliver_shells);
3000 if cylinders == crate::env_read::Mode::On {
3001 return reseated;
3002 }
3003 let plain = boolean_operation_with_diagnostics_impl(first, second, operation, options, closed_inputs).map(without_sliver_shells);
3004 eprintln!(
3005 "boolean.seam_reseat_cylinders check: plain {} volume {:?}, reseated {} volume {:?}",
3006 if plain.is_ok() { "built" } else { "refused" },
3007 volume(&plain),
3008 if reseated.is_ok() { "built" } else { "refused" },
3009 volume(&reseated)
3010 );
3011 return plain;
3012 }
3013 }
3014 boolean_operation_with_diagnostics_impl(first, second, operation, options, closed_inputs).map(without_sliver_shells)
3015}
3016
3017fn without_sliver_shells(mut outcome: KernelOutcome<BrepSolid>) -> KernelOutcome<BrepSolid> {
3019 let dropped = drop_sliver_shells(&mut outcome.value);
3020 if dropped > 0 {
3021 outcome.diagnostics.count_n("sliver_shell.dropped", dropped as u64);
3022 }
3023 outcome
3024}
3025
3026pub fn boolean_operation_with_diagnostics_impl(
3027 first: &BrepSolid,
3028 second: &BrepSolid,
3029 operation: BooleanOperation,
3030 options: &BooleanOptions,
3031 closed_inputs: bool,
3032) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
3033 let _coedge_memo = crate::topology::CoedgeMemoScope::open(true);
3036 if matches!(operation, BooleanOperation::Intersect)
3039 && [first, second].iter().any(|body| body.kind == crate::BodyKind::Sheet)
3040 && match std::env::var("BREP_SHEET_TRIM").as_deref() {
3041 Ok("1") => true,
3042 Ok("0") => false,
3043 _ => options.sheet_trim,
3044 }
3045 {
3046 return sheet::trim(first, second, options);
3047 }
3048 if matches!(operation, BooleanOperation::Union | BooleanOperation::Subtract) {
3057 if let Some(operand) = [first, second]
3058 .iter()
3059 .position(|solid| solid.kind == crate::BodyKind::Sheet)
3060 {
3061 return Err(KernelRefusal::input(
3062 KernelStage::Collect,
3063 "sheet_operand",
3064 format!(
3065 "boolean: operand {operand} is a Sheet, which encloses no solid; union and \
3066 subtract of a sheet are refused; Intersect trims a Sheet by a Solid"
3067 ),
3068 ));
3069 }
3070 }
3071 let mut outcome = boolean_operation_with_diagnostics_core(first, second, operation, options)?;
3077 let closure_started = closed_inputs.then(Instant::now);
3078 if closed_inputs {
3079 for (operand, solid) in [first, second].into_iter().enumerate() {
3080 let open = one_use_edges(solid);
3081 if open > 0 {
3082 return Err(KernelRefusal::input(KernelStage::Collect, "operand_closure", format!(
3083 "boolean: operand {operand} is not a closed shell: {open} of its edges bound only one face, so its inside is undefined"
3084 )));
3085 }
3086 }
3087 }
3088 if let Some(started) = closure_started {
3089 let ms = started.elapsed().as_secs_f64() * 1000.0;
3090 profile_stage("operand_closure_ms", ms);
3091 outcome.diagnostics.measure_max("timing.operand_closure_ms", ms);
3092 }
3093 Ok(outcome)
3094}
3095
3096fn boolean_operation_with_diagnostics_core(
3097 first: &BrepSolid, second: &BrepSolid, operation: BooleanOperation, options: &BooleanOptions,
3098) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
3099
3100 if let Some(offset) = crate::recentre::control_offset_at_entry() {
3103 return boolean_operation_with_diagnostics_at_offset(first, second, operation, options, offset);
3104 }
3105 let mut bounds = operand_bounds(first);
3108 bounds.include(operand_bounds(second));
3109 if let Some(offset) = crate::recentre::guard_offset(bounds) {
3110 crate::recentre::profile_fired("boolean", offset, bounds);
3111 let mut outcome = boolean_translated(first, second, operation, options, offset, crate::recentre::EntryKind::Guard)?;
3112 outcome.diagnostics.count_n("recentre.fired", 1);
3113 outcome.diagnostics.measure_max("recentre.distance", offset.length());
3114 return Ok(outcome);
3115 }
3116 let mut tangent_nodes = Vec::new();
3117 let (mut outcome, soundness_candidates) =
3118 boolean_pipeline(first, second, operation, options, &mut tangent_nodes)
3119 .map_err(|error| attribute_to_tangent_node(error, &tangent_nodes))?;
3120 let stage_started = Instant::now();
3133 let accepted = match &soundness_candidates {
3134 Some(candidates) => crate::accept_sound_against_scoped(&[first, second], outcome.value, "boolean", candidates),
3137 None => crate::accept_sound_against(&[first, second], outcome.value, "boolean"),
3138 };
3139 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
3140 profile_stage("soundness_ms", stage_ms);
3141 outcome.diagnostics.measure_max("timing.soundness_ms", stage_ms);
3142 outcome.value = accepted?;
3143 Ok(outcome)
3144}
3145
3146pub fn boolean_operation_with_diagnostics_at_offset(
3150 first: &BrepSolid,
3151 second: &BrepSolid,
3152 operation: BooleanOperation,
3153 options: &BooleanOptions,
3154 offset: Vec3,
3155) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
3156 boolean_translated(first, second, operation, options, offset, crate::recentre::EntryKind::Control)
3157}
3158
3159fn boolean_translated(
3161 first: &BrepSolid,
3162 second: &BrepSolid,
3163 operation: BooleanOperation,
3164 options: &BooleanOptions,
3165 offset: Vec3,
3166 kind: crate::recentre::EntryKind,
3167) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
3168 let _entry = crate::recentre::TranslatedEntry::open(kind);
3169 let translate = |solid: &BrepSolid, offset: Vec3| {
3170 crate::recentre::translate_solid(solid, offset).map_err(|message| {
3171 KernelRefusal::internal(
3172 KernelStage::Collect,
3173 "translation_control",
3174 format!("boolean: the translation control could not move an operand: {message}"),
3175 )
3176 })
3177 };
3178 let moved_first = translate(first, offset)?;
3179 let moved_second = translate(second, offset)?;
3180 let outcome = boolean_operation_with_diagnostics(&moved_first, &moved_second, operation, options)?;
3181 let value = translate(&outcome.value, offset.scale(-1.0))?;
3182 Ok(KernelOutcome { value, diagnostics: outcome.diagnostics })
3183}
3184
3185struct NaryClock(Option<std::cell::Cell<web_time::Instant>>);
3188
3189impl NaryClock {
3190 fn start() -> Self {
3191 Self(crate::profile::profile_enabled().then(|| std::cell::Cell::new(web_time::Instant::now())))
3192 }
3193
3194 fn lap(&self, code: &str) {
3195 if let Some(cell) = &self.0 {
3196 let now = web_time::Instant::now();
3197 profile_stage(code, (now - cell.get()).as_secs_f64() * 1000.0);
3198 cell.set(now);
3199 }
3200 }
3201}
3202
3203fn profile_stage(code: &str, ms: f64) {
3207 let row = match code {
3208 "heal_ms" => Some("boolean.operand_prepare"),
3209 "imprint_ms" => Some("boolean.imprint"),
3210 "edge_split_ms" => Some("boolean.edge_split"),
3211 "fragment_ms" => Some("boolean.fragment"),
3212 "select_ms" => Some("boolean.select"),
3213 "assemble_ms" => Some("boolean.assemble"),
3214 "face_merge_ms" => Some("boolean.face_merge"),
3215 "soundness_ms" => Some("boolean.soundness"),
3216 "operand_closure_ms" => Some("boolean.operand_closure"),
3217 "seam_prepare_ms" => Some("boolean.seam_prepare"),
3218 "final_validate_ms" => Some("boolean.final_validate"),
3219 _ => None,
3220 };
3221 if let Some(row) = row { profile::record(row, ms); }
3222 if crate::profile::profile_enabled() {
3223 profile_line!("boolean.{code}={ms:.2}");
3224 }
3225}
3226
3227struct BooleanStageDump {
3232 directory: std::path::PathBuf,
3233 serial: usize,
3234}
3235
3236impl BooleanStageDump {
3237 fn open() -> Option<Self> {
3238 static SERIAL: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
3239 let directory = std::env::var("BREP_BOOLEAN_DUMP").ok().filter(|value| !value.is_empty())?;
3240 let serial = SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3241 Some(Self { directory: directory.into(), serial })
3242 }
3243
3244 fn write<T: Serialize + ?Sized>(&self, stage: &str, value: &T) {
3245 let path = self.directory.join(format!("{:03}-{stage}.json", self.serial));
3246 match serde_json::to_string(value) {
3247 Ok(text) => {
3248 if let Err(error) = std::fs::write(&path, text) {
3249 eprintln!("BREP_BOOLEAN_DUMP {}: {error}", path.display());
3250 }
3251 }
3252 Err(error) => eprintln!("BREP_BOOLEAN_DUMP {stage}: {error}"),
3253 }
3254 }
3255}
3256
3257pub fn boolean_policy(
3259 first: &BrepSolid,
3260 second: &BrepSolid,
3261 options: &BooleanOptions,
3262) -> Result<KernelTolerances, KernelRefusal> {
3263 let policy = options
3264 .tolerances
3265 .unwrap_or_else(|| KernelTolerances::for_pair(first, second, options.tolerance));
3266 policy.check().or_input(KernelStage::Collect, "tolerances")?;
3267 Ok(policy)
3268}
3269
3270fn prepared_operands(
3273 first: &BrepSolid,
3274 second: &BrepSolid,
3275 policy: &KernelTolerances,
3276) -> Result<(BrepSolid, BrepSolid), KernelRefusal> {
3277 let stage_started = Instant::now();
3286 let mut first_owned = first.clone();
3287 let mut second_owned = second.clone();
3288 crate::heal::heal_operands(&mut first_owned, policy)?;
3289 crate::heal::heal_operands(&mut second_owned, policy)?;
3290 profile_stage("heal.operands_ms", stage_started.elapsed().as_secs_f64() * 1_000.0);
3291 let refit_started = Instant::now();
3295 crate::heal::refit_inherited_trims_reused(&mut first_owned, policy)?;
3296 crate::heal::refit_inherited_trims_reused(&mut second_owned, policy)?;
3297 profile_stage("heal.refit_ms", refit_started.elapsed().as_secs_f64() * 1_000.0);
3298 if crate::profile::profile_enabled() {
3299 let (hits, misses) = crate::reading_memo::counts();
3300 profile_line!("boolean.reading_memo hits={hits} misses={misses}");
3301 let (served, stored) = crate::heal::refit_memo_counts_served_stored();
3302 profile_line!("boolean.refit_memo served={served} stored={stored}");
3303 let (served, stored, mismatches) = crate::heal::claim_record_memo_counts();
3304 profile_line!("boolean.claim_record_memo served={served} stored={stored} check_mismatches={mismatches}");
3305 }
3306 profile_stage("heal_ms", stage_started.elapsed().as_secs_f64() * 1_000.0);
3307 normalize_operand_band_seams(&mut first_owned)?;
3312 normalize_operand_band_seams(&mut second_owned)?;
3313 Ok((first_owned, second_owned))
3314}
3315
3316fn boolean_imprint_options(options: &BooleanOptions, tolerance: f64) -> ImprintOptions {
3317 let mut imprint_options = options.imprint.clone();
3318 imprint_options.tolerance = tolerance;
3319 imprint_options
3320}
3321
3322pub fn boolean_split_operands(
3332 first: &BrepSolid,
3333 second: &BrepSolid,
3334 options: &BooleanOptions,
3335) -> Result<(BrepSolid, BrepSolid), KernelRefusal> {
3336 if let Some(scaled) = WorkingScale::of(&[first, second], options)? {
3337 return scaled.run(
3338 || boolean_split_operands(first, second, options),
3339 || {
3340 let (split_first, split_second) = boolean_split_operands(&scaled.solids[0], &scaled.solids[1], &scaled.options)
3341 .map_err(|error| scaled.refusal(error))?;
3342 Ok((scaled.back(&split_first)?, scaled.back(&split_second)?))
3343 },
3344 );
3345 }
3346 let policy = boolean_policy(first, second, options)?;
3347 let (first, second) = prepared_operands(first, second, &policy)?;
3348 let imprint = build_imprints(&first, &second, &boolean_imprint_options(options, policy.model))?;
3349 let (split_first, _) = apply_edge_splits_with_map(&first, 0, &imprint)?;
3350 let (split_second, _) = apply_edge_splits_with_map(&second, 1, &imprint)?;
3351 Ok((split_first, split_second))
3352}
3353
3354fn operand_bounds(solid: &BrepSolid) -> crate::Aabb {
3358 let mut bounds = crate::Aabb::from_points(solid.vertices.iter().map(|vertex| vertex.point));
3359 for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
3360 match crate::Aabb::from_surface_controls(&face.surface) {
3361 Ok(face_bounds) => bounds.include(face_bounds),
3362 Err(_) => {
3363 return crate::Aabb {
3364 minimum: Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY),
3365 maximum: Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY),
3366 }
3367 }
3368 }
3369 }
3370 bounds
3371}
3372
3373fn line_or_point_contact(first: &BrepSolid, second: &BrepSolid, bounds: [crate::Aabb; 2]) -> bool {
3379 apart_axes(bounds) >= 2 && plain_hull_solid(first) && plain_hull_solid(second)
3380}
3381
3382fn boxes_share_no_interior(first: &BrepSolid, second: &BrepSolid, bounds: [crate::Aabb; 2]) -> bool {
3385 apart_axes(bounds) >= 1 && plain_hull_solid(first) && plain_hull_solid(second)
3386}
3387
3388fn apart_axes([a, b]: [crate::Aabb; 2]) -> usize {
3390 let apart = |a_min: f64, a_max: f64, b_min: f64, b_max: f64| a_max <= b_min || b_max <= a_min;
3391 [
3392 apart(a.minimum.x, a.maximum.x, b.minimum.x, b.maximum.x),
3393 apart(a.minimum.y, a.maximum.y, b.minimum.y, b.maximum.y),
3394 apart(a.minimum.z, a.maximum.z, b.minimum.z, b.maximum.z),
3395 ]
3396 .into_iter()
3397 .filter(|&apart| apart)
3398 .count()
3399}
3400
3401fn plain_hull_solid(solid: &BrepSolid) -> bool {
3403 solid.kind == crate::BodyKind::Solid
3404 && solid.cells.is_empty()
3405 && solid.shells.iter().flat_map(|shell| &shell.faces).all(|face| {
3406 face.surface.control_points.iter().flatten().all(|control| control.w > 0.0 && control.w.is_finite())
3407 })
3408}
3409
3410fn scope_proved_apart_on() -> bool {
3414 switch!(live "BREP_SCOPE_PROVED_APART", true)
3415}
3416
3417fn soundness_candidates(
3432 solid: &BrepSolid,
3433 scope: &AssemblyScope,
3434 bounds: [crate::Aabb; 2],
3435 band: f64,
3436 unproved: Option<&HashSet<crate::imprint::FaceKey>>,
3437) -> HashSet<u64> {
3438 let mut candidates = HashSet::default();
3439 for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
3440 if scope.examined.contains(&face.id) {
3441 candidates.insert(face.id);
3442 continue;
3443 }
3444 let Some(&operand) = scope.operand_of.get(&face.id) else {
3445 candidates.insert(face.id);
3446 continue;
3447 };
3448 let other = bounds[usize::from(operand == 0)];
3449 match crate::Aabb::from_surface_controls(&face.surface) {
3450 Ok(face_bounds) if !face_bounds.intersects(other, band) => {}
3451 _ => {
3452 let proved_clear = unproved.is_some_and(|unproved| {
3453 scope.source_of.get(&face.id).is_some_and(|key| !unproved.contains(key))
3454 });
3455 if !proved_clear {
3456 candidates.insert(face.id);
3457 }
3458 }
3459 }
3460 }
3461 candidates
3462}
3463
3464
3465fn touching_empty_enabled() -> bool {
3473 switch!("BREP_TOUCHING_EMPTY", true)
3474}
3475
3476thread_local! {
3477 static TOUCHING_PROOF: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
3480}
3481
3482fn hair_deep_overlap(first: &BrepSolid, second: &BrepSolid, tolerance: f64) -> bool {
3489 use crate::AnalyticSurface as A;
3490 fn faces(solid: &BrepSolid) -> Vec<(&crate::AnalyticSurface, crate::spatial::Aabb, &crate::NurbsSurface, &crate::FaceRecord)> {
3491 solid
3492 .shells
3493 .iter()
3494 .flat_map(|shell| &shell.faces)
3495 .filter_map(|face| Some((face.surface.analytic()?, crate::Aabb::from_surface_controls(&face.surface).ok()?, &face.surface, face)))
3496 .collect()
3497 }
3498 let along = |surface: &crate::NurbsSurface, axis: Vec3| {
3500 surface.control_points.iter().flatten().filter_map(|control| control.point().ok()).fold((f64::INFINITY, f64::NEG_INFINITY), |(low, high), point| {
3501 let at = point.dot(axis);
3502 (low.min(at), high.max(at))
3503 })
3504 };
3505 let crossing = |distance: f64, ra: f64, rb: f64| {
3506 let outer = ra + rb - distance;
3507 let nested = distance - (ra - rb).abs();
3508 outer > tolerance && nested > tolerance
3509 };
3510 let boxes_overlap = |a: &crate::spatial::Aabb, b: &crate::spatial::Aabb| {
3511 (a.maximum.x.min(b.maximum.x) - a.minimum.x.max(b.minimum.x)) > tolerance
3512 && (a.maximum.y.min(b.maximum.y) - a.minimum.y.max(b.minimum.y)) > tolerance
3513 && (a.maximum.z.min(b.maximum.z) - a.minimum.z.max(b.minimum.z)) > tolerance
3514 };
3515 for (a, box_a, surface_a, face_a) in faces(first) {
3516 for (b, box_b, surface_b, face_b) in faces(second) {
3517 if !boxes_overlap(&box_a, &box_b) {
3518 continue;
3519 }
3520 match (a, b) {
3521 (A::RuledRevolution { frame: fa, rho0: a0, rho1: a1, .. }, A::RuledRevolution { frame: fb, rho0: b0, rho1: b1, .. })
3522 if (a0 - a1).abs() <= tolerance && (b0 - b1).abs() <= tolerance =>
3523 {
3524 let offset = fb.origin.sub(fa.origin);
3525 let normal = fa.axis.cross(fb.axis);
3526 if normal.length() <= 1e-12 {
3529 let (low_a, high_a) = along(surface_a, fa.axis);
3530 let (low_b, high_b) = along(surface_b, fa.axis);
3531 if high_a.min(high_b) - low_a.max(low_b) <= tolerance {
3532 continue;
3533 }
3534 }
3535 let apart = if normal.length() <= 1e-12 {
3536 offset.sub(fa.axis.scale(offset.dot(fa.axis))).length()
3537 } else {
3538 offset.dot(normal).abs() / normal.length()
3539 };
3540 if crossing(apart, a0.abs(), b0.abs()) {
3541 return true;
3542 }
3543 }
3544 (A::Sphere { frame: fa, radius: ra }, A::Sphere { frame: fb, radius: rb }) => {
3545 if crossing(fb.origin.sub(fa.origin).length(), *ra, *rb)
3550 && !circle_off_face(face_a, first, (fa.origin, *ra), (fb.origin, *rb), tolerance)
3551 && !circle_off_face(face_b, second, (fb.origin, *rb), (fa.origin, *ra), tolerance)
3552 {
3553 return true;
3554 }
3555 }
3556 _ => {}
3557 }
3558 }
3559 }
3560 false
3561}
3562
3563fn circle_off_face(face: &crate::FaceRecord, solid: &BrepSolid, own: (Vec3, f64), other: (Vec3, f64), tolerance: f64) -> bool {
3571 use crate::classification::{parameter_point_in_face, PolygonClass};
3572 let ((ca, ra), (cb, rb)) = (own, other);
3573 if face.loops.iter().all(|lp| lp.coedges.is_empty()) {
3574 return false;
3575 }
3576 fn clear(curve: &crate::NurbsCurve, depth: u32, centre: Vec3, radius: f64, tolerance: f64) -> bool {
3581 let points: Option<Vec<Vec3>> = curve.control_points.iter().map(|control| if control.w > 0.0 { control.point().ok() } else { None }).collect();
3582 let Some(points) = points else { return false };
3583 if points.iter().all(|point| point.sub(centre).length() < radius - tolerance) {
3584 return true;
3585 }
3586 let (mut low, mut high) = (Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY), Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY));
3587 for point in &points {
3588 low = Vec3::new(low.x.min(point.x), low.y.min(point.y), low.z.min(point.z));
3589 high = Vec3::new(high.x.max(point.x), high.y.max(point.y), high.z.max(point.z));
3590 }
3591 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));
3592 if near.sub(centre).length() > radius + tolerance {
3593 return true;
3594 }
3595 if depth == 0 {
3596 return false;
3597 }
3598 let Ok([t0, t1]) = curve.domain() else { return false };
3599 match curve.split(0.5 * (t0 + t1)) {
3600 Ok((left, right)) => clear(&left, depth - 1, centre, radius, tolerance) && clear(&right, depth - 1, centre, radius, tolerance),
3601 Err(_) => false,
3602 }
3603 }
3604 for coedge in face.loops.iter().flat_map(|lp| &lp.coedges) {
3605 let Some(edge) = solid.edges.iter().find(|edge| edge.id == coedge.edge_id) else { return false };
3606 let Ok([d0, d1]) = edge.curve.domain() else { return false };
3607 let mut span = edge.curve.clone();
3609 if edge.t1 < d1 {
3610 match span.split(edge.t1) {
3611 Ok((left, _)) => span = left,
3612 Err(_) => return false,
3613 }
3614 }
3615 if edge.t0 > d0 {
3616 match span.split(edge.t0) {
3617 Ok((_, right)) => span = right,
3618 Err(_) => return false,
3619 }
3620 }
3621 if !clear(&span, 10, cb, rb, tolerance) {
3622 return false;
3623 }
3624 }
3625 let axis = cb.sub(ca);
3626 let distance = axis.length();
3627 let Ok(n) = axis.normalized() else { return false };
3628 let along = (distance * distance + ra * ra - rb * rb) / (2.0 * distance);
3629 let across = ra * ra - along * along;
3630 let Ok(side) = n.perpendicular() else { return false };
3631 if !(across > 0.0) {
3632 return false;
3633 }
3634 let point = ca.add(n.scale(along)).add(side.scale(across.sqrt()));
3635 let Ok(projection) = crate::project_point_to_surface(&face.surface, point) else { return false };
3636 matches!(parameter_point_in_face(face, crate::Vec2 { x: projection.u, y: projection.v }, 1e-9), Ok(PolygonClass::Outside))
3637}
3638
3639
3640fn empty_solid() -> BrepSolid {
3642 BrepSolid {
3643 mass_properties_cache: Default::default(),
3644 cells: Default::default(),
3645 id: 0,
3646 vertices: Vec::new(),
3647 edges: Vec::new(),
3648 shells: Vec::new(),
3649 genus: 0,
3650 kind: crate::BodyKind::Solid,
3651 }
3652}
3653
3654fn concatenate_disjoint(first: &BrepSolid, second: &BrepSolid) -> BrepSolid {
3660 let mut vertices = Vec::new();
3661 let mut edges = Vec::new();
3662 let mut shells = Vec::new();
3663 let mut used_face_names = HashSet::<String>::default();
3664 let (mut next_face_id, mut next_loop_id, mut next_coedge_id) = (1u64, 1u64, 1u64);
3665 for operand in [first, second] {
3666 let vertex_base = vertices.len() as u64;
3667 let edge_base = edges.len() as u64;
3668 let mut vertex_ids: HashMap<u64, u64> = HashMap::default();
3669 for (index, vertex) in operand.vertices.iter().enumerate() {
3670 let id = vertex_base + index as u64 + 1;
3671 vertex_ids.insert(vertex.id, id);
3672 vertices.push(VertexRecord { id, point: vertex.point });
3673 }
3674 let mut edge_ids: HashMap<u64, u64> = HashMap::default();
3675 for (index, edge) in operand.edges.iter().enumerate() {
3676 let id = edge_base + index as u64 + 1;
3677 edge_ids.insert(edge.id, id);
3678 edges.push(EdgeRecord {
3679 id,
3680 curve: edge.curve.clone(),
3681 t0: edge.t0,
3682 t1: edge.t1,
3683 start_vertex_id: vertex_ids.get(&edge.start_vertex_id).copied().unwrap_or(edge.start_vertex_id),
3684 end_vertex_id: vertex_ids.get(&edge.end_vertex_id).copied().unwrap_or(edge.end_vertex_id),
3685 degenerate: edge.degenerate,
3686 name: edge.name.clone(),
3687 });
3688 }
3689 for shell in &operand.shells {
3690 let mut faces = Vec::with_capacity(shell.faces.len());
3691 for face in &shell.faces {
3692 let loops = face
3693 .loops
3694 .iter()
3695 .map(|loop_record| {
3696 let coedges = loop_record
3697 .coedges
3698 .iter()
3699 .map(|coedge| {
3700 let id = next_coedge_id;
3701 next_coedge_id += 1;
3702 CoedgeRecord {
3703 id,
3704 edge_id: edge_ids.get(&coedge.edge_id).copied().unwrap_or(coedge.edge_id),
3705 forward: coedge.forward,
3706 pcurve: coedge.pcurve.clone(),
3707 }
3708 })
3709 .collect();
3710 let id = next_loop_id;
3711 next_loop_id += 1;
3712 LoopRecord { id, coedges }
3713 })
3714 .collect();
3715 let name = face.name.clone().map(|base| {
3716 if used_face_names.insert(base.clone()) {
3717 base
3718 } else {
3719 let mut suffix = 1usize;
3720 loop {
3721 let candidate = format!("{base}_{suffix}");
3722 if used_face_names.insert(candidate.clone()) {
3723 break candidate;
3724 }
3725 suffix += 1;
3726 }
3727 }
3728 });
3729 faces.push(FaceRecord {
3730 id: next_face_id,
3731 surface: face.surface.clone(),
3732 same_sense: face.same_sense,
3733 loops,
3734 name,
3735 });
3736 next_face_id += 1;
3737 }
3738 shells.push(ShellRecord { id: shells.len() as u64 + 1, faces });
3739 }
3740 }
3741 BrepSolid {
3742 mass_properties_cache: Default::default(),
3743 cells: Default::default(),
3744 id: 1,
3745 vertices,
3746 edges,
3747 shells,
3748 genus: first.genus + second.genus,
3749 kind: crate::BodyKind::Solid,
3750 }
3751}
3752
3753fn boolean_pipeline(
3756 first: &BrepSolid,
3757 second: &BrepSolid,
3758 operation: BooleanOperation,
3759 options: &BooleanOptions,
3760 tangent_nodes: &mut Vec<Vec3>,
3761) -> Result<(KernelOutcome<BrepSolid>, Option<HashSet<u64>>), KernelRefusal> {
3762 let _work = crate::imprint::work_profile::Scope::open("boolean");
3763 let replaced_operands = operand_state::replace_operands(first, second, operation, options);
3764 let (first, second) = match &replaced_operands {
3765 Some((first, second)) => (first, second),
3766 None => (first, second),
3767 };
3768 let policy = boolean_policy(first, second, options)?;
3769 let tolerance = policy.model;
3770 let bounds = [operand_bounds(first), operand_bounds(second)];
3785 let disjoint = disjoint_fast_path(options) && !bounds[0].intersects(bounds[1], policy.sew_search);
3786 let contact = !disjoint
3787 && contact_fast_path(options)
3788 && options.seam_reseat_later_references.is_some()
3789 && line_or_point_contact(first, second, bounds);
3790 let contact = contact
3795 || (!disjoint
3796 && matches!(operation, BooleanOperation::Intersect)
3797 && contact_fast_path(options)
3798 && boxes_share_no_interior(first, second, bounds));
3799 if disjoint || contact {
3800 let operation_started = Instant::now();
3801 let mut diagnostics = KernelDiagnostics::default();
3802 diagnostics.count_n(
3803 "collect.faces",
3804 first.shells.iter().chain(&second.shells).map(|shell| shell.faces.len() as u64).sum(),
3805 );
3806 diagnostics.count(if contact { "boolean.contact_fast_path" } else { "boolean.disjoint_fast_path" });
3807 diagnostics.measure_max("tolerance.model", policy.model);
3808 diagnostics.measure_max("tolerance.sew_search", policy.sew_search);
3809 let value = match operation {
3810 BooleanOperation::Union => concatenate_disjoint(first, second),
3811 BooleanOperation::Subtract => first.clone(),
3812 BooleanOperation::Intersect => {
3813 diagnostics.event(
3814 DiagnosticSeverity::Info,
3815 KernelStage::Select,
3816 "boolean.empty_result",
3817 format!("{operation:?} of witnessed-non-overlapping operands is empty"),
3818 );
3819 empty_solid()
3820 }
3821 };
3822 let stage_ms = operation_started.elapsed().as_secs_f64() * 1_000.0;
3823 profile_stage("disjoint_fast_path_ms", stage_ms);
3824 diagnostics.measure_max("timing.total_ms", stage_ms);
3825 return Ok((KernelOutcome { value, diagnostics }, Some(HashSet::default())));
3826 }
3827 let heal_started = Instant::now();
3828 let (first_owned, second_owned) = prepared_operands(first, second, &policy)?;
3829 let heal_ms = heal_started.elapsed().as_secs_f64() * 1_000.0;
3830 let first = &first_owned;
3831 let second = &second_owned;
3832
3833 let mut diagnostics = KernelDiagnostics::default();
3834 diagnostics.measure_max("timing.heal_ms", heal_ms);
3837 let fit_scope = crate::PcurveFitScope::open();
3842 let polyline_scope = crate::PolylineFitScope::open();
3846 let operation_started = Instant::now();
3847 diagnostics.count_n(
3848 "collect.faces",
3849 first
3850 .shells
3851 .iter()
3852 .chain(&second.shells)
3853 .map(|shell| shell.faces.len() as u64)
3854 .sum(),
3855 );
3856 diagnostics.measure_max("tolerance.model", policy.model);
3857 diagnostics.measure_max("tolerance.sew_search", policy.sew_search);
3858
3859 let imprint_options = boolean_imprint_options(options, tolerance);
3860 let stage_started = Instant::now();
3861 let imprint = build_imprints(first, second, &imprint_options)?;
3862 tangent_nodes.extend_from_slice(&imprint.tangent_nodes);
3863 if std::env::var("BREP_DEBUG_BOOL").is_ok() {
3864 for piece in &imprint.pieces {
3865 let start = piece.curve.evaluate(piece.t0);
3866 let end = piece.curve.evaluate(piece.t1);
3867 eprintln!(
3868 "piece {} supports={:?} t=[{:.6},{:.6}] start={:?} end={:?}",
3869 piece.id, piece.support_faces, piece.t0, piece.t1, start, end
3870 );
3871 }
3872 for entry in &imprint.by_face {
3873 eprintln!(
3874 "by_face operand={} face={} pieces={:?}",
3875 entry.operand, entry.face_id, entry.piece_ids
3876 );
3877 }
3878 for split in &imprint.edge_splits {
3879 eprintln!(
3880 "edge_split operand={} edge={} params={:?}",
3881 split.operand, split.edge_id, split.parameters
3882 );
3883 }
3884 }
3885 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
3886 profile_stage("imprint_ms", stage_ms);
3887 diagnostics.measure_max("timing.imprint_ms", stage_ms);
3888 diagnostics.count_n("intersect.pieces", imprint.pieces.len() as u64);
3889 diagnostics.count_n("intersect.vertices", imprint.vertices.len() as u64);
3890 diagnostics.count_n("intersect.edge_splits", imprint.edge_splits.len() as u64);
3891 let (march_swap_rescues, clip_swap_rescues) = crate::imprint::take_rescue_firings();
3892 diagnostics.count_n("intersect.march_swap_rescue", march_swap_rescues);
3893 diagnostics.count_n("intersect.clip_swap_rescue", clip_swap_rescues);
3894 let touch = TouchCensus::build([first, second], &imprint);
3895 touch.report(&mut diagnostics);
3896 let stage_started = Instant::now();
3897 let (split_first, split_map_first) = apply_edge_splits_with_map(first, 0, &imprint)?;
3898 let (split_second, split_map_second) = apply_edge_splits_with_map(second, 1, &imprint)?;
3899 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
3900 profile_stage("edge_split_ms", stage_ms);
3901 diagnostics.measure_max("timing.edge_split_ms", stage_ms);
3902 let stage_started = Instant::now();
3903 crate::classification::classify_profile_begin();
3904 let fragments_a = crate::fragment::fragment_solid_against(&split_first, 0, &imprint, crate::fragment::bounded_carriers(second).then_some((bounds[1], policy.sew_search)))?;
3905 let fragments_b = crate::fragment::fragment_solid_against(&split_second, 1, &imprint, crate::fragment::bounded_carriers(first).then_some((bounds[0], policy.sew_search)))?;
3906 crate::classification::classify_profile_report("fragment");
3907 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
3908 profile_stage("fragment_ms", stage_ms);
3909 diagnostics.measure_max("timing.fragment_ms", stage_ms);
3910 diagnostics.count_n(
3911 "fragment.candidates",
3912 (fragments_a.len() + fragments_b.len()) as u64,
3913 );
3914 touch.report_fragments(&[&fragments_a, &fragments_b], &mut diagnostics);
3915 let a_surface_samples: Vec<Vec3> = fragments_a
3920 .iter()
3921 .flat_map(|fragment| {
3922 std::iter::once(fragment.test_point).chain(fragment.extra_test_points.iter().copied())
3923 })
3924 .collect();
3925 let b_surface_samples: Vec<Vec3> = fragments_b
3926 .iter()
3927 .flat_map(|fragment| {
3928 std::iter::once(fragment.test_point).chain(fragment.extra_test_points.iter().copied())
3929 })
3930 .collect();
3931 let stage_started = Instant::now();
3932 let mut barrier_edges: HashSet<(u8, u64)> = imprint
3933 .pieces
3934 .iter()
3935 .filter_map(|piece| piece.shared_edge.map(|(operand, edge_id, _)| (operand, edge_id)))
3936 .collect();
3937 barrier_edges.extend(imprint.barrier_edges.iter().copied());
3938 for (operand, split_map) in [(0u8, &split_map_first), (1u8, &split_map_second)] {
3944 let minted: Vec<(u8, u64)> = barrier_edges
3945 .iter()
3946 .filter(|(barrier_operand, _)| *barrier_operand == operand)
3947 .filter_map(|(_, edge_id)| split_map.get(edge_id))
3948 .flat_map(|sub_ids| sub_ids.iter().map(|sub_id| (operand, *sub_id)))
3949 .collect();
3950 barrier_edges.extend(minted);
3951 }
3952 crate::classification::classify_profile_begin();
3953 let coincident = coincident_pairs(
3954 &fragments_a,
3955 &fragments_b,
3956 first,
3957 second,
3958 &imprint.cosurface_pairs,
3959 tolerance,
3960 )?;
3961 let sector_mode = sector::sector_mode(options);
3962 let mut select_census = sector::SelectCensus::default();
3963 let mut selected = select_fragments(
3964 fragments_a,
3965 fragments_b,
3966 first,
3967 second,
3968 operation,
3969 tolerance,
3970 &barrier_edges,
3971 &imprint,
3972 &coincident,
3973 sector_mode,
3974 &mut select_census,
3975 )?;
3976 let resewn = resew_coincident_rims(
3977 &mut selected,
3978 [&split_first, &split_second],
3979 [first, second],
3980 &imprint.cosurface_pairs,
3981 operation,
3982 tolerance,
3983 )?;
3984 diagnostics.count_n("select.coincident_pairs", coincident.len() as u64);
3985 diagnostics.count_n("select.rims_resewn", resewn as u64);
3986 crate::classification::classify_profile_report("select");
3987 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
3988 profile_stage("select_ms", stage_ms);
3989 diagnostics.measure_max("timing.select_ms", stage_ms);
3990 diagnostics.count_n("select.fragments", selected.len() as u64);
3991 diagnostics.count_n("select.sector_eligible", select_census.eligible);
3993 diagnostics.count_n("select.sector_primary", select_census.sector_primary);
3994 diagnostics.count_n("select.sector_fallback", select_census.sector_fallback);
3995 diagnostics.count_n("select.sector_disagree", select_census.disagree);
3996 diagnostics.count_n("select.ray_casts", select_census.ray_casts);
3997 diagnostics.count_n("select.on_votes", select_census.on_votes);
3998 diagnostics.count_n("select.overturns", select_census.overturns);
3999 if sector_mode != sector::SectorMode::Off || std::env::var_os("BREP_SECTOR_CENSUS").is_some() {
4000 sector::sector_census_line(|| {
4001 format!(
4002 "selection mode={sector_mode:?} select_ms={stage_ms:.3} selected={} eligible={} primary={} fallback={} disagree={} ray_casts={} on_votes={} overturns={}",
4003 selected.len(),
4004 select_census.eligible,
4005 select_census.sector_primary,
4006 select_census.sector_fallback,
4007 select_census.disagree,
4008 select_census.ray_casts,
4009 select_census.on_votes,
4010 select_census.overturns
4011 )
4012 });
4013 }
4014 if selected.is_empty()
4036 && !imprint.section_evidence
4037 && std::env::var("BREP_EMPTY_BOOLEAN").as_deref() != Ok("0")
4038 {
4039 let strictly_inside = |samples: &[Vec3], other: &BrepSolid| -> Result<bool, KernelRefusal> {
4040 for &sample in samples {
4041 if classify_point(sample, other, tolerance).or_refuse(KernelStage::Validate, "classify_point")?.class == PointClass::In {
4042 return Ok(true);
4043 }
4044 }
4045 Ok(false)
4046 };
4047 let outside_witness = |samples: &[Vec3], other: &BrepSolid| -> Result<bool, KernelRefusal> {
4048 for &sample in samples {
4049 if classify_point(sample, other, tolerance).or_refuse(KernelStage::Validate, "classify_point")?.class == PointClass::Out {
4050 return Ok(true);
4051 }
4052 }
4053 Ok(false)
4054 };
4055 let legitimate = match operation {
4056 BooleanOperation::Intersect => {
4057 !strictly_inside(&a_surface_samples, second)?
4058 && !strictly_inside(&b_surface_samples, first)?
4059 }
4060 BooleanOperation::Subtract => !outside_witness(&a_surface_samples, second)?,
4061 BooleanOperation::Union => false,
4062 };
4063 if legitimate {
4064 diagnostics.event(
4065 DiagnosticSeverity::Info,
4066 KernelStage::Select,
4067 "boolean.empty_result",
4068 format!("{operation:?} of witnessed-non-overlapping operands is empty"),
4069 );
4070 fit_scope.close().report_into(&mut diagnostics);
4071 polyline_scope.close().report_into(&mut diagnostics);
4072 diagnostics.measure_max(
4073 "timing.total_ms",
4074 operation_started.elapsed().as_secs_f64() * 1_000.0,
4075 );
4076 return Ok((
4077 KernelOutcome {
4078 value: empty_solid(),
4079 diagnostics,
4080 },
4081 None,
4082 ));
4083 }
4084 }
4085 if selected.is_empty()
4094 && imprint.section_evidence
4095 && !matches!(operation, BooleanOperation::Union)
4096 && touching_empty_enabled()
4097 && !TOUCHING_PROOF.with(std::cell::Cell::get)
4098 {
4099 let strict = |samples: &[Vec3], other: &BrepSolid, class: PointClass| -> Result<bool, KernelRefusal> {
4100 for &sample in samples {
4101 if classify_point(sample, other, tolerance).or_refuse(KernelStage::Validate, "classify_point")?.class == class {
4102 return Ok(true);
4103 }
4104 }
4105 Ok(false)
4106 };
4107 let witnessed = match operation {
4108 BooleanOperation::Intersect => {
4109 !strict(&a_surface_samples, second, PointClass::In)? && !strict(&b_surface_samples, first, PointClass::In)?
4110 }
4111 BooleanOperation::Subtract => !strict(&a_surface_samples, second, PointClass::Out)?,
4112 BooleanOperation::Union => false,
4113 };
4114 let overlap_free = !hair_deep_overlap(first, second, tolerance);
4120 if witnessed && overlap_free {
4121 TOUCHING_PROOF.with(|flag| flag.set(true));
4122 let proof = inclusion_exclusion_volume(first, second, operation, options, body_volume(first), body_volume(second), false);
4123 TOUCHING_PROOF.with(|flag| flag.set(false));
4124 let volume = |solid: &BrepSolid| body_volume(solid).unwrap_or(f64::INFINITY);
4129 let band = 1e-9 * volume(first).max(volume(second));
4130 if let Some(proof) = proof.filter(|proof| proof.expected.is_finite() && proof.expected.abs() <= band) {
4131 diagnostics.event(
4132 DiagnosticSeverity::Info,
4133 KernelStage::Select,
4134 "boolean.empty_touching",
4135 format!(
4136 "{operation:?} of touching operands is empty: {} reads {:.3e} by {} (band {band:.3e})",
4137 proof.formula, proof.expected, proof.reading
4138 ),
4139 );
4140 fit_scope.close().report_into(&mut diagnostics);
4141 polyline_scope.close().report_into(&mut diagnostics);
4142 diagnostics.measure_max("timing.total_ms", operation_started.elapsed().as_secs_f64() * 1_000.0);
4143 return Ok((KernelOutcome { value: empty_solid(), diagnostics }, None));
4144 }
4145 }
4146 }
4147 let solids = [(0, &split_first), (1, &split_second)]
4148 .into_iter()
4149 .collect::<HashMap<_, _>>();
4150 let dump = BooleanStageDump::open();
4151 if let Some(dump) = &dump {
4152 dump.write("first", &split_first);
4153 dump.write("second", &split_second);
4154 dump.write("selected", &selected);
4155 }
4156 let stage_started = Instant::now();
4157 let assembled_origins: Vec<FaceKey> = if imprint.tangent_sections.is_empty() {
4161 Vec::new()
4162 } else {
4163 selected
4164 .iter()
4165 .map(|fragment| FaceKey { operand: fragment.operand, face_id: fragment.source_face_id })
4166 .collect()
4167 };
4168 let attributable: Vec<crate::imprint::TangentSectionRecord> = imprint
4175 .tangent_sections
4176 .iter()
4177 .filter(|section| imprint.tangent_nodes.is_empty() || section.grazing.is_empty())
4178 .cloned()
4179 .collect();
4180 let attribute = |error: KernelRefusal| {
4181 attribute_to_tangent_section(error, &attributable, &assembled_origins)
4182 };
4183 let cellular_result = matches!(operation, BooleanOperation::Union)
4184 && cellular::enabled(options)
4185 && cellular::complete_contact(first, second, &selected, tolerance);
4186 let (solid, scope) = if cellular_result {
4187 (assemble::assemble_cellular_fragments(selected, &solids, &imprint, tolerance)
4188 .map_err(attribute)?, None)
4189 } else if untouched_passthrough(options) {
4190 assemble_fragments_scoped(selected, &solids, &imprint, tolerance, &touch, touched_assembly(options))
4191 .map_err(attribute)?
4192 } else {
4193 (assemble_fragments(selected, &solids, &imprint, tolerance).map_err(attribute)?, None)
4194 };
4195 if let Some(scope) = &scope {
4196 diagnostics.count_n("passthrough.faces_examined", scope.examined.len() as u64);
4197 }
4198 if let Some(dump) = &dump {
4199 dump.write("assembled", &solid);
4200 }
4201 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
4202 profile_stage("assemble_ms", stage_ms);
4203 diagnostics.measure_max("timing.assemble_ms", stage_ms);
4204 let stage_started = Instant::now();
4205 let declines_before = crate::face_merge::declines_served();
4206 let area_checks_before = crate::face_merge::boundary_area_checks();
4207 if std::env::var("BREP_DEBUG_PREMERGE_VALIDATE").is_ok() {
4208 let issues = solid.validate();
4209 eprintln!(
4210 "pre-merge validation: {} issue(s){}",
4211 issues.len(),
4212 issues
4213 .first()
4214 .map(|issue| format!(" — first: {}", issue.message))
4215 .unwrap_or_default()
4216 );
4217 }
4218 let solid = if solid.kind != crate::BodyKind::Cellular && options.merge_coplanar_faces
4219 && std::env::var("BREP_COPLANAR_MERGE").as_deref() != Ok("0")
4220 {
4221 let merged = match &scope {
4222 Some(scope) => merge_same_surface_faces_scoped(
4226 &solid,
4227 tolerance,
4228 &options.keep_unmerged_name_substrs,
4229 &scope.examined,
4230 )?,
4231 None => merge_same_surface_faces_excluding(
4232 &solid,
4233 tolerance,
4234 &options.keep_unmerged_name_substrs,
4235 )?,
4236 };
4237 let merged = merge_curve_continuation_edges(&merged, tolerance).map_err(|refusal| KernelRefusal { stage: KernelStage::Validate, ..refusal })?;
4242 rejoin::rejoin_unless_referenced(merged, options, tolerance)
4243 } else {
4244 solid
4245 };
4246 if let Some(dump) = &dump {
4247 dump.write("merged", &solid);
4248 }
4249 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
4250 profile_stage("face_merge_ms", stage_ms);
4251 if crate::profile::profile_enabled() {
4252 profile_line!("boolean.merge_declines served={}", crate::face_merge::declines_served() - declines_before);
4253 let area_checks = crate::face_merge::boundary_area_checks();
4254 if area_checks != area_checks_before {
4255 profile_line!("boolean.merge_area_checks boundary={} integrated={}", area_checks.0 - area_checks_before.0, area_checks.1 - area_checks_before.1);
4256 }
4257 }
4258 diagnostics.measure_max("timing.face_merge_ms", stage_ms);
4259 let validation_started = Instant::now();
4260 let validation = solid.validate_detailed_scoped(&policy, scope.as_ref().map(|scope| &scope.examined));
4261 profile_stage("final_validate_ms", validation_started.elapsed().as_secs_f64() * 1000.0);
4262 diagnostics.count_n("validate.issues", validation.issues.len() as u64);
4263 diagnostics.count_n(
4264 "validate.wire_warnings",
4265 validation.wire_warnings.len() as u64,
4266 );
4267 diagnostics.measure_max("validate.max_pcurve_error", validation.max_pcurve_error);
4268 for warning in &validation.wire_warnings {
4269 diagnostics.event(
4270 DiagnosticSeverity::Warning,
4271 KernelStage::Validate,
4272 "validate.uv_wire",
4273 warning.message.clone(),
4274 );
4275 }
4276 for issue in &validation.issues {
4277 diagnostics.event(
4278 DiagnosticSeverity::Error,
4279 KernelStage::Validate,
4280 "validate.brep",
4281 issue.message.clone(),
4282 );
4283 }
4284 fit_scope.close().report_into(&mut diagnostics);
4285 polyline_scope.close().report_into(&mut diagnostics);
4286 diagnostics.measure_max(
4287 "timing.total_ms",
4288 operation_started.elapsed().as_secs_f64() * 1_000.0,
4289 );
4290 if !validation.issues.is_empty() {
4291 return Err(KernelRefusal::new(
4292 RefusalClass::InvalidResultTopology { issues: validation.issues.len() as u32 },
4293 KernelStage::Validate,
4294 format!(
4295 "boolean_operation: invalid result: {:?}",
4296 validation.issues
4297 )));
4298 }
4299 if std::env::var("BREP_DEBUG_BOOL").is_ok() {
4305 if let Ok(report) =
4306 crate::oracle::boolean_semantic_disagreement(first, second, operation, &solid, 200)
4307 {
4308 if report.is_flagged() {
4309 eprintln!(
4310 "[oracle] semantic disagreement rate {:.4} ({} of {} decidable points); sample {:?}",
4311 report.disagreement_rate,
4312 report.disagreements.len(),
4313 report.considered,
4314 report.sample_disagreement()
4315 );
4316 }
4317 }
4318 let fusable_band = crate::tolerance::assembler_weld(policy.model);
4319 let fusables = crate::oracle::boolean_residual_fusables(&solid, fusable_band);
4320 if !fusables.is_empty() {
4321 eprintln!(
4322 "[oracle] {} residual fusable(s) after weld; sample {:?}",
4323 fusables.len(),
4324 fusables.first()
4325 );
4326 }
4327 }
4328 let candidates = scope.as_ref().map(|scope| {
4329 let unproved = (scope_proved_apart_on() && plain_hull_solid(first) && plain_hull_solid(second))
4330 .then(|| imprint.faces_in_unproved_pairs.as_ref())
4331 .flatten()
4332 .map(|faces| faces.iter().copied().collect::<HashSet<_>>());
4333 let candidates = soundness_candidates(
4334 &solid,
4335 scope,
4336 [operand_bounds(first), operand_bounds(second)],
4337 policy.sew_search,
4338 unproved.as_ref(),
4339 );
4340 diagnostics.count_n("passthrough.soundness_candidates", candidates.len() as u64);
4341 crate::soundness::census::profile_operation(&solid, &[first, second], Some(&scope.touched), "boolean");
4342 candidates
4343 });
4344 Ok((
4345 KernelOutcome {
4346 value: solid,
4347 diagnostics,
4348 },
4349 candidates,
4350 ))
4351}
4352
4353