Skip to main content

brep_kernel/props/mass_properties/
solid_props.rs

1use super::*;
2use super::mass_profile;
3use web_time::Instant;
4
5/// The static facts a `mass.face` line carries beside the route: the
6/// recognized carrier kind, the patch degrees and closed directions, and the
7/// trim's size. Read only when `BREP_PROFILE_MASS_FACES` armed the lines.
8fn face_line_meta(face: &FaceRecord) -> (&'static str, usize, usize, bool, bool, usize, usize) {
9    // `kind_label` spells the general carrier with spaces; the profile line is
10    // whitespace-tokenized, so collapse it to one word.
11    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
33/// Emit one `mass.face` line for the face just integrated. `before` is the
34/// counter snapshot taken ahead of its work and `started` the wall clock at
35/// the same point; both are `None` unless the lines are armed.
36fn 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 let (Some(dump), Ok(properties)) = (super::profile::identity_dump(), result.as_ref()) {
60        super::profile::emit_identity(
61            dump,
62            "solid_mass_properties",
63            solid,
64            &[
65                ("volume_bits", properties.volume),
66                ("area_bits", properties.surface_area),
67            ],
68        );
69    }
70    result
71}
72
73/// Validate the memo against the current geometry on EVERY read: topology
74/// records are publicly editable, and copies may have been transformed or healed.
75fn solid_mass_properties_cached(solid: &BrepSolid) -> Result<MassProperties, String> {
76    let identity = face_set_identity(solid);
77    if let Some((cached_identity, properties)) = solid.mass_properties_cache.entry.get() {
78        if cached_identity == identity {
79            if super::profile::mass_profile_enabled() {
80                let measured = solid_mass_properties_inner(solid)?;
81                assert_eq!(properties.volume.to_bits(), measured.volume.to_bits(),
82                    "mass cache changed volume");
83                assert_eq!(properties.surface_area.to_bits(), measured.surface_area.to_bits(),
84                    "mass cache changed area");
85                eprintln!("mass.cache hit faces={} verified=true", identity.faces);
86            }
87            return Ok(properties);
88        }
89    }
90    // Never retain a failed computation, nor an old entry for modified geometry.
91    solid.mass_properties_cache.entry.set(None);
92    let properties = solid_mass_properties_inner(solid)?;
93    solid.mass_properties_cache.entry.set(Some((identity, properties)));
94    Ok(properties)
95}
96
97fn solid_mass_properties_inner(solid: &BrepSolid) -> Result<MassProperties, String> {
98    let mut properties = MassProperties {
99        surface_area: 0.0,
100        volume: 0.0,
101    };
102    let mut volume_compensation = 0.0;
103    let face_lines = super::profile::face_lines_enabled();
104    for (shell_index, shell) in solid.shells.iter().enumerate() {
105        if shell.faces.is_empty() {
106            continue;
107        }
108        // Use the same local reference as the signed-volume orientation gate.
109        // World-origin flux terms can dwarf a small translated solid's volume;
110        // even tiny quadrature or boundary errors then dominate their sum.
111        let reference = shell_volume_reference(shell)?;
112        let kinds = [Integrand::Area, Integrand::VolumeAbout(reference)];
113        for (face_index, face) in shell.faces.iter().enumerate() {
114            mass_profile(|p| p.faces += 1);
115            let line_before = face_lines.then(super::profile::snapshot);
116            let line_started = face_lines.then(Instant::now);
117            let gate_started = super::profile::profile_started();
118            let (area, volume) = if let Some(values) = biperiodic_band_integral(face, &kinds)? {
119                mass_profile(|p| {
120                    p.route_biperiodic += 1;
121                    p.gate_ms += super::profile::elapsed_ms(gate_started);
122                });
123                (values[0], values[1] / 3.0)
124            } else if !is_affine(&face.surface)? && !is_untrimmed(face)? {
125                mass_profile(|p| {
126                    p.trimmed_faces += 1;
127                    p.gate_ms += super::profile::elapsed_ms(gate_started);
128                });
129                // Preserve the shared cell decomposition and integration pass.
130                let values = integrate_trimmed_multi(face, &kinds)?;
131                (values[0], values[1] / 3.0)
132            } else if is_affine(&face.surface)? {
133                mass_profile(|p| {
134                    p.route_affine += 1;
135                    p.gate_ms += super::profile::elapsed_ms(gate_started);
136                });
137                // One parameter-space area and one planar metric for both
138                // numbers, instead of `face_area` and
139                // `face_volume_contribution_about` each walking the trim.
140                affine_area_and_volume_about(face, reference)?
141            } else {
142                mass_profile(|p| {
143                    p.route_untrimmed += 1;
144                    p.gate_ms += super::profile::elapsed_ms(gate_started);
145                });
146                // One station sweep carrying both integrands, instead of one
147                // sweep per integrand.
148                let started = super::profile::profile_started();
149                let values = integrate_untrimmed_multi(face, &kinds)?;
150                mass_profile(|p| p.untrimmed_ms += super::profile::elapsed_ms(started));
151                (values[0], values[1] / 3.0)
152            };
153            emit_face_line(
154                "solid_mass_properties",
155                shell_index,
156                face_index,
157                face,
158                line_before,
159                line_started,
160            );
161            properties.surface_area += area;
162            let next = properties.volume + volume;
163            if properties.volume.abs() >= volume.abs() {
164                volume_compensation += (properties.volume - next) + volume;
165            } else {
166                volume_compensation += (volume - next) + properties.volume;
167            }
168            properties.volume = next;
169        }
170    }
171    properties.volume += volume_compensation;
172    Ok(properties)
173}
174
175/// Exact signed volume. A single nonempty shell shares its area/volume
176/// measurement with subsequent property queries. Multiple shells retain the
177/// original per-shell compensated sum: substituting the across-face sum can
178/// change the last bits and an orientation gate must not change its answer.
179pub fn solid_signed_volume(solid: &BrepSolid) -> Result<f64, String> {
180    let token = super::profile::begin("solid_signed_volume");
181    let result = if solid.shells.len() == 1 && !solid.shells[0].faces.is_empty() {
182        match solid_mass_properties_cached(solid) {
183            Ok(properties) => {
184                if super::profile::mass_profile_enabled() {
185                    let original = solid_signed_volume_uncached(solid)
186                        .expect("shared mass measurement changed a signed-volume refusal");
187                    assert_eq!(properties.volume.to_bits(), original.to_bits(),
188                        "shared mass measurement changed signed volume");
189                }
190                Ok(properties.volume)
191            }
192            // Area computation must not introduce a new signed-volume refusal.
193            Err(_) => solid_signed_volume_uncached(solid),
194        }
195    } else {
196        solid_signed_volume_uncached(solid)
197    };
198    super::profile::end(token);
199    if let (Some(dump), Ok(volume)) = (super::profile::identity_dump(), result.as_ref()) {
200        super::profile::emit_identity(dump, "solid_signed_volume", solid, &[("signed_bits", *volume)]);
201    }
202    result
203}
204
205fn solid_signed_volume_uncached(solid: &BrepSolid) -> Result<f64, String> {
206    let mut volume = 0.0;
207    for shell in &solid.shells {
208        volume += shell_signed_volume(shell)?;
209    }
210    Ok(volume)
211}
212
213pub(super) fn shell_volume_reference(shell: &ShellRecord) -> Result<Vec3, String> {
214    let finite = |point: Vec3| point.x.is_finite() && point.y.is_finite() && point.z.is_finite();
215    for face in &shell.faces {
216        if let Some(coedge) = face
217            .loops
218            .first()
219            .and_then(|loop_record| loop_record.coedges.first())
220        {
221            if let Ok(domain) = coedge.pcurve.domain() {
222                if let Ok(uv) = coedge.pcurve.evaluate(domain[0]) {
223                    if let Ok(point) = face.surface.evaluate(uv.x, uv.y) {
224                        if finite(point) {
225                            return Ok(point);
226                        }
227                    }
228                }
229            }
230        }
231        if let Ok((u_breaks, v_breaks)) = surface_breaks(&face.surface) {
232            let u = 0.5 * (u_breaks[0] + u_breaks[u_breaks.len() - 1]);
233            let v = 0.5 * (v_breaks[0] + v_breaks[v_breaks.len() - 1]);
234            if let Ok(point) = face.surface.evaluate(u, v) {
235                if finite(point) {
236                    return Ok(point);
237                }
238            }
239        }
240        for row in &face.surface.control_points {
241            for control in row {
242                if let Ok(point) = control.point() {
243                    if finite(point) {
244                        return Ok(point);
245                    }
246                }
247            }
248        }
249    }
250    Err("mass_properties: shell has no finite geometric reference".to_string())
251}
252
253/// Exact signed volume of one closed shell. Multi-shell tessellation uses this
254/// to preserve the authored material orientation: exterior shells contribute
255/// positively, while a void boundary contributes negatively.
256pub(crate) fn shell_signed_volume(shell: &ShellRecord) -> Result<f64, String> {
257    let reference = shell_volume_reference(shell)?;
258
259    // A closed shell's divergence-theorem volume is independent of origin,
260    // but evaluating each face about the world origin can cancel enormous
261    // translated face terms down to a tiny cavity volume. Anchor the
262    // integrand on an authored boundary point and compensate the remaining
263    // face sum so the sign is stable for small, far-translated shells.
264    let mut volume = 0.0;
265    let mut compensation = 0.0;
266    let face_lines = super::profile::face_lines_enabled();
267    for (face_index, face) in shell.faces.iter().enumerate() {
268        mass_profile(|p| p.faces += 1);
269        let line_before = face_lines.then(super::profile::snapshot);
270        let line_started = face_lines.then(Instant::now);
271        let contribution = face_volume_contribution_about(face, reference)?;
272        emit_face_line(
273            "shell_signed_volume",
274            0,
275            face_index,
276            face,
277            line_before,
278            line_started,
279        );
280        let next = volume + contribution;
281        if volume.abs() >= contribution.abs() {
282            compensation += (volume - next) + contribution;
283        } else {
284            compensation += (contribution - next) + volume;
285        }
286        volume = next;
287    }
288    Ok(volume + compensation)
289}
290
291/// Exact moments for affine faces via Green's theorem over the trim
292/// pcurves: ∬ g du dv = ∮ G dv with G(u,v) = ∫ g dt.  On an affine carrier
293/// every moment integrand is a low-degree polynomial, so the inner Gauss
294/// antiderivative is exact and the boundary quadrature has the same quality
295/// as `parameter_space_area` — no trim-polygon sampling error.  The loop
296/// winding supplies the orientation sign, matching the affine volume path.
297pub(super) fn affine_moment(face: &FaceRecord, kind: Integrand) -> Result<f64, String> {
298    let ku = crate::KnotVector::new(face.surface.knots_u.clone(), face.surface.degree_u)?;
299    let kv = crate::KnotVector::new(face.surface.knots_v.clone(), face.surface.degree_v)?;
300    let [u0, u1] = ku.domain();
301    let [v0, v1] = kv.domain();
302    let points = &face.surface.control_points;
303    let p00 = points[0][0].point()?;
304    let p10 = points[1][0].point()?;
305    let p01 = points[0][1].point()?;
306    let du = p10.sub(p00).scale(1.0 / (u1 - u0));
307    let dv = p01.sub(p00).scale(1.0 / (v1 - v0));
308    let weighted_normal = du.cross(dv);
309    let g = |u: f64, v: f64| {
310        let point = p00.add(du.scale(u - u0)).add(dv.scale(v - v0));
311        integrand_value(kind, point, weighted_normal)
312    };
313    let inner = |u: f64, v: f64| {
314        let half = (u - u0) * 0.5;
315        let middle = (u + u0) * 0.5;
316        let mut sum = 0.0;
317        for index in 0..GAUSS_X.len() {
318            sum += GAUSS_W[index] * g(middle + half * GAUSS_X[index], v);
319        }
320        sum * half
321    };
322    let mut total = 0.0;
323    for loop_record in &face.loops {
324        for coedge in &loop_record.coedges {
325            for pair in curve_breaks(&coedge.pcurve)?.windows(2) {
326                // The inner antiderivative is a polynomial in u on an affine
327                // carrier and is exact at any order; the boundary walk is the
328                // pcurve's own, so it takes the pcurve's panels (`rule`).
329                for panel in rule::curve_panels(&coedge.pcurve, pair[0], pair[1])? {
330                    for (parameter, weight) in panel.stations() {
331                        let (point, tangent) = coedge.pcurve.deriv1(parameter)?;
332                        total += weight * inner(point.x, point.y) * tangent.y;
333                    }
334                }
335            }
336        }
337    }
338    // The loops closed as the area closes them (`closed_parameter_space_area`):
339    // an open boundary integral moves with the uv origin. Along a straight
340    // chord the integrand is a polynomial of degree at most four, which the
341    // eight-station rule integrates exactly.
342    for (end, start) in loop_closing_chords(face)? {
343        let step = start.y - end.y;
344        if step == 0.0 {
345            continue;
346        }
347        for index in 0..GAUSS_X.len() {
348            let fraction = 0.5 * (GAUSS_X[index] + 1.0);
349            let u = end.x + (start.x - end.x) * fraction;
350            let v = end.y + step * fraction;
351            total += 0.5 * GAUSS_W[index] * inner(u, v) * step;
352        }
353    }
354    Ok(total)
355}
356
357pub(super) fn face_moment(face: &FaceRecord, kind: Integrand) -> Result<f64, String> {
358    if is_affine(&face.surface)? {
359        return affine_moment(face, kind);
360    }
361    if let Some(values) = biperiodic_band_integral(face, &[kind])? {
362        return Ok(values[0]);
363    }
364    if is_untrimmed(face)? {
365        integrate_untrimmed(face, kind)
366    } else {
367        integrate_trimmed(face, kind)
368    }
369}
370
371/// Symmetric-matrix product `A[i][j] = M[k][i] * M[k][j]` reused by the Jacobi
372/// sweep — kept tiny and explicit rather than pulling in a matrix crate.
373pub(super) fn mat3_mul(a: [[f64; 3]; 3], b: [[f64; 3]; 3]) -> [[f64; 3]; 3] {
374    let mut r = [[0.0f64; 3]; 3];
375    for i in 0..3 {
376        for j in 0..3 {
377            for k in 0..3 {
378                r[i][j] += a[i][k] * b[k][j];
379            }
380        }
381    }
382    r
383}
384
385pub(super) fn mat3_transpose(a: [[f64; 3]; 3]) -> [[f64; 3]; 3] {
386    let mut r = [[0.0f64; 3]; 3];
387    for i in 0..3 {
388        for j in 0..3 {
389            r[i][j] = a[j][i];
390        }
391    }
392    r
393}
394
395/// Classic Jacobi eigenvalue iteration for a SYMMETRIC 3×3 matrix. Repeatedly
396/// applies a Givens rotation in the plane of the largest off-diagonal element,
397/// each rotation zeroing that element, until the matrix is diagonal to machine
398/// precision. Returns `(eigenvalues, vectors)` where `vectors` holds the
399/// eigenvectors as COLUMNS (`vectors[i][k]` is component `i` of eigenvector
400/// `k`), unsorted. For a symmetric matrix Jacobi is unconditionally
401/// convergent and the accumulated rotations stay orthonormal, so the columns
402/// are mutually orthonormal by construction.
403pub(super) fn jacobi_eigen_symmetric_3x3(matrix: [[f64; 3]; 3]) -> ([f64; 3], [[f64; 3]; 3]) {
404    // Symmetrize defensively against tiny asymmetry from round-off upstream.
405    let mut a = [
406        [matrix[0][0], 0.0, 0.0],
407        [0.0, matrix[1][1], 0.0],
408        [0.0, 0.0, matrix[2][2]],
409    ];
410    a[0][1] = 0.5 * (matrix[0][1] + matrix[1][0]);
411    a[1][0] = a[0][1];
412    a[0][2] = 0.5 * (matrix[0][2] + matrix[2][0]);
413    a[2][0] = a[0][2];
414    a[1][2] = 0.5 * (matrix[1][2] + matrix[2][1]);
415    a[2][1] = a[1][2];
416
417    let mut v = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]];
418    let scale = a[0][0].abs() + a[1][1].abs() + a[2][2].abs() + 1.0;
419    for _sweep in 0..64 {
420        // Pick the largest off-diagonal magnitude.
421        let pairs = [(0usize, 1usize), (0, 2), (1, 2)];
422        let (mut p, mut q, mut best) = (0usize, 1usize, 0.0f64);
423        for &(i, j) in &pairs {
424            if a[i][j].abs() > best {
425                best = a[i][j].abs();
426                p = i;
427                q = j;
428            }
429        }
430        if best <= 1e-18 * scale {
431            break;
432        }
433        // Angle that zeroes a[p][q]: t = tan(theta) is the smaller root of
434        // t² + 2·theta·t − 1 = 0 with theta = (a_qq − a_pp)/(2 a_pq).
435        let theta = (a[q][q] - a[p][p]) / (2.0 * a[p][q]);
436        let t = if theta == 0.0 {
437            1.0
438        } else {
439            theta.signum() / (theta.abs() + (theta * theta + 1.0).sqrt())
440        };
441        let c = 1.0 / (t * t + 1.0).sqrt();
442        let s = t * c;
443        // Givens rotation J: J[p][p]=J[q][q]=c, J[p][q]=s, J[q][p]=−s.
444        let mut j = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]];
445        j[p][p] = c;
446        j[q][q] = c;
447        j[p][q] = s;
448        j[q][p] = -s;
449        // A ← Jᵀ A J   (drives a[p][q] to zero), V ← V J.
450        a = mat3_mul(mat3_transpose(j), mat3_mul(a, j));
451        v = mat3_mul(v, j);
452    }
453    ([a[0][0], a[1][1], a[2][2]], v)
454}
455
456/// Principal axes/moments from a centroidal inertia tensor (Golovanov §8.11).
457/// Diagonalizes the symmetric tensor, sorts the eigenpairs by moment
458/// ASCENDING, returns each eigenvector as a ROW (`axes[i]` pairs with
459/// `moments[i]`) normalized to unit length, and fixes the sign of the third
460/// axis so the frame is right-handed (determinant +1).
461pub(super) fn principal_frame(inertia: [[f64; 3]; 3]) -> ([f64; 3], [[f64; 3]; 3]) {
462    let (values, vectors) = jacobi_eigen_symmetric_3x3(inertia);
463    // Column k of `vectors` is the eigenvector for `values[k]`.
464    let mut order = [0usize, 1, 2];
465    order.sort_by(|&a, &b| values[a].total_cmp(&values[b]));
466    let mut moments = [0.0f64; 3];
467    let mut axes = [[0.0f64; 3]; 3];
468    for (slot, &k) in order.iter().enumerate() {
469        moments[slot] = values[k];
470        let mut axis = [vectors[0][k], vectors[1][k], vectors[2][k]];
471        let length = (axis[0] * axis[0] + axis[1] * axis[1] + axis[2] * axis[2]).sqrt();
472        if length > 0.0 {
473            axis = [axis[0] / length, axis[1] / length, axis[2] / length];
474        }
475        axes[slot] = axis;
476    }
477    // Right-hand the frame: if axis0 × axis1 points opposite axis2, flip axis2.
478    let cross = [
479        axes[0][1] * axes[1][2] - axes[0][2] * axes[1][1],
480        axes[0][2] * axes[1][0] - axes[0][0] * axes[1][2],
481        axes[0][0] * axes[1][1] - axes[0][1] * axes[1][0],
482    ];
483    let det = cross[0] * axes[2][0] + cross[1] * axes[2][1] + cross[2] * axes[2][2];
484    if det < 0.0 {
485        axes[2] = [-axes[2][0], -axes[2][1], -axes[2][2]];
486    }
487    (moments, axes)
488}
489
490/// Area, volume, centroid, and centroidal inertia (unit density).  Area and
491/// volume use the same exact paths as `solid_mass_properties`; the moment
492/// integrals use divergence-theorem surface quadrature (exact for untrimmed
493/// spans, trim-polygon scanline accuracy for trimmed faces).
494pub fn solid_mass_properties_full(solid: &BrepSolid) -> Result<FullMassProperties, String> {
495    let base = solid_mass_properties(solid)?;
496    let token = super::profile::begin("solid_mass_properties_full.moments");
497    let result = solid_mass_properties_full_moments(solid, base);
498    super::profile::end(token);
499    result
500}
501
502fn solid_mass_properties_full_moments(
503    solid: &BrepSolid,
504    base: MassProperties,
505) -> Result<FullMassProperties, String> {
506    const MOMENT_KINDS: [Integrand; 9] = [
507        Integrand::MomentX,
508        Integrand::MomentY,
509        Integrand::MomentZ,
510        Integrand::SecondXX,
511        Integrand::SecondYY,
512        Integrand::SecondZZ,
513        Integrand::ProductXY,
514        Integrand::ProductXZ,
515        Integrand::ProductYZ,
516    ];
517    let mut moments = [0.0f64; 3];
518    let mut seconds = [0.0f64; 3];
519    let mut products = [0.0f64; 3];
520    for shell in &solid.shells {
521        for face in &shell.faces {
522            mass_profile(|p| p.faces += 1);
523            let results = if !is_affine(&face.surface)? && !is_untrimmed(face)? {
524                mass_profile(|p| p.trimmed_faces += 1);
525                // One cell decomposition, all nine moment integrands per
526                // station, instead of nine full passes per face.
527                integrate_trimmed_multi(face, &MOMENT_KINDS)?
528            } else {
529                MOMENT_KINDS
530                    .iter()
531                    .map(|kind| face_moment(face, *kind))
532                    .collect::<Result<Vec<_>, _>>()?
533            };
534            moments[0] += results[0];
535            moments[1] += results[1];
536            moments[2] += results[2];
537            seconds[0] += results[3];
538            seconds[1] += results[4];
539            seconds[2] += results[5];
540            products[0] += results[6];
541            products[1] += results[7];
542            products[2] += results[8];
543        }
544    }
545    let volume = base.volume;
546    if volume.abs() <= 1e-30 {
547        return Err("solid_mass_properties_full: non-positive volume".into());
548    }
549    let centroid = Vec3::new(
550        moments[0] / volume,
551        moments[1] / volume,
552        moments[2] / volume,
553    );
554    // Inertia about the origin, then parallel-axis down to the centroid.
555    let ixx =
556        seconds[1] + seconds[2] - volume * (centroid.y * centroid.y + centroid.z * centroid.z);
557    let iyy =
558        seconds[0] + seconds[2] - volume * (centroid.x * centroid.x + centroid.z * centroid.z);
559    let izz =
560        seconds[0] + seconds[1] - volume * (centroid.x * centroid.x + centroid.y * centroid.y);
561    let ixy = -(products[0] - volume * centroid.x * centroid.y);
562    let ixz = -(products[1] - volume * centroid.x * centroid.z);
563    let iyz = -(products[2] - volume * centroid.y * centroid.z);
564    let inertia = [[ixx, ixy, ixz], [ixy, iyy, iyz], [ixz, iyz, izz]];
565    let (principal_moments, principal_axes) = principal_frame(inertia);
566    Ok(FullMassProperties {
567        surface_area: base.surface_area,
568        volume,
569        centroid,
570        inertia,
571        principal_moments,
572        principal_axes,
573    })
574}
575