1pub use super::*;
2use super::mass_profile;
3use web_time::Instant;
4
5fn face_line_meta(face: &FaceRecord) -> (&'static str, usize, usize, bool, bool, usize, usize) {
9 let kind = match face.surface.analytic().map(|analytic| analytic.kind_label()) {
12 Some("Surface of revolution") => "Revolution",
13 Some(label) => label,
14 None => "Fitted",
15 };
16 let (closed_u, closed_v) = face.surface.closed_directions().unwrap_or((false, false));
17 let coedges = face
18 .loops
19 .iter()
20 .map(|loop_record| loop_record.coedges.len())
21 .sum();
22 (
23 kind,
24 face.surface.degree_u,
25 face.surface.degree_v,
26 closed_u,
27 closed_v,
28 face.loops.len(),
29 coedges,
30 )
31}
32
33fn emit_face_line(
37 call: &str,
38 shell: usize,
39 face_index: usize,
40 face: &FaceRecord,
41 before: Option<super::profile::MassProfile>,
42 started: Option<Instant>,
43) {
44 let (Some(before), Some(started)) = (before, started) else {
45 return;
46 };
47 let wall_ms = started.elapsed().as_secs_f64() * 1_000.0;
48 let (kind, degree_u, degree_v, closed_u, closed_v, loops, coedges) = face_line_meta(face);
49 super::profile::emit_face(
50 call, shell, face_index, kind, degree_u, degree_v, closed_u, closed_v, loops, coedges,
51 before, wall_ms,
52 );
53}
54
55pub fn solid_mass_properties(solid: &BrepSolid) -> Result<MassProperties, String> {
56 let token = super::profile::begin("solid_mass_properties");
57 let result = solid_mass_properties_cached(solid);
58 super::profile::end(token);
59 if result.is_ok() && sign_terms_oracle_enabled() && solid.kind == crate::BodyKind::Solid
60 && !solid.shells.is_empty() && solid.shells.iter().all(|shell| !shell.faces.is_empty())
61 {
62 verify_solid_sign_terms(solid)?;
63 }
64 if let (Some(dump), Ok(properties)) = (super::profile::identity_dump(), result.as_ref()) {
65 super::profile::emit_identity(
66 dump,
67 "solid_mass_properties",
68 solid,
69 &[
70 ("volume_bits", properties.volume),
71 ("area_bits", properties.surface_area),
72 ],
73 );
74 }
75 result
76}
77
78fn solid_mass_properties_cached(solid: &BrepSolid) -> Result<MassProperties, String> {
81 let identity = face_set_identity(solid);
82 if let Some((cached_identity, properties)) = solid.mass_properties_cache.entry.get() {
83 if cached_identity == identity {
84 if super::profile::mass_profile_enabled() {
85 let measured = solid_mass_properties_inner(solid)?;
86 assert_eq!(properties.volume.to_bits(), measured.volume.to_bits(),
87 "mass cache changed volume");
88 assert_eq!(properties.surface_area.to_bits(), measured.surface_area.to_bits(),
89 "mass cache changed area");
90 eprintln!("mass.cache hit faces={} verified=true", identity.faces);
91 }
92 return Ok(properties);
93 }
94 }
95 solid.mass_properties_cache.entry.set(None);
97 let properties = solid_mass_properties_inner(solid)?;
98 solid.mass_properties_cache.entry.set(Some((identity, properties)));
99 Ok(properties)
100}
101
102pub fn solid_mass_properties_inner(solid: &BrepSolid) -> Result<MassProperties, String> {
103 let mut properties = MassProperties {
104 surface_area: 0.0,
105 volume: 0.0,
106 };
107 let mut volume_compensation = 0.0;
108 let face_lines = super::profile::face_lines_enabled();
109 for (shell_index, shell) in solid.shells.iter().enumerate() {
110 if shell.faces.is_empty() {
111 continue;
112 }
113 let reference = shell_volume_reference(shell)?;
117 let kinds = [Integrand::Area, Integrand::VolumeAbout(reference)];
118 for (face_index, face) in shell.faces.iter().enumerate() {
119 mass_profile(|p| p.faces += 1);
120 let line_before = face_lines.then(super::profile::snapshot);
121 let line_started = face_lines.then(Instant::now);
122 let gate_started = super::profile::profile_started();
123 let (area, volume) = if let Some(values) = biperiodic_band_integral(face, &kinds)? {
124 mass_profile(|p| {
125 p.route_biperiodic += 1;
126 p.gate_ms += super::profile::elapsed_ms(gate_started);
127 });
128 (values[0], values[1] / 3.0)
129 } else if !is_affine(&face.surface)? && !is_untrimmed(face)? {
130 mass_profile(|p| {
131 p.trimmed_faces += 1;
132 p.gate_ms += super::profile::elapsed_ms(gate_started);
133 });
134 let values = integrate_trimmed_multi(face, &kinds)?;
136 (values[0], values[1] / 3.0)
137 } else if is_affine(&face.surface)? {
138 mass_profile(|p| {
139 p.route_affine += 1;
140 p.gate_ms += super::profile::elapsed_ms(gate_started);
141 });
142 affine_area_and_volume_about(face, reference)?
146 } else {
147 mass_profile(|p| {
148 p.route_untrimmed += 1;
149 p.gate_ms += super::profile::elapsed_ms(gate_started);
150 });
151 let started = super::profile::profile_started();
154 let values = integrate_untrimmed_multi(face, &kinds)?;
155 mass_profile(|p| p.untrimmed_ms += super::profile::elapsed_ms(started));
156 (values[0], values[1] / 3.0)
157 };
158 emit_face_line(
159 "solid_mass_properties",
160 shell_index,
161 face_index,
162 face,
163 line_before,
164 line_started,
165 );
166 properties.surface_area += area;
167 let next = properties.volume + volume;
168 if properties.volume.abs() >= volume.abs() {
169 volume_compensation += (properties.volume - next) + volume;
170 } else {
171 volume_compensation += (volume - next) + properties.volume;
172 }
173 properties.volume = next;
174 }
175 }
176 properties.volume += volume_compensation;
177 Ok(properties)
178}
179
180pub fn solid_signed_volume(solid: &BrepSolid) -> Result<f64, String> {
185 let token = super::profile::begin("solid_signed_volume");
186 let result = if solid.shells.len() == 1 && !solid.shells[0].faces.is_empty() {
187 match solid_mass_properties_cached(solid) {
188 Ok(properties) => {
189 if super::profile::mass_profile_enabled() {
190 let original = solid_signed_volume_uncached(solid)
191 .expect("shared mass measurement changed a signed-volume refusal");
192 assert_eq!(properties.volume.to_bits(), original.to_bits(),
193 "shared mass measurement changed signed volume");
194 }
195 Ok(properties.volume)
196 }
197 Err(_) => solid_signed_volume_uncached(solid),
199 }
200 } else {
201 solid_signed_volume_uncached(solid)
202 };
203 super::profile::end(token);
204 if result.is_ok() && sign_terms_oracle_enabled() && solid.kind == crate::BodyKind::Solid {
205 verify_solid_sign_terms(solid)?;
206 }
207 if let (Some(dump), Ok(volume)) = (super::profile::identity_dump(), result.as_ref()) {
208 super::profile::emit_identity(dump, "solid_signed_volume", solid, &[("signed_bits", *volume)]);
209 }
210 result
211}
212
213const SIGN_READING_MARGIN: f64 = 1e-6;
219
220pub fn signed_volume_against(solid: &BrepSolid, bar: f64) -> Result<f64, String> {
227 static EXACT: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
228 if *EXACT.get_or_init(|| std::env::var("BREP_SIGN_READERS_EXACT").as_deref() == Ok("1")) {
229 return solid_signed_volume(solid);
230 }
231 solid_signed_volume_for_sign(solid, bar)
232}
233
234pub fn solid_signed_volume_for_sign(solid: &BrepSolid, bar: f64) -> Result<f64, String> {
255 let enabled = match std::env::var("BREP_SPHERE_SIGN_BOUND") {
256 Ok(value) => value == "1" || value == "on",
257 Err(std::env::VarError::NotPresent) => true,
258 Err(_) => false,
259 };
260 let result = solid_signed_volume_for_sign_with_bound(solid, bar, enabled);
261 if result.is_ok() && sign_terms_oracle_enabled() {
262 verify_solid_sign_terms(solid)?;
263 }
264 result
265}
266
267pub fn solid_signed_volume_for_sign_with_bound(solid: &BrepSolid, bar: f64, enabled: bool) -> Result<f64, String> {
268 if enabled {
269 if let Some(lower) = super::sphere_sign::positive_volume_bound(solid) {
270 if bar.is_finite() && lower > bar {
271 if crate::profile::profile_enabled() {
272 profile_line!("mass.sign_certificate kind=trimmed_spheres lower={lower:.9} bar={bar:.3e}");
273 }
274 return Ok(lower);
275 }
276 }
277 }
278 if sliver_bound_enabled() {
279 if let Some(lower) = sliver_bound_certificate(solid, bar) {
280 return Ok(lower);
281 }
282 }
283 let token = super::profile::begin("solid_signed_volume_for_sign");
284 let outcome = solid_sign_terms_reading(solid);
285 super::profile::end(token);
286 let (reading, magnitude) = outcome?;
287 if (reading - bar).abs() > SIGN_READING_MARGIN * magnitude {
288 return Ok(reading);
289 }
290 solid_signed_volume(solid)
291}
292
293pub const COARSE_SIGN_DEPTH: usize = 1;
296
297#[derive(Clone, Copy, Debug)]
300pub struct CoarseSign {
301 pub reading: f64,
304 pub bound: f64,
307 pub skipped: f64,
310}
311
312pub fn solid_sign_coarse_certificate(solid: &BrepSolid, depth: usize) -> Option<CoarseSign> {
364 let (mut reading, mut bound, mut scale, mut skipped) = (0.0f64, 0.0f64, 0.0f64, 0.0f64);
365 let reach = control_box_volume(solid);
371 let mut faces = Vec::new();
379 for shell in &solid.shells {
380 let reference = shell_volume_reference(shell).ok()?;
381 for face in &shell.faces {
382 let local = face_volume_reference(face).unwrap_or(reference);
383 faces.push((face, local, reference, bound_potential(&face.surface, local)));
384 }
385 }
386 faces.sort_by(|a, b| b.3.total_cmp(&a.3));
387 {
388 for &(face, local, reference, _) in &faces {
389 let (terms, measure) =
390 super::trimmed::with_coarse_quadtree(depth, || face_volume_terms_about(face, local));
391 let terms = terms.ok()?;
392 if measure.declined || !terms.iter().all(|v| v.is_finite()) {
393 return None;
394 }
395 let offset = local.sub(reference);
396 let area = Vec3::new(terms[1], terms[2], terms[3]);
397 let contribution = terms[0] + offset.dot(area);
398 let face_bound = (measure.flux + measure.normal * offset.length()) / 3.0;
399 reading += contribution;
400 bound += face_bound;
401 skipped += measure.skipped;
402 scale += terms[0].abs() + offset.length() * area.length() + face_bound;
403 if !(bound <= reach) {
404 return None;
405 }
406 }
407 }
408 let bound = bound + 1e-9 * scale;
409 [reading, bound, skipped].iter().all(|v| v.is_finite()).then_some(CoarseSign { reading, bound, skipped })
410}
411
412fn bound_potential(surface: &crate::NurbsSurface, center: Vec3) -> f64 {
417 let span = |knots: &[f64], degree: usize| -> f64 {
418 match (knots.get(degree), knots.len().checked_sub(degree + 1).and_then(|i| knots.get(i))) {
419 (Some(low), Some(high)) => (high - low).abs(),
420 _ => f64::INFINITY,
421 }
422 };
423 let area = span(&surface.knots_u, surface.degree_u) * span(&surface.knots_v, surface.degree_v);
424 match surface_flux_bounds(surface, center) {
425 Some((n, r)) if (n * r * area).is_finite() => n * r * area,
426 _ => f64::INFINITY,
427 }
428}
429
430fn control_box_volume(solid: &BrepSolid) -> f64 {
433 let (mut low, mut high) = ([f64::INFINITY; 3], [f64::NEG_INFINITY; 3]);
434 for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
435 for control in face.surface.control_points.iter().flatten() {
436 let Ok(point) = control.point() else { return f64::INFINITY };
437 for (axis, value) in [point.x, point.y, point.z].into_iter().enumerate() {
438 low[axis] = low[axis].min(value);
439 high[axis] = high[axis].max(value);
440 }
441 }
442 }
443 let volume = (0..3).map(|axis| high[axis] - low[axis]).product::<f64>();
444 if volume.is_finite() { volume } else { f64::INFINITY }
445}
446
447fn sliver_bound_enabled() -> bool {
454 switch!(live "BREP_SIGN_SLIVER_BOUND", true)
455}
456
457
458pub fn sliver_bound_certificate(solid: &BrepSolid, bar: f64) -> Option<f64> {
479 if !bar.is_finite() {
480 return None;
481 }
482 let token = super::profile::begin("solid_sign_sliver_bound");
483 let mut prefetched = SignPrefetch::spawn(solid);
486 let outcome = super::trimmed::with_straight_corrections_skipped(|| -> Option<(f64, f64, f64, f64, [usize; 3])> {
487 let (mut reading, mut magnitude, mut bound, mut scale) = (0.0, 0.0, 0.0, 0.0);
488 let mut counts = [0usize; 3]; let mut slot = 0usize;
490 for shell in &solid.shells {
491 let reference = shell_volume_reference(shell).ok()?;
492 let (mut volume, mut compensation) = (0.0f64, 0.0f64);
493 for face in &shell.faces {
494 let local = face_volume_reference(face).unwrap_or(reference);
495 let identity = super::identity::face_contribution_identity(face, local);
496 let offset = local.sub(reference);
497 let ready = prefetched.as_mut().and_then(|prefetched| prefetched.claim(slot));
498 slot += 1;
499 let (ready_bounded, ready_exact) = match ready {
500 Some((bounded, exact)) => (Some(bounded), exact),
501 None => (None, None),
502 };
503 let (terms, face_bound, face_scale) = match crate::reading_memo::peek_sign_terms(identity) {
504 Some(terms) => {
505 counts[0] += 1;
506 (terms?, 0.0, 0.0)
507 }
508 None => match crate::reading_memo::memoized_bounded_sign_terms(identity, || {
509 prefetched_or(ready_bounded, || bounded_face_terms(face, local))
510 }) {
511 Some((terms, per_offset, fixed, rounding)) => {
512 counts[1] += 1;
513 (terms, fixed + per_offset * offset.length(), rounding)
514 }
515 None => {
516 counts[2] += 1;
517 let terms = crate::reading_memo::memoized_sign_terms(identity, || {
518 prefetched_or(ready_exact, || face_volume_terms_about(face, local).ok())
519 })?;
520 (terms, 0.0, 0.0)
521 }
522 },
523 };
524 let area = Vec3::new(terms[1], terms[2], terms[3]);
525 let contribution = terms[0] + offset.dot(area);
526 magnitude += contribution.abs();
527 bound += face_bound;
528 scale += terms[0].abs() + offset.length() * area.length() + face_bound + face_scale * (1.0 + offset.length());
529 let next = volume + contribution;
530 if volume.abs() >= contribution.abs() {
531 compensation += (volume - next) + contribution;
532 } else {
533 compensation += (contribution - next) + volume;
534 }
535 volume = next;
536 }
537 reading += volume + compensation;
538 }
539 Some((reading, magnitude, bound, scale, counts))
540 });
541 super::profile::end(token);
542 if let Some(prefetched) = prefetched {
543 prefetched.report();
544 }
545 let (reading, magnitude, bound, scale, counts) = outcome?;
546 let slack = 1e-9 * scale;
551 let lower = reading - bound - slack;
552 let certified = [reading, magnitude, bound, scale, lower].iter().all(|v| v.is_finite())
553 && lower > bar
554 && lower - bar > SIGN_READING_MARGIN * (magnitude + bound + slack);
555 if crate::profile::profile_enabled() {
556 profile_line!(
557 "mass.sign_certificate kind=sliver_bound certified={certified} cells={reading:.9e} bound={bound:.3e} slack={slack:.3e} magnitude={magnitude:.3e} held={} bounded={} exact={}",
558 counts[0], counts[1], counts[2]
559 );
560 }
561 certified.then_some(lower)
562}
563
564const SIGN_PREFETCH_MIN_FACES: usize = 64;
578
579fn sign_prefetch_mode() -> crate::env_read::Mode {
580 #[cfg(not(test))]
581 {
582 crate::mode_switch!("BREP_SIGN_PREFETCH", true)
583 }
584}
585
586
587type BoundedTerms = Option<([f64; 4], f64, f64, f64)>;
588type SignReady = (BoundedTerms, Option<Option<[f64; 4]>>);
589
590struct SignJob {
591 face: FaceRecord,
592 local: Vec3,
593}
594
595fn sign_job(job: SignJob) -> SignReady {
596 super::trimmed::with_straight_corrections_skipped(|| {
597 let bounded = bounded_face_terms(&job.face, job.local);
598 let exact = bounded.is_none().then(|| face_volume_terms_about(&job.face, job.local).ok());
599 (bounded, exact)
600 })
601}
602
603#[derive(Clone, Copy, Default)]
604struct SignPrefetchTally {
605 check: bool,
606 hits: usize,
607 compared: usize,
608 disagree: usize,
609}
610
611thread_local! {
612 static SIGN_PREFETCH_TALLY: std::cell::Cell<Option<SignPrefetchTally>> = const { std::cell::Cell::new(None) };
614}
615
616struct SignPrefetch {
617 slots: crate::claim_slots::ClaimSlots<SignJob, SignReady>,
618 previous: Option<SignPrefetchTally>,
619}
620
621impl SignPrefetch {
622 fn spawn(solid: &BrepSolid) -> Option<Self> {
623 let mode = sign_prefetch_mode();
624 let faces: usize = solid.shells.iter().map(|shell| shell.faces.len()).sum();
625 if mode == crate::env_read::Mode::Off
626 || faces < SIGN_PREFETCH_MIN_FACES
627 || !crate::claim_slots::helpers_available()
628 {
629 return None;
630 }
631 let mut jobs = Vec::with_capacity(faces);
632 for shell in &solid.shells {
633 let reference = shell_volume_reference(shell).ok()?;
634 for face in &shell.faces {
635 let local = face_volume_reference(face).unwrap_or(reference);
636 jobs.push(SignJob { face: face.clone(), local });
637 }
638 }
639 let slots = crate::claim_slots::ClaimSlots::spawn(jobs, sign_job)?;
640 let tally = SignPrefetchTally { check: mode == crate::env_read::Mode::Check, ..Default::default() };
641 let previous = SIGN_PREFETCH_TALLY.with(|cell| cell.replace(Some(tally)));
642 Some(Self { slots, previous })
643 }
644
645 fn claim(&mut self, index: usize) -> Option<SignReady> {
646 self.slots.claim(index)
647 }
648
649 fn report(self) {
650 let tally = SIGN_PREFETCH_TALLY.with(|cell| cell.replace(self.previous)).unwrap_or_default();
651 if crate::profile::profile_enabled() {
652 profile_line!(
653 "mass.sign_prefetch faces={} check={} taken={} claimed={} hits={} compared={} disagree={}",
654 self.slots.len(),
655 u8::from(tally.check),
656 self.slots.taken,
657 self.slots.claimed,
658 tally.hits,
659 tally.compared,
660 tally.disagree
661 );
662 }
663 }
664}
665
666fn prefetched_or<T: std::fmt::Debug>(ready: Option<T>, compute: impl FnOnce() -> T) -> T {
670 let Some(value) = ready else {
671 return compute();
672 };
673 let check = SIGN_PREFETCH_TALLY.with(|cell| cell.get()).is_some_and(|tally| tally.check);
674 if !check {
675 SIGN_PREFETCH_TALLY.with(|cell| cell.set(cell.get().map(|mut tally| { tally.hits += 1; tally })));
676 return value;
677 }
678 let fresh = compute();
679 let agrees = format!("{fresh:?}") == format!("{value:?}");
680 SIGN_PREFETCH_TALLY.with(|cell| {
681 cell.set(cell.get().map(|mut tally| {
682 tally.compared += 1;
683 tally.disagree += usize::from(!agrees);
684 tally
685 }))
686 });
687 fresh
688}
689
690pub fn bounded_face_terms(face: &FaceRecord, local: Vec3) -> Option<([f64; 4], f64, f64, f64)> {
697 let (terms, measure) = super::trimmed::with_sliver_measure(|| face_volume_terms_about(face, local));
698 let terms = terms.ok()?;
699 if measure.declined || !terms.iter().all(|v| v.is_finite()) {
700 return None;
701 }
702 if measure.measure == 0.0 {
703 return Some((terms, 0.0, 0.0, measure.complement / 3.0));
704 }
705 let (n, r) = surface_flux_bounds(&face.surface, local)?;
706 let per_offset = measure.measure * n / 3.0;
707 let fixed = per_offset * r;
708 [per_offset, fixed].iter().all(|v| v.is_finite()).then_some((terms, per_offset, fixed, measure.complement / 3.0))
709}
710
711pub fn surface_flux_bounds(surface: &crate::NurbsSurface, center: Vec3) -> Option<(f64, f64)> {
723 let net = &surface.control_points;
724 let rows = net.len();
725 let columns = net.first()?.len();
726 surface_flux_bounds_over(surface, center, 0..rows, 0..columns)
727}
728
729pub fn surface_flux_bounds_on_span(surface: &crate::NurbsSurface, center: Vec3, span_u: usize, span_v: usize) -> Option<(f64, f64)> {
735 let (p, q) = (surface.degree_u, surface.degree_v);
736 if span_u < p || span_v < q {
737 return None;
738 }
739 surface_flux_bounds_over(surface, center, span_u - p..span_u + 1, span_v - q..span_v + 1)
740}
741
742fn surface_flux_bounds_over(
743 surface: &crate::NurbsSurface,
744 center: Vec3,
745 row_range: std::ops::Range<usize>,
746 column_range: std::ops::Range<usize>,
747) -> Option<(f64, f64)> {
748 let net = &surface.control_points;
749 let rows = net.len();
750 let columns = net.first()?.len();
751 if rows == 0 || columns == 0 || net.iter().any(|row| row.len() != columns)
752 || row_range.is_empty() || column_range.is_empty() || row_range.end > rows || column_range.end > columns
753 {
754 return None;
755 }
756 let relative = |i: usize, j: usize| -> Option<[f64; 4]> {
757 let q = net[i][j];
758 let values = [q.x - center.x * q.w, q.y - center.y * q.w, q.z - center.z * q.w, q.w];
759 (values.iter().all(|v| v.is_finite()) && q.w > 0.0).then_some(values)
760 };
761 let mut w_min = f64::INFINITY;
762 let mut r = 0.0f64;
763 for i in row_range.clone() {
764 for j in column_range.clone() {
765 let q = relative(i, j)?;
766 w_min = w_min.min(q[3]);
767 r = r.max((q[0] * q[0] + q[1] * q[1] + q[2] * q[2]).sqrt() / q[3]);
768 }
769 }
770 let derivative = |along_u: bool| -> Option<(f64, f64)> {
772 let (degree, knots, count, range) = if along_u {
773 (surface.degree_u, &surface.knots_u, rows, row_range.clone())
774 } else {
775 (surface.degree_v, &surface.knots_v, columns, column_range.clone())
776 };
777 if knots.len() < count + degree + 1 {
778 return None;
779 }
780 let (mut point, mut weight) = (0.0f64, 0.0f64);
781 if degree == 0 {
782 return Some((0.0, 0.0));
783 }
784 for k in range.start..range.end.saturating_sub(1) {
787 let span = knots[k + degree + 1] - knots[k + 1];
788 if !(span > 0.0) {
789 continue;
790 }
791 let factor = degree as f64 / span;
792 let others = if along_u { column_range.clone() } else { row_range.clone() };
793 for other in others {
794 let (a, b) = if along_u {
795 (relative(k, other)?, relative(k + 1, other)?)
796 } else {
797 (relative(other, k)?, relative(other, k + 1)?)
798 };
799 let d = [b[0] - a[0], b[1] - a[1], b[2] - a[2], b[3] - a[3]];
800 point = point.max(factor * (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt());
801 weight = weight.max(factor * d[3].abs());
802 }
803 }
804 Some((point, weight))
805 };
806 let (xu, wu) = derivative(true)?;
807 let (xv, wv) = derivative(false)?;
808 let su = (xu + wu * r) / w_min;
809 let sv = (xv + wv * r) / w_min;
810 let n = su * sv;
811 let (n, r) = (n * (1.0 + 1e-9), r * (1.0 + 1e-9));
813 (n.is_finite() && r.is_finite() && w_min.is_finite()).then_some((n, r))
814}
815
816fn solid_sign_terms_reading(solid: &BrepSolid) -> Result<(f64, f64), String> {
821 super::trimmed::with_straight_corrections_skipped(|| {
822 let (mut reading, mut magnitude) = (0.0, 0.0);
823 for (shell_index, shell) in solid.shells.iter().enumerate() {
824 let (volume, faces) = shell_volume_sign_reading(shell, shell_index)?;
825 reading += volume;
826 magnitude += faces;
827 }
828 Ok((reading, magnitude))
829 })
830}
831
832fn sign_terms_oracle_enabled() -> bool {
833 switch!(live "BREP_SIGN_TERMS_ORACLE", false)
834}
835
836fn verify_solid_sign_terms(solid: &BrepSolid) -> Result<(), String> {
839 let token = super::profile::begin("solid_sign_terms_oracle");
840 let reading = solid_sign_terms_reading(solid).map(|pair| pair.0);
841 super::profile::end(token);
842 check_sign_terms(solid, reading?)
843}
844
845pub fn check_sign_terms(solid: &BrepSolid, reading: f64) -> Result<(), String> {
846 let exact = solid_signed_volume_uncached(solid)?;
847 let error = (reading - exact).abs();
848 let bar = 1e-9 * exact.abs();
849 if !reading.is_finite() || !exact.is_finite() || error > bar {
850 return Err(format!("sign terms oracle: retained {reading:.17e}, whole-body {exact:.17e}, error {error:.3e} exceeds {bar:.3e}"));
851 }
852 super::profile::emit_sign_oracle(solid, reading, exact)?;
853 Ok(())
854}
855
856fn shell_volume_sign_reading(shell: &ShellRecord, shell_index: usize) -> Result<(f64, f64), String> {
860 let reference = shell_volume_reference(shell)?;
861 if crate::profile::profile_enabled() {
862 profile_line!(
863 "mass.sign_reference faces={} reference=({:.9},{:.9},{:.9})",
864 shell.faces.len(), reference.x, reference.y, reference.z
865 );
866 }
867 let mut volume = 0.0;
868 let mut compensation = 0.0;
869 let mut magnitude = 0.0;
870 let face_lines = super::profile::face_lines_enabled();
871 for (face_index, face) in shell.faces.iter().enumerate() {
872 mass_profile(|p| p.faces += 1);
873 let line_before = face_lines.then(super::profile::snapshot);
874 let line_started = face_lines.then(Instant::now);
875 let local = face_volume_reference(face).unwrap_or(reference);
881 let hash_started = super::profile::profile_started();
882 let identity = super::identity::face_contribution_identity(face, local);
883 let hash_ms = super::profile::elapsed_ms(hash_started);
884 let mut reread = false;
885 let terms = match crate::reading_memo::memoized_sign_terms(identity, || {
886 reread = true;
887 face_volume_terms_about(face, local).ok()
888 }) {
889 Some(terms) => terms,
890 None => face_volume_terms_about(face, local)?,
891 };
892 let contribution = terms[0] + local.sub(reference).dot(Vec3::new(terms[1], terms[2], terms[3]));
893 super::profile::sign_face(shell_index, face, reread, hash_ms);
894 emit_face_line("shell_volume_sign_reading", shell_index, face_index, face, line_before, line_started);
895 magnitude += contribution.abs();
896 let next = volume + contribution;
897 if volume.abs() >= contribution.abs() {
898 compensation += (volume - next) + contribution;
899 } else {
900 compensation += (contribution - next) + volume;
901 }
902 volume = next;
903 }
904 Ok((volume + compensation, magnitude))
905}
906
907pub fn solid_signed_volume_uncached(solid: &BrepSolid) -> Result<f64, String> {
908 let mut volume = 0.0;
909 for shell in &solid.shells {
910 volume += shell_signed_volume(shell)?;
911 }
912 Ok(volume)
913}
914
915pub fn shell_volume_reference(shell: &ShellRecord) -> Result<Vec3, String> {
916 shell.faces.iter().find_map(face_volume_reference)
917 .ok_or_else(|| "mass_properties: shell has no finite geometric reference".to_string())
918}
919
920pub fn face_volume_reference(face: &FaceRecord) -> Option<Vec3> {
922 let finite = |point: Vec3| point.x.is_finite() && point.y.is_finite() && point.z.is_finite();
923 if let Some(coedge) = face
924 .loops
925 .first()
926 .and_then(|loop_record| loop_record.coedges.first())
927 {
928 if let Ok(domain) = coedge.pcurve.domain() {
929 if let Ok(uv) = coedge.pcurve.evaluate(domain[0]) {
930 if let Ok(point) = face.surface.evaluate(uv.x, uv.y) {
931 if finite(point) {
932 return Some(point);
933 }
934 }
935 }
936 }
937 }
938 if let Ok((u_breaks, v_breaks)) = surface_breaks(&face.surface) {
939 let u = 0.5 * (u_breaks[0] + u_breaks[u_breaks.len() - 1]);
940 let v = 0.5 * (v_breaks[0] + v_breaks[v_breaks.len() - 1]);
941 if let Ok(point) = face.surface.evaluate(u, v) {
942 if finite(point) {
943 return Some(point);
944 }
945 }
946 }
947 for row in &face.surface.control_points {
948 for control in row {
949 if let Ok(point) = control.point() {
950 if finite(point) {
951 return Some(point);
952 }
953 }
954 }
955 }
956 None
957}
958
959pub fn shell_signed_volume(shell: &ShellRecord) -> Result<f64, String> {
963 let reference = shell_volume_reference(shell)?;
964
965 let mut volume = 0.0;
971 let mut compensation = 0.0;
972 let face_lines = super::profile::face_lines_enabled();
973 for (face_index, face) in shell.faces.iter().enumerate() {
974 mass_profile(|p| p.faces += 1);
975 let line_before = face_lines.then(super::profile::snapshot);
976 let line_started = face_lines.then(Instant::now);
977 let contribution = face_volume_contribution_about(face, reference)?;
978 emit_face_line(
979 "shell_signed_volume",
980 0,
981 face_index,
982 face,
983 line_before,
984 line_started,
985 );
986 let next = volume + contribution;
987 if volume.abs() >= contribution.abs() {
988 compensation += (volume - next) + contribution;
989 } else {
990 compensation += (contribution - next) + volume;
991 }
992 volume = next;
993 }
994 Ok(volume + compensation)
995}
996
997pub(super) fn affine_moment(face: &FaceRecord, kind: Integrand) -> Result<f64, String> {
1004 let ku = crate::KnotVector::new(face.surface.knots_u.clone(), face.surface.degree_u)?;
1005 let kv = crate::KnotVector::new(face.surface.knots_v.clone(), face.surface.degree_v)?;
1006 let [u0, u1] = ku.domain();
1007 let [v0, v1] = kv.domain();
1008 let points = &face.surface.control_points;
1009 let p00 = points[0][0].point()?;
1010 let p10 = points[1][0].point()?;
1011 let p01 = points[0][1].point()?;
1012 let du = p10.sub(p00).scale(1.0 / (u1 - u0));
1013 let dv = p01.sub(p00).scale(1.0 / (v1 - v0));
1014 let weighted_normal = du.cross(dv);
1015 let g = |u: f64, v: f64| {
1016 let point = p00.add(du.scale(u - u0)).add(dv.scale(v - v0));
1017 integrand_value(kind, point, weighted_normal)
1018 };
1019 let inner = |u: f64, v: f64| {
1020 let half = (u - u0) * 0.5;
1021 let middle = (u + u0) * 0.5;
1022 let mut sum = 0.0;
1023 for index in 0..GAUSS_X.len() {
1024 sum += GAUSS_W[index] * g(middle + half * GAUSS_X[index], v);
1025 }
1026 sum * half
1027 };
1028 let mut total = 0.0;
1029 for loop_record in &face.loops {
1030 for coedge in &loop_record.coedges {
1031 for pair in curve_breaks(&coedge.pcurve)?.windows(2) {
1032 for panel in rule::curve_panels(&coedge.pcurve, pair[0], pair[1])? {
1036 for (parameter, weight) in panel.stations() {
1037 let (point, tangent) = coedge.pcurve.deriv1(parameter)?;
1038 total += weight * inner(point.x, point.y) * tangent.y;
1039 }
1040 }
1041 }
1042 }
1043 }
1044 for (end, start) in loop_closing_chords(face)? {
1049 let step = start.y - end.y;
1050 if step == 0.0 {
1051 continue;
1052 }
1053 for index in 0..GAUSS_X.len() {
1054 let fraction = 0.5 * (GAUSS_X[index] + 1.0);
1055 let u = end.x + (start.x - end.x) * fraction;
1056 let v = end.y + step * fraction;
1057 total += 0.5 * GAUSS_W[index] * inner(u, v) * step;
1058 }
1059 }
1060 Ok(total)
1061}
1062
1063pub fn face_moment(face: &FaceRecord, kind: Integrand) -> Result<f64, String> {
1064 if is_affine(&face.surface)? {
1065 return affine_moment(face, kind);
1066 }
1067 if let Some(values) = biperiodic_band_integral(face, &[kind])? {
1068 return Ok(values[0]);
1069 }
1070 if is_untrimmed(face)? {
1071 integrate_untrimmed(face, kind)
1072 } else {
1073 integrate_trimmed(face, kind)
1074 }
1075}
1076
1077pub fn mat3_mul(a: [[f64; 3]; 3], b: [[f64; 3]; 3]) -> [[f64; 3]; 3] {
1080 let mut r = [[0.0f64; 3]; 3];
1081 for i in 0..3 {
1082 for j in 0..3 {
1083 for k in 0..3 {
1084 r[i][j] += a[i][k] * b[k][j];
1085 }
1086 }
1087 }
1088 r
1089}
1090
1091pub fn mat3_transpose(a: [[f64; 3]; 3]) -> [[f64; 3]; 3] {
1092 let mut r = [[0.0f64; 3]; 3];
1093 for i in 0..3 {
1094 for j in 0..3 {
1095 r[i][j] = a[j][i];
1096 }
1097 }
1098 r
1099}
1100
1101pub(super) fn jacobi_eigen_symmetric_3x3(matrix: [[f64; 3]; 3]) -> ([f64; 3], [[f64; 3]; 3]) {
1110 let mut a = [
1112 [matrix[0][0], 0.0, 0.0],
1113 [0.0, matrix[1][1], 0.0],
1114 [0.0, 0.0, matrix[2][2]],
1115 ];
1116 a[0][1] = 0.5 * (matrix[0][1] + matrix[1][0]);
1117 a[1][0] = a[0][1];
1118 a[0][2] = 0.5 * (matrix[0][2] + matrix[2][0]);
1119 a[2][0] = a[0][2];
1120 a[1][2] = 0.5 * (matrix[1][2] + matrix[2][1]);
1121 a[2][1] = a[1][2];
1122
1123 let mut v = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]];
1124 let scale = a[0][0].abs() + a[1][1].abs() + a[2][2].abs() + 1.0;
1125 for _sweep in 0..64 {
1126 let pairs = [(0usize, 1usize), (0, 2), (1, 2)];
1128 let (mut p, mut q, mut best) = (0usize, 1usize, 0.0f64);
1129 for &(i, j) in &pairs {
1130 if a[i][j].abs() > best {
1131 best = a[i][j].abs();
1132 p = i;
1133 q = j;
1134 }
1135 }
1136 if best <= 1e-18 * scale {
1137 break;
1138 }
1139 let theta = (a[q][q] - a[p][p]) / (2.0 * a[p][q]);
1142 let t = if theta == 0.0 {
1143 1.0
1144 } else {
1145 theta.signum() / (theta.abs() + (theta * theta + 1.0).sqrt())
1146 };
1147 let c = 1.0 / (t * t + 1.0).sqrt();
1148 let s = t * c;
1149 let mut j = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]];
1151 j[p][p] = c;
1152 j[q][q] = c;
1153 j[p][q] = s;
1154 j[q][p] = -s;
1155 a = mat3_mul(mat3_transpose(j), mat3_mul(a, j));
1157 v = mat3_mul(v, j);
1158 }
1159 ([a[0][0], a[1][1], a[2][2]], v)
1160}
1161
1162pub fn principal_frame(inertia: [[f64; 3]; 3]) -> ([f64; 3], [[f64; 3]; 3]) {
1168 let (values, vectors) = jacobi_eigen_symmetric_3x3(inertia);
1169 let mut order = [0usize, 1, 2];
1171 order.sort_by(|&a, &b| values[a].total_cmp(&values[b]));
1172 let mut moments = [0.0f64; 3];
1173 let mut axes = [[0.0f64; 3]; 3];
1174 for (slot, &k) in order.iter().enumerate() {
1175 moments[slot] = values[k];
1176 let mut axis = [vectors[0][k], vectors[1][k], vectors[2][k]];
1177 let length = (axis[0] * axis[0] + axis[1] * axis[1] + axis[2] * axis[2]).sqrt();
1178 if length > 0.0 {
1179 axis = [axis[0] / length, axis[1] / length, axis[2] / length];
1180 }
1181 axes[slot] = axis;
1182 }
1183 let cross = [
1185 axes[0][1] * axes[1][2] - axes[0][2] * axes[1][1],
1186 axes[0][2] * axes[1][0] - axes[0][0] * axes[1][2],
1187 axes[0][0] * axes[1][1] - axes[0][1] * axes[1][0],
1188 ];
1189 let det = cross[0] * axes[2][0] + cross[1] * axes[2][1] + cross[2] * axes[2][2];
1190 if det < 0.0 {
1191 axes[2] = [-axes[2][0], -axes[2][1], -axes[2][2]];
1192 }
1193 (moments, axes)
1194}
1195
1196pub fn solid_mass_properties_full(solid: &BrepSolid) -> Result<FullMassProperties, String> {
1201 let base = solid_mass_properties(solid)?;
1202 let token = super::profile::begin("solid_mass_properties_full.moments");
1203 let result = solid_mass_properties_full_moments(solid, base);
1204 super::profile::end(token);
1205 result
1206}
1207
1208pub fn moment_band_route_on() -> bool {
1218 crate::switch!("BREP_MASS_MOMENT_BAND_ROUTE", true)
1219}
1220
1221pub fn moment_local_frame_on() -> bool {
1230 crate::switch!("BREP_MASS_MOMENT_LOCAL_FRAME", true)
1231}
1232
1233fn solid_mass_properties_full_moments(
1234 solid: &BrepSolid,
1235 base: MassProperties,
1236) -> Result<FullMassProperties, String> {
1237 const MOMENT_KINDS: [Integrand; 9] = [
1238 Integrand::MomentX,
1239 Integrand::MomentY,
1240 Integrand::MomentZ,
1241 Integrand::SecondXX,
1242 Integrand::SecondYY,
1243 Integrand::SecondZZ,
1244 Integrand::ProductXY,
1245 Integrand::ProductXZ,
1246 Integrand::ProductYZ,
1247 ];
1248 let origin = if moment_local_frame_on() {
1252 solid.shells.iter().find(|shell| !shell.faces.is_empty()).map(shell_volume_reference).transpose()?
1253 } else {
1254 None
1255 };
1256 let local_kinds = origin.map(|r| {
1257 [
1258 Integrand::MomentAbout(0, r),
1259 Integrand::MomentAbout(1, r),
1260 Integrand::MomentAbout(2, r),
1261 Integrand::SecondAbout(0, r),
1262 Integrand::SecondAbout(1, r),
1263 Integrand::SecondAbout(2, r),
1264 Integrand::ProductAbout(0, r),
1265 Integrand::ProductAbout(1, r),
1266 Integrand::ProductAbout(2, r),
1267 ]
1268 });
1269 let kinds: &[Integrand; 9] = local_kinds.as_ref().unwrap_or(&MOMENT_KINDS);
1270 let mut moments = [0.0f64; 3];
1271 let mut seconds = [0.0f64; 3];
1272 let mut products = [0.0f64; 3];
1273 for shell in &solid.shells {
1274 for face in &shell.faces {
1275 mass_profile(|p| p.faces += 1);
1276 let band = if moment_band_route_on() {
1277 biperiodic_band_integral(face, kinds)?
1278 } else {
1279 None
1280 };
1281 let results = if let Some(values) = band {
1282 mass_profile(|p| p.route_biperiodic += 1);
1283 values
1284 } else if !is_affine(&face.surface)? && !is_untrimmed(face)? {
1285 mass_profile(|p| p.trimmed_faces += 1);
1286 integrate_trimmed_multi(face, kinds)?
1289 } else {
1290 kinds
1291 .iter()
1292 .map(|kind| face_moment(face, *kind))
1293 .collect::<Result<Vec<_>, _>>()?
1294 };
1295 moments[0] += results[0];
1296 moments[1] += results[1];
1297 moments[2] += results[2];
1298 seconds[0] += results[3];
1299 seconds[1] += results[4];
1300 seconds[2] += results[5];
1301 products[0] += results[6];
1302 products[1] += results[7];
1303 products[2] += results[8];
1304 }
1305 }
1306 let volume = base.volume;
1307 if volume.abs() <= 1e-30 {
1308 return Err("solid_mass_properties_full: non-positive volume".into());
1309 }
1310 let centroid = Vec3::new(
1313 moments[0] / volume,
1314 moments[1] / volume,
1315 moments[2] / volume,
1316 );
1317 let ixx =
1319 seconds[1] + seconds[2] - volume * (centroid.y * centroid.y + centroid.z * centroid.z);
1320 let iyy =
1321 seconds[0] + seconds[2] - volume * (centroid.x * centroid.x + centroid.z * centroid.z);
1322 let izz =
1323 seconds[0] + seconds[1] - volume * (centroid.x * centroid.x + centroid.y * centroid.y);
1324 let ixy = -(products[0] - volume * centroid.x * centroid.y);
1325 let ixz = -(products[1] - volume * centroid.x * centroid.z);
1326 let iyz = -(products[2] - volume * centroid.y * centroid.z);
1327 let inertia = [[ixx, ixy, ixz], [ixy, iyy, iyz], [ixz, iyz, izz]];
1328 let (principal_moments, principal_axes) = principal_frame(inertia);
1329 let centroid = origin.map_or(centroid, |r| r.add(centroid));
1330 Ok(FullMassProperties {
1331 surface_area: base.surface_area,
1332 volume,
1333 centroid,
1334 inertia,
1335 principal_moments,
1336 principal_axes,
1337 })
1338}
1339
1340