SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Wave 399/509: STEP import: a void reads as a cavity whichever way its shell flag points, again (and 3 more)
jyvikodbec20dbbe09
diff --git a/crates/geom/src/brep/eval.rs b/crates/geom/src/brep/eval.rsindex 5a5e71a3f8..6ffa2b5e84 100644--- a/crates/geom/src/brep/eval.rs+++ b/crates/geom/src/brep/eval.rs@@ -9,7 +9,7 @@//! Call on validated records. Evaluation of a well-formed record never panics: a point that//! cannot be had (a vanishing weight, a Newton step that does not converge) is `None`.use super::pcurve::Error;-use super::{Curve, Frame, Surface};+use super::{Curve, Curve2, Frame, Surface};use crate::Vec3;use crate::bspline::MAX_SPLINE_DEGREE;use crate::tess::partials::{Partials, tabulate, trig_derivative};@@ -482,3 +482,50 @@ fn solve3(rows: [Vec3; 3], rhs: [f64; 3]) -> Option<Vec3> {let x = (bc * rhs[0] + ca * rhs[1] + ab * rhs[2]) * (1.0 / det);x.is_finite().then_some(x)}++/// 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),+];++/// Pieces each pcurve is integrated in, and how many Gauss panels cover a v range.+const FLUX_PIECES: usize = 32;+const FLUX_PANELS: usize = 4;++/// The flux of `field` through a face, `∫∫ field(S)·(S_u × S_v) du dv` over the (u, v) region its+/// loops (record convention, each use its pcurve and direction) bound, by Green's theorem:+/// `∮ −G du` with `G(u, v) = ∫ field·N ds` from `v0` to `v`. A quadrature for the sign of a+/// shell's volume (`field = p / 3`) or a winding number, which only has to be right to well+/// under a half: no geometry is made from it. Loops round a periodic direction need no seam+/// edge, as a seam's two runs at constant u add nothing to `∮ G du`.+pub fn face_flux(s: &SurfaceEval, v0: f64, loops: &[Vec<(&Curve2, bool)>], field: &dyn Fn(Vec3) -> Vec3) -> Option<f64> {+ let g = |u: f64, v: f64| -> Option<f64> {+ let (mut sum, h) = (0.0, (v - v0) / FLUX_PANELS as f64);+ for panel in 0..FLUX_PANELS {+ let a = v0 + h * panel as f64;+ for (x, w) in GAUSS4 {+ let t = a + 0.5 * h * (x + 1.0);+ let (p, su, sv) = s.derivs(u, t)?;+ sum += 0.5 * h * w * field(p).dot(su.cross(sv));+ }+ }+ sum.is_finite().then_some(sum)+ };+ let mut total = 0.0;+ for (c, forward) in loops.iter().flatten() {+ let [t0, t1] = c.interval()?;+ let at = |k: f64| {+ let f = k / FLUX_PIECES as f64;+ // Exactly the ends at f = 0 and 1, whatever the interval's rounding.+ c.eval(if *forward { t0 * (1.0 - f) + t1 * f } else { t1 * (1.0 - f) + t0 * f })+ };+ for k in 0..FLUX_PIECES {+ let (a, m, z) = (at(k as f64)?, at(k as f64 + 0.5)?, at(k as f64 + 1.0)?);+ total -= g(m[0], m[1])? * (z[0] - a[0]);+ }+ }+ total.is_finite().then_some(total)+}diff --git a/crates/kernel/src/prism.rs b/crates/kernel/src/prism.rsindex 05323d84cb..f71e3366b7 100644--- a/crates/kernel/src/prism.rs+++ b/crates/kernel/src/prism.rs@@ -260,7 +260,7 @@ mod sheets {let mid = hole.segs.first().map(|s| s.point_at(0.5)).ok_or_else(|| failed("face", format!("face {f} has an empty loop")))?;let owner = out[first..].iter_mut()- .filter(|r| r.outer.contains(mid))+ .filter(|r| holds(&r.outer, mid)).min_by(|a, b| a.outer.signed_area().total_cmp(&b.outer.signed_area())).ok_or_else(|| failed("face", format!("face {f} has a hole outside its material")))?;owner.holes.push(hole);@@ -269,6 +269,15 @@ mod sheets {Ok(Regions { regions: out, touching })}+ /// Whether the loop `outer` holds `p`: even-odd against its polyline within a quarter of+ /// `p`'s distance from it, so the polyline's chords cannot pass `p` by (a loop's own+ /// [`Loop2::contains`] reads it within 1e-3 mm, and a hole closer than that to an arc of the+ /// outline was taken for one outside it, a chord cutting it off).+ fn holds(outer: &Loop2, p: Vec2) -> bool {+ let d = outer.segs.iter().map(|s| s.point_at(s.closest_param(p)).dist(p)).fold(f64::INFINITY, f64::min);+ outer.polyline((d * 0.25).clamp(1e-9, 1e-3)).contains(p)+ }+/// The natural normal of a planar surface record.fn natural_normal(s: &Surface) -> Option<Vec3> {let v = |p: [f64; 3]| Vec3::new(p[0], p[1], p[2]);@@ -476,8 +485,8 @@ mod planar_tests {/// Two edges lying on one another within the tolerance, a hair from parallel, meet at a/// point somewhere along their overlap. Taken for a crossing, that point split the square's/// edge once more: 5e-8 mm before its end, which left an edge shorter than the tolerance in- /// the result, or in the middle of a straight edge. The ends of an overlap are what split- /// the edges.+ /// the result, or in the middle of a straight edge. Edges on one line within the tolerance+ /// are one edge of the result: where they meet is no corner.#[test]fn overlapping_lines_a_hair_from_parallel_do_not_cross() {let square = rectangle(Vec2::ZERO, Vec2::new(10.0, 10.0));@@ -498,20 +507,22 @@ mod planar_tests {};let same = |got: &[f64], want: &[f64]| got.len() == want.len() && got.iter().zip(want).all(|(g, w)| (g - w).abs() < 1e-6);for meet in [10.0 - 5e-8, 7.0] {- // Below the square, against its bottom edge: cut away, it leaves the square, the- // bottom edge split only at x = 4, where the quadrilateral's corner lies on it.+ // Below the square, against its bottom edge: cut away, it leaves the square, its four+ // edges whole (the quadrilateral's corner at x = 4 lies within 1e-8 of the bottom+ // edge, on its line, and its edge from there is no more than 1e-8 off it).let below = quad(meet, -5.0);let cut = planar_regions_boolean(std::slice::from_ref(&square), std::slice::from_ref(&below), BoolOp::Cut, 1e-7).unwrap();assert_eq!(cut.len(), 1, "{meet}");- assert!(same(&lengths(&cut[0]), &[4.0, 6.0, 10.0, 10.0, 10.0]), "{meet}: cut edges {:?}", lengths(&cut[0]));+ assert!(same(&lengths(&cut[0]), &[10.0, 10.0, 10.0, 10.0]), "{meet}: cut edges {:?}", lengths(&cut[0]));assert!((cut[0].area() - 100.0).abs() < 1e-6, "{meet}: {}", cut[0].area());// Over the square, flush with that edge and reaching past it to x = 14: the- // union's outline runs along y = 0 once, in the pieces 0..4, 4..10 and 10..14.+ // union's outline runs along y = 0 once, one edge from 0 to 14 (the quadrilateral's+ // bottom edge lies within 1e-8 of the line y = 0 all along).let flush = quad(meet, 5.0);let union = planar_regions_boolean(std::slice::from_ref(&square), std::slice::from_ref(&flush), BoolOp::Union, 1e-7).unwrap_or_else(|e| panic!("{meet}: union {e}"));assert_eq!(union.len(), 1, "{meet}");- assert!(same(&lengths(&union[0]), &[4.0, 4.0, 4.0, 5.0, 5.0, 6.0, 10.0, 10.0]), "{meet}: union edges {:?}", lengths(&union[0]));+ assert!(same(&lengths(&union[0]), &[4.0, 5.0, 5.0, 10.0, 10.0, 14.0]), "{meet}: union edges {:?}", lengths(&union[0]));assert!((union[0].area() - 120.0).abs() < 1e-6, "{meet}: {}", union[0].area());}}@@ -597,7 +608,8 @@ mod planar_tests {/// there left a sliver of edge shorter than the distance within which the loops join their/// pieces; the chaining took it for a second way out of the corner, and a loop of that one/// sliver is open, its area not zero away from the origin: a hole no outline held (no- /// result at all) or a region of its own. The union is the plate and the strip, whole.+ /// result at all) or a region of its own. The union is the plate and the strip, whole: six+ /// edges, the strip's end and the plate's on the line x = 150 one edge from y = 47 to 80.#[test]fn a_bent_edge_crossing_its_neighbour_by_their_corner_leaves_no_sliver() {let union_is_whole = |(plate, strip): (Region2, Region2), what: &str| {@@ -608,7 +620,7 @@ mod planar_tests {assert_eq!(out.len(), 1, "{what}: {out:?}");let lp = &out[0].outer;let shortest = lp.segs.iter().map(Seg2::length).fold(f64::MAX, f64::min);- assert!(out[0].holes.is_empty() && lp.segs.len() == 7 && shortest > 2.9, "{what}: {} edges, shortest {shortest:e}", lp.segs.len());+ assert!(out[0].holes.is_empty() && lp.segs.len() == 6 && shortest > 2.9, "{what}: {} edges, shortest {shortest:e}", lp.segs.len());assert!((out[0].area() - want).abs() < 1e-6, "{what}: {} vs {want}", out[0].area());}};diff --git a/crates/kernel/src/sew.rs b/crates/kernel/src/sew.rsindex 81a449426b..8ebad8631e 100644--- a/crates/kernel/src/sew.rs+++ b/crates/kernel/src/sew.rs@@ -13,7 +13,7 @@use std::collections::HashMap;use std::sync::Arc;-use solidcraft_geom::brep::eval::SurfaceEval;+use solidcraft_geom::brep::eval::{SurfaceEval, face_flux};use solidcraft_geom::brep::{self as b, Curve2, pcurve};use solidcraft_geom::{Ring, Vec3};@@ -1650,53 +1650,6 @@ fn domain_of(surface: &b::Surface, pcs: &[Vec<Curve2>]) -> Option<[[f64; 2]; 2]>Some(out)}-/// 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),-];--/// Pieces each pcurve is integrated in, and how many Gauss panels cover a v range.-const FLUX_PIECES: usize = 32;-const FLUX_PANELS: usize = 4;--/// The flux of `field` through a face, `∫∫ field(S)·(S_u × S_v) du dv` over the (u, v) region its-/// loops (record convention, each use its pcurve and direction) bound, by Green's theorem:-/// `∮ −G du` with `G(u, v) = ∫ field·N ds` from `v0` to `v`. A quadrature for the sign of a-/// shell's volume (`field = p / 3`) or a winding number, which only has to be right to well-/// under a half: no geometry is made from it. Loops round a periodic direction need no seam-/// edge, as a seam's two runs at constant u add nothing to `∮ G du`.-fn face_flux(s: &SurfaceEval, v0: f64, loops: &[Vec<(&Curve2, bool)>], field: &dyn Fn(Vec3) -> Vec3) -> Option<f64> {- let g = |u: f64, v: f64| -> Option<f64> {- let (mut sum, h) = (0.0, (v - v0) / FLUX_PANELS as f64);- for panel in 0..FLUX_PANELS {- let a = v0 + h * panel as f64;- for (x, w) in GAUSS4 {- let t = a + 0.5 * h * (x + 1.0);- let (p, su, sv) = s.derivs(u, t)?;- sum += 0.5 * h * w * field(p).dot(su.cross(sv));- }- }- sum.is_finite().then_some(sum)- };- let mut total = 0.0;- for (c, forward) in loops.iter().flatten() {- let [t0, t1] = c.interval()?;- let at = |k: f64| {- let f = k / FLUX_PIECES as f64;- // Exactly the ends at f = 0 and 1, whatever the interval's rounding.- c.eval(if *forward { t0 * (1.0 - f) + t1 * f } else { t1 * (1.0 - f) + t0 * f })- };- for k in 0..FLUX_PIECES {- let (a, m, z) = (at(k as f64)?, at(k as f64 + 0.5)?, at(k as f64 + 1.0)?);- total -= g(m[0], m[1])? * (z[0] - a[0]);- }- }- total.is_finite().then_some(total)-}-#[cfg(test)]mod tests {use super::*;diff --git a/crates/step/src/topology.rs b/crates/step/src/topology.rsindex 35e85c6859..82916afed3 100644--- a/crates/step/src/topology.rs+++ b/crates/step/src/topology.rs@@ -38,7 +38,7 @@ use std::collections::{HashMap, HashSet};use std::f64::consts::TAU;use solidcraft_geom::Vec3;-use solidcraft_geom::brep::eval::{CurveEval, SurfaceEval};+use solidcraft_geom::brep::eval::{CurveEval, SurfaceEval, face_flux};use solidcraft_geom::brep::pcurve::{self, EdgeUse, TrimEdge, TrimFace, TrimUse, Trims};use solidcraft_geom::brep::{self, Brep, Curve as BCurve, Curve2, Edge, EdgeUseRef, Face, Frame, Loop, Natural, OrientedEdge, OrientedFace, Region, Shell,@@ -950,6 +950,7 @@ impl<'b, 'a> Builder<'b, 'a> {if at_poles > 0 {notes.push(format!("{at_poles} edges split where they pass through a face's pole"));}+ self.start_splines_clear_of_faces()?;let seams = self.add_seams()?;if seams > 0 {notes.push(format!("{seams} seam edges added to faces that wind around their surface"));@@ -1033,6 +1034,42 @@ impl<'b, 'a> Builder<'b, 'a> {// Regions: which shells are closed (every edge used at least twice among its faces).let closed: Vec<bool> = shells.iter().map(|s| self.closed(s)).collect();+ // A void's faces face into the cavity, out of the material: it encloses volume of the+ // opposite sign to the outer shell's. The ORIENTED_CLOSED_SHELL flag alone doesn't say+ // so: some exporters write .F. over a shell already facing into the cavity (#3730),+ // SolidCraft .T.; read by the flag, such a void added its cavity's volume to the solid's.+ // A void enclosing volume of the outer shell's sign is turned inside out, the signs the+ // faces' own surfaces and pcurves give (`face_flux` of p / 3, the divergence theorem).+ let shells = if kind == Kind::Voids && closed.iter().all(|c| *c) {+ let volume = |s: &[(u32, bool)]| -> Option<f64> {+ let mut sum = 0.0;+ for &(f, forward) in s {+ let face = self.faces.get(f as usize)?;+ let on = face_forms.get(f as usize)?.as_ref().unwrap_or(&face.surface);+ let eval = SurfaceEval::new(on).ok()?;+ let edge_loops = face.loops.iter().filter_map(|l| match l {+ LoopB::Edges(es) => Some(es),+ LoopB::Vertex(_) => None,+ });+ let uses: Vec<Vec<(&Curve2, bool)>> =+ edge_loops.zip(pcs.get(f as usize)?).map(|(es, pc)| pc.iter().zip(es).map(|(c, (_, fwd))| (c, *fwd)).collect()).collect();+ let flux = face_flux(&eval, domains.get(f as usize)?[1][0], &uses, &|p| p * (1.0 / 3.0))?;+ sum += if forward { flux } else { -flux };+ }+ sum.is_finite().then_some(sum)+ };+ let outside = shells.first().and_then(|s| volume(s));+ shells+ .into_iter()+ .enumerate()+ .map(|(k, s)| match (outside, k > 0) {+ (Some(o), true) if volume(&s).is_some_and(|v| v * o > 0.0) => s.into_iter().map(|(f, fwd)| (f, !fwd)).collect(),+ _ => s,+ })+ .collect()+ } else {+ shells+ };let mut regions = vec![Region { shells: Vec::new(), void: false }];match kind {Kind::Solid | Kind::Voids => {diff --git a/crates/step/src/topology/seams.rs b/crates/step/src/topology/seams.rsindex 46dd4f9b35..3b9f3b488e 100644--- a/crates/step/src/topology/seams.rs+++ b/crates/step/src/topology/seams.rs@@ -151,7 +151,131 @@ fn meridian(profile: &BCurve, o: Vec3, k: Vec3, angle: f64) -> R<BCurve> {})}+/// A B-spline surface closed around u (its first and last control columns the same, `period`+/// its knot width) started at `s` instead, exactly: `s` inserted to full multiplicity, then the+/// piece from `s` to the end followed by the piece from the start to `s`, moved on by a period.+/// The same points at parameters a period apart before `s`; `None` for another surface or an `s`+/// outside the open domain.+fn restarted(surface: &BSurface, s: f64, period: f64) -> Option<BSurface> {+ use solidcraft_geom::bspline::{HPoint, segment};+ let (u_knots, v_knots, rows): (&Vec<f64>, &Vec<f64>, Vec<Vec<HPoint>>) = match surface {+ BSurface::Spline { u_knots, v_knots, points } => {+ (u_knots, v_knots, points.iter().map(|r| r.iter().map(|p| HPoint { x: p[0], y: p[1], z: p[2], w: 1.0 }).collect()).collect())+ }+ BSurface::RationalSpline { u_knots, v_knots, homogeneous } => {+ (u_knots, v_knots, homogeneous.iter().map(|r| r.iter().map(|h| HPoint { x: h[0], y: h[1], z: h[2], w: h[3] }).collect()).collect())+ }+ _ => return None,+ };+ let n = rows.len();+ let p = u_knots.len().checked_sub(n + 1)?;+ let (u0, u1) = (*u_knots.get(p)?, *u_knots.get(n)?);+ if !(u0 < s && s < u1) || !((u1 - u0 - period).abs() <= 1e-9 * period.max(1.0)) {+ return None;+ }+ // Each v column of control points across u is a curve along u.+ let columns = rows.first()?.len();+ let column = |j: usize| rows.iter().map(|r| r.get(j).copied()).collect::<Option<Vec<HPoint>>>();+ let mut knots: Option<Vec<f64>> = None;+ let mut out: Vec<Vec<HPoint>> = Vec::with_capacity(columns);+ for j in 0..columns {+ let c = column(j)?;+ let (ka, a) = segment(p, u_knots, &c, s, u1).ok()?;+ let (kb, b) = segment(p, u_knots, &c, u0, s).ok()?;+ // The piece after the seam starts where the one before it ends (the closed surface's+ // last column is its first): joined there with multiplicity p.+ let mut k = ka.get(..ka.len() - 1)?.to_vec();+ k.extend(kb.get(p + 1..)?.iter().map(|x| x + period));+ let mut pts = a;+ pts.extend(b.get(1..)?.iter().copied());+ if k.len() != pts.len() + p + 1 || knots.as_ref().is_some_and(|x| *x != k) {+ return None;+ }+ knots = Some(k);+ out.push(pts);+ }+ let u_knots = knots?;+ // Back to rows along u.+ let rows: Vec<Vec<HPoint>> =+ (0..out.first()?.len()).map(|i| out.iter().map(|c| c.get(i).copied()).collect::<Option<Vec<_>>>()).collect::<Option<_>>()?;+ Some(match surface {+ BSurface::Spline { .. } => BSurface::Spline {+ u_knots,+ v_knots: v_knots.clone(),+ points: rows.iter().map(|r| r.iter().map(|h| [h.x / h.w, h.y / h.w, h.z / h.w]).collect()).collect(),+ },+ _ => BSurface::RationalSpline {+ u_knots,+ v_knots: v_knots.clone(),+ homogeneous: rows.iter().map(|r| r.iter().map(|h| [h.x, h.y, h.z, h.w]).collect()).collect(),+ },+ })+}+impl Builder<'_, '_> {+ /// Start every B-spline surface closed around u that a face lies across the start of, without+ /// winding round it, in the middle of the widest stretch of u the face leaves free: the face's+ /// pcurves then run inside the surface's knots, as a kernel's trims have to (one crossing the+ /// start had its pcurve clamped there, mm off its edge). Exact ([`restarted`]). Returns how+ /// many surfaces were started anew.+ pub(super) fn start_splines_clear_of_faces(&mut self) -> R<usize> {+ let mut turned = 0;+ for fi in 0..self.faces.len() {+ let Some(face) = self.faces.get(fi) else { continue };+ if !matches!(face.surface, BSurface::Spline { .. } | BSurface::RationalSpline { .. }) {+ continue;+ }+ let eval = SurfaceEval::new(&face.surface).map_err(|e| e.to_string())?;+ let dom = eval.domain();+ let (Some(period), None, Some((u0, _))) = (dom.period[0], dom.period[1], dom.range[0]) else { continue };+ // How far along u each loop of the face reaches, followed round from its first point+ // (unwrapped across the start); a face winding round is the seams' to handle. The+ // widest loop bounds the face.+ let mut widest: Option<(f64, f64)> = None;+ let mut winds = false;+ for l in &face.loops {+ let LoopB::Edges(es) = l else { continue };+ winds |= self.winding(&eval, es, [Some(period), None])?[0] != 0;+ let mut last: Option<f64> = None;+ let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY);+ for &(e, _) in es {+ let edge = self.edges.get(e as usize).ok_or("edge reference")?;+ let c = CurveEval::new(&edge.curve).map_err(|m| m.to_string())?;+ let [a, b] = edge.interval;+ for k in 0..=SAMPLES {+ let t = a + (b - a) * k as f64 / SAMPLES as f64;+ let Some(q) = c.point(t).and_then(|p| eval.project(p, None, f64::INFINITY)) else { continue };+ let u = last.map_or(q[0], |x| x + wrap_by(q[0] - x, period));+ (lo, hi) = (lo.min(u), hi.max(u));+ last = Some(u);+ }+ }+ if hi - lo > widest.map_or(f64::NEG_INFINITY, |(a, b)| b - a) {+ widest = Some((lo, hi));+ }+ }+ let Some((lo, hi)) = widest else { continue };+ // Across the start: a whole number of periods from it lies inside the reach, clear of+ // its ends (a face that only meets the start there runs inside the knots already).+ let start = u0 + ((hi - u0) / period).floor() * period;+ let clear = 1e-9 * period;+ let crossing = hi - start > clear && start - lo > clear;+ if winds || !crossing || !(hi - lo < period) {+ continue;+ }+ // The middle of the stretch the face leaves free.+ let free = hi + 0.5 * (period - (hi - lo));+ let at = u0 + (free - u0).rem_euclid(period);+ let Some(surface) = restarted(&face.surface, at, period) else { continue };+ if let Some(f) = self.faces.get_mut(fi) {+ f.surface = surface;+ f.extent = None;+ }+ turned += 1;+ }+ Ok(turned)+ }+/// Give every face that winds around its surface without a seam one. Returns how many/// seams were added.pub(super) fn add_seams(&mut self) -> R<usize> {