1use 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
102fn 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(super) 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
293fn sliver_bound_enabled() -> bool {
300 switch!(live "BREP_SIGN_SLIVER_BOUND", true)
301}
302
303
304pub(super) fn sliver_bound_certificate(solid: &BrepSolid, bar: f64) -> Option<f64> {
325 if !bar.is_finite() {
326 return None;
327 }
328 let token = super::profile::begin("solid_sign_sliver_bound");
329 let mut prefetched = SignPrefetch::spawn(solid);
332 let outcome = super::trimmed::with_straight_corrections_skipped(|| -> Option<(f64, f64, f64, f64, [usize; 3])> {
333 let (mut reading, mut magnitude, mut bound, mut scale) = (0.0, 0.0, 0.0, 0.0);
334 let mut counts = [0usize; 3]; let mut slot = 0usize;
336 for shell in &solid.shells {
337 let reference = shell_volume_reference(shell).ok()?;
338 let (mut volume, mut compensation) = (0.0f64, 0.0f64);
339 for face in &shell.faces {
340 let local = face_volume_reference(face).unwrap_or(reference);
341 let identity = super::identity::face_contribution_identity(face, local);
342 let offset = local.sub(reference);
343 let ready = prefetched.as_mut().and_then(|prefetched| prefetched.claim(slot));
344 slot += 1;
345 let (ready_bounded, ready_exact) = match ready {
346 Some((bounded, exact)) => (Some(bounded), exact),
347 None => (None, None),
348 };
349 let (terms, face_bound, face_scale) = match crate::reading_memo::peek_sign_terms(identity) {
350 Some(terms) => {
351 counts[0] += 1;
352 (terms?, 0.0, 0.0)
353 }
354 None => match crate::reading_memo::memoized_bounded_sign_terms(identity, || {
355 prefetched_or(ready_bounded, || bounded_face_terms(face, local))
356 }) {
357 Some((terms, per_offset, fixed, rounding)) => {
358 counts[1] += 1;
359 (terms, fixed + per_offset * offset.length(), rounding)
360 }
361 None => {
362 counts[2] += 1;
363 let terms = crate::reading_memo::memoized_sign_terms(identity, || {
364 prefetched_or(ready_exact, || face_volume_terms_about(face, local).ok())
365 })?;
366 (terms, 0.0, 0.0)
367 }
368 },
369 };
370 let area = Vec3::new(terms[1], terms[2], terms[3]);
371 let contribution = terms[0] + offset.dot(area);
372 magnitude += contribution.abs();
373 bound += face_bound;
374 scale += terms[0].abs() + offset.length() * area.length() + face_bound + face_scale * (1.0 + offset.length());
375 let next = volume + contribution;
376 if volume.abs() >= contribution.abs() {
377 compensation += (volume - next) + contribution;
378 } else {
379 compensation += (contribution - next) + volume;
380 }
381 volume = next;
382 }
383 reading += volume + compensation;
384 }
385 Some((reading, magnitude, bound, scale, counts))
386 });
387 super::profile::end(token);
388 if let Some(prefetched) = prefetched {
389 prefetched.report();
390 }
391 let (reading, magnitude, bound, scale, counts) = outcome?;
392 let slack = 1e-9 * scale;
397 let lower = reading - bound - slack;
398 let certified = [reading, magnitude, bound, scale, lower].iter().all(|v| v.is_finite())
399 && lower > bar
400 && lower - bar > SIGN_READING_MARGIN * (magnitude + bound + slack);
401 if crate::profile::profile_enabled() {
402 profile_line!(
403 "mass.sign_certificate kind=sliver_bound certified={certified} cells={reading:.9e} bound={bound:.3e} slack={slack:.3e} magnitude={magnitude:.3e} held={} bounded={} exact={}",
404 counts[0], counts[1], counts[2]
405 );
406 }
407 certified.then_some(lower)
408}
409
410const SIGN_PREFETCH_MIN_FACES: usize = 64;
424
425fn sign_prefetch_mode() -> crate::env_read::Mode {
426 #[cfg(not(test))]
427 {
428 crate::mode_switch!("BREP_SIGN_PREFETCH", false)
429 }
430}
431
432
433type BoundedTerms = Option<([f64; 4], f64, f64, f64)>;
434type SignReady = (BoundedTerms, Option<Option<[f64; 4]>>);
435
436struct SignJob {
437 face: FaceRecord,
438 local: Vec3,
439}
440
441fn sign_job(job: SignJob) -> SignReady {
442 super::trimmed::with_straight_corrections_skipped(|| {
443 let bounded = bounded_face_terms(&job.face, job.local);
444 let exact = bounded.is_none().then(|| face_volume_terms_about(&job.face, job.local).ok());
445 (bounded, exact)
446 })
447}
448
449#[derive(Clone, Copy, Default)]
450struct SignPrefetchTally {
451 check: bool,
452 hits: usize,
453 compared: usize,
454 disagree: usize,
455}
456
457thread_local! {
458 static SIGN_PREFETCH_TALLY: std::cell::Cell<Option<SignPrefetchTally>> = const { std::cell::Cell::new(None) };
460}
461
462struct SignPrefetch {
463 slots: crate::claim_slots::ClaimSlots<SignJob, SignReady>,
464 previous: Option<SignPrefetchTally>,
465}
466
467impl SignPrefetch {
468 fn spawn(solid: &BrepSolid) -> Option<Self> {
469 let mode = sign_prefetch_mode();
470 let faces: usize = solid.shells.iter().map(|shell| shell.faces.len()).sum();
471 if mode == crate::env_read::Mode::Off || faces < SIGN_PREFETCH_MIN_FACES {
472 return None;
473 }
474 let mut jobs = Vec::with_capacity(faces);
475 for shell in &solid.shells {
476 let reference = shell_volume_reference(shell).ok()?;
477 for face in &shell.faces {
478 let local = face_volume_reference(face).unwrap_or(reference);
479 jobs.push(SignJob { face: face.clone(), local });
480 }
481 }
482 let slots = crate::claim_slots::ClaimSlots::spawn(jobs, sign_job)?;
483 let tally = SignPrefetchTally { check: mode == crate::env_read::Mode::Check, ..Default::default() };
484 let previous = SIGN_PREFETCH_TALLY.with(|cell| cell.replace(Some(tally)));
485 Some(Self { slots, previous })
486 }
487
488 fn claim(&mut self, index: usize) -> Option<SignReady> {
489 self.slots.claim(index)
490 }
491
492 fn report(self) {
493 let tally = SIGN_PREFETCH_TALLY.with(|cell| cell.replace(self.previous)).unwrap_or_default();
494 if crate::profile::profile_enabled() {
495 profile_line!(
496 "mass.sign_prefetch faces={} check={} taken={} claimed={} hits={} compared={} disagree={}",
497 self.slots.len(),
498 u8::from(tally.check),
499 self.slots.taken,
500 self.slots.claimed,
501 tally.hits,
502 tally.compared,
503 tally.disagree
504 );
505 }
506 }
507}
508
509fn prefetched_or<T: std::fmt::Debug>(ready: Option<T>, compute: impl FnOnce() -> T) -> T {
513 let Some(value) = ready else {
514 return compute();
515 };
516 let check = SIGN_PREFETCH_TALLY.with(|cell| cell.get()).is_some_and(|tally| tally.check);
517 if !check {
518 SIGN_PREFETCH_TALLY.with(|cell| cell.set(cell.get().map(|mut tally| { tally.hits += 1; tally })));
519 return value;
520 }
521 let fresh = compute();
522 let agrees = format!("{fresh:?}") == format!("{value:?}");
523 SIGN_PREFETCH_TALLY.with(|cell| {
524 cell.set(cell.get().map(|mut tally| {
525 tally.compared += 1;
526 tally.disagree += usize::from(!agrees);
527 tally
528 }))
529 });
530 fresh
531}
532
533pub(super) fn bounded_face_terms(face: &FaceRecord, local: Vec3) -> Option<([f64; 4], f64, f64, f64)> {
540 let (terms, measure) = super::trimmed::with_sliver_measure(|| face_volume_terms_about(face, local));
541 let terms = terms.ok()?;
542 if measure.declined || !terms.iter().all(|v| v.is_finite()) {
543 return None;
544 }
545 if measure.measure == 0.0 {
546 return Some((terms, 0.0, 0.0, measure.complement / 3.0));
547 }
548 let (n, r) = surface_flux_bounds(&face.surface, local)?;
549 let per_offset = measure.measure * n / 3.0;
550 let fixed = per_offset * r;
551 [per_offset, fixed].iter().all(|v| v.is_finite()).then_some((terms, per_offset, fixed, measure.complement / 3.0))
552}
553
554pub(super) fn surface_flux_bounds(surface: &crate::NurbsSurface, center: Vec3) -> Option<(f64, f64)> {
566 let net = &surface.control_points;
567 let rows = net.len();
568 let columns = net.first()?.len();
569 if rows == 0 || columns == 0 || net.iter().any(|row| row.len() != columns) {
570 return None;
571 }
572 let relative = |i: usize, j: usize| -> Option<[f64; 4]> {
573 let q = net[i][j];
574 let values = [q.x - center.x * q.w, q.y - center.y * q.w, q.z - center.z * q.w, q.w];
575 (values.iter().all(|v| v.is_finite()) && q.w > 0.0).then_some(values)
576 };
577 let mut w_min = f64::INFINITY;
578 let mut r = 0.0f64;
579 for i in 0..rows {
580 for j in 0..columns {
581 let q = relative(i, j)?;
582 w_min = w_min.min(q[3]);
583 r = r.max((q[0] * q[0] + q[1] * q[1] + q[2] * q[2]).sqrt() / q[3]);
584 }
585 }
586 let derivative = |along_u: bool| -> Option<(f64, f64)> {
588 let (degree, knots, count) = if along_u {
589 (surface.degree_u, &surface.knots_u, rows)
590 } else {
591 (surface.degree_v, &surface.knots_v, columns)
592 };
593 if knots.len() < count + degree + 1 {
594 return None;
595 }
596 let (mut point, mut weight) = (0.0f64, 0.0f64);
597 if degree == 0 {
598 return Some((0.0, 0.0));
599 }
600 for k in 0..count.saturating_sub(1) {
601 let span = knots[k + degree + 1] - knots[k + 1];
602 if !(span > 0.0) {
603 continue;
604 }
605 let factor = degree as f64 / span;
606 let others = if along_u { columns } else { rows };
607 for other in 0..others {
608 let (a, b) = if along_u {
609 (relative(k, other)?, relative(k + 1, other)?)
610 } else {
611 (relative(other, k)?, relative(other, k + 1)?)
612 };
613 let d = [b[0] - a[0], b[1] - a[1], b[2] - a[2], b[3] - a[3]];
614 point = point.max(factor * (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt());
615 weight = weight.max(factor * d[3].abs());
616 }
617 }
618 Some((point, weight))
619 };
620 let (xu, wu) = derivative(true)?;
621 let (xv, wv) = derivative(false)?;
622 let su = (xu + wu * r) / w_min;
623 let sv = (xv + wv * r) / w_min;
624 let n = su * sv;
625 let (n, r) = (n * (1.0 + 1e-9), r * (1.0 + 1e-9));
627 (n.is_finite() && r.is_finite() && w_min.is_finite()).then_some((n, r))
628}
629
630fn solid_sign_terms_reading(solid: &BrepSolid) -> Result<(f64, f64), String> {
635 super::trimmed::with_straight_corrections_skipped(|| {
636 let (mut reading, mut magnitude) = (0.0, 0.0);
637 for (shell_index, shell) in solid.shells.iter().enumerate() {
638 let (volume, faces) = shell_volume_sign_reading(shell, shell_index)?;
639 reading += volume;
640 magnitude += faces;
641 }
642 Ok((reading, magnitude))
643 })
644}
645
646fn sign_terms_oracle_enabled() -> bool {
647 switch!(live "BREP_SIGN_TERMS_ORACLE", false)
648}
649
650fn verify_solid_sign_terms(solid: &BrepSolid) -> Result<(), String> {
653 let token = super::profile::begin("solid_sign_terms_oracle");
654 let reading = solid_sign_terms_reading(solid).map(|pair| pair.0);
655 super::profile::end(token);
656 check_sign_terms(solid, reading?)
657}
658
659pub(super) fn check_sign_terms(solid: &BrepSolid, reading: f64) -> Result<(), String> {
660 let exact = solid_signed_volume_uncached(solid)?;
661 let error = (reading - exact).abs();
662 let bar = 1e-9 * exact.abs();
663 if !reading.is_finite() || !exact.is_finite() || error > bar {
664 return Err(format!("sign terms oracle: retained {reading:.17e}, whole-body {exact:.17e}, error {error:.3e} exceeds {bar:.3e}"));
665 }
666 super::profile::emit_sign_oracle(solid, reading, exact)?;
667 Ok(())
668}
669
670fn shell_volume_sign_reading(shell: &ShellRecord, shell_index: usize) -> Result<(f64, f64), String> {
674 let reference = shell_volume_reference(shell)?;
675 if crate::profile::profile_enabled() {
676 profile_line!(
677 "mass.sign_reference faces={} reference=({:.9},{:.9},{:.9})",
678 shell.faces.len(), reference.x, reference.y, reference.z
679 );
680 }
681 let mut volume = 0.0;
682 let mut compensation = 0.0;
683 let mut magnitude = 0.0;
684 let face_lines = super::profile::face_lines_enabled();
685 for (face_index, face) in shell.faces.iter().enumerate() {
686 mass_profile(|p| p.faces += 1);
687 let line_before = face_lines.then(super::profile::snapshot);
688 let line_started = face_lines.then(Instant::now);
689 let local = face_volume_reference(face).unwrap_or(reference);
695 let hash_started = super::profile::profile_started();
696 let identity = super::identity::face_contribution_identity(face, local);
697 let hash_ms = super::profile::elapsed_ms(hash_started);
698 let mut reread = false;
699 let terms = match crate::reading_memo::memoized_sign_terms(identity, || {
700 reread = true;
701 face_volume_terms_about(face, local).ok()
702 }) {
703 Some(terms) => terms,
704 None => face_volume_terms_about(face, local)?,
705 };
706 let contribution = terms[0] + local.sub(reference).dot(Vec3::new(terms[1], terms[2], terms[3]));
707 super::profile::sign_face(shell_index, face, reread, hash_ms);
708 emit_face_line("shell_volume_sign_reading", shell_index, face_index, face, line_before, line_started);
709 magnitude += contribution.abs();
710 let next = volume + contribution;
711 if volume.abs() >= contribution.abs() {
712 compensation += (volume - next) + contribution;
713 } else {
714 compensation += (contribution - next) + volume;
715 }
716 volume = next;
717 }
718 Ok((volume + compensation, magnitude))
719}
720
721fn solid_signed_volume_uncached(solid: &BrepSolid) -> Result<f64, String> {
722 let mut volume = 0.0;
723 for shell in &solid.shells {
724 volume += shell_signed_volume(shell)?;
725 }
726 Ok(volume)
727}
728
729pub(super) fn shell_volume_reference(shell: &ShellRecord) -> Result<Vec3, String> {
730 shell.faces.iter().find_map(face_volume_reference)
731 .ok_or_else(|| "mass_properties: shell has no finite geometric reference".to_string())
732}
733
734pub(super) fn face_volume_reference(face: &FaceRecord) -> Option<Vec3> {
736 let finite = |point: Vec3| point.x.is_finite() && point.y.is_finite() && point.z.is_finite();
737 if let Some(coedge) = face
738 .loops
739 .first()
740 .and_then(|loop_record| loop_record.coedges.first())
741 {
742 if let Ok(domain) = coedge.pcurve.domain() {
743 if let Ok(uv) = coedge.pcurve.evaluate(domain[0]) {
744 if let Ok(point) = face.surface.evaluate(uv.x, uv.y) {
745 if finite(point) {
746 return Some(point);
747 }
748 }
749 }
750 }
751 }
752 if let Ok((u_breaks, v_breaks)) = surface_breaks(&face.surface) {
753 let u = 0.5 * (u_breaks[0] + u_breaks[u_breaks.len() - 1]);
754 let v = 0.5 * (v_breaks[0] + v_breaks[v_breaks.len() - 1]);
755 if let Ok(point) = face.surface.evaluate(u, v) {
756 if finite(point) {
757 return Some(point);
758 }
759 }
760 }
761 for row in &face.surface.control_points {
762 for control in row {
763 if let Ok(point) = control.point() {
764 if finite(point) {
765 return Some(point);
766 }
767 }
768 }
769 }
770 None
771}
772
773pub(crate) fn shell_signed_volume(shell: &ShellRecord) -> Result<f64, String> {
777 let reference = shell_volume_reference(shell)?;
778
779 let mut volume = 0.0;
785 let mut compensation = 0.0;
786 let face_lines = super::profile::face_lines_enabled();
787 for (face_index, face) in shell.faces.iter().enumerate() {
788 mass_profile(|p| p.faces += 1);
789 let line_before = face_lines.then(super::profile::snapshot);
790 let line_started = face_lines.then(Instant::now);
791 let contribution = face_volume_contribution_about(face, reference)?;
792 emit_face_line(
793 "shell_signed_volume",
794 0,
795 face_index,
796 face,
797 line_before,
798 line_started,
799 );
800 let next = volume + contribution;
801 if volume.abs() >= contribution.abs() {
802 compensation += (volume - next) + contribution;
803 } else {
804 compensation += (contribution - next) + volume;
805 }
806 volume = next;
807 }
808 Ok(volume + compensation)
809}
810
811pub(super) fn affine_moment(face: &FaceRecord, kind: Integrand) -> Result<f64, String> {
818 let ku = crate::KnotVector::new(face.surface.knots_u.clone(), face.surface.degree_u)?;
819 let kv = crate::KnotVector::new(face.surface.knots_v.clone(), face.surface.degree_v)?;
820 let [u0, u1] = ku.domain();
821 let [v0, v1] = kv.domain();
822 let points = &face.surface.control_points;
823 let p00 = points[0][0].point()?;
824 let p10 = points[1][0].point()?;
825 let p01 = points[0][1].point()?;
826 let du = p10.sub(p00).scale(1.0 / (u1 - u0));
827 let dv = p01.sub(p00).scale(1.0 / (v1 - v0));
828 let weighted_normal = du.cross(dv);
829 let g = |u: f64, v: f64| {
830 let point = p00.add(du.scale(u - u0)).add(dv.scale(v - v0));
831 integrand_value(kind, point, weighted_normal)
832 };
833 let inner = |u: f64, v: f64| {
834 let half = (u - u0) * 0.5;
835 let middle = (u + u0) * 0.5;
836 let mut sum = 0.0;
837 for index in 0..GAUSS_X.len() {
838 sum += GAUSS_W[index] * g(middle + half * GAUSS_X[index], v);
839 }
840 sum * half
841 };
842 let mut total = 0.0;
843 for loop_record in &face.loops {
844 for coedge in &loop_record.coedges {
845 for pair in curve_breaks(&coedge.pcurve)?.windows(2) {
846 for panel in rule::curve_panels(&coedge.pcurve, pair[0], pair[1])? {
850 for (parameter, weight) in panel.stations() {
851 let (point, tangent) = coedge.pcurve.deriv1(parameter)?;
852 total += weight * inner(point.x, point.y) * tangent.y;
853 }
854 }
855 }
856 }
857 }
858 for (end, start) in loop_closing_chords(face)? {
863 let step = start.y - end.y;
864 if step == 0.0 {
865 continue;
866 }
867 for index in 0..GAUSS_X.len() {
868 let fraction = 0.5 * (GAUSS_X[index] + 1.0);
869 let u = end.x + (start.x - end.x) * fraction;
870 let v = end.y + step * fraction;
871 total += 0.5 * GAUSS_W[index] * inner(u, v) * step;
872 }
873 }
874 Ok(total)
875}
876
877pub(super) fn face_moment(face: &FaceRecord, kind: Integrand) -> Result<f64, String> {
878 if is_affine(&face.surface)? {
879 return affine_moment(face, kind);
880 }
881 if let Some(values) = biperiodic_band_integral(face, &[kind])? {
882 return Ok(values[0]);
883 }
884 if is_untrimmed(face)? {
885 integrate_untrimmed(face, kind)
886 } else {
887 integrate_trimmed(face, kind)
888 }
889}
890
891pub(super) fn mat3_mul(a: [[f64; 3]; 3], b: [[f64; 3]; 3]) -> [[f64; 3]; 3] {
894 let mut r = [[0.0f64; 3]; 3];
895 for i in 0..3 {
896 for j in 0..3 {
897 for k in 0..3 {
898 r[i][j] += a[i][k] * b[k][j];
899 }
900 }
901 }
902 r
903}
904
905pub(super) fn mat3_transpose(a: [[f64; 3]; 3]) -> [[f64; 3]; 3] {
906 let mut r = [[0.0f64; 3]; 3];
907 for i in 0..3 {
908 for j in 0..3 {
909 r[i][j] = a[j][i];
910 }
911 }
912 r
913}
914
915pub(super) fn jacobi_eigen_symmetric_3x3(matrix: [[f64; 3]; 3]) -> ([f64; 3], [[f64; 3]; 3]) {
924 let mut a = [
926 [matrix[0][0], 0.0, 0.0],
927 [0.0, matrix[1][1], 0.0],
928 [0.0, 0.0, matrix[2][2]],
929 ];
930 a[0][1] = 0.5 * (matrix[0][1] + matrix[1][0]);
931 a[1][0] = a[0][1];
932 a[0][2] = 0.5 * (matrix[0][2] + matrix[2][0]);
933 a[2][0] = a[0][2];
934 a[1][2] = 0.5 * (matrix[1][2] + matrix[2][1]);
935 a[2][1] = a[1][2];
936
937 let mut v = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]];
938 let scale = a[0][0].abs() + a[1][1].abs() + a[2][2].abs() + 1.0;
939 for _sweep in 0..64 {
940 let pairs = [(0usize, 1usize), (0, 2), (1, 2)];
942 let (mut p, mut q, mut best) = (0usize, 1usize, 0.0f64);
943 for &(i, j) in &pairs {
944 if a[i][j].abs() > best {
945 best = a[i][j].abs();
946 p = i;
947 q = j;
948 }
949 }
950 if best <= 1e-18 * scale {
951 break;
952 }
953 let theta = (a[q][q] - a[p][p]) / (2.0 * a[p][q]);
956 let t = if theta == 0.0 {
957 1.0
958 } else {
959 theta.signum() / (theta.abs() + (theta * theta + 1.0).sqrt())
960 };
961 let c = 1.0 / (t * t + 1.0).sqrt();
962 let s = t * c;
963 let mut j = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]];
965 j[p][p] = c;
966 j[q][q] = c;
967 j[p][q] = s;
968 j[q][p] = -s;
969 a = mat3_mul(mat3_transpose(j), mat3_mul(a, j));
971 v = mat3_mul(v, j);
972 }
973 ([a[0][0], a[1][1], a[2][2]], v)
974}
975
976pub(super) fn principal_frame(inertia: [[f64; 3]; 3]) -> ([f64; 3], [[f64; 3]; 3]) {
982 let (values, vectors) = jacobi_eigen_symmetric_3x3(inertia);
983 let mut order = [0usize, 1, 2];
985 order.sort_by(|&a, &b| values[a].total_cmp(&values[b]));
986 let mut moments = [0.0f64; 3];
987 let mut axes = [[0.0f64; 3]; 3];
988 for (slot, &k) in order.iter().enumerate() {
989 moments[slot] = values[k];
990 let mut axis = [vectors[0][k], vectors[1][k], vectors[2][k]];
991 let length = (axis[0] * axis[0] + axis[1] * axis[1] + axis[2] * axis[2]).sqrt();
992 if length > 0.0 {
993 axis = [axis[0] / length, axis[1] / length, axis[2] / length];
994 }
995 axes[slot] = axis;
996 }
997 let cross = [
999 axes[0][1] * axes[1][2] - axes[0][2] * axes[1][1],
1000 axes[0][2] * axes[1][0] - axes[0][0] * axes[1][2],
1001 axes[0][0] * axes[1][1] - axes[0][1] * axes[1][0],
1002 ];
1003 let det = cross[0] * axes[2][0] + cross[1] * axes[2][1] + cross[2] * axes[2][2];
1004 if det < 0.0 {
1005 axes[2] = [-axes[2][0], -axes[2][1], -axes[2][2]];
1006 }
1007 (moments, axes)
1008}
1009
1010pub fn solid_mass_properties_full(solid: &BrepSolid) -> Result<FullMassProperties, String> {
1015 let base = solid_mass_properties(solid)?;
1016 let token = super::profile::begin("solid_mass_properties_full.moments");
1017 let result = solid_mass_properties_full_moments(solid, base);
1018 super::profile::end(token);
1019 result
1020}
1021
1022fn solid_mass_properties_full_moments(
1023 solid: &BrepSolid,
1024 base: MassProperties,
1025) -> Result<FullMassProperties, String> {
1026 const MOMENT_KINDS: [Integrand; 9] = [
1027 Integrand::MomentX,
1028 Integrand::MomentY,
1029 Integrand::MomentZ,
1030 Integrand::SecondXX,
1031 Integrand::SecondYY,
1032 Integrand::SecondZZ,
1033 Integrand::ProductXY,
1034 Integrand::ProductXZ,
1035 Integrand::ProductYZ,
1036 ];
1037 let mut moments = [0.0f64; 3];
1038 let mut seconds = [0.0f64; 3];
1039 let mut products = [0.0f64; 3];
1040 for shell in &solid.shells {
1041 for face in &shell.faces {
1042 mass_profile(|p| p.faces += 1);
1043 let results = if !is_affine(&face.surface)? && !is_untrimmed(face)? {
1044 mass_profile(|p| p.trimmed_faces += 1);
1045 integrate_trimmed_multi(face, &MOMENT_KINDS)?
1048 } else {
1049 MOMENT_KINDS
1050 .iter()
1051 .map(|kind| face_moment(face, *kind))
1052 .collect::<Result<Vec<_>, _>>()?
1053 };
1054 moments[0] += results[0];
1055 moments[1] += results[1];
1056 moments[2] += results[2];
1057 seconds[0] += results[3];
1058 seconds[1] += results[4];
1059 seconds[2] += results[5];
1060 products[0] += results[6];
1061 products[1] += results[7];
1062 products[2] += results[8];
1063 }
1064 }
1065 let volume = base.volume;
1066 if volume.abs() <= 1e-30 {
1067 return Err("solid_mass_properties_full: non-positive volume".into());
1068 }
1069 let centroid = Vec3::new(
1070 moments[0] / volume,
1071 moments[1] / volume,
1072 moments[2] / volume,
1073 );
1074 let ixx =
1076 seconds[1] + seconds[2] - volume * (centroid.y * centroid.y + centroid.z * centroid.z);
1077 let iyy =
1078 seconds[0] + seconds[2] - volume * (centroid.x * centroid.x + centroid.z * centroid.z);
1079 let izz =
1080 seconds[0] + seconds[1] - volume * (centroid.x * centroid.x + centroid.y * centroid.y);
1081 let ixy = -(products[0] - volume * centroid.x * centroid.y);
1082 let ixz = -(products[1] - volume * centroid.x * centroid.z);
1083 let iyz = -(products[2] - volume * centroid.y * centroid.z);
1084 let inertia = [[ixx, ixy, ixz], [ixy, iyy, iyz], [ixz, iyz, izz]];
1085 let (principal_moments, principal_axes) = principal_frame(inertia);
1086 Ok(FullMassProperties {
1087 surface_area: base.surface_area,
1088 volume,
1089 centroid,
1090 inertia,
1091 principal_moments,
1092 principal_axes,
1093 })
1094}
1095
1096