diff --git a/crates/kernel/src/blend.rs b/crates/kernel/src/blend.rs
index 209435a3b..f1cc3c452 100644
--- a/crates/kernel/src/blend.rs
+++ b/crates/kernel/src/blend.rs
@@ -228,17 +228,123 @@ pub fn fillet_setback(body: &Body, edges: &[Vec3], radius: f64, setbacks: &[(Vec
crate::blend_smlib::fillet_setback(body, edges, radius, setbacks).and_then(|b| closed(body, b))
}
-/// [`fillet`] whose corners where three blended edges meet are G2 patches. SMLib's fillet
-/// corners are a sphere or a Coons patch that meets the rounds tangentially, so this is refused
-/// rather than quietly given those corners; [`fillet`] (the default) is unchanged.
-pub fn fillet_g2_corners(body: &Body, edges: &[Vec3], radius: f64) -> Result
{
+/// [`fillet`] whose corners where three or more rounded edges meet are G2 patches
+/// ([`crate::corner_g2`]): each such corner is set back, `setbacks` naming a corner by a point at
+/// its vertex and the distance its patch starts along each edge there (the others take
+/// [`crate::DEFAULT_SETBACK_FACTOR`] times the radius), SMLib leaves it open, and a patch that
+/// meets the rounds and the faces round it to the second order fills it. The faces are sewn
+/// into one solid. Without such a corner this is [`fillet`]. Refused: a corner where an edge is
+/// not rounded (SMLib sets back only corners where all are), a setback that does not reach past
+/// where the rounds would meet, a hole that is no height field over its plane or a patch that
+/// does not meet its neighbours within the tolerances.
+pub fn fillet_g2_corners(body: &Body, edges: &[Vec3], radius: f64, setbacks: &[(Vec3, f64)]) -> Result {
let _span = solidcraft_profile::span("kernel", "fillet_g2_corners");
body.require_brep("fillet")?;
if !(radius.is_finite() && radius > 0.0) {
return Err(KernelError::Invalid("the blend radius must be finite and positive".into()));
}
- let _ = edges;
- Err(crate::blend_smlib::unsupported("a fillet with G2 corner patches"))
+ let (picked, _) = crate::blend_smlib::picked_edges(body, edges)?;
+ let rec = body.record();
+ let picked: BTreeSet = picked.into_iter().collect();
+ // Each vertex's edges (a closed edge's one vertex once).
+ let mut at: std::collections::BTreeMap> = std::collections::BTreeMap::new();
+ for (i, e) in rec.edges.iter().enumerate() {
+ if e.uses.is_empty() {
+ continue;
+ }
+ for v in e.vertices {
+ at.entry(v).or_default().insert(i);
+ }
+ }
+ let point = |v: u32| rec.vertices.get(v as usize).map(|x| v3(x.point));
+ let mut corners: Vec = Vec::new();
+ for (v, around) in &at {
+ let rounded = around.iter().filter(|e| picked.contains(e)).count();
+ if rounded < 3 {
+ continue;
+ }
+ let p = point(*v).ok_or_else(|| KernelError::Failed("fillet: a vertex reference".into()))?;
+ if rounded < around.len() {
+ return Err(unsupported(&format!(
+ "a G2 corner at ({:.3}, {:.3}, {:.3}) where an edge is not rounded (the corner is set back, and SMLib sets back only a corner where every edge is)",
+ p.x, p.y, p.z
+ )));
+ }
+ corners.push(p);
+ }
+ if corners.is_empty() {
+ return fillet(body, edges, radius);
+ }
+ // Each corner's setback: the one given at its vertex, else the default.
+ let reach = body.size() * 0.05 + 1e-3;
+ let mut distance = vec![crate::corner_g2::DEFAULT_SETBACK_FACTOR * radius; corners.len()];
+ for (p, d) in setbacks {
+ let k = corners
+ .iter()
+ .enumerate()
+ .map(|(k, c)| (c.dist(*p), k))
+ .filter(|(d, _)| *d <= reach)
+ .min_by(|a, b| a.0.total_cmp(&b.0))
+ .map(|(_, k)| k)
+ .ok_or_else(|| {
+ KernelError::Invalid(format!(
+ "the setback at ({:.3}, {:.3}, {:.3}) names no G2 corner (a vertex where three or more rounded edges meet)",
+ p.x, p.y, p.z
+ ))
+ })?;
+ if let Some(slot) = distance.get_mut(k) {
+ *slot = *d;
+ }
+ }
+ let set_back: Vec<(Vec3, f64)> = corners.iter().copied().zip(distance).collect();
+ let open = crate::blend_smlib::fillet_setback_open(body, edges, radius, &set_back)?;
+ let mut patches = Vec::with_capacity(open.holes.len());
+ for hole in &open.holes {
+ let (patch, _) = crate::corner_g2::corner_patch(&open.sheet, hole, radius)?;
+ patches.push(patch);
+ }
+ let mut parts: Vec<&Body> = vec![&open.sheet];
+ parts.extend(patches.iter());
+ let sewn = crate::stitch(&parts, 0.0)?;
+ let open_shells = sewn.validity();
+ if !open_shells.is_empty() {
+ return Err(KernelError::Failed(format!("fillet: the G2 corners do not close the body: {}", open_shells.join("; "))));
+ }
+ let history = corner_history(&sewn, body, &open.sheet, &patches);
+ closed(body, sewn.with_checked_history(history, &crate::record::counts(&[body])))
+}
+
+/// The history of the sewn G2-cornered fillet over `[body]`: the sewing's history (over the
+/// sheet and the patches) carried through the sheet's (over the body); each patch face made from
+/// the edges whose rounds meet at its corner, as SMLib's own corner patch is, each of its edges
+/// the sheet's.
+fn corner_history(sewn: &Body, body: &Body, sheet: &Body, patches: &[Body]) -> Option {
+ use crate::history::{EdgeOrigin, FaceOrigin};
+ let outer = sewn.history()?.clone();
+ let inner = sheet.history()?;
+ let mut parts = vec![inner.clone()];
+ for patch in patches {
+ let own = patch.history()?;
+ // The patch's face comes from the rounded edges the sheet's faces beside it come from.
+ let mut origins: BTreeSet = BTreeSet::new();
+ for e in &own.edges {
+ for o in &e.origins {
+ let EdgeOrigin::Edge { edge, .. } = o else { continue };
+ for f in inner.edges.get(*edge).map(|x| x.faces.as_slice()).unwrap_or_default() {
+ let beside = inner.faces.get(*f).map(|x| x.origins.as_slice()).unwrap_or_default();
+ origins.extend(beside.iter().copied().filter(|g| matches!(g, FaceOrigin::Edge { .. })));
+ }
+ }
+ }
+ let mut h = own.clone().substituted(0, inner).ok()?;
+ for f in &mut h.faces {
+ *f = crate::record::generated(origins.iter().copied().collect());
+ }
+ parts.push(h);
+ }
+ let h = outer.over(&parts.iter().collect::>()).ok()?;
+ h.check_counts((sewn.face_count(), sewn.edge_count()), &crate::record::counts(&[body])).ok()?;
+ Some(h)
}
/// The step of the radius search: three significant digits of the requested radius.
diff --git a/crates/kernel/src/blend_smlib.rs b/crates/kernel/src/blend_smlib.rs
index 64096cfb7..b7e2c14e0 100644
--- a/crates/kernel/src/blend_smlib.rs
+++ b/crates/kernel/src/blend_smlib.rs
@@ -43,6 +43,22 @@ pub(crate) fn fillet_setback(body: &Body, edges: &[Vec3], radius: f64, setbacks:
imp::blend_setback(body, edges, &vec![radius; edges.len()], setbacks)
}
+/// A set-back blend whose corners SMLib leaves open ([`fillet_setback_open`]): the sheet, its
+/// history over the body it was made from, and per corner the edges round its hole in order,
+/// each its index in the sheet's edge order with whether the face beside it runs it forwards
+/// (counter-clockwise about the solid's outward normal).
+pub(crate) struct OpenCorners {
+ pub(crate) sheet: Body,
+ pub(crate) holes: Vec>,
+}
+
+/// [`fillet_setback`] with each set-back corner left open: SMLib builds the rounds up to the
+/// corners' setback sections and the curves on the faces between them, and leaves out the patch
+/// that would fill each corner, for the caller to fill.
+pub(crate) fn fillet_setback_open(body: &Body, edges: &[Vec3], radius: f64, setbacks: &[(Vec3, f64)]) -> Result {
+ imp::blend_setback_open(body, edges, &vec![radius; edges.len()], setbacks)
+}
+
/// Curvature-continuous rounds with the setback of a round of `radius` ([`crate::fillet_g2`]).
pub(crate) fn fillet_g2(body: &Body, edges: &[Vec3], radius: f64) -> Result {
imp::blend(body, "G2 fillet", Kind::Curvature, edges, &vec![radius; edges.len()])
@@ -204,6 +220,43 @@ mod imp {
run(body, what, &picked.edges, |b| b.blend_setback(Blend::Round, &picked.points, sizes, &corners, &distances, tol))
}
+ /// [`blend_setback`] with the set-back corners left open (`super::OpenCorners`).
+ pub(super) fn blend_setback_open(body: &Body, edges: &[Vec3], sizes: &[f64], setbacks: &[(Vec3, f64)]) -> Result {
+ let what = "fillet with open setback corners";
+ body.require_brep(what)?;
+ sizes_ok(what, sizes)?;
+ if setbacks.is_empty() || setbacks.len() > solidcraft_smlib::MAX_POINTS {
+ return Err(KernelError::Invalid(format!("{what}: give 1…{} corners", solidcraft_smlib::MAX_POINTS)));
+ }
+ if setbacks.iter().any(|(p, d)| !p.is_finite() || !(d.is_finite() && *d > 1e-6 && *d < 1e6)) {
+ return Err(KernelError::Invalid(format!("{what}: each corner is a finite point with a positive, finite setback")));
+ }
+ let picked = resolve(body, edges)?;
+ let corners = corner_vertices(body, setbacks.iter().map(|(p, _)| *p))?;
+ let distances: Vec = setbacks.iter().map(|(_, d)| *d).collect();
+ let tol = pick_tolerance(body);
+ let (sheet, holes, order) =
+ run_with(body, what, &picked.edges, |b| b.blend_setback_open(Blend::Round, &picked.points, sizes, &corners, &distances, tol))?;
+ // SMLib's indices in the sheet's own orders.
+ let place = |list: &[usize], i: usize| if list.is_empty() { Some(i) } else { list.get(i).copied() };
+ let renumber = |hole: &solidcraft_smlib::Hole| -> Result> {
+ hole.edges
+ .iter()
+ .map(|h| {
+ let edge = match &order {
+ Some(o) => place(&o.edges, h.edge),
+ None => Some(h.edge),
+ };
+ edge.filter(|e| *e < sheet.edge_count())
+ .map(|e| (e, h.forward))
+ .ok_or_else(|| failed(what, "hole", "an edge SMLib names is not in the sheet"))
+ })
+ .collect()
+ };
+ let holes = holes.iter().map(renumber).collect::>>()?;
+ Ok(super::OpenCorners { sheet, holes })
+ }
+
/// The body's vertex nearest each point, within the pick tolerance: the ends of its edges.
fn corner_vertices(body: &Body, picks: impl Iterator) -> Result> {
let mesh = body.mesh(&crate::MeshTolerance::chord((body.size() * 2e-3).max(1e-3)))?;
@@ -249,10 +302,21 @@ mod imp {
/// `op` on `body` in SMLib, tagged as operand 0, checked, decoded, with its history.
fn run(body: &Body, what: &str, edges: &[usize], op: impl FnOnce(&Brep) -> solidcraft_smlib::Result) -> Result {
+ run_with(body, what, edges, |b| op(b).map(|r| (r, ()))).map(|(out, (), _)| out)
+ }
+
+ /// [`run`] for an `op` that also gives something of its own, with where SMLib's faces and
+ /// edges of the result are in the body's orders.
+ fn run_with(
+ body: &Body,
+ what: &str,
+ edges: &[usize],
+ op: impl FnOnce(&Brep) -> solidcraft_smlib::Result<(Brep, T)>,
+ ) -> Result<(Body, T, Option)> {
guard(what, || {
let (sb, order) = smlib_body_ordered(body)?;
let tagged = sb.tagged(0).map_err(|e| failed(what, "tag", e))?;
- let r = op(&tagged).map_err(|e| match e {
+ let (r, extra) = op(&tagged).map_err(|e| match e {
SmError::Unsupported => super::unsupported(&format!("this {what}, which SMLib cannot build exactly")),
SmError::NoEffect => KernelError::Failed(format!("SMLib made no change: the {what} reported success but built no face")),
SmError::NoRoom => KernelError::TooLarge(format!("the {what} is larger than the faces beside its edges allow")),
@@ -266,8 +330,8 @@ mod imp {
return Err(failed(what, step, check));
}
let (out, result_order) = body_from_smlib_ordered(&r)?;
- let history = match (order, result_order) {
- (Some(o), Some(ro)) => match r.history().map_err(|e| failed(what, "history", e))?.history(&[o], &ro) {
+ let history = match (order, &result_order) {
+ (Some(o), Some(ro)) => match r.history().map_err(|e| failed(what, "history", e))?.history(&[o], ro) {
Ok(mut h) => {
let operand = History::identity(body).edges;
let replaced = blended(body, edges, &h);
@@ -281,7 +345,7 @@ mod imp {
},
_ => None,
};
- Ok(out.with_checked_history(history, &record::counts(&[body])).inherit_regularization_protection(body))
+ Ok((out.with_checked_history(history, &record::counts(&[body])).inherit_regularization_protection(body), extra, result_order))
})
}
diff --git a/crates/kernel/src/corner_g2.rs b/crates/kernel/src/corner_g2.rs
index 3c40f7f1f..63cd23a99 100644
--- a/crates/kernel/src/corner_g2.rs
+++ b/crates/kernel/src/corner_g2.rs
@@ -1,502 +1,51 @@
-//! G2 corner patches: the patch that fills a vertex where filleted edges meet, built to repeat each
-//! blend's surface up to the second order instead of the rolling ball's sphere.
+//! G2 fillet corners (`corner: G2`): the corner where three or more rounded edges meet, filled
+//! with a patch that meets every face around it to the second order, instead of the rolling
+//! ball's sphere (or SMLib's Coons patch), which is only tangent to the rounds and keeps its own
+//! 1 / r across each seam.
//!
-//! [`crate::blend_corner`] and [`crate::curvecorner`] fill the corner of a vertex with a piece of
-//! the ball that rolls along the three edges (a sphere for equal radii, a rational patch for
-//! unequal ones). That patch is tangent to every blend along the sections where they stop, so the
-//! corner is G1 — but across a seam the ball keeps its own 1/r where a fillet is flat along its
-//! axis, so the two surfaces meet with a jump in curvature.
+//! The corner is set back: SMLib runs each round whole to its cross-section a setback from the
+//! vertex and leaves the corner open ([`crate::blend_smlib::fillet_setback_open`]), so the hole's
+//! boundary is the rounds' sections and, on each face between two rounds, SMLib's curve from one
+//! round's contact line to the next. Each hole is filled with one face
+//! ([`crate::fill::matched_patch`]): a bicubic height field over the hole's plane fitted to every
+//! face beside the hole — its position, its tangent plane and its normal curvature across the
+//! boundary, read off the face's own surface — the rounds and the planes alike, so the patch is
+//! G2 to all of them. The faces are sewn into one solid by SMLib ([`crate::stitch`]).
//!
-//! Here the corner is one tensor patch whose boundary is the blends' section curves themselves and
-//! whose cross-sections carry each blend's own derivatives: the position, the direction the patch
-//! leaves the blend's surface in, and the blend's curvature vector along that direction are the
-//! first three control points of every cross-section, one control point per continuity condition,
-//! exactly as [`crate::bridge`]'s sections do. The other end of every cross-section gathers at
-//! `apex` — a point inside the material the corner caps — where the sections arrive in a common
-//! tangent plane with a common curvature, so the patch closes there smoothly like a sphere's pole.
-//! Along a seam the patch therefore repeats the blend up to the second order (G2).
-//!
-//! The boundary is a closed loop (the three sections joined corner to corner), so the direction
-//! along it is a *closed* cubic B-spline: an interpolating curve with free ends swings wide at the
-//! corner where the loop joins and folds the patch there. Where two blends meet at that corner
-//! their sections leave in directions 90° apart and ask for different curvature at that one point
-//! (a fillet is flat across its own seam, the other is not), which no single surface can hold; the
-//! corner is a still point of the construction and [`seam_error`] is measured clear of it. A patch
-//! that folds, or a corner with no room, is refused rather than replaced by the G1 ball.
+//! Without a setback the boundary would be the three sections alone, meeting at points where
+//! two rounds 90° apart ask for different curvatures; with it, the only points where two faces
+//! disagree are the hole's corners, where a section ends on a plane: the round's G1 seam with the
+//! plane, whose 1 / r jump every round has along its whole length, ends there, and no surface is
+//! G2 to both the round and the plane at that point. The patch passes from one to the other
+//! within 15% of each side from the corner (`solidcraft_geom::fill_matched::FADE_SHARE`) and
+//! is G2 along the rest of every seam.
-use solidcraft_geom::Vec3;
-use solidcraft_geom::brep::{self as b, eval::SurfaceEval};
-use solidcraft_geom::bspline::{HPoint, NurbsSurface};
+use solidcraft_geom::fill_matched::MatchedFill;
-use crate::blend::unsupported;
-use crate::bridge::Frame;
+use crate::body::Body;
use crate::{KernelError, Result};
-/// A corner's name in an error.
-fn fail(m: impl std::fmt::Display) -> KernelError {
- KernelError::Failed(format!("G2 corner: {m}"))
-}
+/// A corner's default setback: this times its round's radius along each edge. It must reach
+/// past where the rounds meet without one (the radius, at a square corner), and SMLib's own
+/// patch bulges past the faces beyond about twice the radius; one and a half leaves the patch a
+/// side as long as the round's section is wide, with room either way.
+pub const DEFAULT_SETBACK_FACTOR: f64 = 1.5;
-/// Conditions each end of a cross-section carries: position, tangent and curvature.
-const END_CONDITIONS: usize = 3;
-/// Degree across the patch: three conditions at each end, less the control point they share.
-const ACROSS: usize = 2 * END_CONDITIONS - 1;
-/// Degree along the seam loop.
-const ALONG: usize = 3;
-/// Fewest stations a section curve may be sampled at (a cubic through them).
-const MIN_STATIONS: usize = 4;
-/// Most stations one section curve may carry.
-const MAX_STATIONS: usize = 512;
-/// How much of a station's `leave` has to lie across its seam for the patch to have a direction to
-/// leave the blend in at all.
-const ACROSS_ENOUGH: f64 = 0.2;
+/// How far the patch's normal curvature across a seam may be from the face's, clear of the hole's
+/// corners: this share of the corner's round's curvature 1 / r, the jump a rolling ball makes.
+pub const CURVATURE_SHARE: f64 = 5e-3;
-/// A G2 corner patch: its surface, and its boundary as the section curves themselves, each an
-/// interval of the surface's own boundary curve (the `v = 0` line, `seam_curve`) from one corner of
-/// the vertex to the next, so that it lies on the patch exactly.
-#[derive(Clone, Debug, PartialEq)]
-pub struct CornerPatch {
- pub surface: b::Surface,
- pub seam_curve: b::Curve,
- /// Each side's interval of `seam_curve` (its parameter is the surface's u).
- pub seams: Vec<[f64; 2]>,
-}
-
-/// The G2 corner patch over three blends' section curves: `sides[i]` is one blend's section curve,
-/// sampled in order from one corner of the vertex to the next, each side's last station the next
-/// side's first (the three close a loop). `apex` is a point inside the material the corner caps;
-/// the patch gathers there. Its boundary is the section curves themselves (one interval of the
-/// patch's own boundary curve per side); the caller orients the face where it sews it in.
-pub fn corner_g2_patch(sides: &[Vec], apex: Vec3) -> Result {
- build(sides, apex)
-}
-
-/// The seam's own direction at station `i` of a side, from a four-point central difference through
-/// the stations (`crate::bridge::frames` samples a chain evenly, and a corner's own callers do the
-/// same): a two-point chord would only be second order in the step and would tilt the corner's
-/// tangent plane by more than G2 is judged at. `None` within two stations of a side's end.
-fn seam_tangent(side: &[Frame], i: usize) -> Option {
- let at = |j: isize| usize::try_from(j).ok().and_then(|j| side.get(j)).map(|f| f.p);
- let (a, b, c, d) = (at(i as isize - 2)?, at(i as isize - 1)?, at(i as isize + 1)?, at(i as isize + 2)?);
- (b * 8.0 - a - c * 8.0 + d).normalized()
-}
-
-/// The seam's direction at every station of the closed loop (the same difference, wrapping round
-/// its ends), falling back to the chord to a neighbour where the four points are not there.
-fn loop_tangents(frames: &[Frame]) -> Vec