Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

Wave 184/509: kernel: the general fill's tests read the record; five- and six-sided fills are patches about a centre (and 3 more)

jyviko13bb81b8477b
diff --git a/crates/kernel/src/assemble.rs b/crates/kernel/src/assemble.rs
index 14f7b6afdf..a33f86ad1d 100644
--- a/crates/kernel/src/assemble.rs
+++ b/crates/kernel/src/assemble.rs
@@ -13,9 +13,7 @@
use solidcraft_geom::Vec3;
use solidcraft_geom::brep::eval::{CurveEval, SurfaceEval};
use solidcraft_geom::brep::pcurve::{EdgeUse, pcurves_within};
-use solidcraft_geom::brep::{
- Brep, Curve, Curve2, Edge, EdgeUseRef, Face, Loop, Natural, OrientedEdge, OrientedFace, Region, Shell, Surface, VERSION, Vertex,
-};
+use solidcraft_geom::brep::{Brep, Curve, Curve2, Edge, Face, Loop, Natural, OrientedEdge, OrientedFace, Region, Shell, Surface, VERSION, Vertex};
use crate::body::Body;
use crate::history::{EdgeOrigin, FaceProv};
@@ -206,172 +204,100 @@ impl Assembly {
CurveEval::new(&e.curve).ok()?.point(t)
}
- /// The record of the faces left and added, in canonical order.
+ /// The record of the faces left and added, in canonical order (`Brep::canonical`), checked:
+ /// each face's loops stored relative to its surface's natural normal with their pcurves and
+ /// parameter box, shells and regions as the source's (a region whose outer shell lost every
+ /// face is gone).
pub(crate) fn finish(&self) -> Result<Finished> {
- // Faces in canonical order: by region, shell and the shell's own order (the assembly's).
- let mut by_shell: Vec<Vec<usize>> = vec![Vec::new(); self.shells];
- for (i, f) in self.faces.iter().enumerate() {
- if let Some(f) = f {
- by_shell.get_mut(f.shell).ok_or_else(|| invalid("shell reference"))?.push(i);
- }
+ // The faces left and added, in assembly order, each in its shell.
+ let kept: Vec<usize> = self.faces.iter().enumerate().filter(|(_, f)| f.is_some()).map(|(i, _)| i).collect();
+ let mut by_shell: Vec<Vec<u32>> = vec![Vec::new(); self.shells];
+ let mut faces: Vec<Face> = Vec::with_capacity(kept.len());
+ let mut sides: Vec<bool> = Vec::with_capacity(kept.len());
+ for (k, &i) in kept.iter().enumerate() {
+ let f = self.faces.get(i).and_then(Option::as_ref).ok_or_else(|| invalid("face reference"))?;
+ by_shell.get_mut(f.shell).ok_or_else(|| invalid("shell reference"))?.push(index(k)?);
+ faces.push(self.stored(i, f)?);
+ sides.push(f.natural_out);
}
- let mut shell_order: Vec<usize> = Vec::new();
- let mut shell_new: Vec<Option<u32>> = vec![None; self.shells];
+ let shells = by_shell
+ .iter()
+ .map(|members| {
+ let faces =
+ members.iter().map(|&k| Ok(OrientedFace { face: k, forward: *sides.get(k as usize).ok_or_else(|| invalid("face reference"))? }));
+ Ok(Shell::Faces { faces: faces.collect::<Result<_>>()?, wires: Vec::new() })
+ })
+ .collect::<Result<Vec<_>>>()?;
+ let used = |s: u32| by_shell.get(s as usize).is_some_and(|f| !f.is_empty());
let mut regions: Vec<Region> = Vec::new();
for region in &self.regions {
- let mut shells = Vec::new();
- for &s in &region.shells {
- let s = s as usize;
- if by_shell.get(s).is_none_or(Vec::is_empty) {
- continue;
- }
- let slot = shell_new.get_mut(s).ok_or_else(|| invalid("shell reference"))?;
- let n = match slot {
- Some(n) => *n,
- None => {
- let n = index(shell_order.len())?;
- shell_order.push(s);
- *slot = Some(n);
- n
- }
- };
- shells.push(n);
- }
// A bounded region whose outer shell went is gone (its faces were all taken away).
- if regions.is_empty() || region.shells.first().is_some_and(|s| by_shell.get(*s as usize).is_some_and(|f| !f.is_empty())) {
- regions.push(Region { shells, void: region.void });
+ if regions.is_empty() || region.shells.first().is_some_and(|s| used(*s)) {
+ regions.push(Region { shells: region.shells.iter().copied().filter(|s| used(*s)).collect(), void: region.void });
}
}
- let order: Vec<usize> = shell_order.iter().filter_map(|s| by_shell.get(*s)).flatten().copied().collect();
+ let edges = self.edges.iter().map(|a| Edge {
+ curve: a.curve.clone(),
+ interval: a.interval,
+ vertices: a.vertices,
+ tolerance: a.tolerance,
+ uses: Vec::new(),
+ });
+ let loose =
+ Brep { version: VERSION, tolerance: self.tolerance, regions, shells, faces, edges: edges.collect(), vertices: self.vertices.clone() };
+ let part = loose.canonical().map_err(invalid)?;
+ part.brep.check_geometry().map_err(invalid)?;
let mut face_map: Vec<Option<usize>> = vec![None; self.faces.len()];
- for (k, i) in order.iter().enumerate() {
- if let Some(slot) = face_map.get_mut(*i) {
- *slot = Some(k);
+ for (c, &k) in part.faces.iter().enumerate() {
+ if let Some(slot) = kept.get(k as usize).and_then(|i| face_map.get_mut(*i)) {
+ *slot = Some(c);
}
}
- // Each face's pcurves and stored loops, in canonical face order.
- let mut faces: Vec<Face> = Vec::with_capacity(order.len());
- let mut forward: Vec<bool> = Vec::with_capacity(order.len());
- for &i in &order {
- let f = self.faces.get(i).and_then(Option::as_ref).ok_or_else(|| invalid("face reference"))?;
- let loops: Vec<Vec<AUse>> = f
- .loops
- .iter()
- .map(|l| {
- let mut l = l.clone();
- if !f.natural_out {
- reverse(&mut l);
- }
- l
- })
- .collect();
- let uses: Vec<Vec<EdgeUse<'_>>> = loops
- .iter()
- .map(|l| {
- l.iter()
- .map(|u| {
- let e = self.edges.get(u.edge as usize).ok_or_else(|| invalid("edge reference"))?;
- Ok(EdgeUse {
- edge: u.edge,
- curve: &e.curve,
- interval: e.interval,
- forward: u.forward,
- tolerance: e.tolerance,
- given: u.given.as_ref(),
- })
- })
- .collect::<Result<Vec<_>>>()
- })
- .collect::<Result<_>>()?;
- let pcurves = pcurves_within(&f.surface, &uses, self.tolerance, f.domain).map_err(|e| invalid(format!("face {i}: {e}")))?;
- let domain = domain_of(&f.surface, &pcurves, f.domain).ok_or_else(|| invalid(format!("face {i}: no parameter box")))?;
- let stored = loops
- .iter()
- .zip(&pcurves)
- .map(|(l, pc)| Loop::Edges {
- edges: l.iter().zip(pc).map(|(u, pcurve)| OrientedEdge { edge: u.edge, forward: u.forward, pcurve: pcurve.clone() }).collect(),
- })
- .collect();
- faces.push(Face { surface: f.surface.clone(), domain, loops: stored });
- forward.push(f.natural_out);
- }
- // Edges in first appearance walking faces → loops → uses (backwards in a face whose
- // side in its shell is reversed), with their uses in that order.
- let mut edge_new: Vec<Option<u32>> = vec![None; self.edges.len()];
- let mut edge_order: Vec<usize> = Vec::new();
- let mut walked: Vec<Vec<EdgeUseRef>> = Vec::new();
- for (fi, (f, fw)) in faces.iter().zip(&forward).enumerate() {
- for (li, l) in f.loops.iter().enumerate() {
- let Loop::Edges { edges } = l else { continue };
- let n = edges.len();
- for k in 0..n {
- let p = if *fw { k } else { n - 1 - k };
- let u = edges.get(p).ok_or_else(|| invalid("edge use"))?;
- let slot = edge_new.get_mut(u.edge as usize).ok_or_else(|| invalid("edge reference"))?;
- let ne = match slot {
- Some(ne) => *ne,
- None => {
- let ne = index(edge_order.len())?;
- edge_order.push(u.edge as usize);
- walked.push(Vec::new());
- *slot = Some(ne);
- ne
- }
- };
- let at = EdgeUseRef { face: index(fi)?, r#loop: index(li)?, position: index(p)?, upper: !u.forward };
- walked.get_mut(ne as usize).ok_or_else(|| invalid("edge use"))?.push(at);
- }
- }
- }
- for f in &mut faces {
- for l in &mut f.loops {
- if let Loop::Edges { edges } = l {
- for u in edges {
- u.edge = edge_new.get(u.edge as usize).copied().flatten().ok_or_else(|| invalid("edge reference"))?;
- }
+ Ok(Finished { record: part.brep, faces: face_map, edges: part.edges.iter().map(|e| *e as usize).collect() })
+ }
+
+ /// Face `i` as the record stores it: its loops relative to its surface's natural normal, each
+ /// use with its pcurve (the record's own where the use kept one), and its parameter box.
+ fn stored(&self, i: usize, f: &AFace) -> Result<Face> {
+ let loops: Vec<Vec<AUse>> = f
+ .loops
+ .iter()
+ .map(|l| {
+ let mut l = l.clone();
+ if !f.natural_out {
+ reverse(&mut l);
}
- }
- }
- // Vertices in first appearance walking edges (start, end).
- let mut vertex_new: Vec<Option<u32>> = vec![None; self.vertices.len()];
- let mut vertices: Vec<Vertex> = Vec::new();
- let mut edges: Vec<Edge> = Vec::with_capacity(edge_order.len());
- for (e, uses) in edge_order.iter().zip(walked) {
- let a = self.edges.get(*e).ok_or_else(|| invalid("edge reference"))?;
- let mut ends = [0u32; 2];
- for (slot, v) in ends.iter_mut().zip(a.vertices) {
- let nv = vertex_new.get_mut(v as usize).ok_or_else(|| invalid("vertex reference"))?;
- *slot = match nv {
- Some(n) => *n,
- None => {
- let n = index(vertices.len())?;
- vertices.push(self.vertices.get(v as usize).cloned().ok_or_else(|| invalid("vertex reference"))?);
- *nv = Some(n);
- n
- }
- };
- }
- edges.push(Edge { curve: a.curve.clone(), interval: a.interval, vertices: ends, tolerance: a.tolerance, uses });
- }
- let shells = shell_order
+ l
+ })
+ .collect();
+ let uses: Vec<Vec<EdgeUse<'_>>> = loops
.iter()
- .map(|s| {
- let faces = by_shell
- .get(*s)
- .into_iter()
- .flatten()
- .map(|i| {
- let k = face_map.get(*i).copied().flatten().ok_or_else(|| invalid("face reference"))?;
- Ok(OrientedFace { face: index(k)?, forward: *forward.get(k).ok_or_else(|| invalid("face reference"))? })
+ .map(|l| {
+ l.iter()
+ .map(|u| {
+ let e = self.edges.get(u.edge as usize).ok_or_else(|| invalid("edge reference"))?;
+ Ok(EdgeUse {
+ edge: u.edge,
+ curve: &e.curve,
+ interval: e.interval,
+ forward: u.forward,
+ tolerance: e.tolerance,
+ given: u.given.as_ref(),
+ })
})
- .collect::<Result<Vec<_>>>()?;
- Ok(Shell::Faces { faces, wires: Vec::new() })
+ .collect::<Result<Vec<_>>>()
})
- .collect::<Result<Vec<_>>>()?;
- let record = Brep { version: VERSION, tolerance: self.tolerance, regions, shells, faces, edges, vertices };
- record.validate().map_err(invalid)?;
- record.check_geometry().map_err(invalid)?;
- Ok(Finished { record, faces: face_map, edges: edge_order })
+ .collect::<Result<_>>()?;
+ let pcurves = pcurves_within(&f.surface, &uses, self.tolerance, f.domain).map_err(|e| invalid(format!("face {i}: {e}")))?;
+ let domain = domain_of(&f.surface, &pcurves, f.domain).ok_or_else(|| invalid(format!("face {i}: no parameter box")))?;
+ let stored = loops
+ .iter()
+ .zip(&pcurves)
+ .map(|(l, pc)| Loop::Edges {
+ edges: l.iter().zip(pc).map(|(u, pcurve)| OrientedEdge { edge: u.edge, forward: u.forward, pcurve: pcurve.clone() }).collect(),
+ })
+ .collect();
+ Ok(Face { surface: f.surface.clone(), domain, loops: stored })
}
}
diff --git a/crates/kernel/src/fill_general_tests.rs b/crates/kernel/src/fill_general_tests.rs
index cc1f0f2887..c23e44b467 100644
--- a/crates/kernel/src/fill_general_tests.rs
+++ b/crates/kernel/src/fill_general_tests.rs
@@ -3,64 +3,115 @@
//! against the analytic surface the loop was cut from, or against a quadrature of the fitted
//! surface itself, never against the mesher alone.
-use mt::{BoundedCurve, InnerSpace, ParametricCurve, ParametricSurface, ParametricSurface3D};
+use solidcraft_geom::brep::{self as b, eval::CurveEval, eval::SurfaceEval};
use solidcraft_geom::{Loop2, Plane, Region2, Vec2, Vec3};
-use truck_modeling as mt;
use super::{PATCH_ANGLE_TOL_DEG, PatchReport, PatchSpec, face_tolerance, patch_edges_report};
-use crate::body::{Body, from_p3, p3};
+use crate::body::Body;
use crate::bridge::Continuity;
use crate::{BoolOp, boolean, box_solid, copy_faces, cylinder, extrude, measure, patch_edges, stitch, torus};
-/// The surface's parameters nearest `p`: the nearest of a grid of samples (or `hint`), then
-/// Gauss–Newton within the domain.
-fn nearest(s: &mt::Surface, p: Vec3, hint: Option<(f64, f64)>) -> (f64, f64) {
- let (Some((u0, u1)), Some((v0, v1))) = s.try_range_tuple() else { panic!("a bounded surface") };
- let p = p3(p);
- let (mut u, mut v) = match hint {
- Some(h) => h,
- None => {
- let n = 100;
- let mut best = (f64::MAX, u0, v0);
- for i in 0..=n {
- for j in 0..=n {
- let (u, v) = (u0 + (u1 - u0) * i as f64 / n as f64, v0 + (v1 - v0) * j as f64 / n as f64);
- let d = (s.subs(u, v) - p).magnitude();
- if d < best.0 {
- best = (d, u, v);
+/// A body's faces as surfaces over their parameter boxes, with the (u, v) polygon of each face's
+/// loops (its exact pcurves, sampled).
+struct Faces {
+ faces: Vec<(SurfaceEval, [[f64; 2]; 2], Vec<Vec<[f64; 2]>>)>,
+}
+
+impl Faces {
+ fn of(body: &Body) -> Faces {
+ let r = body.record();
+ let faces = r
+ .faces
+ .iter()
+ .map(|f| {
+ let polys = f
+ .loops
+ .iter()
+ .filter_map(|l| match l {
+ b::Loop::Edges { edges } => Some(
+ edges
+ .iter()
+ .flat_map(|u| {
+ let [t0, t1] = r.edges[u.edge as usize].interval;
+ (0..64).map(move |k| {
+ let x = k as f64 / 64.0;
+ u.pcurve.eval(if u.forward { t0 + (t1 - t0) * x } else { t1 - (t1 - t0) * x }).unwrap()
+ })
+ })
+ .collect(),
+ ),
+ b::Loop::Vertex { .. } => None,
+ })
+ .collect();
+ (SurfaceEval::new(&f.surface).unwrap(), f.domain, polys)
+ })
+ .collect();
+ Faces { faces }
+ }
+
+ /// The face, parameters and point of the fill nearest `p`.
+ fn nearest(&self, p: Vec3) -> (usize, [f64; 2], Vec3) {
+ let mut best: Option<(f64, usize, [f64; 2], Vec3)> = None;
+ for (k, (s, dom, _)) in self.faces.iter().enumerate() {
+ let [[u0, u1], [v0, v1]] = *dom;
+ let Some(uv) = s.project(p, None, f64::INFINITY) else { continue };
+ let uv = [uv[0].clamp(u0, u1), uv[1].clamp(v0, v1)];
+ let q = s.point(uv).unwrap();
+ if best.is_none_or(|(d, ..)| q.dist(p) < d) {
+ best = Some((q.dist(p), k, uv, q));
+ }
+ }
+ let (_, k, uv, q) = best.unwrap();
+ (k, uv, q)
+ }
+
+ /// `∫∫ f(S, S_u × S_v) du dv` over every face's own region (inside its loops' (u, v)
+ /// polygons), by the midpoint rule on an `n × n` grid over each region's box.
+ fn quadrature(&self, n: usize, f: &dyn Fn(Vec3, Vec3) -> f64) -> f64 {
+ let mut sum = 0.0;
+ for (s, _, polys) in &self.faces {
+ let all: Vec<[f64; 2]> = polys.iter().flatten().copied().collect();
+ let (mut lo, mut hi) = ([f64::MAX; 2], [f64::MIN; 2]);
+ for q in &all {
+ lo = [lo[0].min(q[0]), lo[1].min(q[1])];
+ hi = [hi[0].max(q[0]), hi[1].max(q[1])];
+ }
+ let inside = |u: f64, v: f64| {
+ let mut w = false;
+ for poly in polys {
+ for k in 0..poly.len() {
+ let (a, c) = (poly[k], poly[(k + 1) % poly.len()]);
+ if (a[1] > v) != (c[1] > v) && u < a[0] + (v - a[1]) / (c[1] - a[1]) * (c[0] - a[0]) {
+ w = !w;
+ }
+ }
+ }
+ w
+ };
+ let (du, dv) = ((hi[0] - lo[0]) / n as f64, (hi[1] - lo[1]) / n as f64);
+ for i in 0..n {
+ for j in 0..n {
+ let (u, v) = (lo[0] + (i as f64 + 0.5) * du, lo[1] + (j as f64 + 0.5) * dv);
+ if inside(u, v) {
+ let (p, su, sv) = s.derivs(u, v).unwrap();
+ sum += f(p, su.cross(sv)) * du * dv;
}
}
}
- (best.1, best.2)
- }
- };
- for _ in 0..60 {
- let (q, a, b) = (s.subs(u, v), s.uder(u, v), s.vder(u, v));
- let r = q - p;
- let (aa, ab, bb) = (a.dot(a), a.dot(b), b.dot(b));
- let det = aa * bb - ab * ab;
- if det.abs() < 1e-300 {
- break;
}
- let (ga, gb) = (a.dot(r), b.dot(r));
- u = (u - (bb * ga - ab * gb) / det).clamp(u0, u1);
- v = (v - (aa * gb - ab * ga) / det).clamp(v0, v1);
+ sum
}
- (u, v)
}
-fn v3(v: mt::Vector3) -> Vec3 {
- Vec3::new(v.x, v.y, v.z)
-}
-
-/// Points along every edge of the loop: `per` on each.
-fn rim_points(face: &mt::Face, per: usize) -> Vec<Vec3> {
+/// Points along every free edge of the fill (its loop): `per` on each.
+fn rim_points(body: &Body, per: usize) -> Vec<Vec3> {
+ let r = body.record();
let mut out = Vec::new();
- for e in face.boundaries().iter().flat_map(|w| w.edge_iter()) {
- let c = e.oriented_curve();
- let (t0, t1) = c.range_tuple();
+ for e in r.edges.iter().filter(|e| e.uses.len() == 1) {
+ let c = CurveEval::new(&e.curve).unwrap();
+ let [t0, t1] = e.interval;
for k in 0..per {
- out.push(from_p3(c.subs(t0 + (t1 - t0) * (k as f64 + 0.5) / per as f64)));
+ out.push(c.point(t0 + (t1 - t0) * (k as f64 + 0.5) / per as f64).unwrap());
}
}
out
@@ -71,105 +122,54 @@ fn rim_points(face: &mt::Face, per: usize) -> Vec<Vec3> {
/// the whole loop: a fold would show as 180°), and the largest difference between the patch's
/// normal curvature across the loop and `curvature(p)`, the neighbour's.
fn along_the_loop(fill: &Body, normal: &dyn Fn(Vec3) -> Vec3, curvature: &dyn Fn(Vec3) -> f64) -> (f64, f64, f64) {
- let face = fill.solid.face_iter().next().unwrap().clone();
- let s = face.surface();
- let pts = rim_points(&face, 200);
- let mut found = Vec::with_capacity(pts.len());
- let mut hint = None;
- for p in &pts {
- let uv = nearest(&s, *p, hint);
- hint = Some(uv);
- found.push(uv);
- }
+ let faces = Faces::of(fill);
+ let pts = rim_points(fill, 200);
+ let found: Vec<(usize, [f64; 2], Vec3)> = pts.iter().map(|p| faces.nearest(*p)).collect();
+ let patch_normal = |k: usize, uv: [f64; 2]| {
+ let (_, su, sv) = faces.faces[k].0.derivs(uv[0], uv[1]).unwrap();
+ su.cross(sv).normalized().unwrap()
+ };
// One sign for the whole loop: the one most rim points agree with.
- let patch_normal = |(u, v): (f64, f64)| v3(s.normal(u, v));
- let agree: f64 = pts.iter().zip(&found).map(|(p, uv)| patch_normal(*uv).dot(normal(*p)).signum()).sum();
+ let agree: f64 = pts.iter().zip(&found).map(|(p, (k, uv, _))| patch_normal(*k, *uv).dot(normal(*p)).signum()).sum();
let sign = agree.signum();
let (mut gap, mut angle, mut kappa) = (0.0f64, 0.0f64, 0.0f64);
- for (k, (p, &(u, v))) in pts.iter().zip(&found).enumerate() {
- gap = gap.max(from_p3(s.subs(u, v)).dist(*p));
- let n = patch_normal((u, v));
+ for (i, (p, &(k, uv, q))) in pts.iter().zip(&found).enumerate() {
+ gap = gap.max(q.dist(*p));
+ let n = patch_normal(k, uv);
let want = normal(*p) * sign;
angle = angle.max(n.dot(want).clamp(-1.0, 1.0).acos().to_degrees());
// Across the loop: the tangent-plane direction square to the rim.
- let next = pts.get(k + 1).or(pts.get(k.wrapping_sub(1))).copied().unwrap();
+ let next = pts.get(i + 1).or(pts.get(i.wrapping_sub(1))).copied().unwrap();
let t = (next - *p).normalized().unwrap();
let Some(d) = n.cross(t).normalized() else { continue };
- let (su, sv) = (v3(s.uder(u, v)), v3(s.vder(u, v)));
+ let s = &faces.faces[k].0;
+ let (_, su, sv) = s.derivs(uv[0], uv[1]).unwrap();
// d = a·su + b·sv.
let (aa, ab, bb) = (su.dot(su), su.dot(sv), sv.dot(sv));
let det = aa * bb - ab * ab;
- let (a, b) = ((bb * d.dot(su) - ab * d.dot(sv)) / det, (aa * d.dot(sv) - ab * d.dot(su)) / det);
- // The second derivatives by central differences of the surface's own points.
- let h = 1e-3;
- let e = |du: f64, dv: f64| from_p3(s.subs(u + du * h, v + dv * h));
- let suu = (e(1.0, 0.0) - e(0.0, 0.0) * 2.0 + e(-1.0, 0.0)) * (1.0 / (h * h));
- let svv = (e(0.0, 1.0) - e(0.0, 0.0) * 2.0 + e(0.0, -1.0)) * (1.0 / (h * h));
- let suv = (e(1.0, 1.0) - e(1.0, -1.0) - e(-1.0, 1.0) + e(-1.0, -1.0)) * (0.25 / (h * h));
- let second = suu * (a * a) + suv * (2.0 * a * b) + svv * (b * b);
+ let (a, c) = ((bb * d.dot(su) - ab * d.dot(sv)) / det, (aa * d.dot(sv) - ab * d.dot(su)) / det);
+ let (suu, suv, svv) = s.second(uv[0], uv[1]).unwrap();
+ let second = suu * (a * a) + suv * (2.0 * a * c) + svv * (c * c);
kappa = kappa.max((second.dot(want) - curvature(*p)).abs());
}
(gap, angle, kappa)
}
-/// `∫∫ f(S, S_u × S_v) du dv` over the face's own region of its surface (its loop taken into
-/// parameter space by the nearest parameters of points along it), by the midpoint rule on a
-/// `n × n` grid over the region's box: the quadrature the mesher's area is checked against.
-fn quadrature(face: &mt::Face, n: usize, f: &dyn Fn(Vec3, Vec3) -> f64) -> f64 {
- let s = face.surface();
- let mut poly: Vec<(f64, f64)> = Vec::new();
- let mut hint = None;
- for p in rim_points(face, 400) {
- let uv = nearest(&s, p, hint);
- hint = Some(uv);
- poly.push(uv);
- }
- let (mut lo, mut hi) = ((f64::MAX, f64::MAX), (f64::MIN, f64::MIN));
- for &(u, v) in &poly {
- lo = (lo.0.min(u), lo.1.min(v));
- hi = (hi.0.max(u), hi.1.max(v));
- }
- let inside = |u: f64, v: f64| {
- let mut w = false;
- for k in 0..poly.len() {
- let (a, b) = (poly[k], poly[(k + 1) % poly.len()]);
- if (a.1 > v) != (b.1 > v) && u < a.0 + (v - a.1) / (b.1 - a.1) * (b.0 - a.0) {
- w = !w;
- }
- }
- w
- };
- let (du, dv) = ((hi.0 - lo.0) / n as f64, (hi.1 - lo.1) / n as f64);
- let mut sum = 0.0;
- for i in 0..n {
- for j in 0..n {
- let (u, v) = (lo.0 + (i as f64 + 0.5) * du, lo.1 + (j as f64 + 0.5) * dv);
- if inside(u, v) {
- sum += f(from_p3(s.subs(u, v)), v3(s.uder(u, v)).cross(v3(s.vder(u, v)))) * du * dv;
- }
- }
- }
- sum
-}
-
-/// The fill is one face on the open body's own edges, within the fill's tolerance of them; its
-/// mesh has no folded triangle (each faces the way its corners' normals do); and the mesher's
-/// area agrees with a quadrature of the surface over its own region. Returns the area.
+/// The fill is a sheet on the open body's own edges (its free edges lie on the body's edge curves;
+/// a loop of five or more edges is filled by patches about a centre, its edges in halves), within
+/// the fill's tolerance of them; its mesh has no folded triangle (each faces the way its corners'
+/// normals do); and the mesher's area agrees with a quadrature of the surfaces over their own
+/// regions. Returns the area.
fn check_face(name: &str, open: &Body, fill: &Body) -> f64 {
assert!(fill.is_surface());
- assert_eq!(fill.face_count(), 1, "{name}: one face");
- let own: Vec<mt::EdgeID> = open.solid.edge_iter().map(|e| e.id()).collect();
- assert!(fill.solid.edge_iter().all(|e| own.contains(&e.id())), "{name}: an edge that is not the body's");
- let face = fill.solid.face_iter().next().unwrap().clone();
- let s = face.surface();
- let tol = face_tolerance(open);
- let mut off = 0.0f64;
- let mut hint = None;
- for p in rim_points(&face, 64) {
- let uv = nearest(&s, p, hint);
- hint = Some(uv);
- off = off.max(from_p3(s.subs(uv.0, uv.1)).dist(p));
+ assert!(fill.face_count() >= 1, "{name}: a face");
+ let (own, made) = (open.record(), fill.record());
+ for e in made.edges.iter().filter(|e| e.uses.len() == 1) {
+ assert!(own.edges.iter().any(|o| o.curve == e.curve), "{name}: an edge that is not the body's");
}
+ let faces = Faces::of(fill);
+ let tol = face_tolerance(open);
+ let off = rim_points(fill, 64).iter().map(|p| faces.nearest(*p).2.dist(*p)).fold(0.0f64, f64::max);
assert!(off <= tol * 1.01, "{name}: an edge is {off} off the face (tolerance {tol})");
let m = fill.mesh(&crate::MeshTolerance::chord(0.01)).unwrap();
assert!(!m.triangles.is_empty(), "{name}: the face meshes");
@@ -182,8 +182,8 @@ fn check_face(name: &str, open: &Body, fill: &Body) -> f64 {
}
}
let area = measure(fill).unwrap().area;
- let quad = quadrature(&face, 500, &|_, n| n.len());
- eprintln!("{name}: one face, edges within {off:e} (tolerance {tol:e}), mesh area {area:.4}, quadrature {quad:.4}");
+ let quad = faces.quadrature(500, &|_, n| n.len());
+ eprintln!("{name}: {} faces, edges within {off:e} (tolerance {tol:e}), mesh area {area:.4}, quadrature {quad:.4}", fill.face_count());
assert!((area - quad).abs() < 3e-3 * quad, "{name}: mesh area {area} against the surface's {quad}");
area
}
@@ -211,12 +211,16 @@ fn open_tube() -> (Body, Vec<Vec3>) {
/// `body` without its planar faces but those at height `z0` or `z1` (the ends of a cylinder):
/// a cut solid's walls (and ends) as a surface, the faces the cut made taken away.
fn curved_and_ends(body: &Body, ends: &[f64]) -> Body {
- let drop: Vec<usize> = body
- .solid
- .face_iter()
+ let r = body.record();
+ let drop: Vec<usize> = r
+ .faces
+ .iter()
.enumerate()
- .filter(|(_, f)| match f.surface() {
- mt::Surface::Plane(p) => !ends.iter().any(|z| (p.origin().z - z).abs() < 1e-9 && p.normal().z.abs() > 1.0 - 1e-12),
+ .filter(|(_, f)| match &f.surface {
+ b::Surface::Plane { origin, u_axis, v_axis } => {
+ let n = Vec3::from(*u_axis).cross(Vec3::from(*v_axis)).normalized().unwrap();
+ !ends.iter().any(|z| (origin[2] - z).abs() < 1e-9 && n.z.abs() > 1.0 - 1e-12)
+ }
_ => false,
})
.map(|(i, _)| i)
@@ -229,22 +233,14 @@ fn curved_and_ends(body: &Body, ends: &[f64]) -> Body {
/// A point on each edge that bounds only one face of `body` (its free edges): the middle of
/// each, where the edge picker samples it.
fn free_edge_points(body: &Body) -> Vec<Vec3> {
- let mut uses: std::collections::HashMap<mt::EdgeID, (usize, mt::Edge)> = std::collections::HashMap::new();
- for f in body.solid.face_iter() {
- for e in f.boundaries().iter().flat_map(|w| w.edge_iter()) {
- uses.entry(e.id()).or_insert((0, e.clone())).0 += 1;
- }
- }
- let mut points = uses
- .values()
- .filter(|(n, _)| *n == 1)
- .map(|(_, e)| {
- let c = e.curve();
- let (t0, t1) = c.range_tuple();
- from_p3(c.subs(0.5 * (t0 + t1)))
- })
+ let r = body.record();
+ let mut points = r
+ .edges
+ .iter()
+ .filter(|e| e.uses.len() == 1)
+ .map(|e| CurveEval::new(&e.curve).unwrap().point(0.5 * (e.interval[0] + e.interval[1])).unwrap())
.collect::<Vec<_>>();
- // In a fixed order, whatever the map's.
+ // In a fixed order.
points.sort_by(|a, b| (a.z, a.y, a.x).partial_cmp(&(b.z, b.y, b.x)).unwrap());
points
}
@@ -283,8 +279,7 @@ fn an_opened_tube_end_capped_g1_and_g2_meets_the_wall() {
// patch (∫∫ (z − 30)·n_z dA), independent of the mesher.
let closed = stitch(&[&open, &fill], 0.0).unwrap();
assert!(!closed.is_surface(), "{name}: the cap closes the tube");
- let face = fill.solid.face_iter().next().unwrap().clone();
- let dome = quadrature(&face, 500, &|p, n| (p.z - 30.0) * n.z).abs();
+ let dome = Faces::of(&fill).quadrature(500, &|p, n| (p.z - 30.0) * n.z).abs();
let (got, want) = (measure(&closed).unwrap().volume, std::f64::consts::PI * 100.0 * 30.0 + dome);
eprintln!("{name}: sealed volume {got:.3}, tube + dome {want:.3}");
assert!((got - want).abs() < 2e-4 * want, "{name}: {got} vs {want}");
@@ -320,16 +315,15 @@ fn a_window_cut_through_a_cylinder_wall_past_half_way_fills_g1_close_to_the_cyli
let (gap, angle, _) = along_the_loop(&fill, &radial, &|_| 0.0);
eprintln!("{name}: along the window (1600 points): within {gap:e}, normal within {angle:.5}° of the wall's");
// How far the fill strays from the cylinder it replaces, inside.
- let face = fill.solid.face_iter().next().unwrap().clone();
- let s = face.surface();
- let (Some((u0, u1)), Some((v0, v1))) = s.try_range_tuple() else { panic!() };
let mut stray = 0.0f64;
- for i in 0..=40 {
- for j in 0..=40 {
- let p = from_p3(s.subs(u0 + (u1 - u0) * i as f64 / 40.0, v0 + (v1 - v0) * j as f64 / 40.0));
- let ang = p.y.atan2(p.x);
- if ang.abs() < half - 0.05 && p.z > 15.5 && p.z < 24.5 {
- stray = stray.max((Vec2::new(p.x, p.y).len() - 10.0).abs());
+ for (s, [[u0, u1], [v0, v1]], _) in &Faces::of(&fill).faces {
+ for i in 0..=40 {
+ for j in 0..=40 {
+ let p = s.point([u0 + (u1 - u0) * i as f64 / 40.0, v0 + (v1 - v0) * j as f64 / 40.0]).unwrap();
+ let ang = p.y.atan2(p.x);
+ if ang.abs() < half - 0.05 && p.z > 15.5 && p.z < 24.5 {
+ stray = stray.max((Vec2::new(p.x, p.y).len() - 10.0).abs());
+ }
}
}
}
@@ -389,11 +383,12 @@ fn pentagon_window() -> (Body, Vec<Vec3>) {
}
#[test]
-fn a_five_sided_window_fills_as_one_face_g1_and_through_a_point() {
+fn a_five_sided_window_fills_g1_and_through_a_point() {
let (open, rim) = pentagon_window();
let (fill, r) = patch_edges_report(&open, &rim, &spec(Continuity::G1)).unwrap();
report("pentagon g1", &r);
- assert!(fill.edge_count() >= 5, "the rim's own edges (five, or more where a seam splits one)");
+ // Five patches about a centre: each rim edge in two halves, and five spokes.
+ assert!(fill.face_count() == 5 && fill.edge_count() >= 15, "five patches on the rim's halves and five spokes");
check_face("pentagon g1", &open, &fill);
let (gap, angle, _) = along_the_loop(&fill, &radial, &|_| 0.0);
eprintln!("pentagon g1: along the rim: within {gap:e}, normal within {angle:.5}° of the wall's");
@@ -406,9 +401,7 @@ fn a_five_sided_window_fills_as_one_face_g1_and_through_a_point() {
let (fill, r) = patch_edges_report(&open, &rim, &spec).unwrap();
report(&name, &r);
check_face(&name, &open, &fill);
- let s = fill.solid.face_iter().next().unwrap().surface();
- let (u, v) = nearest(&s, point, None);
- let off = from_p3(s.subs(u, v)).dist(point);
+ let off = Faces::of(&fill).nearest(point).2.dist(point);
eprintln!("{name}: the point is {off:e} off the surface");
assert!(off <= face_tolerance(&open), "{name}: {off}");
}
@@ -431,17 +424,14 @@ fn a_hexagonal_rim_fills_through_a_point_and_g1_to_walls_meeting_at_angles_holds
let open = copy_faces(&solid, &keep).unwrap();
let plain = patch_edges(&open, &rim).unwrap();
let sealed = |f: &Body| measure(&stitch(&[&open, f], 0.0).unwrap()).unwrap().volume;
- // Six sides, G0, through a point 3 mm above the middle of the plain fill: one face.
- let s = plain.solid.face_iter().next().unwrap().surface();
- let (u, v) = nearest(&s, Vec3::new(0.0, 0.0, 12.0), None);
- let point = from_p3(s.subs(u, v)) + Vec3::Z * 3.0;
+ // Six sides, G0, through a point 3 mm above the middle of the plain fill: six patches about
+ // a centre.
+ let point = Faces::of(&plain).nearest(Vec3::new(0.0, 0.0, 12.0)).2 + Vec3::Z * 3.0;
let (lifted, r) = patch_edges_report(&open, &rim, &PatchSpec { points: vec![point], ..PatchSpec::default() }).unwrap();
report("hexagon through a point", &r);
- assert_eq!(lifted.edge_count(), 6, "the rim's own six edges");
+ assert_eq!((lifted.face_count(), lifted.edge_count()), (6, 18), "six patches on the rim's twelve halves and six spokes");
check_face("hexagon through a point", &open, &lifted);
- let s = lifted.solid.face_iter().next().unwrap().surface();
- let (u, v) = nearest(&s, point, None);
- let off = from_p3(s.subs(u, v)).dist(point);
+ let off = Faces::of(&lifted).nearest(point).2.dist(point);
eprintln!("hexagon through a point: the point is {off:e} off the surface; sealed {:.2} against {:.2} plain", sealed(&lifted), sealed(&plain));
assert!(off <= face_tolerance(&open) && sealed(&lifted) > sealed(&plain));
// G1 to the walls: at a corner no surface is tangent to both walls (its tangent plane there
@@ -491,9 +481,7 @@ fn per_edge_continuity_and_hostile_specs() {
check_face("pentagon g1 crown 0.1", &open, &full);
let (_, angle, _) = along_the_loop(&full, &radial, &|_| 0.0);
let middle = |b: &Body| {
- let s = b.solid.face_iter().next().unwrap().surface();
- let (u, v) = nearest(&s, Vec3::new(10.0, 0.0, 20.0), None);
- let p = from_p3(s.subs(u, v));
+ let p = Faces::of(b).nearest(Vec3::new(10.0, 0.0, 20.0)).2;
Vec2::new(p.x, p.y).len()
};
let (a, b) = (middle(&plain), middle(&full));
diff --git a/crates/kernel/src/loft_rails_tests.rs b/crates/kernel/src/loft_rails_tests.rs
index 4755dfee2b..a978100eb8 100644
--- a/crates/kernel/src/loft_rails_tests.rs
+++ b/crates/kernel/src/loft_rails_tests.rs
@@ -42,15 +42,15 @@ fn volume(b: &crate::Body) -> f64 {
b.volume_at(1e-4).unwrap()
}
-/// How far `p` is from the nearest face of the body.
+/// How far `p` is from the nearest face's surface of the body.
fn off(b: &crate::Body, p: Vec3) -> f64 {
- use truck_modeling::{ParametricSurface, SearchNearestParameter};
- b.solid
- .face_iter()
+ b.record()
+ .faces
+ .iter()
.filter_map(|f| {
- let s = f.surface();
- let (u, v) = s.search_nearest_parameter(crate::body::p3(p), None, 100)?;
- Some(crate::body::from_p3(s.subs(u, v)).dist(p))
+ let s = solidcraft_geom::brep::eval::SurfaceEval::new(&f.surface).ok()?;
+ let uv = s.project(p, None, f64::INFINITY)?;
+ Some(s.point(uv)?.dist(p))
})
.fold(f64::INFINITY, f64::min)
}
diff --git a/crates/kernel/src/surface_second_derivative_tests.rs b/crates/kernel/src/surface_second_derivative_tests.rs
index 76265437f8..9509d98e1e 100644
--- a/crates/kernel/src/surface_second_derivative_tests.rs
+++ b/crates/kernel/src/surface_second_derivative_tests.rs
@@ -1,36 +1,33 @@
-//! The vendored truck-geometry's second derivatives of B-spline and NURBS surfaces (`uuder`,
-//! `vvder`) against finite differences of the surface itself, for degrees 2 to 5. Upstream's
-//! were short of the factor p − 1, so every curvature read from a cubic surface came out half its
-//! value (#763: a G2 boundary surface measured half the cylinder's curvature it does carry).
-//! These pin the vendored fix, so a refresh of the crate can't quietly bring the error back.
+//! The record evaluator's second derivatives of B-spline and NURBS surfaces
+//! (`SurfaceEval::second`) against finite differences of the surface itself, for degrees 2 to 5:
+//! every curvature the kernel reads (continuity, the G2 fill's frames) comes from them (#763: a G2
+//! boundary surface once measured half the cylinder's curvature it does carry).
use solidcraft_geom::Vec3;
-use truck_modeling as mt;
-use truck_modeling::ParametricSurface;
+use solidcraft_geom::brep::{Surface, eval::SurfaceEval};
-use crate::body::from_p3;
-
-/// A degree-`p` × degree-`q` surface on a 5 × 6 net with an interior knot each way, bent in z.
-fn surface(p: usize, q: usize) -> mt::BSplineSurface<mt::Point3> {
+/// A degree-`p` × degree-`q` surface on a net of `p + 3` × `q + 3` points with interior knots each
+/// way, bent in z: its knots and points (`rows[i][j]`, i along u).
+fn net(p: usize, q: usize) -> (Vec<f64>, Vec<f64>, Vec<Vec<[f64; 3]>>) {
let knots = |d: usize, n: usize| {
let inner: Vec<f64> = (1..n - d).map(|k| k as f64 / (n - d) as f64).collect();
let mut k = vec![0.0; d + 1];
k.extend(inner);
k.extend(vec![1.0; d + 1]);
- mt::KnotVec::from(k)
+ k
};
let (nu, nv) = (p + 3, q + 3);
- let rows: Vec<Vec<mt::Point3>> = (0..nu)
+ let rows = (0..nu)
.map(|i| {
(0..nv)
.map(|j| {
let (x, y) = (i as f64 * 2.0, j as f64 * 1.5);
- mt::Point3::new(x + 0.3 * y, y, 0.4 * x * x - 0.2 * y * y + 0.1 * x * y)
+ [x + 0.3 * y, y, 0.4 * x * x - 0.2 * y * y + 0.1 * x * y]
})
.collect()
})
.collect();
- mt::BSplineSurface::new((knots(p, nu), knots(q, nv)), rows)
+ (knots(p, nu), knots(q, nv), rows)
}
/// Second differences of `f` along the parameter line, central inside and one-sided at the ends.
@@ -45,34 +42,35 @@ fn second(f: impl Fn(f64) -> Vec3, t: f64) -> Vec3 {
}
}
-fn v3(x: mt::Vector3) -> Vec3 {
- Vec3::new(x.x, x.y, x.z)
+/// The surface's second derivatives along u and v at each `(u, v)` against finite differences.
+fn check(s: &SurfaceEval, at: &[(f64, f64)], what: &str) {
+ for &(u, v) in at {
+ let uu = second(|t| s.point([t, v]).unwrap(), u);
+ let vv = second(|t| s.point([u, t]).unwrap(), v);
+ let (suu, _, svv) = s.second(u, v).unwrap();
+ let scale = uu.len().max(vv.len()).max(1.0);
+ assert!(suu.dist(uu) < 1e-4 * scale, "{what}: S_uu at ({u}, {v}): {suu:?} vs {uu:?}");
+ assert!(svv.dist(vv) < 1e-4 * scale, "{what}: S_vv at ({u}, {v}): {svv:?} vs {vv:?}");
+ }
}
#[test]
fn bspline_surface_second_derivatives_match_finite_differences() {
for p in 2..=5 {
for q in 2..=5 {
- let s = surface(p, q);
- for (u, v) in [(0.0, 0.0), (0.37, 0.0), (0.5, 0.61), (1.0, 0.2), (0.13, 1.0)] {
- let uu = second(|t| from_p3(s.subs(t, v)), u);
- let vv = second(|t| from_p3(s.subs(u, t)), v);
- let scale = uu.len().max(vv.len()).max(1.0);
- assert!(v3(s.uuder(u, v)).dist(uu) < 1e-4 * scale, "degree ({p}, {q}) uuder at ({u}, {v}): {:?} vs {uu:?}", s.uuder(u, v));
- assert!(v3(s.vvder(u, v)).dist(vv) < 1e-4 * scale, "degree ({p}, {q}) vvder at ({u}, {v}): {:?} vs {vv:?}", s.vvder(u, v));
- }
+ let (u_knots, v_knots, points) = net(p, q);
+ let s = SurfaceEval::new(&Surface::Spline { u_knots, v_knots, points }).unwrap();
+ check(&s, &[(0.0, 0.0), (0.37, 0.0), (0.5, 0.61), (1.0, 0.2), (0.13, 1.0)], &format!("degree ({p}, {q})"));
}
}
}
-/// A rational surface's second derivatives come from its homogeneous B-spline's: they are right
-/// too.
+/// A rational surface's second derivatives come from its homogeneous B-spline's by the quotient
+/// rule: they are right too.
#[test]
fn nurbs_surface_second_derivatives_match_finite_differences() {
- let b = surface(3, 3);
- let (ku, kv) = b.knot_vecs().clone();
- let rows: Vec<Vec<mt::Vector4>> = b
- .control_points()
+ let (u_knots, v_knots, points) = net(3, 3);
+ let homogeneous = points
.iter()
.enumerate()
.map(|(i, row)| {
@@ -80,17 +78,11 @@ fn nurbs_surface_second_derivatives_match_finite_differences() {
.enumerate()
.map(|(j, p)| {
let w = 1.0 + 0.3 * ((i + 2 * j) % 3) as f64;
- mt::Vector4::new(p.x * w, p.y * w, p.z * w, w)
+ [p[0] * w, p[1] * w, p[2] * w, w]
})
.collect()
})
.collect();
- let s = mt::NurbsSurface::new(mt::BSplineSurface::new((ku, kv), rows));
- for (u, v) in [(0.0, 0.0), (0.37, 0.0), (0.5, 0.61), (1.0, 0.2)] {
- let uu = second(|t| from_p3(s.subs(t, v)), u);
- let vv = second(|t| from_p3(s.subs(u, t)), v);
- let scale = uu.len().max(vv.len()).max(1.0);
- assert!(v3(s.uuder(u, v)).dist(uu) < 1e-4 * scale, "uuder at ({u}, {v}): {:?} vs {uu:?}", s.uuder(u, v));
- assert!(v3(s.vvder(u, v)).dist(vv) < 1e-4 * scale, "vvder at ({u}, {v}): {:?} vs {vv:?}", s.vvder(u, v));
- }
+ let s = SurfaceEval::new(&Surface::RationalSpline { u_knots, v_knots, homogeneous }).unwrap();
+ check(&s, &[(0.0, 0.0), (0.37, 0.0), (0.5, 0.61), (1.0, 0.2)], "rational");
}