1use crate::fit::{
2 evaluate_surface, evaluate_surface_from_vertices, fit_profile_clock, fit_profile_note,
3 fit_profile_start, fit_profile_take, fit_surface_from_vertices_with_path, fit_surface_with_path,
4 selection_scale, vertex_selection_scale, FitProfile,
5};
6use crate::numerical::recognition as numerical;
7use crate::{
8 AdaptiveSampling, AnalyticSurface, AnalyzedMesh, ConstraintMask, FitPath, HypothesisPolicy,
9 Mesh, MeshAnalysisOptions, MetadataTrust, RecognitionError, RecognitionOptions,
10 RecognitionResult, SurfaceFitResult, SurfaceHint, SurfaceRegion, SurfaceType,
11 UnresolvedRegionDiagnostic,
12};
13use std::cmp::Ordering;
14use std::collections::{BTreeSet, VecDeque};
15use web_time::Instant;
16
17const TYPES: [SurfaceType; 5] = [
18 SurfaceType::Plane,
19 SurfaceType::Sphere,
20 SurfaceType::Cylinder,
21 SurfaceType::Cone,
22 SurfaceType::Torus,
23];
24
25const MODEL_COMPLEXITY_PENALTY_UNIT: f64 = numerical::MODEL_COMPLEXITY_PENALTY_UNIT;
26
27#[derive(Clone, Copy, Debug)]
28struct ModelRank {
29 numerically_exact: bool,
30 score: f64,
31}
32
33fn compare_model_rank(
34 left: ModelRank,
35 left_kind: SurfaceType,
36 right: ModelRank,
37 right_kind: SurfaceType,
38) -> Ordering {
39 right
40 .numerically_exact
41 .cmp(&left.numerically_exact)
42 .then_with(|| left.score.total_cmp(&right.score))
43 .then(left_kind.cmp(&right_kind))
44}
45
46pub fn reconstruct_surface(
52 mesh: &Mesh,
53 triangle_indices: &[usize],
54 hint: &SurfaceHint,
55 options: &RecognitionOptions,
56) -> Result<SurfaceFitResult, RecognitionError> {
57 options.validate()?;
58 let analyzed = mesh.analyze(&MeshAnalysisOptions {
59 feature_angle: options.feature_angle,
60 ..Default::default()
61 })?;
62 analyzed.validate_selection(triangle_indices)?;
63 reconstruct_analyzed(&analyzed, triangle_indices, hint, options)
64}
65
66pub fn reconstruct_surface_from_vertices(
74 mesh: &Mesh,
75 vertex_indices: &[usize],
76 hint: &SurfaceHint,
77 options: &RecognitionOptions,
78) -> Result<SurfaceFitResult, RecognitionError> {
79 options.validate()?;
80 let analyzed = mesh.analyze(&MeshAnalysisOptions {
81 feature_angle: options.feature_angle,
82 ..Default::default()
83 })?;
84 analyzed.validate_vertex_selection(vertex_indices)?;
85 reconstruct_selected(
86 &analyzed,
87 Selection::Vertices(vertex_indices),
88 hint,
89 options,
90 )
91}
92
93#[derive(Clone, Copy)]
94enum Selection<'a> {
95 Triangles(&'a [usize]),
96 Vertices(&'a [usize]),
97}
98
99impl Selection<'_> {
100 fn scale(self, mesh: &AnalyzedMesh) -> f64 {
101 match self {
102 Self::Triangles(ids) => selection_scale(mesh, ids),
103 Self::Vertices(ids) => vertex_selection_scale(mesh, ids),
104 }
105 }
106
107 fn fit(
108 self,
109 mesh: &AnalyzedMesh,
110 kind: SurfaceType,
111 initial: Option<AnalyticSurface>,
112 fixed: ConstraintMask,
113 options: &RecognitionOptions,
114 path: FitPath,
115 ) -> Result<SurfaceFitResult, RecognitionError> {
116 match self {
117 Self::Triangles(ids) => {
118 fit_surface_with_path(mesh, ids, kind, initial, fixed, options, path)
119 }
120 Self::Vertices(ids) => {
121 fit_surface_from_vertices_with_path(mesh, ids, kind, initial, fixed, options, path)
122 }
123 }
124 }
125
126 fn evaluate(
127 self,
128 mesh: &AnalyzedMesh,
129 surface: AnalyticSurface,
130 options: &RecognitionOptions,
131 path: FitPath,
132 ) -> Result<SurfaceFitResult, RecognitionError> {
133 match self {
134 Self::Triangles(ids) => evaluate_surface(mesh, ids, surface, options, path),
135 Self::Vertices(ids) => {
136 evaluate_surface_from_vertices(mesh, ids, surface, options, path)
137 }
138 }
139 }
140
141 fn accepted(self, model: &SurfaceFitResult, options: &RecognitionOptions, scale: f64) -> bool {
142 accepted_impl(
143 model,
144 options,
145 scale,
146 matches!(self, Self::Vertices(_))
147 || matches!(options.sampling, crate::SamplingMode::Vertices),
148 )
149 }
150}
151
152pub fn recognize_surfaces(
158 mesh: &Mesh,
159 options: &RecognitionOptions,
160) -> Result<Vec<SurfaceRegion>, RecognitionError> {
161 Ok(recognize_surfaces_with_unresolved(mesh, options)?.regions)
162}
163
164pub fn recognize_surfaces_with_unresolved(
170 mesh: &Mesh,
171 options: &RecognitionOptions,
172) -> Result<RecognitionResult, RecognitionError> {
173 recognize_budgeted(mesh, options, &mut AttemptBudget::unlimited(), &[])
174}
175
176#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
180#[non_exhaustive]
181pub struct RecognitionWork {
182 pub attempts: usize,
185 pub rounds: usize,
187 pub exhausted: bool,
191 pub seeded_components: usize,
194 pub hypotheses_by_kind: [usize; 5],
197 pub stops_at_risk_bound: usize,
201 pub stops_at_hypothesis_cap: usize,
205 pub stops_at_seed_exhaustion: usize,
208 pub stops_at_budget: usize,
211}
212
213impl RecognitionWork {
214 fn absorb(&mut self, other: &RecognitionWork) {
216 self.attempts += other.attempts;
217 self.rounds += other.rounds;
218 self.exhausted |= other.exhausted;
219 self.seeded_components += other.seeded_components;
220 for (mine, theirs) in self.hypotheses_by_kind.iter_mut().zip(&other.hypotheses_by_kind) {
221 *mine += theirs;
222 }
223 self.stops_at_risk_bound += other.stops_at_risk_bound;
224 self.stops_at_hypothesis_cap += other.stops_at_hypothesis_cap;
225 self.stops_at_seed_exhaustion += other.stops_at_seed_exhaustion;
226 self.stops_at_budget += other.stops_at_budget;
227 }
228}
229
230#[doc(hidden)]
236#[derive(Clone, Debug, Default, PartialEq)]
237pub struct ExtractionProfile {
238 pub extraction_seconds: f64,
241 pub whole_fit_seconds: f64,
243 pub seed_order_seconds: f64,
246 pub seed_choice_seconds: f64,
248 pub neighborhood_seconds: f64,
250 pub sample_seconds: f64,
252 pub fit_seconds: [f64; 5],
255 pub fits: [usize; 5],
257 pub support_seconds: f64,
259 pub refit_winning_seconds: f64,
262 pub refit_dominated_seconds: f64,
265 pub refits_winning: usize,
267 pub refits_dominated: usize,
269 pub refits_dominated_exact: usize,
273 pub refit_dominated_exact_seconds: f64,
275 pub rank_seconds: f64,
277 pub rank_dominated_seconds: f64,
279 pub rounds: usize,
281 pub seeds_consumed: usize,
283 pub seed_slots: usize,
286 pub support_triangles_tested: usize,
288 pub distance_evaluations: usize,
290 pub distinct_vertices_evaluated: usize,
292 pub abandoned_rounds: usize,
295 pub abandoned_triangles: usize,
297 pub abandoned_with_piece: usize,
300 pub abandoned_piece_triangles: usize,
302 pub sample_fitter: FitProfile,
304 pub whole_fitter: FitProfile,
306 pub refit_fitter: FitProfile,
308 pub torus_sample_outcomes: [usize; 4],
312 pub torus_sample_outcome_seconds: [f64; 4],
314}
315
316impl ExtractionProfile {
317 fn absorb(&mut self, other: &ExtractionProfile) {
318 self.whole_fit_seconds += other.whole_fit_seconds;
319 self.seed_order_seconds += other.seed_order_seconds;
320 self.seed_choice_seconds += other.seed_choice_seconds;
321 self.neighborhood_seconds += other.neighborhood_seconds;
322 self.sample_seconds += other.sample_seconds;
323 for kind in 0..5 {
324 self.fit_seconds[kind] += other.fit_seconds[kind];
325 self.fits[kind] += other.fits[kind];
326 }
327 self.support_seconds += other.support_seconds;
328 self.refit_winning_seconds += other.refit_winning_seconds;
329 self.refit_dominated_seconds += other.refit_dominated_seconds;
330 self.refits_winning += other.refits_winning;
331 self.refits_dominated += other.refits_dominated;
332 self.refits_dominated_exact += other.refits_dominated_exact;
333 self.refit_dominated_exact_seconds += other.refit_dominated_exact_seconds;
334 self.rank_seconds += other.rank_seconds;
335 self.rank_dominated_seconds += other.rank_dominated_seconds;
336 self.rounds += other.rounds;
337 self.seeds_consumed += other.seeds_consumed;
338 self.seed_slots += other.seed_slots;
339 self.support_triangles_tested += other.support_triangles_tested;
340 self.distance_evaluations += other.distance_evaluations;
341 self.distinct_vertices_evaluated += other.distinct_vertices_evaluated;
342 self.abandoned_rounds += other.abandoned_rounds;
343 self.abandoned_triangles += other.abandoned_triangles;
344 self.abandoned_with_piece += other.abandoned_with_piece;
345 self.abandoned_piece_triangles += other.abandoned_piece_triangles;
346 self.sample_fitter.absorb(&other.sample_fitter);
347 self.whole_fitter.absorb(&other.whole_fitter);
348 self.refit_fitter.absorb(&other.refit_fitter);
349 for outcome in 0..4 {
350 self.torus_sample_outcomes[outcome] += other.torus_sample_outcomes[outcome];
351 self.torus_sample_outcome_seconds[outcome] += other.torus_sample_outcome_seconds[outcome];
352 }
353 }
354
355 fn take_fitter(profile: &mut Option<Self>, slot: fn(&mut Self) -> &mut FitProfile) {
358 if let (Some(profile), Some(fitter)) = (profile, fit_profile_take()) {
359 slot(profile).absorb(&fitter);
360 }
361 }
362
363 fn torus_sample(&mut self, outcome: usize, seconds: f64) {
366 self.torus_sample_outcomes[outcome] += 1;
367 self.torus_sample_outcome_seconds[outcome] += seconds;
368 }
369
370 fn charge(profile: &mut Option<Self>, started: Option<Instant>, slot: fn(&mut Self) -> &mut f64) {
372 if let (Some(profile), Some(started)) = (profile, started) {
373 *slot(profile) += started.elapsed().as_secs_f64();
374 }
375 }
376
377 fn refit(&mut self, started: Option<Instant>, count: usize, incumbent: usize, exact: bool) {
380 let seconds = started.map_or(0.0, |started| started.elapsed().as_secs_f64());
381 if count < incumbent {
382 self.refits_dominated += 1;
383 self.refit_dominated_seconds += seconds;
384 if exact {
385 self.refits_dominated_exact += 1;
386 self.refit_dominated_exact_seconds += seconds;
387 }
388 } else {
389 self.refits_winning += 1;
390 self.refit_winning_seconds += seconds;
391 }
392 }
393
394 fn abandon(&mut self, mesh: &AnalyzedMesh, remaining: &Remaining, options: &RecognitionOptions) {
397 self.abandoned_rounds += 1;
398 self.abandoned_triangles += remaining.len();
399 let ids: Vec<usize> = remaining.iter().copied().collect();
400 let pieces: usize = mesh
401 .connected_components(&ids, options.respect_features)
402 .iter()
403 .filter(|piece| piece.len() >= options.minimum_support)
404 .map(Vec::len)
405 .sum();
406 if pieces > 0 {
407 self.abandoned_with_piece += 1;
408 self.abandoned_piece_triangles += pieces;
409 }
410 }
411}
412
413#[derive(Default)]
415struct SupportTally {
416 triangles: usize,
417 evaluations: usize,
418 vertices: std::collections::HashSet<usize>,
419}
420
421#[doc(hidden)]
425pub fn recognize_surfaces_with_extraction_profile(
426 mesh: &Mesh,
427 options: &RecognitionOptions,
428 max_attempts: usize,
429 kinds: &[SurfaceType],
430) -> Result<(RecognitionResult, RecognitionWork, ExtractionProfile), RecognitionError> {
431 let kinds: Vec<_> = TYPES.into_iter().filter(|kind| kinds.is_empty() || kinds.contains(kind)).collect();
432 let mut budget = AttemptBudget {
433 limit: Some(max_attempts),
434 kinds,
435 work: RecognitionWork::default(),
436 profile: Some(ExtractionProfile::default()),
437 };
438 let result = recognize_budgeted(mesh, options, &mut budget, &[])?;
439 Ok((result, budget.work, budget.profile.unwrap_or_default()))
440}
441
442fn kind_index(kind: SurfaceType) -> usize {
443 TYPES
444 .iter()
445 .position(|&candidate| candidate == kind)
446 .expect("every primitive kind is in TYPES")
447}
448
449#[derive(Clone, Debug, PartialEq)]
452pub struct ComponentCandidate {
453 pub triangle_indices: Vec<usize>,
455 pub surface: AnalyticSurface,
457}
458
459const CANDIDATE_ROUNDOFF_EPSILONS: f64 = 64.0;
475
476pub fn recognize_surfaces_with_attempt_budget(
491 mesh: &Mesh,
492 options: &RecognitionOptions,
493 max_attempts: usize,
494 kinds: &[SurfaceType],
495) -> Result<(RecognitionResult, RecognitionWork), RecognitionError> {
496 let kinds: Vec<_> = TYPES.into_iter().filter(|kind| kinds.is_empty() || kinds.contains(kind)).collect();
497 let mut budget = AttemptBudget {
498 limit: Some(max_attempts),
499 kinds,
500 work: RecognitionWork::default(),
501 profile: None,
502 };
503 let result = recognize_budgeted(mesh, options, &mut budget, &[])?;
504 Ok((result, budget.work))
505}
506
507pub fn recognize_surfaces_with_candidates(
518 mesh: &Mesh,
519 options: &RecognitionOptions,
520 candidates: &[ComponentCandidate],
521) -> Result<(RecognitionResult, RecognitionWork), RecognitionError> {
522 let mut budget = AttemptBudget::unlimited();
523 let candidates: Vec<(Vec<usize>, AnalyticSurface)> = candidates
525 .iter()
526 .map(|candidate| {
527 let mut ids = candidate.triangle_indices.clone();
528 ids.sort_unstable();
529 ids.dedup();
530 (ids, candidate.surface)
531 })
532 .collect();
533 let result = recognize_budgeted(mesh, options, &mut budget, &candidates)?;
534 Ok((result, budget.work))
535}
536
537struct AttemptBudget {
538 limit: Option<usize>,
539 kinds: Vec<SurfaceType>,
541 work: RecognitionWork,
542 profile: Option<ExtractionProfile>,
544}
545
546impl AttemptBudget {
547 fn unlimited() -> Self {
548 Self {
549 limit: None,
550 kinds: TYPES.to_vec(),
551 work: RecognitionWork::default(),
552 profile: None,
553 }
554 }
555
556 fn admit(&mut self, want: usize) -> usize {
560 if self.work.exhausted {
561 return 0;
562 }
563 let admitted = match self.limit {
564 Some(limit) => want.min(limit.saturating_sub(self.work.attempts)),
565 None => want,
566 };
567 self.work.attempts += admitted;
568 admitted
569 }
570
571 fn refund(&mut self, count: usize) {
573 self.work.attempts -= count;
574 }
575
576 fn take(&mut self) -> bool {
578 if self.work.exhausted || self.limit.is_some_and(|limit| self.work.attempts >= limit) {
579 self.work.exhausted = true;
580 return false;
581 }
582 self.work.attempts += 1;
583 true
584 }
585}
586
587fn recognize_budgeted(
588 mesh: &Mesh,
589 options: &RecognitionOptions,
590 budget: &mut AttemptBudget,
591 candidates: &[(Vec<usize>, AnalyticSurface)],
592) -> Result<RecognitionResult, RecognitionError> {
593 options.validate()?;
594 let analyzed = mesh.analyze(&MeshAnalysisOptions {
595 feature_angle: options.feature_angle,
596 ..Default::default()
597 })?;
598 let mut assigned = vec![false; analyzed.triangles.len()];
599 let mut regions = Vec::new();
600 let mut metadata_failures = Vec::new();
601 for metadata in &analyzed.source_metadata {
603 let ids: Vec<_> = metadata
604 .triangle_indices
605 .iter()
606 .copied()
607 .filter(|&i| !assigned[i] && analyzed.triangles[i].area > 0.0)
608 .collect();
609 if ids.is_empty() {
610 continue;
611 }
612 let mut metadata_options = options.clone();
613 if let Some(source_tolerance) = metadata.source_tolerance {
614 metadata_options.distance_tolerance =
615 metadata_options.distance_tolerance.max(source_tolerance);
616 }
617 match reconstruct_analyzed(&analyzed, &ids, &metadata.hint, &metadata_options) {
618 Ok(mut fit)
619 if metadata
620 .orientation
621 .is_none_or(|orientation| orientation == fit.orientation) =>
622 {
623 if let Some(orientation) = metadata.orientation {
624 fit.orientation = orientation;
625 }
626 if metadata.source_tolerance.is_some() || metadata.orientation.is_some() {
627 fit.diagnostics.reason.push_str(
628 "; source orientation and tolerance metadata validated when supplied",
629 );
630 }
631 for &i in &ids {
632 assigned[i] = true;
633 }
634 regions.push(to_region(fit, ids));
635 }
636 Ok(fit) => metadata_failures.push((
637 metadata.clone(),
638 ids,
639 format!(
640 "supplied metadata orientation {:?} disagrees with reconstructed orientation {}",
641 metadata.orientation, fit.orientation
642 ),
643 )),
644 Err(error) => metadata_failures.push((metadata.clone(), ids, error.to_string())),
645 }
646 }
647 let remaining: Vec<_> = analyzed
648 .all_non_degenerate()
649 .into_iter()
650 .filter(|&i| !assigned[i])
651 .collect();
652 let components = if options.discover_regions {
653 analyzed.connected_components(&remaining, options.respect_features)
654 } else {
655 vec![remaining]
656 };
657 let extraction_started = budget.profile.is_some().then(Instant::now);
658 extract_components(&analyzed, &components, options, candidates, &mut regions, budget);
659 ExtractionProfile::charge(&mut budget.profile, extraction_started, |p| &mut p.extraction_seconds);
660 if options.allow_disconnected_same_surface {
661 merge_disconnected_regions(&analyzed, options, &mut regions);
662 }
663 regions.sort_by_key(|region| {
664 region
665 .triangle_indices
666 .first()
667 .copied()
668 .unwrap_or(usize::MAX)
669 });
670 let mut covered = vec![false; analyzed.triangles.len()];
671 for region in ®ions {
672 for &id in ®ion.triangle_indices {
673 covered[id] = true;
674 }
675 }
676 let unresolved_triangles = analyzed
677 .all_non_degenerate()
678 .into_iter()
679 .filter(|&id| !covered[id])
680 .collect::<Vec<_>>();
681 let unresolved_set: BTreeSet<_> = unresolved_triangles.iter().copied().collect();
682 let mut unresolved_diagnostics = metadata_failures
683 .into_iter()
684 .filter_map(|(metadata, ids, metadata_error)| {
685 let mut triangle_indices: Vec<_> = ids
686 .into_iter()
687 .filter(|id| unresolved_set.contains(id))
688 .collect();
689 triangle_indices.sort_unstable();
690 triangle_indices.dedup();
691 (!triangle_indices.is_empty()).then(|| UnresolvedRegionDiagnostic {
692 triangle_indices,
693 source_face_id: metadata.source_face_id,
694 source_face_name: metadata.source_face_name,
695 source_surface_id: metadata.source_surface_id,
696 reason: format!(
697 "source metadata validation or reconstruction failed ({metadata_error}); generic analytic fallback also left this subset unresolved"
698 ),
699 })
700 })
701 .collect::<Vec<_>>();
702 unresolved_diagnostics.sort_by(|left, right| {
703 left.triangle_indices
704 .cmp(&right.triangle_indices)
705 .then_with(|| left.source_face_id.cmp(&right.source_face_id))
706 .then_with(|| left.source_face_name.cmp(&right.source_face_name))
707 .then_with(|| left.source_surface_id.cmp(&right.source_surface_id))
708 .then_with(|| left.reason.cmp(&right.reason))
709 });
710 Ok(RecognitionResult {
711 regions,
712 unresolved_triangles,
713 unresolved_diagnostics,
714 })
715}
716
717#[doc(hidden)]
722pub fn reconstruct_analyzed(
723 mesh: &AnalyzedMesh,
724 ids: &[usize],
725 hint: &SurfaceHint,
726 options: &RecognitionOptions,
727) -> Result<SurfaceFitResult, RecognitionError> {
728 options.validate()?;
732 mesh.validate_selection(ids)?;
733 reconstruct_selected(mesh, Selection::Triangles(ids), hint, options)
734}
735
736fn reconstruct_selected(
737 mesh: &AnalyzedMesh,
738 selection: Selection<'_>,
739 hint: &SurfaceHint,
740 options: &RecognitionOptions,
741) -> Result<SurfaceFitResult, RecognitionError> {
742 let scale = selection.scale(mesh);
743 let metadata_started = options.collect_phase_timings.then(Instant::now);
744 let metadata_trust = match hint {
745 SurfaceHint::Unknown => MetadataTrust::Unknown,
746 SurfaceHint::KnownType { .. } => MetadataTrust::TypeOnly,
747 SurfaceHint::InitialGuess { trust, .. } | SurfaceHint::Constrained { trust, .. } => *trust,
748 SurfaceHint::ExactCandidate { .. } => MetadataTrust::Exact,
749 };
750 let metadata_seconds = metadata_started.map(|started| started.elapsed().as_secs_f64());
751 let result = match hint {
752 SurfaceHint::Unknown => best_model(
753 mesh,
754 selection,
755 scale,
756 options,
757 FitPath::GenericRecognition,
758 None,
759 ConstraintMask::default(),
760 ),
761 SurfaceHint::KnownType { surface_type } => fit_result(
762 mesh,
763 selection,
764 *surface_type,
765 None,
766 ConstraintMask::default(),
767 scale,
768 options,
769 FitPath::KnownTypeFit,
770 true,
771 None,
772 ),
773 SurfaceHint::InitialGuess { surface, trust } => {
774 if matches!(
775 trust,
776 crate::MetadataTrust::Exact | crate::MetadataTrust::StrongHint
777 ) {
778 let mut valid = selection.evaluate(mesh, *surface, options, FitPath::HintReused)?;
779 if selection.accepted(&valid, options, scale) {
780 valid.diagnostics.reason = "supplied parameters validated".into();
781 valid.diagnostics.metadata_trust = metadata_trust;
782 valid.diagnostics.phase_timings.metadata_inspection_seconds = metadata_seconds;
783 return Ok(valid);
784 }
785 }
786 fit_result(
787 mesh,
788 selection,
789 surface.surface_type(),
790 Some(*surface),
791 ConstraintMask::default(),
792 scale,
793 options,
794 FitPath::UnconstrainedRefinement,
795 true,
796 Some(*surface),
797 )
798 }
799 SurfaceHint::Constrained {
800 surface_type,
801 constraints,
802 ..
803 } => {
804 if constraints.initial.is_none() && constraints.fixed != ConstraintMask::default() {
805 return Err(RecognitionError::InvalidSelection(
806 "fixed constraints require initial parameter values".into(),
807 ));
808 }
809 fit_result(
810 mesh,
811 selection,
812 *surface_type,
813 constraints.initial,
814 constraints.fixed,
815 scale,
816 options,
817 FitPath::ConstrainedRefinement,
818 true,
819 constraints.initial,
820 )
821 }
822 SurfaceHint::ExactCandidate { surface } => {
823 let mut valid =
824 selection.evaluate(mesh, *surface, options, FitPath::ExactCandidateReused)?;
825 if selection.accepted(&valid, options, scale) {
826 valid.diagnostics.fixed_parameters = ConstraintMask {
827 origin_or_center: true,
828 axis_or_normal: true,
829 radius: true,
830 major_radius: true,
831 angle: true,
832 };
833 valid.diagnostics.reason =
834 "exact source parameters validated and were reused unchanged".into();
835 valid.diagnostics.metadata_trust = metadata_trust;
836 valid.diagnostics.phase_timings.metadata_inspection_seconds = metadata_seconds;
837 return Ok(valid);
838 }
839 fit_result(
840 mesh,
841 selection,
842 surface.surface_type(),
843 Some(*surface),
844 ConstraintMask::default(),
845 scale,
846 options,
847 FitPath::HintRejectedFallback,
848 true,
849 Some(*surface),
850 )
851 .or_else(|_| {
852 best_model(
853 mesh,
854 selection,
855 scale,
856 options,
857 FitPath::HintRejectedFallback,
858 Some(*surface),
859 ConstraintMask::default(),
860 )
861 })
862 }
863 }?;
864 Ok(with_metadata_diagnostics(
865 result,
866 metadata_trust,
867 metadata_seconds,
868 ))
869}
870
871fn with_metadata_diagnostics(
872 mut result: SurfaceFitResult,
873 trust: MetadataTrust,
874 elapsed_seconds: Option<f64>,
875) -> SurfaceFitResult {
876 result.diagnostics.metadata_trust = trust;
877 result.diagnostics.phase_timings.metadata_inspection_seconds = elapsed_seconds;
878 result
879}
880
881#[allow(clippy::too_many_arguments)]
882fn fit_result(
883 mesh: &AnalyzedMesh,
884 selection: Selection<'_>,
885 kind: SurfaceType,
886 initial: Option<AnalyticSurface>,
887 fixed: ConstraintMask,
888 scale: f64,
889 options: &RecognitionOptions,
890 path: FitPath,
891 skipped: bool,
892 supplied: Option<AnalyticSurface>,
893) -> Result<SurfaceFitResult, RecognitionError> {
894 let mut fitted = selection.fit(mesh, kind, initial, fixed, options, path)?;
895 let evaluation_started = options.collect_phase_timings.then(Instant::now);
896 if !selection.accepted(&fitted, options, scale) {
897 return Err(RecognitionError::FitFailed {
898 surface: Some(kind.name()),
899 reason: format!(
900 "residuals exceed tolerance (max {:.3e}, normal {:.3e} rad)",
901 fitted.metrics.max_error, fitted.metrics.max_normal_error
902 ),
903 });
904 }
905 fitted.diagnostics.generic_classification_skipped = skipped;
906 fitted.diagnostics.supplied_surface = supplied;
907 fitted.diagnostics.reason = "requested model fitted and validated".into();
908 fitted
909 .diagnostics
910 .phase_timings
911 .candidate_evaluation_seconds =
912 evaluation_started.map(|started| started.elapsed().as_secs_f64());
913 Ok(fitted)
914}
915
916fn best_model(
917 mesh: &AnalyzedMesh,
918 selection: Selection<'_>,
919 scale: f64,
920 options: &RecognitionOptions,
921 path: FitPath,
922 supplied: Option<AnalyticSurface>,
923 fixed: ConstraintMask,
924) -> Result<SurfaceFitResult, RecognitionError> {
925 best_model_impl(mesh, selection, scale, options, path, supplied, fixed, true)
926}
927
928#[allow(clippy::too_many_arguments)]
929fn best_model_impl(
930 mesh: &AnalyzedMesh,
931 selection: Selection<'_>,
932 scale: f64,
933 options: &RecognitionOptions,
934 path: FitPath,
935 supplied: Option<AnalyticSurface>,
936 fixed: ConstraintMask,
937 use_score_bounds: bool,
938) -> Result<SurfaceFitResult, RecognitionError> {
939 let evaluation_started = options.collect_phase_timings.then(Instant::now);
940 let mut tally = SelectionTally::start(selection);
941 let tolerance = options.distance_tolerance + options.relative_tolerance * scale.max(1.0);
942 let mut candidates = Vec::new();
943 let mut rejected = Vec::new();
944 for kind in TYPES {
945 let fit_started = tally.clock(&candidates);
946 match selection.fit(mesh, kind, None, fixed, options, path) {
947 Ok(model) if selection.accepted(&model, options, scale) => {
948 let rank_started = tally.fitted(fit_started, kind, 0);
949 let rank = model_rank(
950 mesh,
951 selection,
952 kind,
953 &model,
954 tolerance,
955 options.normal_tolerance,
956 );
957 tally.ranked(rank_started);
958 candidates.push((rank, kind, model));
959 }
960 Ok(model) => {
961 tally.fitted(fit_started, kind, 1);
962 rejected.push((
963 kind,
964 format!(
965 "max distance {:.3e}, max normal {:.3e}",
966 model.metrics.max_error, model.metrics.max_normal_error
967 ),
968 ))
969 }
970 Err(e) => {
971 tally.fitted(fit_started, kind, 2);
972 rejected.push((kind, e.to_string()))
973 }
974 }
975 if use_score_bounds {
976 if let Some(bound) = unseen_model_score_lower_bound(kind) {
977 if let Some((best_index, rank, best_kind)) = candidates
978 .iter()
979 .enumerate()
980 .min_by(|(_, a), (_, b)| compare_model_rank(a.0, a.1, b.0, b.1))
981 .map(|(index, candidate)| (index, candidate.0, candidate.1))
982 {
983 if rank.numerically_exact && rank.score < bound {
989 tally.finish(Some(best_kind), true);
990 let (_, _, model) = candidates.remove(best_index);
991 record_tolerance_valid_losers(&mut rejected, candidates, best_kind, rank);
992 rejected.sort_by_key(|(candidate_kind, _)| *candidate_kind);
993 let reason = format!(
994 "{} selected after {} candidate(s) from a score below every unseen model's proven lower bound",
995 best_kind.name(),
996 kind as usize + 1,
997 );
998 return Ok(decorate_best_model(
999 model,
1000 supplied,
1001 fixed,
1002 kind as usize + 1,
1003 rejected,
1004 &reason,
1005 evaluation_started.as_ref(),
1006 ));
1007 }
1008 }
1009 }
1010 }
1011 }
1012 let filter_started = tally.filter_clock();
1020 let valid_sphere = candidates
1021 .iter()
1022 .any(|(_, kind, _)| *kind == SurfaceType::Sphere);
1023 if valid_sphere {
1024 let mut retained = Vec::with_capacity(candidates.len());
1025 for (rank, kind, model) in candidates {
1026 let sphere_limit_major_radius = match &model.surface {
1027 AnalyticSurface::Torus(torus) if torus.major_radius <= tolerance => {
1028 Some(torus.major_radius)
1029 }
1030 _ => None,
1031 };
1032 if kind == SurfaceType::Torus {
1033 if let Some(major_radius) = sphere_limit_major_radius {
1034 rejected.push((
1035 kind,
1036 format!(
1037 "tolerance-valid candidate excluded as a non-identifiable sphere-limit torus: score {:.6e}, numerically_exact={}, major radius {major_radius:.3e} <= spatial tolerance {tolerance:.3e}; rms distance {:.3e}, max distance {:.3e}, rms normal {:.3e}, max normal {:.3e}",
1038 rank.score,
1039 rank.numerically_exact,
1040 model.metrics.rms_error,
1041 model.metrics.max_error,
1042 model.metrics.rms_normal_error,
1043 model.metrics.max_normal_error,
1044 ),
1045 ));
1046 continue;
1047 }
1048 }
1049 retained.push((rank, kind, model));
1050 }
1051 candidates = retained;
1052 }
1053 if let Some((cylinder_rank, _, cylinder)) = candidates
1064 .iter()
1065 .find(|(_, kind, _)| *kind == SurfaceType::Cylinder)
1066 .cloned()
1067 {
1068 let mut retained = Vec::with_capacity(candidates.len());
1069 for (rank, kind, model) in candidates {
1070 if kind == SurfaceType::Torus
1071 && torus_is_non_identifiable_cylinder_limit(
1072 rank,
1073 &model.metrics,
1074 cylinder_rank,
1075 &cylinder.metrics,
1076 tolerance,
1077 )
1078 {
1079 let rms_gain = (cylinder.metrics.rms_error - model.metrics.rms_error).max(0.0);
1080 rejected.push((
1081 kind,
1082 format!(
1083 "tolerance-valid candidate excluded as a non-identifiable cylinder-limit torus: score {:.6e}, numerically_exact={}, RMS-position gain {rms_gain:.3e} <= {:.3e} (1% of spatial tolerance), torus RMS normal {:.3e} >= cylinder RMS normal {:.3e}; rms distance {:.3e}, max distance {:.3e}, max normal {:.3e}",
1084 rank.score,
1085 rank.numerically_exact,
1086 tolerance * numerical::TORUS_CYLINDER_LIMIT_RMS_GAIN_FRACTION,
1087 model.metrics.rms_normal_error,
1088 cylinder.metrics.rms_normal_error,
1089 model.metrics.rms_error,
1090 model.metrics.max_error,
1091 model.metrics.max_normal_error,
1092 ),
1093 ));
1094 continue;
1095 }
1096 retained.push((rank, kind, model));
1097 }
1098 candidates = retained;
1099 }
1100 if let (Some((torus_rank, _, torus)), Some((cylinder_rank, _, cylinder))) = (
1108 candidates
1109 .iter()
1110 .find(|(_, kind, _)| *kind == SurfaceType::Torus)
1111 .cloned(),
1112 candidates
1113 .iter()
1114 .find(|(_, kind, _)| *kind == SurfaceType::Cylinder)
1115 .cloned(),
1116 ) {
1117 let carrier_normal_disagreement = max_oriented_carrier_normal_disagreement(
1118 mesh,
1119 selection,
1120 options.sampling,
1121 &torus,
1122 &cylinder,
1123 );
1124 if torus_observably_dominates_cylinder(
1125 torus_rank,
1126 &torus.metrics,
1127 cylinder_rank,
1128 &cylinder.metrics,
1129 tolerance,
1130 carrier_normal_disagreement,
1131 ) {
1132 let rms_position_gain = cylinder.metrics.rms_error - torus.metrics.rms_error;
1133 candidates.retain(|(_, kind, _)| *kind != SurfaceType::Cylinder);
1134 rejected.push((
1135 SurfaceType::Cylinder,
1136 format!(
1137 "tolerance-valid cylinder excluded because the torus observably resolves second curvature: RMS-position gain {rms_position_gain:.3e} (threshold {:.3e}), oriented carrier-normal disagreement {:.3e} (threshold {:.3e}); torus RMS/max distance {:.3e}/{:.3e} versus cylinder {:.3e}/{:.3e}; torus RMS/max normal {:.3e}/{:.3e} versus cylinder {:.3e}/{:.3e}",
1138 tolerance * numerical::TORUS_CYLINDER_LIMIT_RMS_GAIN_FRACTION,
1139 carrier_normal_disagreement.unwrap_or(0.0),
1140 numerical::EXACT_MODEL_NORMAL_ROUNDOFF_RADIANS,
1141 torus.metrics.rms_error,
1142 torus.metrics.max_error,
1143 cylinder.metrics.rms_error,
1144 cylinder.metrics.max_error,
1145 torus.metrics.rms_normal_error,
1146 torus.metrics.max_normal_error,
1147 cylinder.metrics.rms_normal_error,
1148 cylinder.metrics.max_normal_error,
1149 ),
1150 ));
1151 }
1152 }
1153 tally.filtered(filter_started);
1154 candidates.sort_by(|a, b| compare_model_rank(a.0, a.1, b.0, b.1));
1155 tally.finish(candidates.first().map(|candidate| candidate.1), false);
1156 if candidates.is_empty() {
1157 return Err(RecognitionError::FitFailed {
1158 surface: None,
1159 reason: "no analytic model passed distance, normal, and support gates".into(),
1160 });
1161 }
1162 let (selected_rank, selected_kind, model) = candidates.remove(0);
1163 record_tolerance_valid_losers(&mut rejected, candidates, selected_kind, selected_rank);
1164 rejected.sort_by_key(|(candidate_kind, _)| *candidate_kind);
1165 Ok(decorate_best_model(
1166 model,
1167 supplied,
1168 fixed,
1169 TYPES.len(),
1170 rejected,
1171 "best tolerance-valid model selected by numerical-exactness tier, residual score, and simplicity penalty",
1172 evaluation_started.as_ref(),
1173 ))
1174}
1175
1176struct SelectionTally {
1179 started: Option<Instant>,
1180 size: usize,
1181 seconds: [Option<f64>; 5],
1183 outcome: [u8; 5],
1185 after_exact: [bool; 5],
1186 after_valid: [bool; 5],
1187 rank_seconds: f64,
1188 filter_seconds: f64,
1189}
1190
1191impl SelectionTally {
1192 fn start(selection: Selection<'_>) -> Self {
1193 let size = match selection {
1194 Selection::Triangles(ids) | Selection::Vertices(ids) => ids.len(),
1195 };
1196 Self {
1197 started: fit_profile_clock(),
1198 size,
1199 seconds: [None; 5],
1200 outcome: [0; 5],
1201 after_exact: [false; 5],
1202 after_valid: [false; 5],
1203 rank_seconds: 0.0,
1204 filter_seconds: 0.0,
1205 }
1206 }
1207
1208 fn clock(&mut self, candidates: &[(ModelRank, SurfaceType, SurfaceFitResult)]) -> Option<(Instant, bool, bool)> {
1210 self.started?;
1211 let exact = candidates.iter().any(|(rank, ..)| rank.numerically_exact);
1212 Some((Instant::now(), exact, !candidates.is_empty()))
1213 }
1214
1215 fn fitted(&mut self, started: Option<(Instant, bool, bool)>, kind: SurfaceType, outcome: u8) -> Option<Instant> {
1216 let (started, exact, valid) = started?;
1217 let index = kind_index(kind);
1218 self.seconds[index] = Some(started.elapsed().as_secs_f64());
1219 self.outcome[index] = outcome;
1220 self.after_exact[index] = exact;
1221 self.after_valid[index] = valid;
1222 Some(Instant::now())
1223 }
1224
1225 fn ranked(&mut self, started: Option<Instant>) {
1226 if let Some(started) = started {
1227 self.rank_seconds += started.elapsed().as_secs_f64();
1228 }
1229 }
1230
1231 fn filter_clock(&self) -> Option<Instant> {
1232 self.started.map(|_| Instant::now())
1233 }
1234
1235 fn filtered(&mut self, started: Option<Instant>) {
1236 if let Some(started) = started {
1237 self.filter_seconds += started.elapsed().as_secs_f64();
1238 }
1239 }
1240
1241 fn finish(&self, selected: Option<SurfaceType>, bound_exit: bool) {
1242 let tally = self;
1243 fit_profile_note(self.started, |profile, seconds| {
1244 profile.selections += 1;
1245 profile.selection_size += tally.size;
1246 profile.selections_bound_exit += usize::from(bound_exit);
1247 if selected.is_none() {
1248 profile.selections_failed += 1;
1249 profile.selections_failed_seconds += seconds;
1250 }
1251 profile.rank_seconds += tally.rank_seconds;
1252 profile.filter_seconds += tally.filter_seconds;
1253 for index in 0..5 {
1254 let Some(fit_seconds) = tally.seconds[index] else {
1255 continue;
1256 };
1257 profile.kind_fits[index] += 1;
1258 profile.kind_seconds[index] += fit_seconds;
1259 match tally.outcome[index] {
1260 1 => profile.kind_rejected[index] += 1,
1261 2 => profile.kind_errors[index] += 1,
1262 _ => {}
1263 }
1264 if selected.is_some_and(|kind| kind_index(kind) == index) {
1265 profile.kind_won[index] += 1;
1266 } else {
1267 if tally.outcome[index] == 0 {
1268 profile.kind_valid_lost[index] += 1;
1269 }
1270 profile.kind_lost_seconds[index] += fit_seconds;
1271 }
1272 if tally.after_exact[index] {
1273 profile.kind_after_exact[index] += 1;
1274 profile.kind_after_exact_seconds[index] += fit_seconds;
1275 }
1276 if tally.after_valid[index] {
1277 profile.kind_after_valid[index] += 1;
1278 profile.kind_after_valid_seconds[index] += fit_seconds;
1279 }
1280 }
1281 });
1282 }
1283}
1284
1285fn torus_observably_dominates_cylinder(
1286 torus_rank: ModelRank,
1287 torus: &crate::FitMetrics,
1288 cylinder_rank: ModelRank,
1289 cylinder: &crate::FitMetrics,
1290 spatial_tolerance: f64,
1291 carrier_normal_disagreement: Option<f64>,
1292) -> bool {
1293 !torus_rank.numerically_exact
1294 && !cylinder_rank.numerically_exact
1295 && torus.rms_error <= cylinder.rms_error
1296 && torus.max_error <= cylinder.max_error
1297 && torus.rms_normal_error <= cylinder.rms_normal_error
1298 && torus.max_normal_error <= cylinder.max_normal_error
1299 && ((cylinder.rms_error - torus.rms_error)
1300 > spatial_tolerance * numerical::TORUS_CYLINDER_LIMIT_RMS_GAIN_FRACTION
1301 || carrier_normal_disagreement.is_some_and(|disagreement| {
1302 disagreement > numerical::EXACT_MODEL_NORMAL_ROUNDOFF_RADIANS
1303 && torus.rms_normal_error < cylinder.rms_normal_error
1304 }))
1305}
1306
1307fn max_oriented_carrier_normal_disagreement(
1308 mesh: &AnalyzedMesh,
1309 selection: Selection<'_>,
1310 sampling: crate::SamplingMode,
1311 left: &SurfaceFitResult,
1312 right: &SurfaceFitResult,
1313) -> Option<f64> {
1314 let mut max_disagreement = 0.0_f64;
1315 let mut samples = 0_usize;
1316 let mut measure = |point| -> Option<()> {
1317 let left_normal = left.surface.normal_at(point)? * left.orientation as f64;
1318 let right_normal = right.surface.normal_at(point)? * right.orientation as f64;
1319 if !left_normal.is_finite() || !right_normal.is_finite() {
1320 return None;
1321 }
1322 let disagreement = left_normal.dot(right_normal).clamp(-1.0, 1.0).acos();
1323 if !disagreement.is_finite() {
1324 return None;
1325 }
1326 max_disagreement = max_disagreement.max(disagreement);
1327 samples += 1;
1328 Some(())
1329 };
1330
1331 match selection {
1332 Selection::Triangles(ids) => {
1333 if matches!(
1334 sampling,
1335 crate::SamplingMode::TriangleCentroids | crate::SamplingMode::CentroidsAndVertices
1336 ) {
1337 for &id in ids {
1338 if mesh.triangles[id].area > 0.0 {
1339 measure(mesh.triangles[id].centroid)?;
1340 }
1341 }
1342 }
1343 if matches!(
1344 sampling,
1345 crate::SamplingMode::Vertices | crate::SamplingMode::CentroidsAndVertices
1346 ) {
1347 let vertices: BTreeSet<_> = ids
1348 .iter()
1349 .filter(|&&id| mesh.triangles[id].area > 0.0)
1350 .flat_map(|&id| mesh.triangles[id].vertices)
1351 .collect();
1352 for vertex in vertices {
1353 measure(mesh.vertices[vertex])?;
1354 }
1355 }
1356 }
1357 Selection::Vertices(vertices) => {
1358 for &vertex in vertices {
1359 measure(mesh.vertices[vertex])?;
1360 }
1361 }
1362 }
1363 (samples > 0).then_some(max_disagreement)
1364}
1365
1366fn torus_is_non_identifiable_cylinder_limit(
1367 torus_rank: ModelRank,
1368 torus: &crate::FitMetrics,
1369 cylinder_rank: ModelRank,
1370 cylinder: &crate::FitMetrics,
1371 spatial_tolerance: f64,
1372) -> bool {
1373 (!torus_rank.numerically_exact || cylinder_rank.numerically_exact)
1374 && torus.rms_normal_error >= cylinder.rms_normal_error
1375 && (cylinder.rms_error - torus.rms_error).max(0.0)
1376 <= spatial_tolerance * numerical::TORUS_CYLINDER_LIMIT_RMS_GAIN_FRACTION
1377}
1378
1379fn record_tolerance_valid_losers(
1380 rejected: &mut Vec<(SurfaceType, String)>,
1381 mut candidates: Vec<(ModelRank, SurfaceType, SurfaceFitResult)>,
1382 selected_kind: SurfaceType,
1383 selected_rank: ModelRank,
1384) {
1385 candidates.sort_by_key(|(_, kind, _)| *kind);
1386 rejected.extend(candidates.into_iter().map(|(rank, kind, model)| {
1387 (
1388 kind,
1389 format!(
1390 "tolerance-valid candidate not selected: score {:.6e}, numerically_exact={} versus selected {} score {:.6e}, numerically_exact={}; rms distance {:.3e}, max distance {:.3e}, rms normal {:.3e}, max normal {:.3e}",
1391 rank.score,
1392 rank.numerically_exact,
1393 selected_kind.name(),
1394 selected_rank.score,
1395 selected_rank.numerically_exact,
1396 model.metrics.rms_error,
1397 model.metrics.max_error,
1398 model.metrics.rms_normal_error,
1399 model.metrics.max_normal_error,
1400 ),
1401 )
1402 }));
1403}
1404
1405
1406fn unseen_model_score_lower_bound(after: SurfaceType) -> Option<f64> {
1407 let degrees = match after {
1408 SurfaceType::Plane => 4.0,
1409 SurfaceType::Sphere => 5.0,
1410 SurfaceType::Cylinder => 6.0,
1411 SurfaceType::Cone => 8.0,
1412 SurfaceType::Torus => return None,
1413 };
1414 Some(degrees * MODEL_COMPLEXITY_PENALTY_UNIT)
1415}
1416
1417fn decorate_best_model(
1418 mut answer: SurfaceFitResult,
1419 supplied: Option<AnalyticSurface>,
1420 fixed: ConstraintMask,
1421 candidates_evaluated: usize,
1422 rejected_competitors: Vec<(SurfaceType, String)>,
1423 reason: &str,
1424 evaluation_started: Option<&Instant>,
1425) -> SurfaceFitResult {
1426 answer.diagnostics.supplied_surface = supplied;
1427 answer.diagnostics.fixed_parameters = fixed;
1428 answer.diagnostics.generic_classification_skipped = false;
1429 answer.diagnostics.reason = reason.into();
1430 answer.diagnostics.candidates_evaluated = candidates_evaluated;
1431 answer.diagnostics.rejected_competitors = rejected_competitors;
1432 answer
1433 .diagnostics
1434 .phase_timings
1435 .candidate_evaluation_seconds =
1436 evaluation_started.map(|started| started.elapsed().as_secs_f64());
1437 answer
1438}
1439
1440fn model_rank(
1441 mesh: &AnalyzedMesh,
1442 selection: Selection<'_>,
1443 kind: SurfaceType,
1444 model: &SurfaceFitResult,
1445 distance_tolerance: f64,
1446 normal_tolerance: f64,
1447) -> ModelRank {
1448 let vertices: BTreeSet<_> = match selection {
1449 Selection::Triangles(ids) => ids
1450 .iter()
1451 .flat_map(|&id| mesh.triangles[id].vertices)
1452 .collect(),
1453 Selection::Vertices(ids) => ids.iter().copied().collect(),
1454 };
1455 let coordinate_scale = vertices
1456 .into_iter()
1457 .map(|vertex| {
1458 let point = mesh.vertices[vertex];
1459 point.x.abs().max(point.y.abs()).max(point.z.abs())
1460 })
1461 .fold(1.0_f64, f64::max);
1462 let position_roundoff =
1463 numerical::EXACT_VERTEX_ROUNDOFF_MULTIPLIER * f64::EPSILON * coordinate_scale;
1464 ModelRank {
1465 numerically_exact: model.metrics.max_error <= position_roundoff
1466 && model.metrics.max_normal_error <= numerical::EXACT_MODEL_NORMAL_ROUNDOFF_RADIANS,
1467 score: model_selection_score(kind, &model.metrics, distance_tolerance, normal_tolerance),
1468 }
1469}
1470
1471fn model_selection_score(
1472 kind: SurfaceType,
1473 metrics: &crate::FitMetrics,
1474 distance_tolerance: f64,
1475 normal_tolerance: f64,
1476) -> f64 {
1477 let complexity = match kind {
1478 SurfaceType::Plane => 3.,
1479 SurfaceType::Sphere => 4.,
1480 SurfaceType::Cylinder => 5.,
1481 SurfaceType::Cone => 6.,
1482 SurfaceType::Torus => 8.,
1483 };
1484 metrics.rms_error / distance_tolerance.max(numerical::SCORE_DISTANCE_DENOMINATOR_FLOOR)
1490 + metrics.rms_normal_error / normal_tolerance.max(numerical::SCORE_NORMAL_DENOMINATOR_FLOOR)
1491 + complexity * MODEL_COMPLEXITY_PENALTY_UNIT
1492}
1493
1494
1495fn accepted_impl(
1496 model: &SurfaceFitResult,
1497 options: &RecognitionOptions,
1498 scale: f64,
1499 vertex_samples_only: bool,
1500) -> bool {
1501 let distance = options.distance_tolerance + options.relative_tolerance * scale.max(1.0);
1502 let numerical_position =
1512 numerical::EXACT_VERTEX_ROUNDOFF_MULTIPLIER * f64::EPSILON * scale.max(1.0);
1513 let exact_vertices_with_coherent_sense = vertex_samples_only
1514 && model.metrics.max_error <= numerical_position
1515 && model.metrics.rms_normal_error < std::f64::consts::FRAC_PI_2;
1516 model.metrics.max_error <= distance
1517 && (model.metrics.rms_normal_error <= options.normal_tolerance
1521 || exact_vertices_with_coherent_sense)
1522 && model.metrics.support_triangles >= options.minimum_support
1523 && model.metrics.supported_area >= options.minimum_support_area
1524}
1525fn to_region(fit: SurfaceFitResult, ids: Vec<usize>) -> SurfaceRegion {
1526 SurfaceRegion {
1527 surface: fit.surface,
1528 orientation: fit.orientation,
1529 triangle_indices: ids,
1530 metrics: fit.metrics,
1531 confidence: fit.confidence,
1532 diagnostics: fit.diagnostics,
1533 }
1534}
1535
1536fn merge_disconnected_regions(
1537 mesh: &AnalyzedMesh,
1538 options: &RecognitionOptions,
1539 regions: &mut Vec<SurfaceRegion>,
1540) {
1541 let mut left = 0;
1542 while left < regions.len() {
1543 let mut right = left + 1;
1544 while right < regions.len() {
1545 if regions[left].surface.surface_type() != regions[right].surface.surface_type()
1546 || regions[left].orientation != regions[right].orientation
1547 {
1548 right += 1;
1549 continue;
1550 }
1551 let mut ids = regions[left].triangle_indices.clone();
1552 ids.extend_from_slice(®ions[right].triangle_indices);
1553 ids.sort_unstable();
1554 let hint = SurfaceHint::InitialGuess {
1555 surface: regions[left].surface,
1556 trust: crate::MetadataTrust::InitialGuess,
1557 };
1558 let Ok(mut fit) = reconstruct_analyzed(mesh, &ids, &hint, options) else {
1559 right += 1;
1560 continue;
1561 };
1562 if fit.orientation != regions[left].orientation {
1563 right += 1;
1564 continue;
1565 }
1566 fit.diagnostics
1567 .reason
1568 .push_str("; disconnected supports were jointly refitted and merged by request");
1569 regions[left] = to_region(fit, ids);
1570 regions.remove(right);
1571 right = left + 1;
1573 }
1574 left += 1;
1575 }
1576}
1577
1578fn worker_threads(options: &RecognitionOptions) -> usize {
1582 #[cfg(target_arch = "wasm32")]
1583 {
1584 let _ = options;
1585 1
1586 }
1587 #[cfg(not(target_arch = "wasm32"))]
1588 {
1589 match options.threads {
1590 0 => std::thread::available_parallelism().map_or(1, |cores| cores.get()),
1591 threads => threads,
1592 }
1593 }
1594}
1595
1596fn parallel_map<T: Send>(workers: usize, count: usize, f: impl Fn(usize) -> T + Sync) -> Vec<T> {
1601 parallel_map_on_workers(workers, count, |_, index| f(index))
1602}
1603
1604fn parallel_map_on_workers<T: Send>(
1607 workers: usize,
1608 count: usize,
1609 f: impl Fn(usize, usize) -> T + Sync,
1610) -> Vec<T> {
1611 #[cfg(target_arch = "wasm32")]
1612 let _ = workers;
1613 #[cfg(not(target_arch = "wasm32"))]
1614 {
1615 let workers = workers.min(count);
1616 if workers > 1 {
1617 let next = std::sync::atomic::AtomicUsize::new(0);
1618 let collected: Vec<Vec<(usize, T)>> = std::thread::scope(|scope| {
1619 let handles: Vec<_> = (0..workers)
1620 .map(|worker| {
1621 let (next, f) = (&next, &f);
1622 scope.spawn(move || {
1623 let mut mine = Vec::new();
1624 loop {
1625 let index = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1626 if index >= count {
1627 break;
1628 }
1629 mine.push((index, f(worker, index)));
1630 }
1631 mine
1632 })
1633 })
1634 .collect();
1635 handles
1636 .into_iter()
1637 .map(|handle| handle.join().unwrap_or_else(|payload| std::panic::resume_unwind(payload)))
1638 .collect()
1639 });
1640 let mut slots: Vec<Option<T>> = (0..count).map(|_| None).collect();
1641 for (index, value) in collected.into_iter().flatten() {
1642 slots[index] = Some(value);
1643 }
1644 return slots.into_iter().map(|slot| slot.expect("every index was evaluated once")).collect();
1645 }
1646 }
1647 (0..count).map(|index| f(0, index)).collect()
1648}
1649
1650fn extract_components(
1664 mesh: &AnalyzedMesh,
1665 components: &[Vec<usize>],
1666 options: &RecognitionOptions,
1667 candidates: &[(Vec<usize>, AnalyticSurface)],
1668 out: &mut Vec<SurfaceRegion>,
1669 budget: &mut AttemptBudget,
1670) {
1671 let workers = worker_threads(options);
1672 let eligible = components
1673 .iter()
1674 .filter(|component| component.len() >= options.minimum_support)
1675 .count();
1676 if workers > 1 && eligible >= workers && !budget.work.exhausted {
1677 let mut largest_first: Vec<usize> = (0..components.len()).collect();
1678 largest_first.sort_by_key(|&index| std::cmp::Reverse(components[index].len()));
1679 let kinds = &budget.kinds;
1680 let profiling = budget.profile.is_some();
1681 let mut extracted = parallel_map(workers, components.len(), |slot| {
1682 let index = largest_first[slot];
1683 let mut local = AttemptBudget {
1684 limit: None,
1685 kinds: kinds.clone(),
1686 work: RecognitionWork::default(),
1687 profile: profiling.then(ExtractionProfile::default),
1688 };
1689 let mut regions = Vec::new();
1690 extract_component(mesh, &components[index], options, candidates, &mut regions, &mut local, 1);
1691 (index, regions, local.work, local.profile)
1692 });
1693 extracted.sort_by_key(|(index, ..)| *index);
1694 for (index, regions, work, profile) in extracted {
1695 debug_assert!(!work.exhausted && work.stops_at_budget == 0, "an unlimited budget refuses nothing");
1696 if budget.work.exhausted {
1697 break;
1698 }
1699 let fits = budget
1700 .limit
1701 .is_none_or(|limit| budget.work.attempts.saturating_add(work.attempts) <= limit);
1702 if fits {
1703 out.extend(regions);
1704 budget.work.absorb(&work);
1705 if let (Some(total), Some(profile)) = (&mut budget.profile, &profile) {
1706 total.absorb(profile);
1707 }
1708 } else {
1709 extract_component(mesh, &components[index], options, candidates, out, budget, 1);
1713 debug_assert!(budget.work.exhausted);
1714 }
1715 }
1716 return;
1717 }
1718 for component in components {
1719 extract_component(mesh, component, options, candidates, out, budget, workers);
1720 }
1721}
1722
1723fn extract_component(
1724 mesh: &AnalyzedMesh,
1725 component: &[usize],
1726 options: &RecognitionOptions,
1727 candidates: &[(Vec<usize>, AnalyticSurface)],
1728 out: &mut Vec<SurfaceRegion>,
1729 budget: &mut AttemptBudget,
1730 workers: usize,
1731) {
1732 if component.len() < options.minimum_support || budget.work.exhausted {
1733 return;
1734 }
1735 let whole_started = budget.profile.is_some().then(Instant::now);
1736 fit_profile_start(budget.profile.is_some());
1737 let whole = reconstruct_analyzed(mesh, component, &SurfaceHint::Unknown, options);
1738 ExtractionProfile::take_fitter(&mut budget.profile, |p| &mut p.whole_fitter);
1739 if let Ok(fit) = whole {
1740 ExtractionProfile::charge(&mut budget.profile, whole_started, |p| &mut p.whole_fit_seconds);
1741 out.push(to_region(fit, component.to_vec()));
1742 return;
1743 }
1744 if let Some(fit) = candidate_fit(mesh, component, options, candidates) {
1745 ExtractionProfile::charge(&mut budget.profile, whole_started, |p| &mut p.whole_fit_seconds);
1746 budget.work.seeded_components += 1;
1747 out.push(to_region(fit, component.to_vec()));
1748 return;
1749 }
1750 ExtractionProfile::charge(&mut budget.profile, whole_started, |p| &mut p.whole_fit_seconds);
1751 if let HypothesisPolicy::Adaptive(policy) = &options.hypothesis_policy {
1752 return extract_component_adaptive(mesh, component, options, out, budget, policy);
1753 }
1754 let mut remaining = Remaining::new(mesh, component);
1764 let mut rng = SplitMix(options.deterministic_seed.unwrap_or(0x52414e534143));
1765 let batch_size = if workers > 1 { workers * budget.kinds.len() } else { 1 };
1766 let scratch: Vec<std::sync::Mutex<Scratch>> =
1767 (0..workers.max(1)).map(|_| std::sync::Mutex::new(Scratch::new(mesh))).collect();
1768 let profiling = budget.profile.is_some();
1769 while remaining.len() >= options.minimum_support {
1770 let seed_order_started = profiling.then(Instant::now);
1771 let ids: Vec<_> = remaining.iter().copied().collect();
1772 let kinds = budget.kinds.clone();
1777 let seed_orders: Vec<_> = kinds
1778 .iter()
1779 .map(|_| shuffled_seed_order(&ids, &mut rng))
1780 .collect();
1781 ExtractionProfile::charge(&mut budget.profile, seed_order_started, |p| &mut p.seed_order_seconds);
1782 let mut best: Option<(usize, ModelRank, SurfaceFitResult, Vec<usize>)> = None;
1783 let attempt_cap = options.max_hypotheses.min(ids.len() * kinds.len());
1784 let mut attempts_required = attempt_cap;
1785 let mut attempt = 0;
1786 let mut region_growth_seconds = options.collect_phase_timings.then_some(0.0);
1787 while attempt < attempts_required {
1788 let want = batch_size.min(attempts_required - attempt);
1789 let admitted = budget.admit(want);
1790 let drawn: Vec<(usize, SurfaceType)> = (attempt..attempt + admitted)
1791 .map(|index| {
1792 let slot = index % kinds.len();
1793 (seed_orders[slot][index / kinds.len()], kinds[slot])
1794 })
1795 .collect();
1796 for &(_, kind) in &drawn {
1797 budget.work.hypotheses_by_kind[kind_index(kind)] += 1;
1798 }
1799 let incumbent = best.as_ref().map_or(0, |(count, ..)| *count);
1800 let evaluated = parallel_map_on_workers(workers, admitted, |worker, offset| {
1801 let (seed, kind) = drawn[offset];
1802 let mut scratch = scratch[worker].lock().unwrap_or_else(|poisoned| poisoned.into_inner());
1804 classical_hypothesis(mesh, &remaining, &mut scratch, seed, kind, options, incumbent, profiling)
1805 });
1806 let mut applied = 0;
1807 for (offset, (probe_best, growth_seconds, profile)) in evaluated.into_iter().enumerate() {
1808 let attempt_index = attempt + offset;
1809 if attempt_index >= attempts_required {
1810 break;
1811 }
1812 applied += 1;
1813 if let (Some(total), Some(seconds)) = (&mut region_growth_seconds, growth_seconds) {
1814 *total += seconds;
1815 }
1816 if let (Some(total), Some(profile)) = (&mut budget.profile, &profile) {
1817 total.absorb(profile);
1818 }
1819 let Some((_, rank, mut fit, support)) = probe_best else {
1820 continue;
1821 };
1822 fit.diagnostics.hypotheses_generated = attempt_index + 1;
1823 let area = fit.metrics.supported_area;
1824 let replace = best.as_ref().is_none_or(|(count, old_rank, old, _)| {
1825 support.len() > *count
1826 || (support.len() == *count
1827 && (area > old.metrics.supported_area
1828 || (area == old.metrics.supported_area
1829 && compare_model_rank(
1830 rank,
1831 fit.surface.surface_type(),
1832 *old_rank,
1833 old.surface.surface_type(),
1834 ) == Ordering::Less)))
1835 });
1836 if replace {
1837 let support_fraction = support.len() as f64 / ids.len() as f64;
1838 attempts_required = attempts_required.min(required_seed_hypotheses(
1839 options.confidence,
1840 support_fraction,
1841 kinds.len(),
1842 attempt_cap,
1843 ));
1844 attempts_required = attempts_required.max(attempt_index + 1);
1845 best = Some((support.len(), rank, fit, support));
1846 }
1847 }
1848 for &(_, kind) in &drawn[applied..] {
1851 budget.work.hypotheses_by_kind[kind_index(kind)] -= 1;
1852 }
1853 budget.refund(admitted - applied);
1854 attempt += applied;
1855 if applied < admitted {
1856 break;
1857 }
1858 if admitted < want {
1859 budget.work.exhausted = true;
1861 budget.work.stops_at_budget += 1;
1862 return;
1863 }
1864 }
1865 if attempts_required < attempt_cap {
1868 budget.work.stops_at_risk_bound += 1;
1869 } else {
1870 budget.work.stops_at_hypothesis_cap += 1;
1871 }
1872 if let Some(profile) = &mut budget.profile {
1873 profile.rounds += 1;
1874 profile.seeds_consumed += attempt;
1875 profile.seed_slots += ids.len() * kinds.len();
1876 if best.is_none() {
1877 profile.abandon(mesh, &remaining, options);
1878 }
1879 }
1880 let Some((_, _, mut fit, support)) = best else {
1881 break;
1882 };
1883 fit.diagnostics.phase_timings.region_growth_seconds = region_growth_seconds;
1884 for id in &support {
1885 remaining.remove(id);
1886 }
1887 budget.work.rounds += 1;
1888 out.push(to_region(fit, support));
1889 }
1890}
1891
1892#[allow(clippy::type_complexity, clippy::too_many_arguments)]
1900fn classical_hypothesis(
1901 mesh: &AnalyzedMesh,
1902 remaining: &Remaining,
1903 scratch: &mut Scratch,
1904 seed: usize,
1905 kind: SurfaceType,
1906 options: &RecognitionOptions,
1907 incumbent: usize,
1908 profiling: bool,
1909) -> (
1910 Option<(usize, ModelRank, SurfaceFitResult, Vec<usize>)>,
1911 Option<f64>,
1912 Option<ExtractionProfile>,
1913) {
1914 let mut region_growth_seconds = options.collect_phase_timings.then_some(0.0);
1915 let mut profile = profiling.then(ExtractionProfile::default);
1916 let sample_size = hypothesis_sample_triangles(kind);
1924 let mut probe_limit = options
1927 .hypothesis_probe_triangles
1928 .max(sample_size)
1929 .min(remaining.len());
1930 let mut probe_best: Option<(usize, ModelRank, SurfaceFitResult, Vec<usize>)> = None;
1931 let mut search = Neighborhood::start(scratch, seed);
1932 loop {
1933 let started = profiling.then(Instant::now);
1934 let probe = search.grow(mesh, remaining, scratch, probe_limit, probe_crease(options));
1935 ExtractionProfile::charge(&mut profile, started, |p| &mut p.neighborhood_seconds);
1936 if probe.len() < sample_size {
1937 break;
1938 }
1939 let started = profiling.then(Instant::now);
1940 let sample = diverse_hypothesis_sample(mesh, seed, &probe, sample_size);
1941 ExtractionProfile::charge(&mut profile, started, |p| &mut p.sample_seconds);
1942 let mut grew_beyond_probe = false;
1943 let mut reconstructed_probe = false;
1944 let started = profiling.then(Instant::now);
1945 fit_profile_start(profiling);
1946 let fitted = fit_surface_with_path(
1947 mesh,
1948 &sample,
1949 kind,
1950 None,
1951 ConstraintMask::default(),
1952 options,
1953 FitPath::GenericRecognition,
1954 );
1955 ExtractionProfile::take_fitter(&mut profile, |p| &mut p.sample_fitter);
1956 let fit_seconds = started.map_or(0.0, |started| started.elapsed().as_secs_f64());
1957 let mut torus_outcome = 0;
1959 if let Some(profile) = &mut profile {
1960 profile.fit_seconds[kind_index(kind)] += fit_seconds;
1961 profile.fits[kind_index(kind)] += 1;
1962 }
1963 if let Ok(candidate) = fitted {
1964 torus_outcome = 1;
1965 let growth_started = options.collect_phase_timings.then(Instant::now);
1966 let started = profiling.then(Instant::now);
1967 let mut tally = profiling.then(SupportTally::default);
1968 let support = support_component(
1969 mesh,
1970 remaining,
1971 scratch,
1972 seed,
1973 candidate.surface,
1974 options,
1975 tally.as_mut(),
1976 );
1977 ExtractionProfile::charge(&mut profile, started, |p| &mut p.support_seconds);
1978 if let (Some(profile), Some(tally)) = (&mut profile, tally) {
1979 profile.support_triangles_tested += tally.triangles;
1980 profile.distance_evaluations += tally.evaluations;
1981 profile.distinct_vertices_evaluated += tally.vertices.len();
1982 }
1983 if let (Some(total), Some(started)) = (&mut region_growth_seconds, growth_started) {
1984 *total += started.elapsed().as_secs_f64();
1985 }
1986 grew_beyond_probe = support.len() > probe.len();
1987 if support.len() >= options.minimum_support {
1988 let started = profiling.then(Instant::now);
1989 fit_profile_start(profiling);
1990 let refitted = reconstruct_analyzed(
1991 mesh,
1992 &support,
1993 &SurfaceHint::InitialGuess {
1994 surface: candidate.surface,
1995 trust: crate::MetadataTrust::InitialGuess,
1996 },
1997 options,
1998 );
1999 ExtractionProfile::take_fitter(&mut profile, |p| &mut p.refit_fitter);
2000 torus_outcome = if refitted.is_ok() { 3 } else { 2 };
2001 if let Some(profile) = &mut profile {
2002 let exhausted = probe.len() == remaining.len() || probe.len() < probe_limit;
2003 profile.refit(started, support.len(), incumbent, !grew_beyond_probe || exhausted);
2004 }
2005 if let Ok(fit) = refitted {
2006 reconstructed_probe = true;
2007 let started = profiling.then(Instant::now);
2008 let area = fit.metrics.supported_area;
2009 let support_scale = selection_scale(mesh, &support);
2010 let support_tolerance = options.distance_tolerance
2011 + options.relative_tolerance * support_scale.max(1.0);
2012 let rank = model_rank(
2013 mesh,
2014 Selection::Triangles(&support),
2015 fit.surface.surface_type(),
2016 &fit,
2017 support_tolerance,
2018 options.normal_tolerance,
2019 );
2020 let replace = probe_best.as_ref().is_none_or(|(count, old_rank, old, _)| {
2021 support.len() > *count
2022 || (support.len() == *count
2023 && (area > old.metrics.supported_area
2024 || (area == old.metrics.supported_area
2025 && compare_model_rank(
2026 rank,
2027 fit.surface.surface_type(),
2028 *old_rank,
2029 old.surface.surface_type(),
2030 ) == Ordering::Less)))
2031 });
2032 ExtractionProfile::charge(&mut profile, started, |p| &mut p.rank_seconds);
2033 if support.len() < incumbent {
2034 ExtractionProfile::charge(&mut profile, started, |p| &mut p.rank_dominated_seconds);
2035 }
2036 if replace {
2037 probe_best = Some((support.len(), rank, fit, support));
2038 }
2039 }
2040 }
2041 }
2042 if let (Some(profile), SurfaceType::Torus) = (&mut profile, kind) {
2043 profile.torus_sample(torus_outcome, fit_seconds);
2044 }
2045 let exhausted = probe.len() == remaining.len() || probe.len() < probe_limit;
2046 if (grew_beyond_probe && reconstructed_probe) || exhausted {
2047 break;
2048 }
2049 probe_limit = probe_limit.saturating_mul(2).min(remaining.len());
2054 }
2055 (probe_best, region_growth_seconds, profile)
2056}
2057
2058const HYPOTHESIS_COST_UNITS: [f64; 5] = [1.0, 5.0, 13.0, 27.0, 920.0];
2066
2067fn uniform_index(rng: &mut SplitMix, n: usize) -> usize {
2069 debug_assert!(n > 0);
2070 let n_u64 = n as u64;
2071 let zone = (u64::MAX / n_u64) * n_u64;
2072 loop {
2073 let value = rng.next();
2074 if value < zone {
2075 return (value % n_u64) as usize;
2076 }
2077 }
2078}
2079
2080fn unit_interval(rng: &mut SplitMix) -> f64 {
2082 (rng.next() >> 11) as f64 / (1u64 << 53) as f64
2083}
2084
2085fn standard_normal(rng: &mut SplitMix) -> f64 {
2087 let u = loop {
2088 let u = unit_interval(rng);
2089 if u > 0.0 {
2090 break u;
2091 }
2092 };
2093 let v = unit_interval(rng);
2094 (-2.0 * u.ln()).sqrt() * (2.0 * std::f64::consts::PI * v).cos()
2095}
2096
2097fn gamma_sample(rng: &mut SplitMix, shape: f64) -> f64 {
2099 debug_assert!(shape >= 1.0);
2100 let d = shape - 1.0 / 3.0;
2101 let c = 1.0 / (9.0 * d).sqrt();
2102 loop {
2103 let x = standard_normal(rng);
2104 let v = 1.0 + c * x;
2105 if v <= 0.0 {
2106 continue;
2107 }
2108 let v = v * v * v;
2109 let u = unit_interval(rng);
2110 if u > 0.0 && u.ln() < 0.5 * x * x + d - d * v + d * v.ln() {
2111 return d * v;
2112 }
2113 }
2114}
2115
2116fn beta_sample(rng: &mut SplitMix, successes: usize, failures: usize) -> f64 {
2119 let x = gamma_sample(rng, successes as f64 + 1.0);
2120 let y = gamma_sample(rng, failures as f64 + 1.0);
2121 x / (x + y)
2122}
2123
2124fn choose_arm(draws: &[usize], scores: &[f64], eligible: &[bool], floor_share: f64, total: usize) -> usize {
2129 let arms = draws.len();
2130 debug_assert!(arms > 0 && scores.len() == arms && eligible.len() == arms);
2131 let minimum = (floor_share * (total + 1) as f64 / arms as f64).ceil() as usize;
2132 let deficient = (0..arms)
2133 .filter(|&i| eligible[i] && draws[i] < minimum)
2134 .min_by(|&a, &b| draws[a].cmp(&draws[b]).then(a.cmp(&b)));
2135 if let Some(arm) = deficient {
2136 return arm;
2137 }
2138 (0..arms)
2139 .filter(|&i| eligible[i])
2140 .fold(None, |best: Option<usize>, i| match best {
2141 Some(b) if scores[i] <= scores[b] => Some(b),
2142 _ => Some(i),
2143 })
2144 .expect("at least one eligible arm")
2145}
2146
2147#[derive(Clone, Copy, Debug, Default)]
2151struct KindPosterior {
2152 reached: f64,
2154 failed: f64,
2156 support_share: f64,
2158 rescued: f64,
2161 unrescued: f64,
2163}
2164
2165impl KindPosterior {
2166 fn halve(&mut self) {
2167 self.reached *= 0.5;
2168 self.failed *= 0.5;
2169 self.support_share *= 0.5;
2170 self.rescued *= 0.5;
2171 self.unrescued *= 0.5;
2172 }
2173
2174 fn rescue_rate(&self) -> f64 {
2177 (self.rescued + 1.0) / (self.rescued + self.unrescued + 2.0)
2178 }
2179
2180 fn sample_value(&self, rng: &mut SplitMix, prior_share: f64) -> f64 {
2184 let success = beta_sample(rng, self.reached.round() as usize, self.failed.round() as usize);
2185 let mean_share = (self.support_share + prior_share) / (self.reached + 1.0);
2186 success * mean_share
2187 }
2188}
2189
2190const TEMPERATURE_BANK: [f64; 7] = [0.05, 0.1, 0.25, 0.5, 1.0, 2.0, f64::INFINITY];
2196
2197const UNIFORM_ARM: usize = TEMPERATURE_BANK.len() - 1;
2200
2201#[derive(Clone, Copy, Debug, Default)]
2204struct TemperatureArm {
2205 tried: f64,
2207 improved: f64,
2209 gain: f64,
2211}
2212
2213impl TemperatureArm {
2214 fn halve(&mut self) {
2215 self.tried *= 0.5;
2216 self.improved *= 0.5;
2217 self.gain *= 0.5;
2218 }
2219
2220 fn mean_gain(&self, prior_gain: f64) -> f64 {
2223 (self.gain + prior_gain) / (self.improved + 1.0)
2224 }
2225
2226 fn sample_value(&self, rng: &mut SplitMix, prior_gain: f64) -> f64 {
2230 let improved = self.improved.round().max(0.0) as usize;
2231 let failed = (self.tried - self.improved).round().max(0.0) as usize;
2232 beta_sample(rng, improved, failed) * self.mean_gain(prior_gain)
2233 }
2234}
2235
2236fn choose_temperature(bank: &[TemperatureArm], rng: &mut SplitMix, prior_gain: f64) -> usize {
2238 let mut best = 0;
2239 let mut best_value = f64::NEG_INFINITY;
2240 for (arm, state) in bank.iter().enumerate() {
2241 let value = state.sample_value(rng, prior_gain);
2242 if value > best_value {
2243 best = arm;
2244 best_value = value;
2245 }
2246 }
2247 best
2248}
2249
2250fn round_error_share(delta_total: f64, extracted: usize, component_size: usize) -> f64 {
2255 delta_total * extracted as f64 / component_size as f64
2256}
2257
2258fn boltzmann_seed(
2263 rng: &mut SplitMix,
2264 ids: &[usize],
2265 tried: &[bool],
2266 incumbent: &[bool],
2267 explored: &[f64],
2268 temperature: f64,
2269) -> Option<usize> {
2270 let weight = |position: usize| -> f64 {
2271 if tried[position] || incumbent[position] {
2272 0.0
2273 } else {
2274 (-explored[ids[position]] / temperature).exp()
2275 }
2276 };
2277 let total: f64 = (0..ids.len()).map(weight).sum();
2278 if !(total > 0.0) {
2279 return None;
2280 }
2281 let mut target = unit_interval(rng) * total;
2282 let mut last = None;
2283 for position in 0..ids.len() {
2284 let w = weight(position);
2285 if w <= 0.0 {
2286 continue;
2287 }
2288 last = Some(position);
2289 if target < w {
2290 return Some(position);
2291 }
2292 target -= w;
2293 }
2294 last
2295}
2296
2297fn extract_component_adaptive(
2347 mesh: &AnalyzedMesh,
2348 component: &[usize],
2349 options: &RecognitionOptions,
2350 out: &mut Vec<SurfaceRegion>,
2351 budget: &mut AttemptBudget,
2352 policy: &AdaptiveSampling,
2353) {
2354 let mut remaining = Remaining::new(mesh, component);
2355 let mut scratch = Scratch::new(mesh);
2356 let mut rng = SplitMix(options.deterministic_seed.unwrap_or(0x52414e534143));
2357 let kinds = budget.kinds.clone();
2358 let kind_count = kinds.len();
2359 let mean_cost =
2360 kinds.iter().map(|&kind| HYPOTHESIS_COST_UNITS[kind_index(kind)]).sum::<f64>() / kind_count as f64;
2361 let kind_cost: Vec<f64> =
2362 kinds.iter().map(|&kind| HYPOTHESIS_COST_UNITS[kind_index(kind)] + mean_cost).collect();
2363 let mut posterior = vec![KindPosterior::default(); kind_count];
2364 let mut bank = [TemperatureArm::default(); TEMPERATURE_BANK.len()];
2365 let mut explored = vec![0.0f64; mesh.triangles.len()];
2368 let delta_total = 1.0 - options.confidence;
2369 let component_size = component.len();
2370 let profiling = budget.profile.is_some();
2371 while remaining.len() >= options.minimum_support {
2372 let seed_order_started = profiling.then(Instant::now);
2373 let ids: Vec<usize> = remaining.iter().copied().collect();
2374 let n = ids.len();
2375 posterior.iter_mut().for_each(KindPosterior::halve);
2376 bank.iter_mut().for_each(TemperatureArm::halve);
2377 let mut tried: Vec<Vec<bool>> = vec![vec![false; n]; kind_count];
2378 let mut tried_count = vec![0usize; kind_count];
2379 let mut kind_draws = vec![0usize; kind_count];
2380 let mut incumbent = vec![false; n];
2381 let mut best: Option<(usize, ModelRank, SurfaceFitResult, Vec<usize>)> = None;
2382 let attempt_cap = options.max_hypotheses.min(n * kind_count);
2383 let mut attempt = 0;
2384 let mut region_growth_seconds = options.collect_phase_timings.then_some(0.0);
2385 let mut stopped_early = false;
2386 ExtractionProfile::charge(&mut budget.profile, seed_order_started, |p| &mut p.seed_order_seconds);
2387 while attempt < attempt_cap {
2388 if !budget.take() {
2389 budget.work.stops_at_budget += 1;
2390 return;
2391 }
2392 let attempt_index = attempt;
2393 attempt += 1;
2394 let seed_choice_started = profiling.then(Instant::now);
2395 let incumbent_count = best.as_ref().map_or(0, |(count, ..)| *count);
2396 let w = best.as_ref().map_or(0.0, |(count, ..)| *count as f64 / n as f64);
2397 let prior_gain = if w > 0.0 { w } else { 1.0 / kind_count as f64 };
2398 let eligible: Vec<bool> = tried_count.iter().map(|&tried| tried < n).collect();
2399 debug_assert!(eligible.iter().any(|&open| open), "seed exhaustion leaves a kind to draw");
2400 let scores: Vec<f64> = posterior
2401 .iter()
2402 .zip(&kind_cost)
2403 .map(|(kind, cost)| kind.sample_value(&mut rng, prior_gain) / cost)
2404 .collect();
2405 let kind_slot = choose_arm(&kind_draws, &scores, &eligible, policy.kind_floor, attempt_index);
2406 let kind = kinds[kind_slot];
2407 budget.work.hypotheses_by_kind[kind_index(kind)] += 1;
2408 kind_draws[kind_slot] += 1;
2409 let (arm, position) = if unit_interval(&mut rng) < policy.seed_exploration {
2410 (UNIFORM_ARM, uniform_index(&mut rng, n))
2411 } else {
2412 let arm = choose_temperature(&bank, &mut rng, prior_gain);
2413 let position = boltzmann_seed(
2414 &mut rng,
2415 &ids,
2416 &tried[kind_slot],
2417 &incumbent,
2418 &explored,
2419 TEMPERATURE_BANK[arm] * policy.seed_temperature,
2420 )
2421 .unwrap_or_else(|| uniform_index(&mut rng, n));
2422 (arm, position)
2423 };
2424 ExtractionProfile::charge(&mut budget.profile, seed_choice_started, |p| &mut p.seed_choice_seconds);
2425 let mut improvement = None;
2428 if !tried[kind_slot][position] {
2429 tried[kind_slot][position] = true;
2430 tried_count[kind_slot] += 1;
2431 let seed = ids[position];
2432 let sample_size = hypothesis_sample_triangles(kind);
2433 let mut probe_limit =
2434 options.hypothesis_probe_triangles.max(sample_size).min(remaining.len());
2435 let mut probe_best: Option<(usize, ModelRank, SurfaceFitResult, Vec<usize>)> = None;
2436 let mut did_work = false;
2437 let mut reached_any = false;
2438 let mut doubled_past_hopeless = false;
2439 let mut search = Neighborhood::start(&mut scratch, seed);
2440 loop {
2441 let started = profiling.then(Instant::now);
2442 let probe = search.grow(mesh, &remaining, &mut scratch, probe_limit, probe_crease(options));
2443 ExtractionProfile::charge(&mut budget.profile, started, |p| &mut p.neighborhood_seconds);
2444 if probe.len() < sample_size {
2445 break;
2446 }
2447 let started = profiling.then(Instant::now);
2448 let sample = diverse_hypothesis_sample(mesh, seed, &probe, sample_size);
2449 ExtractionProfile::charge(&mut budget.profile, started, |p| &mut p.sample_seconds);
2450 let mut grew_beyond_probe = false;
2451 let mut reconstructed_probe = false;
2452 let mut reached = false;
2453 did_work = true;
2454 let started = profiling.then(Instant::now);
2455 fit_profile_start(profiling);
2456 let fitted = fit_surface_with_path(
2457 mesh,
2458 &sample,
2459 kind,
2460 None,
2461 ConstraintMask::default(),
2462 options,
2463 FitPath::GenericRecognition,
2464 );
2465 ExtractionProfile::take_fitter(&mut budget.profile, |p| &mut p.sample_fitter);
2466 let fit_seconds = started.map_or(0.0, |started| started.elapsed().as_secs_f64());
2467 let mut torus_outcome = 0;
2469 if let Some(profile) = &mut budget.profile {
2470 profile.fit_seconds[kind_index(kind)] += fit_seconds;
2471 profile.fits[kind_index(kind)] += 1;
2472 }
2473 if let Ok(candidate) = fitted {
2474 torus_outcome = 1;
2475 let growth_started = options.collect_phase_timings.then(Instant::now);
2476 let started = profiling.then(Instant::now);
2477 let mut tally = profiling.then(SupportTally::default);
2478 let support = support_component(
2479 mesh,
2480 &remaining,
2481 &mut scratch,
2482 seed,
2483 candidate.surface,
2484 options,
2485 tally.as_mut(),
2486 );
2487 ExtractionProfile::charge(&mut budget.profile, started, |p| &mut p.support_seconds);
2488 if let (Some(profile), Some(tally)) = (&mut budget.profile, tally) {
2489 profile.support_triangles_tested += tally.triangles;
2490 profile.distance_evaluations += tally.evaluations;
2491 profile.distinct_vertices_evaluated += tally.vertices.len();
2492 }
2493 if let (Some(total), Some(started)) =
2494 (&mut region_growth_seconds, growth_started)
2495 {
2496 *total += started.elapsed().as_secs_f64();
2497 }
2498 grew_beyond_probe = support.len() > probe.len();
2499 if support.len() >= options.minimum_support {
2500 reached = true;
2501 let started = profiling.then(Instant::now);
2502 fit_profile_start(profiling);
2503 let refitted = reconstruct_analyzed(
2504 mesh,
2505 &support,
2506 &SurfaceHint::InitialGuess {
2507 surface: candidate.surface,
2508 trust: crate::MetadataTrust::InitialGuess,
2509 },
2510 options,
2511 );
2512 ExtractionProfile::take_fitter(&mut budget.profile, |p| &mut p.refit_fitter);
2513 torus_outcome = if refitted.is_ok() { 3 } else { 2 };
2514 if let Some(profile) = &mut budget.profile {
2515 let exhausted =
2516 probe.len() == remaining.len() || probe.len() < probe_limit;
2517 profile.refit(
2518 started,
2519 support.len(),
2520 incumbent_count,
2521 !grew_beyond_probe || exhausted,
2522 );
2523 }
2524 if let Ok(fit) = refitted {
2525 reconstructed_probe = true;
2526 let started = profiling.then(Instant::now);
2527 let area = fit.metrics.supported_area;
2528 let support_scale = selection_scale(mesh, &support);
2529 let support_tolerance = options.distance_tolerance
2530 + options.relative_tolerance * support_scale.max(1.0);
2531 let rank = model_rank(
2532 mesh,
2533 Selection::Triangles(&support),
2534 fit.surface.surface_type(),
2535 &fit,
2536 support_tolerance,
2537 options.normal_tolerance,
2538 );
2539 let replace =
2540 probe_best.as_ref().is_none_or(|(count, old_rank, old, _)| {
2541 support.len() > *count
2542 || (support.len() == *count
2543 && (area > old.metrics.supported_area
2544 || (area == old.metrics.supported_area
2545 && compare_model_rank(
2546 rank,
2547 fit.surface.surface_type(),
2548 *old_rank,
2549 old.surface.surface_type(),
2550 ) == Ordering::Less)))
2551 });
2552 ExtractionProfile::charge(&mut budget.profile, started, |p| &mut p.rank_seconds);
2553 if support.len() < incumbent_count {
2554 ExtractionProfile::charge(&mut budget.profile, started, |p| {
2555 &mut p.rank_dominated_seconds
2556 });
2557 }
2558 if replace {
2559 probe_best = Some((support.len(), rank, fit, support));
2560 }
2561 }
2562 }
2563 }
2564 if let (Some(profile), SurfaceType::Torus) = (&mut budget.profile, kind) {
2565 profile.torus_sample(torus_outcome, fit_seconds);
2566 }
2567 if reached {
2568 if doubled_past_hopeless && !reached_any {
2569 posterior[kind_slot].rescued += 1.0;
2570 }
2571 reached_any = true;
2572 }
2573 let exhausted = probe.len() == remaining.len() || probe.len() < probe_limit;
2574 if (grew_beyond_probe && reconstructed_probe) || exhausted {
2575 break;
2576 }
2577 if !reached_any && !doubled_past_hopeless {
2578 let continue_probability =
2584 policy.probe_floor.max(posterior[kind_slot].rescue_rate());
2585 if unit_interval(&mut rng) >= continue_probability {
2586 break;
2587 }
2588 doubled_past_hopeless = true;
2589 }
2590 probe_limit = probe_limit.saturating_mul(2).min(remaining.len());
2591 }
2592 if doubled_past_hopeless && !reached_any {
2593 posterior[kind_slot].unrescued += 1.0;
2594 }
2595 if did_work {
2596 if reached_any {
2597 posterior[kind_slot].reached += 1.0;
2598 } else {
2599 posterior[kind_slot].failed += 1.0;
2600 }
2601 }
2602 if let Some((count, rank, mut fit, support)) = probe_best {
2603 posterior[kind_slot].support_share += count as f64 / n as f64;
2604 let area = fit.metrics.supported_area;
2605 let replace = best.as_ref().is_none_or(|(best_count, old_rank, old, _)| {
2606 count > *best_count
2607 || (count == *best_count
2608 && (area > old.metrics.supported_area
2609 || (area == old.metrics.supported_area
2610 && compare_model_rank(
2611 rank,
2612 fit.surface.surface_type(),
2613 *old_rank,
2614 old.surface.surface_type(),
2615 ) == Ordering::Less)))
2616 });
2617 if replace {
2618 let previous = best.as_ref().map_or(0, |(count, ..)| *count);
2619 improvement = Some(count.saturating_sub(previous) as f64 / n as f64);
2620 if let Some((_, _, _, old_support)) = &best {
2621 for &id in old_support {
2622 explored[id] += 1.0;
2623 }
2624 }
2625 incumbent.iter_mut().for_each(|flag| *flag = false);
2626 for &id in &support {
2627 if let Ok(at) = ids.binary_search(&id) {
2628 incumbent[at] = true;
2629 }
2630 }
2631 fit.diagnostics.hypotheses_generated = attempt_index + 1;
2632 best = Some((count, rank, fit, support));
2633 } else {
2634 for &id in &support {
2635 explored[id] += 1.0;
2636 }
2637 }
2638 }
2639 }
2640 bank[arm].tried += 1.0;
2641 if let Some(gain) = improvement {
2642 bank[arm].improved += 1.0;
2643 bank[arm].gain += gain;
2644 }
2645 if let Some((count, ..)) = &best {
2646 let w = *count as f64 / n as f64;
2650 let round_delta = round_error_share(delta_total, *count, component_size);
2651 let certified = (0..kind_count).all(|slot| {
2652 tried_count[slot] >= n
2653 || (1.0 - policy.seed_exploration * w).powi(kind_draws[slot] as i32) <= round_delta
2654 });
2655 if certified {
2656 budget.work.stops_at_risk_bound += 1;
2657 stopped_early = true;
2658 break;
2659 }
2660 }
2661 if tried_count.iter().all(|&count| count >= n) {
2662 budget.work.stops_at_seed_exhaustion += 1;
2663 stopped_early = true;
2664 break;
2665 }
2666 }
2667 if !stopped_early {
2668 budget.work.stops_at_hypothesis_cap += 1;
2669 }
2670 if let Some(profile) = &mut budget.profile {
2671 profile.rounds += 1;
2672 profile.seeds_consumed += attempt;
2673 profile.seed_slots += n * kind_count;
2674 if best.is_none() {
2675 profile.abandon(mesh, &remaining, options);
2676 }
2677 }
2678 let Some((_, _, mut fit, support)) = best else {
2679 break;
2680 };
2681 fit.diagnostics.phase_timings.region_growth_seconds = region_growth_seconds;
2682 for id in &support {
2683 remaining.remove(id);
2684 }
2685 budget.work.rounds += 1;
2686 out.push(to_region(fit, support));
2687 }
2688}
2689
2690fn candidate_fit(
2693 mesh: &AnalyzedMesh,
2694 component: &[usize],
2695 options: &RecognitionOptions,
2696 candidates: &[(Vec<usize>, AnalyticSurface)],
2697) -> Option<SurfaceFitResult> {
2698 if candidates.is_empty() {
2699 return None;
2700 }
2701 let mut ids = component.to_vec();
2702 ids.sort_unstable();
2703 let surface = candidates.iter().find_map(|(candidate, surface)| {
2704 let mut usable = candidate
2705 .iter()
2706 .copied()
2707 .filter(|&id| id < mesh.triangles.len() && mesh.triangles[id].area > 0.0);
2708 usable.by_ref().eq(ids.iter().copied()).then_some(*surface)
2709 })?;
2710 let magnitude = ids
2711 .iter()
2712 .flat_map(|&tid| mesh.triangles[tid].vertices)
2713 .map(|vid| {
2714 let p = mesh.vertices[vid];
2715 p.x.abs().max(p.y.abs()).max(p.z.abs())
2716 })
2717 .fold(1.0_f64, f64::max);
2718 let mut seeded = options.clone();
2719 seeded.distance_tolerance += CANDIDATE_ROUNDOFF_EPSILONS * f64::EPSILON * magnitude;
2720 let scale = selection_scale(mesh, &ids);
2721 let mut fit = evaluate_surface(mesh, &ids, surface, &seeded, FitPath::ExactCandidateReused).ok()?;
2722 let vertex_samples_only = matches!(seeded.sampling, crate::SamplingMode::Vertices);
2723 if !accepted_impl(&fit, &seeded, scale, vertex_samples_only) {
2724 return None;
2725 }
2726 fit.diagnostics.reason = "a supplied component carrier validated whole after the component's own whole fit was refused".into();
2727 Some(fit)
2728}
2729
2730fn shuffled_seed_order(ids: &[usize], rng: &mut SplitMix) -> Vec<usize> {
2731 let mut order = ids.to_vec();
2732 for upper in (2..=order.len()).rev() {
2733 let upper_u64 = upper as u64;
2734 let zone = (u64::MAX / upper_u64) * upper_u64;
2737 let index = loop {
2738 let value = rng.next();
2739 if value < zone {
2740 break (value % upper_u64) as usize;
2741 }
2742 };
2743 order.swap(upper - 1, index);
2744 }
2745 order
2746}
2747
2748const fn hypothesis_sample_triangles(kind: SurfaceType) -> usize {
2757 match kind {
2758 SurfaceType::Plane => 3,
2759 SurfaceType::Sphere => 4,
2760 SurfaceType::Cylinder => 6,
2764 SurfaceType::Cone => 4,
2765 SurfaceType::Torus => 6,
2766 }
2767}
2768
2769fn diverse_hypothesis_sample(
2775 mesh: &AnalyzedMesh,
2776 seed: usize,
2777 probe: &[usize],
2778 count: usize,
2779) -> Vec<usize> {
2780 debug_assert!(probe.contains(&seed));
2781 debug_assert!(count > 0 && probe.len() >= count);
2782 let mut selected = Vec::with_capacity(count);
2783 selected.push(seed);
2784 while selected.len() < count {
2785 let mut best: Option<(f64, f64, usize)> = None;
2786 for &candidate in probe {
2787 if selected.contains(&candidate) {
2788 continue;
2789 }
2790 let triangle = &mesh.triangles[candidate];
2791 let (normal_gap, spatial_gap) = selected.iter().fold(
2792 (f64::INFINITY, f64::INFINITY),
2793 |(normal_gap, spatial_gap), &chosen| {
2794 let other = &mesh.triangles[chosen];
2795 (
2796 normal_gap
2797 .min(1.0 - triangle.normal.dot(other.normal).abs().clamp(0.0, 1.0)),
2798 spatial_gap.min((triangle.centroid - other.centroid).length_squared()),
2799 )
2800 },
2801 );
2802 let key = (normal_gap, spatial_gap, std::cmp::Reverse(candidate));
2803 if best
2804 .as_ref()
2805 .is_none_or(|&(best_normal, best_spatial, best_id)| {
2806 (normal_gap, spatial_gap, std::cmp::Reverse(candidate))
2807 > (best_normal, best_spatial, std::cmp::Reverse(best_id))
2808 })
2809 {
2810 best = Some((key.0, key.1, candidate));
2811 }
2812 }
2813 selected.push(best.expect("probe has enough distinct triangles").2);
2814 }
2815 selected.sort_unstable();
2816 selected
2817}
2818
2819fn required_seed_hypotheses(
2826 confidence: f64,
2827 support_fraction: f64,
2828 kinds: usize,
2829 cap: usize,
2830) -> usize {
2831 let minimum = kinds.min(cap).max(1);
2832 if confidence <= 0.0 || support_fraction >= 1.0 {
2833 return minimum;
2834 }
2835 if support_fraction <= 0.0 || cap <= minimum {
2836 return cap.max(1);
2837 }
2838 let rounds = ((1.0 - confidence).ln() / (1.0 - support_fraction).ln())
2839 .ceil()
2840 .max(1.0) as usize;
2841 rounds.saturating_mul(kinds).clamp(minimum, cap)
2842}
2843
2844struct Remaining {
2848 ordered: BTreeSet<usize>,
2849 member: Vec<bool>,
2850}
2851
2852impl Remaining {
2853 fn new(mesh: &AnalyzedMesh, ids: &[usize]) -> Self {
2854 let mut member = vec![false; mesh.triangles.len()];
2855 for &id in ids {
2856 member[id] = true;
2857 }
2858 Self {
2859 ordered: ids.iter().copied().collect(),
2860 member,
2861 }
2862 }
2863
2864 fn len(&self) -> usize {
2865 self.ordered.len()
2866 }
2867
2868 fn iter(&self) -> std::collections::btree_set::Iter<'_, usize> {
2869 self.ordered.iter()
2870 }
2871
2872 fn contains(&self, id: usize) -> bool {
2873 self.member[id]
2874 }
2875
2876 fn remove(&mut self, id: &usize) {
2877 self.ordered.remove(id);
2878 self.member[*id] = false;
2879 }
2880}
2881
2882struct Scratch {
2885 probe: Vec<u32>,
2886 probe_epoch: u32,
2887 support: Vec<u32>,
2888 support_epoch: u32,
2889}
2890
2891impl Scratch {
2892 fn new(mesh: &AnalyzedMesh) -> Self {
2893 Self {
2894 probe: vec![0; mesh.triangles.len()],
2895 probe_epoch: 0,
2896 support: vec![0; mesh.triangles.len()],
2897 support_epoch: 0,
2898 }
2899 }
2900
2901 fn probe_stamp(&mut self) -> u32 {
2903 if self.probe_epoch == u32::MAX {
2904 self.probe.fill(0);
2905 self.probe_epoch = 0;
2906 }
2907 self.probe_epoch += 1;
2908 self.probe_epoch
2909 }
2910
2911 fn support_stamps(&mut self) -> (u32, u32) {
2913 if self.support_epoch >= u32::MAX - 1 {
2914 self.support.fill(0);
2915 self.support_epoch = 0;
2916 }
2917 self.support_epoch += 2;
2918 (self.support_epoch - 1, self.support_epoch)
2919 }
2920}
2921
2922struct Neighborhood {
2929 stamp: u32,
2930 visited: Vec<usize>,
2931 queue: VecDeque<usize>,
2932}
2933
2934impl Neighborhood {
2935 fn start(scratch: &mut Scratch, seed: usize) -> Self {
2936 let stamp = scratch.probe_stamp();
2937 scratch.probe[seed] = stamp;
2938 Self {
2939 stamp,
2940 visited: vec![seed],
2941 queue: VecDeque::from([seed]),
2942 }
2943 }
2944
2945 fn grow(
2949 &mut self,
2950 mesh: &AnalyzedMesh,
2951 allowed: &Remaining,
2952 scratch: &mut Scratch,
2953 limit: usize,
2954 crease: Option<f64>,
2955 ) -> Vec<usize> {
2956 while let Some(id) = self.queue.pop_front() {
2957 if self.visited.len() >= limit {
2958 self.queue.push_front(id);
2960 break;
2961 }
2962 for &n in mesh.triangles[id].neighbors.iter().flatten() {
2963 if crease.is_some_and(|cos| mesh.triangles[id].normal.dot(mesh.triangles[n].normal) < cos) {
2964 continue;
2965 }
2966 if allowed.contains(n) && scratch.probe[n] != self.stamp {
2967 scratch.probe[n] = self.stamp;
2968 self.visited.push(n);
2969 self.queue.push_back(n);
2970 }
2971 }
2972 }
2973 let mut probe = self.visited.clone();
2974 probe.sort_unstable();
2975 probe
2976 }
2977}
2978
2979fn probe_crease(options: &RecognitionOptions) -> Option<f64> {
2982 options.probe_crease_gate.then(|| options.normal_tolerance.cos())
2983}
2984
2985fn triangle_support(
2986 mesh: &AnalyzedMesh,
2987 id: usize,
2988 surface: AnalyticSurface,
2989 options: &RecognitionOptions,
2990 mut tally: Option<&mut SupportTally>,
2991) -> bool {
2992 let t = &mesh.triangles[id];
2993 let tolerance =
2994 options.distance_tolerance + options.relative_tolerance * mesh.diagonal.max(1.0);
2995 if let Some(tally) = tally.as_deref_mut() {
2996 tally.triangles += 1;
2997 }
2998 if t.vertices.iter().any(|&v| {
2999 if let Some(tally) = tally.as_deref_mut() {
3000 tally.evaluations += 1;
3001 tally.vertices.insert(v);
3002 }
3003 surface.signed_distance(mesh.vertices[v]).abs() > tolerance
3004 }) {
3005 return false;
3006 }
3007 let Some(normal) = surface.normal_at(t.centroid) else {
3008 return false;
3009 };
3010 t.normal.dot(normal).abs().clamp(-1.0, 1.0).acos() <= options.normal_tolerance
3011}
3012#[allow(clippy::too_many_arguments)]
3019fn support_component(
3020 mesh: &AnalyzedMesh,
3021 candidates: &Remaining,
3022 scratch: &mut Scratch,
3023 seed: usize,
3024 surface: AnalyticSurface,
3025 options: &RecognitionOptions,
3026 mut tally: Option<&mut SupportTally>,
3027) -> Vec<usize> {
3028 if !candidates.contains(seed)
3029 || !triangle_support(mesh, seed, surface, options, tally.as_deref_mut())
3030 {
3031 return Vec::new();
3032 }
3033 let (rejected, accepted) = scratch.support_stamps();
3034 let stamps = &mut scratch.support;
3035 stamps[seed] = accepted;
3036 let mut seen = vec![seed];
3037 let mut queue = VecDeque::from([seed]);
3038 while let Some(id) = queue.pop_front() {
3039 for &n in mesh.triangles[id].neighbors.iter().flatten() {
3040 if !candidates.contains(n) || stamps[n] == accepted || stamps[n] == rejected {
3041 continue;
3042 }
3043 if triangle_support(mesh, n, surface, options, tally.as_deref_mut()) {
3044 stamps[n] = accepted;
3045 seen.push(n);
3046 queue.push_back(n);
3047 } else {
3048 stamps[n] = rejected;
3049 }
3050 }
3051 }
3052 seen.sort_unstable();
3053 seen
3054}
3055struct SplitMix(u64);
3056impl SplitMix {
3057 fn next(&mut self) -> u64 {
3058 self.0 = self.0.wrapping_add(0x9e3779b97f4a7c15);
3059 let mut z = self.0;
3060 z = (z ^ (z >> 30)).wrapping_mul(0xbf58476d1ce4e5b9);
3061 z = (z ^ (z >> 27)).wrapping_mul(0x94d049bb133111eb);
3062 z ^ (z >> 31)
3063 }
3064}
3065