SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Measure: the area of a flat face with holes comes from its exact edges (#12373)
phanooba2c4a1267bc5
diff --git a/crates/engine/src/cmd/measure_exact.rs b/crates/engine/src/cmd/measure_exact.rsindex b32a1b9e50..be3493de92 100644--- a/crates/engine/src/cmd/measure_exact.rs+++ b/crates/engine/src/cmd/measure_exact.rs@@ -3,26 +3,161 @@//! 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.+//!+//! A flat face's area is the area its exact edges enclose (#12372): its outer loop's area+//! less its holes'. The display mesh's polygon for a round hole runs inside the circle, so+//! the mesh's holes are too small and the face reads too big.use std::f64::consts::PI;use solidcore_record::Vec3;-use solidcore_record::brep::Curve;+use solidcore_record::brep::{Curve, Loop};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.+/// them: a flat patch, 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::Plane { normal, point } => flat_patch(body, patch, normal, point),FaceSurface::Cylinder { origin, axis, radius } => cylinder_band(body, mesh, patch, origin, axis, radius),FaceSurface::Sphere { radius, .. } => sphere(body, patch, radius),_ => None,}}+/// Two orthonormal directions in a plane and a point on it: the plane's own 2D coordinates.+struct PlaneFrame {+ origin: Vec3,+ normal: Vec3,+ x: Vec3,+ y: Vec3,+}++impl PlaneFrame {+ fn new(normal: UnitVec3, origin: Vec3) -> Option<PlaneFrame> {+ let n = normal.vec();+ // The world axis least along the normal gives a direction across it.+ let across = if n.x.abs() <= n.y.abs() && n.x.abs() <= n.z.abs() {+ Vec3::X+ } else if n.y.abs() <= n.z.abs() {+ Vec3::Y+ } else {+ Vec3::Z+ };+ let x = n.cross(across).normalized()?;+ Some(PlaneFrame { origin, normal: n, x, y: n.cross(x) })+ }++ /// The 2D coordinates of point `p`.+ fn point(&self, p: Vec3) -> (f64, f64) {+ let d = p - self.origin;+ (d.dot(self.x), d.dot(self.y))+ }++ /// The 2D components of direction `d`.+ fn dir(&self, d: Vec3) -> (f64, f64) {+ (d.dot(self.x), d.dot(self.y))+ }+}++/// The area of a flat patch: every face of it lies on one plane, and each face's area is the+/// area its loops of exact edges enclose.+fn flat_patch(body: &Body, patch: &[usize], normal: UnitVec3, point: Vec3) -> Option<f64> {+ let tol = (body.size() * 1e-9).max(1e-9);+ let frame = PlaneFrame::new(normal, point)?;+ let mut total = 0.0;+ for &face in patch {+ match solidcraft_kernel::face_surface(body, face)? {+ FaceSurface::Plane { normal: n, point: p }+ if n.vec().dot(frame.normal).abs() >= 1.0 - 1e-9 && (p - point).dot(frame.normal).abs() <= tol => {}+ _ => return None,+ }+ total += flat_face(body, face, &frame, tol)?;+ }+ (total.is_finite() && total > 0.0).then_some(total)+}++/// The area of flat face `face`: the area its outer loop encloses, less the areas its holes+/// enclose. The outer loop is the one that encloses the most: every hole lies inside it.+fn flat_face(body: &Body, face: usize, frame: &PlaneFrame, tol: f64) -> Option<f64> {+ let mut loops: Vec<f64> = Vec::new();+ for l in &body.record().faces.get(face)?.loops {+ let Loop::Edges { edges } = l else { continue };+ let mut enclosed = 0.0;+ for used in edges {+ enclosed += edge_sweep(body, used.edge as usize, used.forward, frame, tol)?;+ }+ loops.push(enclosed.abs());+ }+ let outer = loops.iter().copied().fold(0.0, f64::max);+ let area = outer - (loops.iter().sum::<f64>() - outer);+ (area.is_finite() && area > 0.0).then_some(area)+}++/// Four-point Gauss–Legendre nodes and weights on `[−1, 1]`.+const GAUSS4: [(f64, f64); 4] = [+ (-0.861_136_311_594_052_6, 0.347_854_845_137_453_8),+ (-0.339_981_043_584_856_3, 0.652_145_154_862_546_2),+ (0.339_981_043_584_856_3, 0.652_145_154_862_546_2),+ (0.861_136_311_594_052_6, 0.347_854_845_137_453_8),+];++/// Gauss panels along an edge that is neither a line nor a circle.+const SWEEP_PANELS: usize = 64;++/// The signed area that edge `edge` sweeps about the frame's origin, `½∫(x dy − y dx)`, run+/// along the loop's direction (`forward`: from the edge's start to its end). Summed round a+/// loop, it is the area the loop encloses (by Green's theorem). A circle or an arc of one is+/// worked out in closed form: the triangle to its chord and the circular segment beyond it.+/// `None` for an edge off the plane, or one whose curve gives no derivative.+fn edge_sweep(body: &Body, edge: usize, forward: bool, frame: &PlaneFrame, tol: f64) -> Option<f64> {+ let triangle = |a: Vec3, b: Vec3| {+ let ((ax, ay), (bx, by)) = (frame.point(a), frame.point(b));+ 0.5 * (ax * by - bx * ay)+ };+ if let Some(c) = solidcraft_kernel::edge_circle(body, edge) {+ let along = c.axis.vec().dot(frame.normal);+ if along.abs() < 1.0 - 1e-9 || (c.center - frame.origin).dot(frame.normal).abs() > tol {+ return None;+ }+ // The arc runs counter-clockwise about its axis from its start to its end.+ let (a, b, turn) = if forward { (c.start, c.end, along.signum()) } else { (c.end, c.start, -along.signum()) };+ let segment = 0.5 * c.radius * c.radius * (c.angle - c.angle.sin());+ return Some(triangle(a, b) + turn * segment);+ }+ let e = body.record().edges.get(edge)?;+ if matches!(e.curve, Curve::Line { .. }) {+ let c = solidcraft_geom::brep::eval::CurveEval::new(e.parameters()).ok()?;+ let [t0, t1] = e.interval;+ let (a, b) = (c.point(t0)?, c.point(t1)?);+ let off = |p: Vec3| (p - frame.origin).dot(frame.normal).abs() > tol.max(e.tolerance);+ if off(a) || off(b) {+ return None;+ }+ return Some(if forward { triangle(a, b) } else { triangle(b, a) });+ }+ let c = solidcraft_geom::brep::eval::CurveEval::new(e.parameters()).ok()?;+ let [t0, t1] = e.interval;+ let h = (t1 - t0) / SWEEP_PANELS as f64;+ let mut swept = 0.0;+ for panel in 0..SWEEP_PANELS {+ let start = t0 + h * panel as f64;+ for (x, w) in GAUSS4 {+ let (p, d) = c.derivs(start + 0.5 * h * (x + 1.0))?;+ if (p - frame.origin).dot(frame.normal).abs() > tol.max(e.tolerance) {+ return None;+ }+ let ((px, py), (dx, dy)) = (frame.point(p), frame.dir(d));+ swept += 0.5 * h * w * 0.5 * (px * dy - py * dx);+ }+ }+ let swept = if forward { swept } else { -swept };+ swept.is_finite().then_some(swept)+}+/// 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> {diff --git a/crates/engine/src/cmd/measure_sel.rs b/crates/engine/src/cmd/measure_sel.rsindex 531be79af3..4d073b7b0a 100644--- a/crates/engine/src/cmd/measure_sel.rs+++ b/crates/engine/src/cmd/measure_sel.rs@@ -351,8 +351,9 @@ fn describe(s: &Session, st: &solidcraft_doc::ModelState, sel: &Sel) -> Option<Ilet patch = m.surface_patch(*index);let tris = patch.iter().flat_map(|f| face_tris(&m, *f)).collect::<Vec<_>>();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.+ // A face is measured on the surface it lies on and the exact edges around it, not+ // on the triangles of the display mesh, which run inside every curve: a curved+ // face's and a round hole's alike.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));diff --git a/crates/engine/src/measure_surface_tests.rs b/crates/engine/src/measure_surface_tests.rsindex 346eff3e7e..6d025da9e5 100644--- a/crates/engine/src/measure_surface_tests.rs+++ b/crates/engine/src/measure_surface_tests.rs@@ -1,5 +1,5 @@-//! 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).+//! Measure on a body's faces: the area comes from the exact surface and edges, not from the+//! display mesh's triangles, which run inside a curve (#9086, #12372).#![allow(clippy::unwrap_used)]use std::f64::consts::TAU;@@ -75,9 +75,9 @@ fn a_sphere_is_as_big_as_its_exact_surface() {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.+/// A planar face with straight edges keeps its area.///-/// The face picked is the box's side at x = 40 (30 × 10), which the mesh measures exactly.+/// The face picked is the box's side at x = 40 (30 × 10).#[test]fn a_flat_face_keeps_its_area() {let mut s = Session::default();@@ -91,6 +91,78 @@ fn a_flat_face_keeps_its_area() {assert!(close(&r["items"][0]["area_mm2"], 300.0, 1e-6), "{r}");}+/// The flat face at height `z` whose plane is across Z, as a pick.+fn flat_face_at(s: &Session, z: f64) -> Value {+ face_of(+ s,+ |f| matches!(f, solidcraft_kernel::FaceSurface::Plane { normal, point } if normal.vec().z.abs() > 1.0 - 1e-9 && (point.z - z).abs() < 1e-6),+ )+}++/// A flat face with round holes is the plate less its exact holes: the display mesh's+/// polygon for each hole runs inside the circle, so the mesh's holes were too small and the+/// face read 2293.875 mm² (#12372, the report's own plate).+#[test]+fn a_flat_face_with_round_holes_is_the_plate_less_its_exact_holes() {+ 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"}));+ run(&mut s, "solid.cylinder", json!({"radius": 5, "height": 12, "base": [40, 20, -1], "operation": "cut"}));+ for z in [0.0, 10.0] {+ let face = flat_face_at(&s, z);+ let r = measure(&mut s, vec![face]);+ let want = 60.0 * 40.0 - std::f64::consts::PI * (9.0 + 25.0);+ assert!(close(&r["items"][0]["area_mm2"], want, 1e-6), "the face at z = {z} is 60 × 40 − π(3² + 5²) = {want}: {r}");+ }+}++/// A flat face whose outer edge is a circle is the exact disc, πr² (#12372).+#[test]+fn a_cylinders_end_is_its_exact_disc() {+ let mut s = Session::default();+ run(&mut s, "solid.cylinder", json!({"radius": 5, "height": 20, "base": [40, 10, 0], "operation": "new"}));+ let face = flat_face_at(&s, 20.0);+ let r = measure(&mut s, vec![face]);+ assert!(close(&r["items"][0]["area_mm2"], std::f64::consts::PI * 25.0, 1e-9), "the end is the disc π·5²: {r}");+}++/// A flat face whose outer loop mixes straight edges and an arc: a quarter of a round bite+/// cut from a plate's corner leaves 60 × 40 − π·8²/4 (#12372).+#[test]+fn a_flat_face_with_an_arc_in_its_outline_is_exact() {+ let mut s = Session::default();+ run(&mut s, "solid.box", json!({"length": 60, "width": 40, "height": 10}));+ run(&mut s, "solid.cylinder", json!({"radius": 8, "height": 12, "base": [0, 0, -1], "operation": "cut"}));+ let face = flat_face_at(&s, 10.0);+ let r = measure(&mut s, vec![face]);+ let want = 60.0 * 40.0 - std::f64::consts::PI * 64.0 / 4.0;+ assert!(close(&r["items"][0]["area_mm2"], want, 1e-6), "the plate less a quarter of the bite is {want}: {r}");+}++/// A flat face with an elliptic hole is the plate less the ellipse, πab: an edge that is neither+/// a line nor a circle is summed along its curve (#12372). The kernel keeps the ellipse as a+/// cubic spline fitted to it, which encloses 2·10⁻³ mm² more than πab here; the display mesh's+/// polygon read 2024.696 mm², 1.7 mm² off. Both faces read the same, though their loops run+/// the hole's edges opposite ways round.+#[test]+fn a_flat_face_with_an_elliptic_hole_is_the_plate_less_the_exact_ellipse() {+ let mut s = Session::default();+ run(&mut s, "solid.box", json!({"length": 60, "width": 40, "height": 10}));+ run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Cut"}));+ run(&mut s, "sketch.ellipse", json!({"center": [30, 20], "major": [45, 20], "minor_radius": 8}));+ run(&mut s, "sketch.finish", json!({}));+ run(&mut s, "solid.extrude", json!({"sketch": "Cut", "through_all": true, "operation": "cut", "direction": "symmetric"}));+ let want = 60.0 * 40.0 - std::f64::consts::PI * 15.0 * 8.0;+ let mut areas = Vec::new();+ for z in [0.0, 10.0] {+ let face = flat_face_at(&s, z);+ let r = measure(&mut s, vec![face]);+ assert!(close(&r["items"][0]["area_mm2"], want, 1e-2), "the face at z = {z} is 60 × 40 − π·15·8 = {want}: {r}");+ areas.push(r["items"][0]["area_mm2"].as_f64().unwrap());+ }+ assert!((areas[0] - areas[1]).abs() < 1e-9, "both faces read the same: {areas:?}");+}+/// 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