* Measure: the area of a curved face on the exact surface, not the display mesh (#9086) * Measure: a non-straight border edge leaves the band to the mesh; fix the Vec3 imports (#9086) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: bherbruck <brennen.herbruck@gmail.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,139 @@
|
||||
//! What a face measures on the surface behind it (#9086).
|
||||
//!
|
||||
//! A curved face's area is the area of the surface it lies on: a cylinder's band is
|
||||
//! r·θ·h and a whole sphere 4πr². The display mesh's triangles run inside a curve, so
|
||||
//! their sum falls short of it.
|
||||
|
||||
use std::f64::consts::PI;
|
||||
|
||||
use solidcore_record::Vec3;
|
||||
use solidcore_record::brep::Curve;
|
||||
use solidcraft_geom::prelude::*;
|
||||
use solidcraft_geom::{Mesh, UnitVec3};
|
||||
use solidcraft_kernel::{Body, FaceSurface};
|
||||
|
||||
/// The area of the patch of faces `patch` of `body`, worked out on the surface behind
|
||||
/// them: a cylinder's band, or a sphere. `None` where the surface does not give one, and
|
||||
/// the caller keeps the measure of the mesh.
|
||||
pub(crate) fn patch_area(body: &Body, mesh: &Mesh, patch: &[usize]) -> Option<f64> {
|
||||
match solidcraft_kernel::face_surface(body, *patch.first()?)? {
|
||||
FaceSurface::Cylinder { origin, axis, radius } => cylinder_band(body, mesh, patch, origin, axis, radius),
|
||||
FaceSurface::Sphere { radius, .. } => sphere(body, patch, radius),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The edges on the border of the patch: the ones a face of the patch shares with a face
|
||||
/// outside it, and the ones it keeps to itself.
|
||||
fn border_edges(mesh: &Mesh, patch: &[usize]) -> Vec<usize> {
|
||||
mesh.edge_faces
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, faces)| {
|
||||
let inside = faces.iter().filter(|f| patch.contains(&(**f as usize))).count();
|
||||
inside > 0 && (faces.len() == 1 || inside < faces.len())
|
||||
})
|
||||
.map(|(edge, _)| edge)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether edge `edge` is a straight line parallel to `axis`.
|
||||
fn straight_along(body: &Body, edge: usize, axis: UnitVec3) -> bool {
|
||||
let Some(e) = body.record().edges.get(edge) else { return false };
|
||||
if !matches!(e.curve, Curve::Line { .. }) {
|
||||
return false;
|
||||
}
|
||||
let Ok(c) = solidcraft_geom::brep::eval::CurveEval::new(e.parameters()) else { return false };
|
||||
let [t0, t1] = e.interval;
|
||||
let (Some(a), Some(b)) = (c.point(t0), c.point(t1)) else { return false };
|
||||
(b - a).normalized().is_some_and(|d| d.dot(axis.vec()).abs() >= 1.0 - 1e-9)
|
||||
}
|
||||
|
||||
/// The area of a cylindrical band: the radius of the surface, the turn the band covers
|
||||
/// and the distance between its two rims.
|
||||
fn cylinder_band(body: &Body, mesh: &Mesh, patch: &[usize], origin: Vec3, axis: UnitVec3, radius: f64) -> Option<f64> {
|
||||
if !(radius.is_finite() && radius > 0.0) {
|
||||
return None;
|
||||
}
|
||||
let tol = radius * 1e-6;
|
||||
// The whole patch lies on one cylinder.
|
||||
for f in patch {
|
||||
match solidcraft_kernel::face_surface(body, *f)? {
|
||||
FaceSurface::Cylinder { origin: o, axis: a, radius: r } => {
|
||||
if (r - radius).abs() > tol || o.dist(origin) > tol || a.vec().dot(axis.vec()).abs() < 1.0 - 1e-9 {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
// The rims of the band: the circles that bound it, each across the axis.
|
||||
let mut rims: Vec<(f64, f64)> = Vec::new();
|
||||
for edge in border_edges(mesh, patch) {
|
||||
// An edge that is not a circle but a straight line along the axis (a seam, a straight
|
||||
// cut along the band) leaves the turn of the band to its rims alone. Any other edge
|
||||
// (the saddle rim of a bore through the wall) cuts the band: not ours to measure.
|
||||
let Some(circle) = solidcraft_kernel::edge_circle(body, edge) else {
|
||||
if straight_along(body, edge, axis) {
|
||||
continue;
|
||||
}
|
||||
return None;
|
||||
};
|
||||
if circle.axis.vec().dot(axis.vec()).abs() < 1.0 - 1e-9 || (circle.radius - radius).abs() > tol {
|
||||
return None;
|
||||
}
|
||||
let d = circle.center - origin;
|
||||
let height = d.dot(axis.vec());
|
||||
if (d - axis.vec() * height).len() > tol {
|
||||
return None;
|
||||
}
|
||||
rims.push((height, circle.angle));
|
||||
}
|
||||
// The two rims: the band runs between them, and both cover the same turn.
|
||||
let mut levels: Vec<(f64, f64)> = Vec::new();
|
||||
for (height, angle) in rims {
|
||||
match levels.iter_mut().find(|(h, _)| (*h - height).abs() <= tol) {
|
||||
Some((_, a)) => *a += angle,
|
||||
None => levels.push((height, angle)),
|
||||
}
|
||||
}
|
||||
if levels.len() != 2 {
|
||||
return None;
|
||||
}
|
||||
levels.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
let (low, low_turn) = levels[0];
|
||||
let (high, high_turn) = levels[1];
|
||||
let height = high - low;
|
||||
if !(height > 0.0) || (low_turn - high_turn).abs() > low_turn.max(high_turn) * 1e-6 {
|
||||
return None;
|
||||
}
|
||||
Some(radius * low_turn * height)
|
||||
}
|
||||
|
||||
/// The area of a sphere: 4πr², when the body is the whole of it.
|
||||
fn sphere(body: &Body, patch: &[usize], radius: f64) -> Option<f64> {
|
||||
if !(radius.is_finite() && radius > 0.0) {
|
||||
return None;
|
||||
}
|
||||
// The whole patch lies on one sphere.
|
||||
for f in patch {
|
||||
match solidcraft_kernel::face_surface(body, *f)? {
|
||||
FaceSurface::Sphere { radius: r, .. } if (r - radius).abs() <= radius * 1e-6 => {}
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
// The body is the whole sphere: every face of it lies on that sphere and the patch
|
||||
// holds them all. A body with a face of its own (a sphere that was cut) is a piece of
|
||||
// the sphere, whose area this does not work out: the measure of the mesh stands in
|
||||
// for it.
|
||||
for f in 0..body.record().faces.len() {
|
||||
match solidcraft_kernel::face_surface(body, f)? {
|
||||
FaceSurface::Sphere { radius: r, .. } if (r - radius).abs() <= radius * 1e-6 => {}
|
||||
_ => return None,
|
||||
}
|
||||
if !patch.contains(&f) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Some(4.0 * PI * radius * radius)
|
||||
}
|
||||
@@ -350,7 +350,10 @@ fn describe(s: &Session, st: &solidcraft_doc::ModelState, sel: &Sel) -> Option<I
|
||||
let m = b.mesh();
|
||||
let patch = m.surface_patch(*index);
|
||||
let tris = patch.iter().flat_map(|f| face_tris(&m, *f)).collect::<Vec<_>>();
|
||||
let area: f64 = tris.iter().map(|[a, b, c]| (*b - *a).cross(*c - *a).len() * 0.5).sum();
|
||||
let on_mesh: f64 = tris.iter().map(|[a, b, c]| (*b - *a).cross(*c - *a).len() * 0.5).sum();
|
||||
// A curved face is measured on the surface it lies on, not on the triangles of
|
||||
// the display mesh, which run inside the curve.
|
||||
let area = super::measure_exact::patch_area(&b.body, &m, &patch).unwrap_or(on_mesh);
|
||||
let normals: Vec<UnitVec3> = tris.iter().filter_map(|[a, b, c]| (*b - *a).cross(*c - *a).unit()).collect();
|
||||
let planar = normals.first().copied().filter(|n0| normals.iter().all(|n| n.dot(*n0) > 1.0 - 1e-6));
|
||||
let mut json = json!({"type": "face", "area_mm2": area, "planar": planar.is_some()});
|
||||
|
||||
@@ -74,6 +74,7 @@ mod libraries;
|
||||
pub mod mass_properties;
|
||||
mod material_properties;
|
||||
mod materials;
|
||||
mod measure_exact;
|
||||
mod measure_sel;
|
||||
mod measure_shape;
|
||||
mod mesh;
|
||||
|
||||
@@ -2366,6 +2366,8 @@ mod large_assembly_tests;
|
||||
#[cfg(test)]
|
||||
mod measure_centre_tests;
|
||||
#[cfg(test)]
|
||||
mod measure_surface_tests;
|
||||
#[cfg(test)]
|
||||
mod naming_history_tests;
|
||||
#[cfg(test)]
|
||||
mod pattern_suppress_tests;
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
//! Measure on a body's curved faces: the area comes from the exact surface, not from the
|
||||
//! display mesh's triangles, which run inside a curve (#9086).
|
||||
#![allow(clippy::unwrap_used)]
|
||||
|
||||
use std::f64::consts::TAU;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use solidcore_record::Vec3;
|
||||
|
||||
use crate::Session;
|
||||
|
||||
fn run(s: &mut Session, id: &str, p: Value) -> Value {
|
||||
match s.execute(id, &p) {
|
||||
Ok(v) => v,
|
||||
Err(e) => panic!("{id} {p}: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn close(v: &Value, want: f64, tol: f64) -> bool {
|
||||
v.as_f64().is_some_and(|x| (x - want).abs() <= tol)
|
||||
}
|
||||
|
||||
/// The first face whose analytic surface satisfies `want`, as a pick.
|
||||
fn face_of(s: &Session, want: impl Fn(solidcraft_kernel::FaceSurface) -> bool) -> Value {
|
||||
let st = s.model.state();
|
||||
let b = st.bodies.first().unwrap();
|
||||
let m = b.mesh();
|
||||
let n = m.tri_face.iter().map(|f| *f as usize + 1).max().unwrap();
|
||||
let f = (0..n).find(|&f| solidcraft_kernel::face_surface(&b.body, f).is_some_and(&want)).expect("face");
|
||||
let p = m.triangles.iter().zip(&m.tri_face).find(|(_, tf)| **tf as usize == f).and_then(|(t, _)| m.tri(t)).unwrap()[0];
|
||||
json!({"type": "face", "body": b.name, "index": f, "point": p})
|
||||
}
|
||||
|
||||
fn measure(s: &mut Session, items: Vec<Value>) -> Value {
|
||||
run(s, "inspect.measure", json!({ "items": items }))
|
||||
}
|
||||
|
||||
/// A cylinder's side face is as big as its exact lateral area, 2πrh, in the same reply that
|
||||
/// gives its exact radius and diameter: the area came from the display mesh's triangles, which
|
||||
/// run inside the curve (#9086, the report's own cylinder).
|
||||
#[test]
|
||||
fn a_cylinders_side_face_is_as_big_as_its_exact_lateral_area() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "solid.cylinder", json!({"radius": 5, "height": 20, "base": [40, 10, 0], "operation": "new"}));
|
||||
let side = face_of(&s, |f| matches!(f, solidcraft_kernel::FaceSurface::Cylinder { radius, .. } if (radius - 5.0).abs() < 1e-6));
|
||||
let r = measure(&mut s, vec![side]);
|
||||
let item = &r["items"][0];
|
||||
assert!(close(&item["diameter"], 10.0, 1e-9), "the same reply gives the exact diameter: {r}");
|
||||
assert!(close(&item["area_mm2"], TAU * 5.0 * 20.0, 1e-6), "the side face's area is its exact 2πrh: {r}");
|
||||
}
|
||||
|
||||
/// A hole's wall is as big as its exact lateral area, 2πrh: the area came from the display
|
||||
/// mesh's triangles, which run inside the curve (#9086).
|
||||
#[test]
|
||||
fn a_holes_wall_is_as_big_as_its_exact_lateral_area() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "solid.box", json!({"length": 60, "width": 40, "height": 10}));
|
||||
run(&mut s, "solid.cylinder", json!({"radius": 3, "height": 12, "base": [15, 20, -1], "operation": "cut"}));
|
||||
let wall = face_of(&s, |f| matches!(f, solidcraft_kernel::FaceSurface::Cylinder { radius, .. } if (radius - 3.0).abs() < 1e-6));
|
||||
let r = measure(&mut s, vec![wall]);
|
||||
let item = &r["items"][0];
|
||||
assert!(close(&item["diameter"], 6.0, 1e-9), "the same reply gives the exact diameter: {r}");
|
||||
assert!(close(&item["area_mm2"], TAU * 3.0 * 10.0, 1e-6), "the hole's wall is its exact 2πrh: {r}");
|
||||
}
|
||||
|
||||
/// A sphere's area is its exact 4πr², not the area of the display mesh's triangles (#9086).
|
||||
#[test]
|
||||
fn a_sphere_is_as_big_as_its_exact_surface() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "solid.sphere", json!({"radius": 10, "base": [0, 0, 0], "operation": "new"}));
|
||||
let ball = face_of(&s, |f| matches!(f, solidcraft_kernel::FaceSurface::Sphere { radius, .. } if (radius - 10.0).abs() < 1e-6));
|
||||
let r = measure(&mut s, vec![ball]);
|
||||
let item = &r["items"][0];
|
||||
assert!(close(&item["diameter"], 20.0, 1e-9), "the same reply gives the exact diameter: {r}");
|
||||
assert!(close(&item["area_mm2"], 4.0 * std::f64::consts::PI * 100.0, 1e-4), "the sphere's area is its exact 4πr²: {r}");
|
||||
}
|
||||
|
||||
/// A planar face's area is unchanged: it is exact on the mesh already.
|
||||
///
|
||||
/// The face picked is the box's side at x = 40 (30 × 10), which the mesh measures exactly.
|
||||
#[test]
|
||||
fn a_flat_face_keeps_its_area() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 10}));
|
||||
let st = s.model.state();
|
||||
let b = st.bodies.first().unwrap();
|
||||
let m = b.mesh();
|
||||
let side = m.triangles.iter().zip(&m.tri_face).find(|(_, tf)| **tf as usize == 2).and_then(|(t, _)| m.tri(t)).unwrap()[0];
|
||||
let pick = json!({"type": "face", "body": b.name, "index": 2, "point": side});
|
||||
let r = measure(&mut s, vec![pick]);
|
||||
assert!(close(&r["items"][0]["area_mm2"], 300.0, 1e-6), "{r}");
|
||||
}
|
||||
|
||||
/// The body's own volume is its exact πr²h, not the display mesh's (#9086).
|
||||
///
|
||||
/// The volume of a body is still measured on a tessellation of it: the exact volume of a
|
||||
/// body is measured on its surfaces, which is a follow-up to the faces' own areas.
|
||||
#[test]
|
||||
#[ignore = "the body's volume still comes from a tessellation: the exact volume of a body is a follow-up (#9086)"]
|
||||
fn a_cylinders_volume_is_its_exact_value() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "solid.cylinder", json!({"radius": 5, "height": 20, "base": [40, 10, 0], "operation": "new"}));
|
||||
let name = s.model.state().bodies.first().unwrap().name.clone();
|
||||
let r = measure(&mut s, vec![json!({"type": "body", "name": name})]);
|
||||
assert!(close(&r["items"][0]["volume_mm3"], std::f64::consts::PI * 25.0 * 20.0, 1e-3), "{r}");
|
||||
}
|
||||
|
||||
/// The body's bounding box is its exact one: the tessellation's runs inside a curve (#9086).
|
||||
///
|
||||
/// The box of a body is still measured on a tessellation of it: the exact box of a body is
|
||||
/// measured on its surfaces, which is a follow-up to the faces' own areas.
|
||||
#[test]
|
||||
#[ignore = "the body's box still comes from a tessellation: the exact box of a body is a follow-up (#9086)"]
|
||||
fn a_cylinders_bounding_box_is_its_exact_one() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "solid.cylinder", json!({"radius": 5, "height": 20, "base": [40, 10, 0], "operation": "new"}));
|
||||
let r = run(&mut s, "inspect.measure", json!({}));
|
||||
let bb = &r["bodies"][0]["bbox"];
|
||||
assert!(close(&bb["min"][0], 35.0, 1e-6) && close(&bb["max"][0], 45.0, 1e-6), "the box's X runs from 35 to 45: {r}");
|
||||
assert!(close(&bb["min"][1], 5.0, 1e-6) && close(&bb["max"][1], 15.0, 1e-6), "the box's Y runs from 5 to 15: {r}");
|
||||
}
|
||||
|
||||
/// The report's own cylinder, measured as the report measured it (#9086).
|
||||
#[test]
|
||||
fn the_reports_cylinder_measures_exactly() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "solid.cylinder", json!({"radius": 5, "height": 20, "base": [40, 10, 0], "operation": "new"}));
|
||||
let side = face_of(&s, |f| matches!(f, solidcraft_kernel::FaceSurface::Cylinder { radius, .. } if (radius - 5.0).abs() < 1e-6));
|
||||
let r = measure(&mut s, vec![side]);
|
||||
let area = r["items"][0]["area_mm2"].as_f64().unwrap();
|
||||
let want = TAU * 5.0 * 20.0;
|
||||
assert!((area - want).abs() / want < 1e-6, "the side face's area {area} against its exact {want}: {r}");
|
||||
let _ = Vec3::new(40.0, 10.0, 20.0);
|
||||
}
|
||||
|
||||
/// A bore through the cylinder's wall cuts a rim that is not a circle: the band is no longer
|
||||
/// the uncut 2πrh, so the exact shortcut gives way to the mesh's measure.
|
||||
#[test]
|
||||
fn a_bore_through_the_wall_is_not_measured_as_the_uncut_band() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "solid.cylinder", json!({"radius": 5, "height": 20, "base": [0, 0, 0], "operation": "new"}));
|
||||
run(&mut s, "solid.cylinder", json!({"radius": 1, "height": 14, "base": [-7, 0, 10], "axis": [1, 0, 0], "operation": "cut"}));
|
||||
let side = face_of(&s, |f| matches!(f, solidcraft_kernel::FaceSurface::Cylinder { radius, .. } if (radius - 5.0).abs() < 1e-6));
|
||||
let r = measure(&mut s, vec![side]);
|
||||
let area = r["items"][0]["area_mm2"].as_f64().unwrap();
|
||||
assert!(area < TAU * 5.0 * 20.0 - 1.0, "the bored wall's area {area} is less than the uncut {}: {r}", TAU * 5.0 * 20.0);
|
||||
}
|
||||
Reference in New Issue
Block a user