diff --git a/crates/kernel/src/blend.rs b/crates/kernel/src/blend.rs
index accaa4860..43b51b00e 100644
--- a/crates/kernel/src/blend.rs
+++ b/crates/kernel/src/blend.rs
@@ -769,3 +769,7 @@ mod tests {
assert!(out.validity().is_empty(), "{:?}", out.validity());
}
}
+
+#[cfg(test)]
+#[path = "curvecorner_tests.rs"]
+mod corner_tests;
diff --git a/crates/kernel/src/blend_vertex.rs b/crates/kernel/src/blend_vertex.rs
deleted file mode 100644
index 018cf5c92..000000000
--- a/crates/kernel/src/blend_vertex.rs
+++ /dev/null
@@ -1,404 +0,0 @@
-//! Fillets of the three edges at a convex vertex of any smooth faces, of one radius: the rounds
-//! end in a piece of sphere, as they do at the corner of a box.
-//!
-//! The ball of the fillets' radius that touches the three faces there (its centre `c`, its
-//! contacts `q`) ends each round: round `k` stops at the circle where the ball meets the plane
-//! through `c` and the contacts of its two faces, and the sphere's patch joins the three circles.
-//! The construction uses only what a round with a plane end does already:
-//! 1. cut off the corner beyond the three planes (a skewed box whose three faces are those
-//! planes), so each of the three edges ends square on a plane face;
-//! 2. round the three edges one after another, each ending in its plane face, which a round's
-//! end arc and the sides it uses up reduce to a quarter disc of the ball's section;
-//! 3. replace the three quarter discs, which meet along radii at `c`, by the sphere's patch,
-//! which has the three end arcs for its boundary.
-
-use std::collections::{HashMap, HashSet};
-
-use solidcraft_geom::Vec3;
-use truck_modeling::{self as mt};
-
-use crate::blend::{edge_mid, too_large, unsupported, vtx};
-use crate::body::{Body, Solid, from_p3, p3, v3};
-use crate::curveblend::project;
-use crate::record;
-use crate::{BoolOp, KernelError, Result};
-
-/// Round the edges nearest the points, `radius` each. The three edges meeting at a vertex that
-/// all lie among them end in a sphere; the others are rounded as they would be alone.
-pub(crate) fn fillet_ball_vertices(body: &Body, edges: &[Vec3], radius: f64) -> Result
{
- body.require_brep("fillet")?;
- if !(radius.is_finite() && radius > 1e-6 && radius < 1e6) {
- return Err(KernelError::Invalid("fillet size must be positive".into()));
- }
- if edges.len() < 3 {
- return Err(unsupported("a vertex with three rounded edges"));
- }
- let counts = record::counts(&[body]);
- let mut cur = crate::boolean_record::healed(body)?;
- let mut todo: Vec = edges.to_vec();
- let mut done = false;
- while let Some((at, picks)) = find_vertex(&cur, &todo)? {
- let next = round_vertex(&cur, at, radius)?;
- cur = record::after(next, &cur, &counts);
- todo.retain(|p| !picks.iter().any(|q| q.dist(*p) < 1e-12));
- done = true;
- }
- if !done {
- return Err(unsupported("a vertex with three rounded edges"));
- }
- if todo.is_empty() { Ok(cur) } else { crate::blend::fillet(&cur, &todo, radius) }
-}
-
-/// A vertex of three edges all among the picked ones (its position) and their picks.
-fn find_vertex(cur: &Body, picks: &[Vec3]) -> Result)>> {
- let size = cur.size();
- let tol = (size * 2e-3).max(1e-3);
- let solid = cur.deep_copy();
- let all = Body::unique_edges(&solid);
- // The picked edges, by identity, with the pick each came from.
- let mut picked: Vec<(mt::EdgeID, Vec3)> = Vec::new();
- for p in picks {
- let Some((idx, dist)) = cur.nearest_edge(*p, tol)? else { return Ok(None) };
- if dist > size * 0.05 + 1e-3 {
- return Err(KernelError::Invalid(format!("no edge near {:?}", [p.x, p.y, p.z])));
- }
- if let Some(e) = all.get(idx)
- && !picked.iter().any(|(id, _)| *id == e.id())
- {
- picked.push((e.id(), *p));
- }
- }
- let mut at_vertex: HashMap> = HashMap::new();
- for e in &all {
- let Some((_, p)) = picked.iter().find(|(id, _)| *id == e.id()) else { continue };
- for v in [e.absolute_front(), e.absolute_back()] {
- at_vertex.entry(v.id()).or_default().push((e.id(), *p));
- }
- }
- for (vid, list) in at_vertex {
- let degree = all.iter().filter(|e| e.absolute_front().id() == vid || e.absolute_back().id() == vid).count();
- if list.len() == 3 && degree == 3 {
- let v = all.iter().find_map(|e| [e.absolute_front(), e.absolute_back()].into_iter().find(|v| v.id() == vid));
- if let Some(v) = v {
- return Ok(Some((vtx(v), list.iter().map(|(_, p)| *p).collect())));
- }
- }
- }
- Ok(None)
-}
-
-/// The ball touching three faces from inside, near the corner `v`: its centre and contacts.
-struct Ball {
- c: Vec3,
- /// Contact with each face, and the face's outward normal there.
- q: [Vec3; 3],
-}
-
-fn ball_at(faces: &[&mt::Face; 3], v: Vec3, r: f64, tol: f64) -> Result {
- let rows = |n: [Vec3; 3]| [[n[0].x, n[0].y, n[0].z], [n[1].x, n[1].y, n[1].z], [n[2].x, n[2].y, n[2].z]];
- let near = |p: Vec3, hint: &mut [Option<(f64, f64)>; 3]| -> Option<([Vec3; 3], [Vec3; 3])> {
- let mut q = [Vec3::ZERO; 3];
- let mut n = [Vec3::ZERO; 3];
- for (i, f) in faces.iter().enumerate() {
- let (qi, ni, uv) = project(f, p, hint[i])?;
- (q[i], n[i], hint[i]) = (qi, ni, Some(uv));
- }
- Some((q, n))
- };
- let mut hint = [None; 3];
- let (_, n0) = near(v, &mut hint).ok_or_else(|| unsupported("the faces at the vertex"))?;
- // The planes' ball first: each face r inside its tangent plane at the vertex.
- let x = crate::polyhedron::solve3_pub(rows(n0), [-r, -r, -r]).ok_or_else(|| unsupported("a vertex whose faces do not meet in a corner"))?;
- let mut c = v + Vec3::new(x[0], x[1], x[2]);
- for _ in 0..60 {
- let (q, n) = near(c, &mut hint).ok_or_else(|| unsupported("the ball at the vertex"))?;
- let g = [(c - q[0]).dot(n[0]) + r, (c - q[1]).dot(n[1]) + r, (c - q[2]).dot(n[2]) + r];
- let d = crate::polyhedron::solve3_pub(rows(n), [-g[0], -g[1], -g[2]])
- .ok_or_else(|| unsupported("a vertex whose faces do not meet in a corner"))?;
- let dc = Vec3::new(d[0], d[1], d[2]);
- c += dc;
- if !c.is_finite() {
- break;
- }
- if dc.len() < tol * 1e-3 && g.iter().all(|x| x.abs() < tol) {
- let (q, n) = near(c, &mut hint).ok_or_else(|| unsupported("the ball at the vertex"))?;
- // A convex corner: the vertex lies out from every face the ball touches.
- if n.iter().any(|ni| (v - c).dot(*ni) < 0.25 * r) {
- return Err(unsupported("rounds at a corner that is not convex"));
- }
- return Ok(Ball { c, q });
- }
- }
- Err(unsupported("the ball does not fit at the vertex"))
-}
-
-/// Round the three edges at the vertex at `at`, ending in a sphere.
-fn round_vertex(cur: &Body, at: Vec3, r: f64) -> Result {
- let size = cur.size();
- let tol = (size * 1e-7).max(1e-9);
- let solid = cur.deep_copy();
- let all = Body::unique_edges(&solid);
- let face_list: Vec<&mt::Face> = solid.face_iter().collect();
- // The vertex, its three edges and the faces between them.
- let v = all
- .iter()
- .flat_map(|e| [e.absolute_front().clone(), e.absolute_back().clone()])
- .find(|v| vtx(v).dist(at) <= size * 1e-9 + 1e-12)
- .ok_or_else(|| KernelError::Failed("fillet vertex".into()))?;
- let edges: Vec = all.iter().filter(|e| *e.absolute_front() == v || *e.absolute_back() == v).cloned().collect();
- let faces_of = |e: &mt::Edge| -> Vec {
- (0..face_list.len()).filter(|i| face_list.get(*i).is_some_and(|f| f.edge_iter().any(|x| x.id() == e.id()))).collect()
- };
- let mut around: Vec = Vec::new();
- for e in &edges {
- for f in faces_of(e) {
- if !around.contains(&f) {
- around.push(f);
- }
- }
- }
- let [fa, fb, fc] = around[..] else { return Err(unsupported("a vertex of three faces")) };
- let (Some(a), Some(b), Some(c)) = (face_list.get(fa), face_list.get(fb), face_list.get(fc)) else {
- return Err(KernelError::Failed("faces".into()));
- };
- let faces = [*a, *b, *c];
- let ball = ball_at(&faces, vtx(&v), r, tol * 100.0)?;
- // The plane of each edge's end: through the centre and the contacts of the edge's two faces,
- // its normal out toward the vertex.
- let mut normals: Vec = Vec::with_capacity(3);
- for e in &edges {
- let sides: Vec = faces_of(e).iter().filter_map(|f| around.iter().position(|x| x == f)).collect();
- let [i, j] = sides[..] else { return Err(unsupported("an edge not between two faces")) };
- let (Some(qi), Some(qj)) = (ball.q.get(i), ball.q.get(j)) else { return Err(KernelError::Failed("contacts".into())) };
- let m = (*qi - ball.c).cross(*qj - ball.c).normalized().ok_or_else(|| unsupported("a ball that touches an edge's faces at one point"))?;
- normals.push(if m.dot(vtx(&v) - ball.c) < 0.0 { -m } else { m });
- }
- let [m0, m1, m2] = normals[..] else { return Err(KernelError::Failed("planes".into())) };
- // The corner beyond the three planes, a skewed box from the centre along the three lines
- // where two of the planes meet, long enough to hold the corner of the body.
- let gen_ = |x: Vec3, y: Vec3, toward: Vec3| -> Result {
- let g = x.cross(y).normalized().ok_or_else(|| unsupported("planes that do not meet in a corner"))?;
- Ok(if g.dot(toward) < 0.0 { -g } else { g })
- };
- let reach = 3.0 * (vtx(&v).dist(ball.c) + r);
- let (g0, g1, g2) = (gen_(m1, m2, m0)? * reach, gen_(m2, m0, m1)? * reach, gen_(m0, m1, m2)? * reach);
- let unit = crate::build::box_solid(Vec3::ZERO, Vec3::new(1.0, 1.0, 1.0))?;
- let m = [[g0.x, g0.y, g0.z, 0.0], [g1.x, g1.y, g1.z, 0.0], [g2.x, g2.y, g2.z, 0.0], [ball.c.x, ball.c.y, ball.c.z, 1.0]];
- let cutter = crate::ops::transform_matrix(&unit, m)?;
- let notched = crate::ops::boolean(cur, &cutter, BoolOp::Cut)?.ok_or_else(|| unsupported("a corner this small"))?;
- // The cut splits a curved face along the trace of its plane (the whole way across, not just
- // where the plane cuts): the pieces are one face again.
- let notched = crate::guard("merge split faces", || merge_split_faces(¬ched, cur, size))?;
- // A point on what is left of each edge, half way from where its plane crosses it to its far end.
- let mut picks: Vec = Vec::with_capacity(3);
- for (e, m) in edges.iter().zip(&normals) {
- picks.push(remaining_pick(e, &v, ball.c, *m)?);
- }
- // Round them one after another, in an order that works.
- let mut last: Option = None;
- for order in [[0usize, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]] {
- let mut step = notched.clone();
- let mut ok = true;
- for k in order {
- let Some(p) = picks.get(k) else { return Err(KernelError::Failed("pick".into())) };
- match crate::blend::fillet(&step, &[*p], r) {
- Ok(b) => step = b,
- Err(e) => {
- last = Some(e);
- ok = false;
- break;
- }
- }
- }
- if ok {
- return close_with_sphere(&step, &ball, [m0, m1, m2], r, vtx(&v));
- }
- }
- Err(last.unwrap_or_else(|| unsupported("the three rounds at a vertex")))
-}
-
-/// A point on edge `e` between where the plane (through `c`, normal `m`) crosses it and its far
-/// end (the end that is not `v`).
-fn remaining_pick(e: &mt::Edge, v: &mt::Vertex, c: Vec3, m: Vec3) -> Result {
- use mt::{BoundedCurve, ParametricCurve};
- let curve = e.curve();
- let (lo, hi) = curve.range_tuple();
- // From the end at the vertex (outside the plane's far side) to the far end.
- let (near, far) = if e.absolute_front() == v { (lo, hi) } else { (hi, lo) };
- let side = |t: f64| (from_p3(curve.subs(t)) - c).dot(m);
- let (mut a, mut b) = (near, far);
- if !(side(a) > 0.0 && side(b) < 0.0) {
- return Err(too_large("the blend is larger than the neighbouring faces"));
- }
- for _ in 0..80 {
- let mid = 0.5 * (a + b);
- if side(mid) > 0.0 { a = mid } else { b = mid }
- }
- Ok(from_p3(curve.subs(0.5 * (0.5 * (a + b) + far))))
-}
-
-/// `step` has the three rounds ending in three quarter discs; the sphere's patch takes their place.
-fn close_with_sphere(step: &Body, ball: &Ball, planes: [Vec3; 3], r: f64, v: Vec3) -> Result {
- let size = step.size();
- let on_tol = (size * 1e-6).max(1e-9);
- let solid = step.deep_copy();
- let faces: Vec = solid.face_iter().cloned().collect();
- // The face in each plane: a plane face through the centre.
- let mut discs: Vec = Vec::new();
- for m in planes {
- let found = faces.iter().position(|f| {
- crate::blend::plane_normal(f).is_some_and(|n| n.dot(m).abs() > 1.0 - 1e-9)
- && f.vertex_iter().next().is_some_and(|p| (vtx(&p) - ball.c).dot(m).abs() <= on_tol * 10.0)
- && f.vertex_iter().any(|p| vtx(&p).dist(ball.c) <= on_tol * 10.0)
- });
- let Some(i) = found else { return Err(unsupported("the ends of the three rounds")) };
- discs.push(i);
- }
- // The arc of each: its one edge that is not a straight line.
- let mut arcs: Vec = Vec::with_capacity(3);
- for i in &discs {
- let f = faces.get(*i).ok_or_else(|| KernelError::Failed("face".into()))?;
- let curved: Vec = f.edge_iter().filter(|e| !matches!(e.curve(), mt::Curve::Line(_))).collect();
- let [arc] = &curved[..] else { return Err(unsupported("the ends of the three rounds")) };
- arcs.push(arc.absolute_clone());
- }
- // The three arcs in a loop.
- let first_arc = arcs.first().cloned().ok_or_else(|| KernelError::Failed("arc".into()))?;
- let mut used: HashSet = HashSet::from([first_arc.id()]);
- let mut wire: Vec = vec![first_arc];
- for _ in 0..2 {
- let end = wire.last().map(|e| e.back().clone()).ok_or_else(|| KernelError::Failed("arc".into()))?;
- let next = arcs
- .iter()
- .find(|a| !used.contains(&a.id()) && (*a.front() == end || *a.back() == end))
- .ok_or_else(|| unsupported("the ends of the three rounds"))?;
- used.insert(next.id());
- wire.push(if *next.front() == end { next.clone() } else { next.inverse() });
- }
- if wire.last().map(|e| e.back().clone()) != wire.first().map(|e| e.front().clone()) {
- return Err(unsupported("the ends of the three rounds"));
- }
- // A sphere about the centre, its poles and seam away from the patch.
- let out = (v - ball.c).normalized().ok_or_else(|| KernelError::Failed("sphere".into()))?;
- let side = out.any_perp();
- let (np, sp, back) = (ball.c + side * r, ball.c - side * r, ball.c - out * r);
- let meridian = mt::builder::circle_arc(&mt::builder::vertex(p3(np)), &mt::builder::vertex(p3(sp)), p3(back));
- let mut surf =
- mt::Surface::RevolutedCurve(mt::Processor::new(mt::RevolutedCurve::by_revolution(meridian.oriented_curve(), p3(ball.c), v3(side))));
- {
- use mt::{ParametricSurface3D, SearchNearestParameter};
- if let Some((u, w)) = surf.search_nearest_parameter(p3(ball.c + out * r), None, 100) {
- let n = surf.normal(u, w);
- if Vec3::new(n.x, n.y, n.z).dot(out) < 0.0 {
- surf = mt::Invertible::inverse(&surf);
- }
- }
- }
- // The patch runs each arc opposite to the round that ends on it.
- let rest: Vec<&mt::Face> = faces.iter().enumerate().filter(|(i, _)| !discs.contains(i)).map(|(_, f)| f).collect();
- let uses = |id: mt::EdgeID| {
- rest.iter().find_map(|f| {
- f.boundaries().iter().flat_map(|w| w.edge_iter().cloned().collect::>()).find(|x| x.id() == id).map(|x| x.front().id())
- })
- };
- if let (Some(first), Some(front)) = (wire.first(), wire.first().and_then(|e| uses(e.id())))
- && front == first.front().id()
- {
- wire = wire.iter().rev().map(|e| e.inverse()).collect();
- }
- let patch = mt::Face::try_new(vec![mt::Wire::from(wire)], surf).map_err(|e| KernelError::Failed(format!("sphere patch: {e}")))?;
- let mut new_faces: Vec = rest.into_iter().cloned().collect();
- new_faces.push(patch);
- let mut shells = solid.boundaries().clone();
- let si = shells.iter().position(|sh| sh.face_iter().any(|f| discs.iter().any(|i| faces.get(*i).is_some_and(|d| d.id() == f.id())))).unwrap_or(0);
- if let Some(sh) = shells.get_mut(si) {
- *sh = new_faces.into();
- }
- let out: Solid = Solid::try_new(shells).map_err(|e| KernelError::Failed(format!("rounds ending in a sphere: {e}")))?;
- record::rebuilt(out, &[&step.solid], &record::Rebuild::default())
-}
-
-/// `body` with the curved faces that are pieces of one input face (as the cut that made `body`
-/// recorded them) joined again: the edges two pieces share go, the rest make the one boundary.
-fn merge_split_faces(body: &Body, source: &Body, size: f64) -> Result {
- let tol = (size * 1e-6).max(1e-9);
- let Some(history) = body.history() else { return Ok(body.clone()) };
- let solid = body.deep_copy();
- let faces: Vec = solid.face_iter().cloned().collect();
- if history.faces.len() != faces.len() {
- return Ok(body.clone());
- }
- let on = |a: &mt::Face, p: Vec3| project(a, p, None).is_some_and(|(q, _, uv)| crate::curveblend::in_range(a, uv) && q.dist(p) <= tol * 10.0);
- // Pieces by the input face they come from.
- let mut groups: Vec> = Vec::new();
- for (i, f) in history.faces.iter().enumerate() {
- let curved = faces.get(i).is_some_and(|x| crate::blend::plane_normal(x).is_none());
- if !(curved && f.change == crate::history::Change::Split && f.origins.len() == 1) {
- continue;
- }
- match groups.iter_mut().find(|g| g.first().and_then(|k| history.faces.get(*k)).is_some_and(|o| o.origins == f.origins)) {
- Some(g) => g.push(i),
- None => groups.push(vec![i]),
- }
- }
- let mut out: Vec> = faces.iter().cloned().map(Some).collect();
- let mut merged_any = false;
- for group in groups.iter().filter(|g| g.len() >= 2) {
- let pieces: Vec<&mt::Face> = group.iter().filter_map(|i| faces.get(*i)).collect();
- if pieces.iter().any(|f| f.boundaries().len() != 1) {
- continue;
- }
- // Edges used once, as the pieces walk them.
- let all: Vec =
- pieces.iter().flat_map(|f| f.boundaries().iter().flat_map(|w| w.edge_iter().cloned().collect::>()).collect::>()).collect();
- let mut uses: HashMap = HashMap::new();
- for e in &all {
- *uses.entry(e.id()).or_default() += 1;
- }
- let mut left: Vec = all.into_iter().filter(|e| uses.get(&e.id()) == Some(&1)).collect();
- let Some(start) = left.pop() else { continue };
- let mut wire = vec![start];
- while let Some(end) = wire.last().map(|e| e.back().clone()) {
- if wire.first().is_some_and(|e| *e.front() == end) {
- break;
- }
- let Some(at) = left.iter().position(|e| *e.front() == end) else { break };
- wire.push(left.swap_remove(at));
- }
- // One closed boundary, all of it used.
- if !left.is_empty() || wire.first().map(|e| e.front().clone()) != wire.last().map(|e| e.back().clone()) {
- continue;
- }
- // A boolean may restrict a piece's surface to its own parameter box. The
- // joined boundary needs the original face's full patch, not an extrapolation
- // of one piece (which the bounded display planner correctly refuses).
- let all_on = |f: &mt::Face| {
- pieces.iter().all(|p| p.vertex_iter().all(|v| on(f, vtx(&v))) && p.edge_iter().all(|e| edge_mid(&e).is_none_or(|m| on(f, m))))
- };
- let original = group.first().and_then(|i| history.faces.get(*i)).and_then(|h| match h.origins.as_slice() {
- [crate::history::FaceOrigin::Face { operand: 0, face }] => source.solid.face_iter().nth(*face),
- _ => None,
- });
- let Some(like) = original.filter(|f| all_on(f)).or_else(|| pieces.iter().copied().find(|f| all_on(f))) else { continue };
- let Ok(joined) = mt::Face::try_new(vec![mt::Wire::from(wire)], like.oriented_surface()) else { continue };
- let Some(first) = group.first() else { continue };
- for i in group {
- if let Some(slot) = out.get_mut(*i) {
- *slot = None;
- }
- }
- if let Some(slot) = out.get_mut(*first) {
- *slot = Some(joined);
- }
- merged_any = true;
- }
- if !merged_any {
- return Ok(body.clone());
- }
- let mut shells = solid.boundaries().clone();
- if let Some(sh) = shells.first_mut() {
- *sh = out.into_iter().flatten().collect::>().into();
- }
- let rebuilt = Solid::try_new(shells).map_err(|e| KernelError::Failed(format!("a corner cut: {e}")))?;
- record::rebuilt(rebuilt, &[&body.solid], &record::Rebuild::default())
-}
diff --git a/crates/kernel/src/curveblend.rs b/crates/kernel/src/curveblend.rs
deleted file mode 100644
index 1051cae30..000000000
--- a/crates/kernel/src/curveblend.rs
+++ /dev/null
@@ -1,2257 +0,0 @@
-//! Rolling-ball blends along a closed chain of smooth edges between two smooth groups of faces
-//! of any surfaces (a branch pipe meeting a main pipe, a boss on a cylinder). A ball rolls along
-//! the edge touching both sides; its centre traces the spine and its contacts the curves where
-//! the blend meets each side. The blend face is a rational B-spline through the circular
-//! cross-sections (exact arcs at the samples), the side faces are trimmed back to the contact
-//! curves, and seams that met the edge (lines, or arcs of an end face) are shortened to the
-//! contacts.
-//!
-//! The ball's size along the chain is one of [`Size`]: one radius all along (the ordinary
-//! fillet), a chord width across the blend (each section spans the requested width from contact
-//! to contact, so its radius is `chord / (2 sin(ψ/2))` for the `ψ` between the two outward
-//! normals where the ball touches), or a radius law along the chain (a [`RadiusSpline`] whose
-//! positions are the fraction of the chain's arc length, zero only at an end, where the blend
-//! closes to the edge's end point as the straight-edge fillet does).
-
-use std::collections::HashMap;
-
-use solidcraft_geom::Vec3;
-use truck_modeling::{self as mt, builder};
-
-use crate::blend::too_large;
-use crate::blend_variable::RadiusSpline;
-use crate::body::{Solid, from_p3, p3};
-use crate::record::Rebuild;
-use crate::{KernelError, Result};
-
-fn unsupported(msg: &str) -> KernelError {
- KernelError::Failed(format!("not supported yet: {msg}"))
-}
-
-/// Samples per edge for the contact curves and the blend surface.
-const SAMPLES: usize = 24;
-const MAX_SAMPLES: usize = 369;
-const MAX_CHAIN_SAMPLES: usize = 100_000;
-/// Sections past a slanted end of an open chain.
-const EXTENSION: usize = 8;
-/// `1 + n1·n2` below this: a knife edge, where the faces' normals are opposite and the ball's
-/// centre is found by sliding along the faces rather than from their normals.
-const KNIFE: f64 = 1e-4;
-/// An end face this close to square-on-to-its-sides' normal counts as tangent to a side.
-const TANGENT_END: f64 = 1e-6;
-/// Times the run past a tangent end is halved when the ball does not fit along it (and the run
-/// past a curved end is shortened when its sections wrap round).
-const TANGENT_RETRIES: usize = 8;
-/// The longest step between the centres of neighbouring sections past an open chain's end, as a
-/// multiple of the step along the end tangent: longer, and the sections have wrapped round a
-/// curved edge's ring of centres.
-const MAX_STEP_STRETCH: f64 = 3.0;
-/// Slides of the ball's centre along a knife edge's faces, each 1.6 times the last.
-const KNIFE_STEPS: usize = 40;
-/// Corrections of the radius a chord fillet makes to the width it measures across the blend.
-const CHORD_STEPS: usize = 12;
-/// A section this close to a point is closed: the blend ends at the edge's end point (a radius
-/// that has run to zero there).
-const CLOSED: f64 = 1e-7;
-/// Parameters an edge is sampled at to measure the arc length a radius law is read off.
-const LENGTH_STEPS: usize = 64;
-
-/// The ball's size along the edge chain.
-#[derive(Clone, Copy)]
-enum Size<'a> {
- /// One radius all along.
- Constant(f64),
- /// The width across the blend, from contact to contact, at every station.
- Chord(f64),
- /// The radius at the station's arc-length fraction along the chain, 0 at the front and 1 at
- /// the back of its edge.
- Law(&'a RadiusSpline),
-}
-
-struct Fit {
- surface: mt::Surface,
- contacts: [mt::Curve; 2],
- /// Parameter range belonging to this edge (the fit includes neighbouring sections).
- range: (f64, f64),
- /// The part of the fit that is the chain's own run, as fractions of its parameter range.
- span: (f64, f64),
-}
-
-struct Guide {
- sections: Vec,
- /// The size law's parameter (the arc-length fraction along the chain) at each section: the
- /// radius between the samples is read off the law there, not off the spine's own length.
- law: Vec,
- lengths: Vec,
- /// The part of the guide that is the chain itself, as fractions of its length: the sections
- /// run on past the ends of the chain (only so that the fit can be cut back there) and the fit
- /// is checked for accuracy on the chain alone.
- span: (f64, f64),
-}
-
-impl Guide {
- /// A guide whose law parameter is the section's own fraction of it (the size is one radius,
- /// which needs no law).
- fn new(sections: Vec) -> Result {
- let den = sections.len().max(2) - 1;
- let law = (0..sections.len()).map(|i| i as f64 / den as f64).collect();
- Self::with_law(sections, law)
- }
-
- fn with_law(sections: Vec, law: Vec) -> Result {
- if sections.len() != law.len() {
- return Err(unsupported("degenerate rolling-ball spine"));
- }
- let mut lengths = vec![0.0];
- let mut total = 0.0;
- for pair in sections.windows(2) {
- let (Some(a), Some(b)) = (pair.first(), pair.get(1)) else { continue };
- total += a.c.dist(b.c);
- lengths.push(total);
- }
- if !total.is_finite() || total <= 1e-12 {
- return Err(unsupported("degenerate rolling-ball spine"));
- }
- Ok(Self { sections, law, lengths, span: (0.0, 1.0) })
- }
-
- /// The centre and tangent at `along` of the spine.
- fn anchor(&self, along: f64) -> Option<(Vec3, Vec3)> {
- self.anchor_at(along).map(|(centre, tangent, _)| (centre, tangent))
- }
-
- /// [`Guide::anchor`] with the size law's parameter at that station.
- fn anchor_at(&self, along: f64) -> Option<(Vec3, Vec3, f64)> {
- if self.lengths.len() < 2 || !along.is_finite() || !(0.0..=1.0).contains(&along) {
- return None;
- }
- let distance = self.lengths.last()? * along;
- let hi = self.lengths.partition_point(|length| *length < distance).clamp(1, self.lengths.len().checked_sub(1)?);
- let (a, b) = (self.sections.get(hi - 1)?, self.sections.get(hi)?);
- let (lo, hi_length) = (self.lengths.get(hi - 1)?, self.lengths.get(hi)?);
- let span = hi_length - lo;
- if span <= 1e-12 {
- return None;
- }
- let fraction = (distance - lo) / span;
- let law = self.law.get(hi - 1)? * (1.0 - fraction) + self.law.get(hi)? * fraction;
- Some((a.c + (b.c - a.c) * fraction, (b.c - a.c).normalized()?, law))
- }
-}
-
-/// One interpolation for both the face and its boundary curves. Fitting the contacts
-/// independently gives different end conditions and leaves gaps between the same faces.
-fn fit_sections(sections: &[Vec], k: usize, closed: bool, round: bool) -> Result {
- let fail = |m: &str| KernelError::Failed(format!("curve blend: {m}"));
- let n = sections.len();
- let list = sections.get(k).ok_or_else(|| fail("section"))?;
- let mut before = Vec::new();
- if closed || k > 0 {
- let prev = sections.get((k + n - 1) % n).ok_or_else(|| fail("section"))?;
- before.extend(prev.iter().rev().skip(1).take(2).rev().copied());
- }
- let mut after = Vec::new();
- if closed || k + 1 < n {
- let next = sections.get((k + 1) % n).ok_or_else(|| fail("section"))?;
- after.extend(next.iter().skip(1).take(2).copied());
- }
- fit_strip(list, &before, &after, round)
-}
-
-/// [`fit_sections`] with the neighbouring sections given: best spaced as the strip's own, since
-/// the interpolation's parameters are uniform.
-fn fit_strip(list: &[Section], before: &[Section], after: &[Section], round: bool) -> Result {
- use mt::Cut;
- let fail = |m: &str| KernelError::Failed(format!("curve blend: {m}"));
- let mut ext = Vec::with_capacity(list.len() + before.len() + after.len());
- ext.extend(before.iter().copied());
- ext.extend(list.iter().copied());
- ext.extend(after.iter().copied());
- let before = before.len();
- let ctrl: Vec<[mt::Vector4; 3]> = ext.iter().map(|s| section_controls(s, round)).collect::>().ok_or_else(|| fail("section"))?;
- let mut rows = Vec::with_capacity(3);
- let mut vknots = None;
- for j in 0..3 {
- let xyz: Vec = ctrl.iter().filter_map(|c| c.get(j)).map(|c| Vec3::new(c.x, c.y, c.z)).collect();
- let ww: Vec = ctrl.iter().filter_map(|c| c.get(j)).map(|c| Vec3::new(c.w, 0.0, 0.0)).collect();
- let bx = crate::build::interpolate_cubic(&xyz).ok_or_else(|| fail("blend surface"))?;
- let bw = crate::build::interpolate_cubic(&ww).ok_or_else(|| fail("blend surface"))?;
- vknots = Some(bx.knot_vec().clone());
- rows.push(bx.control_points().iter().zip(bw.control_points()).map(|(p, w)| mt::Vector4::new(p.x, p.y, p.z, w.x)).collect::>());
- }
- let vk = vknots.ok_or_else(|| fail("knots"))?;
- let den = ext.len().saturating_sub(1) as f64;
- if den <= 0.0 {
- return Err(fail("empty sections"));
- }
- let range = (before as f64 / den, (before + list.len().saturating_sub(1)) as f64 / den);
- let contact = |row: usize| -> Result {
- let points = rows.get(row).cloned().ok_or_else(|| fail("contact row"))?;
- let bs = mt::BSplineCurve::try_new(vk.clone(), points).map_err(|e| fail(&e.to_string()))?;
- let mut curve = mt::NurbsCurve::new(bs);
- if range.0 > 0.0 {
- curve = curve.cut(range.0);
- }
- if range.1 < 1.0 {
- let _ = curve.cut(range.1);
- }
- Ok(mt::Curve::NurbsCurve(curve))
- };
- let contacts = [contact(0)?, contact(2)?];
- let bs = mt::BSplineSurface::try_new((mt::KnotVec::bezier_knot(2), vk), rows).map_err(|e| fail(&e.to_string()))?;
- Ok(Fit { surface: mt::Surface::NurbsSurface(mt::NurbsSurface::new(bs)), contacts, range, span: (0.0, 1.0) })
-}
-
-/// Compare the fitted strip with a solved circular section between interpolation nodes.
-/// This checks the supporting contacts as well as the middle of the fillet band.
-fn section_fits(fit: &Fit, section: &Section, along: f64, round: bool, sigma: f64, tolerance: f64) -> bool {
- use mt::{ParametricSurface, ParametricSurface3D, SearchNearestParameter};
- let Some(ctrl) = section_controls(section, round) else { return false };
- let v = fit.range.0 + (fit.range.1 - fit.range.0) * along;
- for u in [0.0, 0.25, 0.5, 0.75, 1.0] {
- let [a, b, c] = ctrl;
- let h = a * (1.0 - u) * (1.0 - u) + b * (2.0 * u * (1.0 - u)) + c * u * u;
- if !h.w.is_finite() || h.w <= 1e-12 {
- return false;
- }
- let exact = Vec3::new(h.x / h.w, h.y / h.w, h.z / h.w);
- // The input intersection edge may use piecewise leader-curve parameters. A
- // parameter-speed change is not a geometric error: compare nearest points, with
- // contacts constrained to the corresponding boundary and all probes to the strip.
- let (probe_u, probe_v) = if u == 0.0 || u == 1.0 {
- let Some(contact) = fit.contacts.get(usize::from(u == 1.0)) else { return false };
- let Some(parameter) = contact.search_nearest_parameter(p3(exact), v, 32) else { return false };
- (u, parameter.clamp(fit.range.0, fit.range.1))
- } else {
- let Some((pu, pv)) = fit.surface.search_nearest_parameter(p3(exact), Some((u, v)), 32) else { return false };
- (pu.clamp(0.0, 1.0), pv.clamp(fit.range.0, fit.range.1))
- };
- let actual = from_p3(fit.surface.subs(probe_u, probe_v));
- if !actual.is_finite() || actual.dist(exact) > tolerance {
- return false;
- }
- if round && (u == 0.0 || u == 1.0) {
- let Some(want) = ((section.c - exact) * sigma).normalized() else { return false };
- let normal = fit.surface.normal(probe_u, probe_v);
- let Some(normal) = Vec3::new(normal.x, normal.y, normal.z).normalized() else { return false };
- if normal.dot(want).abs() < 0.5f64.to_radians().cos() {
- return false;
- }
- }
- }
- true
-}
-
-/// Where a blend strip run on past a chain end meets the end face: the contacts' parameters
-/// there and the end curve from contact 1 to contact 2 (fitted through points where the
-/// strip's cross-section curves meet the face's surface, and checked against both).
-fn end_cap(fit: &Fit, g: &mt::Face, at: &Section, seams: [Option<&mt::Edge>; 2], round: bool, tolerance: f64) -> Result<(f64, f64, mt::Curve)> {
- use mt::{ParametricCurve, ParametricSurface, SearchNearestParameter};
- let fail = || unsupported("the blend's end on its end face");
- let (surf, gs) = (&fit.surface, g.surface());
- let mid = if round { at.c + ((at.q1 - at.c) + (at.q2 - at.c)).normalized().ok_or_else(fail)? * at.c.dist(at.q1) } else { (at.q1 + at.q2) * 0.5 };
- let (_, v_start) = surf.search_nearest_parameter(p3(mid), None, 100).ok_or_else(fail)?;
- // S(u, v) = G(a, b) for v, a, b by Newton from v.
- let meet = |u: f64, v: f64| -> Option {
- let mut v = v;
- let (mut a, mut b) = gs.search_nearest_parameter(surf.subs(u, v), None, 100)?;
- for _ in 0..60 {
- let f = from_p3(surf.subs(u, v)) - from_p3(gs.subs(a, b));
- if !f.is_finite() {
- return None;
- }
- if f.len() <= tolerance * 1e-3 {
- return (-1e-9..=1.0 + 1e-9).contains(&v).then_some(v.clamp(0.0, 1.0));
- }
- let (sv, ga, gb) = (surf.vder(u, v), gs.uder(a, b), gs.vder(a, b));
- let m = [[sv.x, -ga.x, -gb.x], [sv.y, -ga.y, -gb.y], [sv.z, -ga.z, -gb.z]];
- let [dv, da, db] = crate::polyhedron::solve3_pub(m, [-f.x, -f.y, -f.z])?;
- // Keep each step within the strip's parameters.
- let k = if dv.abs() > 0.1 { 0.1 / dv.abs() } else { 1.0 };
- v += dv * k;
- a += da * k;
- b += db * k;
- }
- None
- };
- for m in [16usize, 32, 64] {
- let mut pts = Vec::with_capacity(m + 1);
- let mut vs = Vec::with_capacity(m + 1);
- // From the middle out to both contacts, each search starting where the last ended.
- let half = m / 2;
- let mid_v = meet(0.5_f64.min(half as f64 / m as f64), v_start).ok_or_else(fail)?;
- let mut found = vec![None; m + 1];
- if let Some(slot) = found.get_mut(half) {
- *slot = Some(mid_v);
- }
- let mut last = mid_v;
- for i in (0..half).rev() {
- last = meet(i as f64 / m as f64, last).ok_or_else(fail)?;
- if let Some(slot) = found.get_mut(i) {
- *slot = Some(last);
- }
- }
- last = mid_v;
- for i in half + 1..=m {
- last = meet(i as f64 / m as f64, last).ok_or_else(fail)?;
- if let Some(slot) = found.get_mut(i) {
- *slot = Some(last);
- }
- }
- for (i, v) in found.iter().enumerate() {
- let v = v.ok_or_else(fail)?;
- vs.push(v);
- pts.push(from_p3(surf.subs(i as f64 / m as f64, v)));
- }
- snap_to_seams(&mut pts, seams, tolerance);
- let bs = crate::build::interpolate_cubic(&pts).ok_or_else(fail)?;
- let fits = (0..m).all(|i| {
- let q = p3(from_p3(bs.subs((i as f64 + 0.5) / m as f64)));
- let hint = vs.get(i).map(|v| ((i as f64 + 0.5) / m as f64, *v));
- let on_g = gs.search_nearest_parameter(q, None, 100).is_some_and(|(a, b)| from_p3(gs.subs(a, b)).dist(from_p3(q)) <= tolerance);
- let on_s = surf.search_nearest_parameter(q, hint, 100).is_some_and(|(u, v)| from_p3(surf.subs(u, v)).dist(from_p3(q)) <= tolerance);
- on_g && on_s
- });
- if fits {
- let (Some(t1), Some(t2)) = (vs.first(), vs.last()) else { return Err(fail()) };
- // Both contacts are cut there: strictly inside the strip's own part.
- let inside = |t: f64| t > fit.range.0 + 1e-6 && t < fit.range.1 - 1e-6;
- if !(inside(*t1) && inside(*t2)) {
- return Err(too_large("the blend is larger than the neighbouring faces (site 309)"));
- }
- return Ok((*t1, *t2, mt::Curve::BSplineCurve(bs)));
- }
- }
- Err(fail())
-}
-
-/// The ends of an end curve (contact 1 to contact 2) that land within `tolerance` of an end of
-/// their side's seam are that point exactly: the blend and the faces there meet at one vertex.
-fn snap_to_seams(pts: &mut [Vec3], seams: [Option<&mt::Edge>; 2], tolerance: f64) {
- let snap = |p: &mut Vec3, seam: Option<&mt::Edge>| {
- for q in seam.into_iter().flat_map(|e| [from_p3(e.front().point()), from_p3(e.back().point())]) {
- if p.dist(q) <= tolerance {
- *p = q;
- }
- }
- };
- if let Some(first) = pts.first_mut() {
- snap(first, seams[0]);
- }
- if let Some(last) = pts.last_mut() {
- snap(last, seams[1]);
- }
-}
-
-/// Where a blend strip run on past a chain end meets an end face that lies along the edge and is
-/// tangent to one side there (a wall running out into the face, an earlier round that touches a
-/// side along its contact): the end curve from contact 1 to contact 2, the same result as
-/// [`end_cap`]. The strip touches the face along the tangent side's contact, so a Newton solve
-/// for the crossing is singular there.
-///
-/// Both ends of the curve are where a contact meets a seam, which is a plain crossing: the
-/// tangent side's contact leaves the end face where it crosses the seam of that side with the
-/// face, the other contact where it crosses the other side's seam. Between those stations each
-/// cross-section crosses the face once, a simple root. Either station may lie before or after
-/// the vertex's section: the curve runs inwards along the edge or out along the extension.
-fn tangent_cap(fit: &Fit, g: &mt::Face, tangent_side: u8, seams: [Option<&mt::Edge>; 2], tolerance: f64) -> Result<(f64, f64, mt::Curve)> {
- use mt::{BoundedCurve, ParametricCurve, ParametricSurface, SearchNearestParameter};
- let fail = || unsupported("the blend's end on its end face");
- let surf = &fit.surface;
- let (lo, hi) = (fit.range.0.min(fit.range.1), fit.range.0.max(fit.range.1));
- let (u_t, u_o, seam_t, seam_o) = if tangent_side == 1 { (0.0, 1.0, seams[0], seams[1]) } else { (1.0, 0.0, seams[1], seams[0]) };
- let (seam_t, seam_o) = (seam_t.ok_or_else(fail)?, seam_o.ok_or_else(fail)?);
- // The station where the strip's contact `u` crosses `seam`.
- let crossing = |u: f64, seam: &mt::Edge| -> Option {
- let curve = seam.curve();
- let (a, b) = curve.range_tuple();
- let polyline: Vec = (0..=1024).map(|i| from_p3(curve.subs(a + (b - a) * f64::from(i) / 1024.0))).collect();
- let dist = |v: f64| -> f64 {
- let x = from_p3(surf.subs(u, v));
- polyline.windows(2).map(|w| x.dist_to_segment(w[0], w[1])).fold(f64::INFINITY, f64::min)
- };
- let n = 400;
- let step = (hi - lo) / f64::from(n);
- let (mut best, mut best_d) = (lo, f64::INFINITY);
- for i in 0..=n {
- let v = lo + step * f64::from(i);
- let d = dist(v);
- if d < best_d {
- (best, best_d) = (v, d);
- }
- }
- let (mut x0, mut x1) = ((best - step).max(lo), (best + step).min(hi));
- let phi = 0.618_033_988_749_894_9;
- for _ in 0..80 {
- let (c, d) = (x1 - phi * (x1 - x0), x0 + phi * (x1 - x0));
- if dist(c) < dist(d) {
- x1 = d;
- } else {
- x0 = c;
- }
- }
- let v = 0.5 * (x0 + x1);
- (dist(v) <= tolerance).then_some(v)
- };
- let (rt, ra) = (crossing(u_t, seam_t), crossing(u_o, seam_o));
- let v_t = rt.ok_or_else(fail)?;
- let v_a = ra.ok_or_else(|| too_large("the blend is larger than the neighbouring faces (site 387)"))?;
- let inside = |t: f64| t > lo + 1e-6 && t < hi - 1e-6;
- if !(inside(v_a) && inside(v_t)) || (v_a - v_t).abs() < 1e-9 {
- return Err(too_large("the blend is larger than the neighbouring faces (site 390)"));
- }
- // How far the strip's point (u, v) is outside the end face (negative: inside the body).
- let outside = |u: f64, v: f64| -> Option {
- let x = from_p3(surf.subs(u, v));
- let (q, n, _) = project(g, x, None)?;
- Some((x - q).dot(n))
- };
- // Root of `f` between `lo` and `hi`, `f(lo)` and `f(hi)` of different sign.
- let bisect = |f: &dyn Fn(f64) -> Option, mut x0: f64, mut x1: f64| -> Option {
- let f0 = f(x0)?;
- for _ in 0..60 {
- let mid = 0.5 * (x0 + x1);
- let fm = f(mid)?;
- if fm.abs() <= tolerance * 1e-6 {
- return Some(mid);
- }
- if fm.is_sign_negative() == f0.is_sign_negative() {
- x0 = mid;
- } else {
- x1 = mid;
- }
- }
- Some(0.5 * (x0 + x1))
- };
- for m in [16usize, 32, 64, 128] {
- // The curve at stations v_i from the crossing contact to the tangent one, as (u, v, point).
- let mut stations: Vec<(f64, f64, Vec3)> = Vec::with_capacity(m + 1);
- for i in 0..=m {
- // Clustered at both ends, where the curve can meet a contact tangentially (a square
- // root in the station) and a uniform spacing would fit it poorly.
- let v = v_a + (v_t - v_a) * 0.5 * (1.0 - (std::f64::consts::PI * i as f64 / m as f64).cos());
- let u = if i == 0 {
- u_o
- } else if i == m {
- u_t
- } else {
- let at_t = outside(u_t, v).ok_or_else(fail)?;
- let at_o = outside(u_o, v).ok_or_else(fail)?;
- // No crossing where the contacts are on one side: the curve is at the tangent one.
- if at_t * at_o >= 0.0 { u_t } else { bisect(&|x| outside(x, v), u_o, u_t).ok_or_else(fail)? }
- };
- stations.push((u, v, from_p3(surf.subs(u, v))));
- }
- let mut pts: Vec = stations.iter().map(|x| x.2).collect();
- // The curve runs from contact 1 to contact 2.
- if u_o == 1.0 {
- pts.reverse();
- }
- snap_to_seams(&mut pts, seams, tolerance);
- let bs = crate::build::interpolate_cubic(&pts).ok_or_else(fail)?;
- let gs = g.surface();
- let fits = stations.windows(2).enumerate().all(|(i, w)| {
- let (Some(a), Some(b)) = (w.first(), w.get(1)) else { return false };
- let t = if u_o == 1.0 { 1.0 - (i as f64 + 0.5) / m as f64 } else { (i as f64 + 0.5) / m as f64 };
- let q = p3(from_p3(bs.subs(t)));
- let hint = (0.5 * (a.0 + b.0), 0.5 * (a.1 + b.1));
- let on_g = gs.search_nearest_parameter(q, None, 100).is_some_and(|(x, y)| from_p3(gs.subs(x, y)).dist(from_p3(q)) <= tolerance);
- let on_s = surf.search_nearest_parameter(q, Some(hint), 100).is_some_and(|(x, y)| from_p3(surf.subs(x, y)).dist(from_p3(q)) <= tolerance);
- on_g && on_s
- });
- if fits {
- let (t1, t2) = if u_o == 0.0 { (v_a, v_t) } else { (v_t, v_a) };
- return Ok((t1, t2, mt::Curve::BSplineCurve(bs)));
- }
- }
- Err(fail())
-}
-
-/// One cross-section of the blend: ball centre and its contacts with side 1 and side 2.
-#[derive(Clone, Copy, Debug)]
-struct Section {
- c: Vec3,
- q1: Vec3,
- q2: Vec3,
-}
-
-/// The third condition of a section's solve, in place of staying in the plane square to the edge: a contact held at a seam.
-#[derive(Clone, Copy)]
-enum Extra<'a> {
- /// Side `k`'s contact lies in this plane (a point on it, its normal): beside a straight seam.
- Plane(usize, Vec3, Vec3),
- /// Side `k`'s contact lies on this curved seam (a lofted wall's seam between its two halves).
- Seam(usize, &'a mt::Edge),
-}
-
-/// The seam's point nearest `x` and its unit tangent there.
-fn nearest_on_seam(seam: &mt::Edge, x: Vec3) -> Option<(Vec3, Vec3)> {
- use mt::{BoundedCurve, ParametricCurve, SearchNearestParameter};
- let curve = seam.curve();
- let (lo, hi) = curve.range_tuple();
- let at = |t: f64| from_p3(curve.subs(t));
- // The nearest of a few samples starts the search: a long seam holds the point's neighbourhood
- // far from its ends.
- let hint = (0..=64).map(|i| lo + (hi - lo) * i as f64 / 64.0).min_by(|a, b| at(*a).dist(x).total_cmp(&at(*b).dist(x)))?;
- let t = curve.search_nearest_parameter(p3(x), hint, 100)?.clamp(lo, hi);
- let d = curve.der(t);
- Some((at(t), Vec3::new(d.x, d.y, d.z).normalized()?))
-}
-
-/// Nearest point of a face's surface and the outward normal there.
-pub(crate) fn project(f: &mt::Face, p: Vec3, hint: Option<(f64, f64)>) -> Option<(Vec3, Vec3, (f64, f64))> {
- use mt::{ParametricSurface, ParametricSurface3D, SearchNearestParameter};
- let s = f.oriented_surface();
- let uv = s.search_nearest_parameter(p3(p), hint, 100).or_else(|| s.search_nearest_parameter(p3(p), None, 100))?;
- let q = from_p3(s.subs(uv.0, uv.1));
- let n = s.normal(uv.0, uv.1);
- Some((q, Vec3::new(n.x, n.y, n.z).normalized()?, uv))
-}
-
-/// Whether `uv` lies within the parameters of the face's surface (unbounded directions pass).
-pub(crate) fn in_range(f: &mt::Face, uv: (f64, f64)) -> bool {
- use mt::ParametricSurface;
- use std::ops::Bound;
- let inside = |range: (Bound, Bound), x: f64| {
- let slack = |a: f64, b: f64| (b - a).abs() * 1e-6 + 1e-9;
- match range {
- (Bound::Included(a) | Bound::Excluded(a), Bound::Included(b) | Bound::Excluded(b)) => x >= a - slack(a, b) && x <= b + slack(a, b),
- (Bound::Included(a) | Bound::Excluded(a), Bound::Unbounded) => x >= a - 1e-9,
- (Bound::Unbounded, Bound::Included(b) | Bound::Excluded(b)) => x <= b + 1e-9,
- (Bound::Unbounded, Bound::Unbounded) => true,
- }
- };
- let (ru, rv) = f.oriented_surface().parameter_range();
- uv.0.is_finite() && uv.1.is_finite() && inside(ru, uv.0) && inside(rv, uv.1)
-}
-
-/// Solve for the ball touching both sides near `p`. `extra` adds a third condition (a plane the
-/// side-k contact must lie in, or a curved seam it must lie on); without it the centre stays in the
-/// plane through `p` square to `t`. `sigma` is +1 when the ball sits outside the material (concave edge), −1 inside.
-/// `cusp` is ±1 at a knife edge (the faces' normals opposite: both leave the edge the same way,
-/// along `cusp · n1 × t`, and the ball lies where the cusp has opened to its width), else 0.
-#[allow(clippy::too_many_arguments)]
-fn solve(f1: &[&mt::Face], f2: &[&mt::Face], p: Vec3, t: Vec3, r: f64, sigma: f64, cusp: f64, extra: Option>, tol: f64) -> Option {
- solve_from(f1, f2, p, t, r, sigma, cusp, extra, tol, None)
-}
-
-/// [`solve`], started from the centre `start` when given (the corner builder's balls at a knife
-/// edge start beside the last one).
-#[allow(clippy::too_many_arguments)]
-fn solve_from(
- f1: &[&mt::Face],
- f2: &[&mt::Face],
- p: Vec3,
- t: Vec3,
- r: f64,
- sigma: f64,
- cusp: f64,
- extra: Option>,
- tol: f64,
- start: Option,
-) -> Option {
- // The nearest face of a side (several faces on one smooth surface group). Each face's
- // search starts from its last answer: the centre moves little between iterations. An
- // answer outside the surface's parameters, or farther than that last point (the search
- // ran away or settled on the far side), is searched again cold.
- let last = std::cell::RefCell::new(HashMap::::new());
- let near = |fs: &[&mt::Face], c: Vec3| -> Option<(Vec3, Vec3)> {
- fs.iter()
- .filter_map(|f| {
- let prev = last.borrow().get(&f.id()).copied();
- let warm =
- prev.and_then(|(uv, q)| project(f, c, Some(uv)).filter(|(x, _, uv)| in_range(f, *uv) && x.dist(c) <= q.dist(c) + tol * 1e-3));
- let (q, n, uv) = match warm {
- Some(x) => x,
- None => project(f, c, None)?,
- };
- last.borrow_mut().insert(f.id(), (uv, q));
- Some((q, n))
- })
- .min_by(|a, b| a.0.dist(c).total_cmp(&b.0.dist(c)))
- };
- let (q1, n1) = near(f1, p)?;
- let (q2, n2) = near(f2, p)?;
- let _ = (q1, q2);
- let den = 1.0 + n1.dot(n2);
- let mut c = if let Some(c) = start {
- c
- } else if cusp != 0.0 && den.abs() < KNIFE {
- // The normals are (nearly) opposite: `(n1 + n2) / den` has no direction. The centre is r
- // inside face 1 and slides along it, away from the edge, until it is r from face 2 too.
- let w = n1.cross(t).normalized()? * cusp;
- let centre = |s: f64| -> Option {
- let (qa, na) = near(f1, p + w * s)?;
- Some(qa + na * (sigma * r))
- };
- let gap = |s: f64| -> Option {
- let c = centre(s)?;
- let (q2, n2) = near(f2, c)?;
- Some((c - q2).dot(n2) - sigma * r)
- };
- let (mut lo, mut g_lo) = (0.0, gap(0.0)?);
- let mut hi = None;
- let mut s = r * 0.05;
- for _ in 0..KNIFE_STEPS {
- let Some(g) = gap(s) else { break };
- if g == 0.0 || g.is_sign_negative() != g_lo.is_sign_negative() {
- hi = Some(s);
- break;
- }
- (lo, g_lo) = (s, g);
- s *= 1.6;
- }
- let mut hi = hi?;
- for _ in 0..60 {
- let mid = 0.5 * (lo + hi);
- match gap(mid) {
- Some(g) if g.is_sign_negative() == g_lo.is_sign_negative() => lo = mid,
- Some(_) => hi = mid,
- None => break,
- }
- }
- centre(0.5 * (lo + hi))?
- } else {
- if den.abs() < 1e-9 {
- return None;
- }
- p + (n1 + n2) * (sigma * r / den)
- };
- for _ in 0..60 {
- let (q1, n1) = near(f1, c)?;
- let (q2, n2) = near(f2, c)?;
- let g1 = (c - q1).dot(n1) - sigma * r;
- let g2 = (c - q2).dot(n2) - sigma * r;
- // Third row: stay in the section plane, or put a contact on the seam plane.
- let (row3, g3) = match extra {
- None => (t, (c - p).dot(t)),
- Some(Extra::Plane(k, o, m)) => {
- let q = if k == 1 { q1 } else { q2 };
- (m, (q - o).dot(m))
- }
- Some(Extra::Seam(k, seam)) => {
- // The plane through the seam's nearest point to the contact, square to that side's
- // surface, taken afresh each step: it holds the contact on the curved seam as the
- // steps close in.
- let (q, n) = if k == 1 { (q1, n1) } else { (q2, n2) };
- let (on_seam, d) = nearest_on_seam(seam, q)?;
- let m = d.cross(n).normalized()?;
- (m, (q - on_seam).dot(m))
- }
- };
- let a = [[n1.x, n1.y, n1.z], [n2.x, n2.y, n2.z], [row3.x, row3.y, row3.z]];
- let b = [-g1, -g2, -g3];
- let x = crate::polyhedron::solve3_pub(a, b)?;
- let dc = Vec3::new(x[0], x[1], x[2]);
- c += dc;
- if dc.len() < tol * 1e-3 && g1.abs() < tol && g2.abs() < tol && g3.abs() < tol {
- let (q1, _) = near(f1, c)?;
- let (q2, _) = near(f2, c)?;
- return Some(Section { c, q1, q2 });
- }
- }
- None
-}
-
-/// Contacts of a convex chamfer in a cross-section normal to a straight edge. The caller
-/// checks that sweeping the section stays on both supports within the fitting tolerance.
-pub(crate) fn straight_chamfer_contacts(f1: &mt::Face, f2: &mt::Face, p: Vec3, d: Vec3, r: f64, tolerance: f64) -> Option<(Vec3, Vec3)> {
- let section = solve(&[f1], &[f2], p, d, r, -1.0, 0.0, None, tolerance)?;
- Some((section.q1, section.q2))
-}
-
-/// The section whose two contacts are `chord` apart: the ball's radius is `chord / (2 sin(ψ/2))`
-/// for the `ψ` between the two outward normals where it touches, `|q1 − q2| = 2 r sin(ψ/2)`. The
-/// normals turn as the ball grows against curved faces, so the width is measured on the solved
-/// section and the radius corrected until it matches (the width is proportional to the radius,
-/// so the corrections converge quickly). The normals at `p` give the first radius, exact where
-/// both faces are planar; `None` where the faces meet too nearly tangentially to span a chord.
-#[allow(clippy::too_many_arguments)]
-fn solve_chord(
- f1: &[&mt::Face],
- f2: &[&mt::Face],
- p: Vec3,
- t: Vec3,
- chord: f64,
- sigma: f64,
- cusp: f64,
- extra: Option>,
- tol: f64,
-) -> Option<(Section, f64)> {
- let normal = |fs: &[&mt::Face]| fs.iter().filter_map(|f| project(f, p, None)).min_by(|a, b| a.0.dist(p).total_cmp(&b.0.dist(p))).map(|x| x.1);
- let (n1, n2) = (normal(f1)?, normal(f2)?);
- let half = (n1.dot(n2).clamp(-1.0, 1.0).acos() / 2.0).sin();
- if !(half > 1e-3) {
- return None;
- }
- let mut r = chord / (2.0 * half);
- for _ in 0..CHORD_STEPS {
- if !(r.is_finite() && r > 0.0 && r < 1e9) {
- return None;
- }
- let s = solve(f1, f2, p, t, r, sigma, cusp, extra, tol)?;
- let width = s.q1.dist(s.q2);
- if !width.is_finite() || width <= 0.0 {
- return None;
- }
- if (width - chord).abs() <= (chord * 1e-9).max(tol * 0.5) {
- return Some((s, r));
- }
- r *= chord / width;
- }
- None
-}
-
-/// The rolling ball at one station, sized by the blend's law.
-struct Sizer<'a> {
- size: Size<'a>,
- /// The tolerance the section's equations are solved at.
- tol: f64,
-}
-
-impl Sizer<'_> {
- /// The section at `p` (tangent `t`, the size law's parameter `s`) holding the third
- /// condition `extra` when given, with the radius it was solved at.
- #[allow(clippy::too_many_arguments)]
- fn section(
- &self,
- f1: &[&mt::Face],
- f2: &[&mt::Face],
- p: Vec3,
- t: Vec3,
- s: f64,
- sigma: f64,
- cusp: f64,
- extra: Option>,
- ) -> Option<(Section, f64)> {
- match self.size {
- Size::Constant(r) => solve(f1, f2, p, t, r, sigma, cusp, extra, self.tol).map(|x| (x, r)),
- Size::Chord(chord) => solve_chord(f1, f2, p, t, chord, sigma, cusp, extra, self.tol),
- Size::Law(law) => {
- let r = law_beyond(law, s)?;
- if !(r.is_finite() && (0.0..1e6).contains(&r)) {
- return None;
- }
- solve(f1, f2, p, t, r, sigma, cusp, extra, self.tol).map(|x| (x, r))
- }
- }
- }
-
- /// What a station the ball does not fit at is refused with: a chord too large is about the
- /// size asked for, anything else about where the ball is.
- fn refusal(&self) -> KernelError {
- match self.size {
- Size::Chord(_) => too_large("the blend is larger than the neighbouring faces (site 704)"),
- _ => unsupported("the ball doesn't fit along the edge"),
- }
- }
-}
-
-/// Whether the strip's curvature jumps where two runs of sections meet (each three sections from
-/// the joint outward, the joint's first): for the centres or either contact, the difference of
-/// the circles through them would move the middle section by more than a tenth of `tolerance`.
-fn bends(a: [&Section; 3], b: [&Section; 3], tolerance: f64) -> bool {
- let curvature = |p: [Vec3; 3]| {
- let (x, y, z) = (p[1] - p[0], p[2] - p[1], p[2] - p[0]);
- let d = x.len() * y.len() * z.len();
- if d > 1e-300 { 2.0 * x.cross(y).len() / d } else { 0.0 }
- };
- let h = a[0].c.dist(a[1].c);
- [|s: &Section| s.c, |s: &Section| s.q1, |s: &Section| s.q2]
- .iter()
- .any(|f| (curvature(a.map(f)) - curvature(b.map(f))).abs() * h * h > tolerance * 0.1)
-}
-
-/// Whether the section is a point: a blend whose radius has run to zero, closing to the edge's
-/// end point there.
-fn closed_section(s: &Section) -> bool {
- s.c.dist(s.q1) <= CLOSED && s.c.dist(s.q2) <= CLOSED
-}
-
-/// Homogeneous control points of the circular (or straight) cross-section from q1 to q2.
-fn section_controls(s: &Section, round: bool) -> Option<[mt::Vector4; 3]> {
- let h = |p: Vec3, w: f64| mt::Vector4::new(p.x * w, p.y * w, p.z * w, w);
- if !round {
- let m = (s.q1 + s.q2) * 0.5;
- return Some([h(s.q1, 1.0), h(m, 1.0), h(s.q2, 1.0)]);
- }
- if closed_section(s) {
- // A closed section: the arc has shrunk to the edge's end point, all three controls
- // there, so the fitted strips of the neighbouring faces meet at that vertex.
- return Some([h(s.c, 1.0), h(s.c, 1.0), h(s.c, 1.0)]);
- }
- let (a, b) = (s.q1 - s.c, s.q2 - s.c);
- let theta = a.normalized()?.dot(b.normalized()?).clamp(-1.0, 1.0).acos();
- if !(theta > 1e-6 && theta < std::f64::consts::PI - 1e-6) {
- return None;
- }
- let half = (theta / 2.0).cos();
- let bis = (a + b).normalized()?;
- let m = s.c + bis * (a.len() / half);
- Some([h(s.q1, 1.0), h(m, half), h(s.q2, 1.0)])
-}
-
-/// Where to start the ball at a knife edge through `p` (direction `t`, the sides running on from
-/// it along `into`): the first point along them, from the edge, where they are a diameter
-/// apart, midway.
-fn knife_start(o1: &[&mt::Face], o2: &[&mt::Face], p: Vec3, t: Vec3, into: Vec3, r: f64) -> Option {
- let w = (into - t * into.dot(t)).normalized()?;
- (1..=256).find_map(|k| {
- let x = p + w * (r * k as f64 / 8.0);
- let a = o1.iter().filter_map(|f| project(f, x, None)).min_by(|a, b| a.0.dist(x).total_cmp(&b.0.dist(x)))?;
- let b = o2.iter().filter_map(|f| project(f, x, None)).min_by(|a, b| a.0.dist(x).total_cmp(&b.0.dist(x)))?;
- let c = (a.0 + b.0) * 0.5;
- (a.0.dist(b.0) >= 2.0 * r).then(|| c - t * (c - p).dot(t))
- })
-}
-
-/// Whether two faces meeting at no angle at `pm` (the first's outward normal `n1`, running on
-/// from the edge along `into`) hold the material between them: a little way in, the second is
-/// behind the first.
-fn knife_convex(f1: &mt::Face, f2: &mt::Face, pm: Vec3, into: Vec3, r: f64) -> Option {
- let x = pm + into * r;
- let (a, b) = (project(f1, x, None)?, project(f2, x, None)?);
- Some((b.0 - a.0).dot(a.1) < 0.0)
-}
-
-/// The nearest point of a face's (oriented) surface to `x`, its outward normal and parameters;
-/// `last`: where the last search on it ended (the points asked about come in small steps).
-fn nearest_on(surface: &mt::Surface, last: &std::cell::Cell>, x: Vec3) -> Option<(Vec3, Vec3, (f64, f64))> {
- use mt::{ParametricSurface, ParametricSurface3D, SearchNearestParameter};
- // The nearest of the search from the last answer, a fresh one (the first time, also from
- // a grid over the surface's parameters: a fresh search on a conic can settle on its far
- // side) and either kept within the parameters (past them a conic runs on round).
- let (ru, rv) = surface.try_range_tuple();
- let ((u0, u1), (v0, v1)) = (ru.unwrap_or((f64::NEG_INFINITY, f64::INFINITY)), rv.unwrap_or((f64::NEG_INFINITY, f64::INFINITY)));
- let inside = |uv: (f64, f64)| uv.0 >= u0 - 1e-9 && uv.0 <= u1 + 1e-9 && uv.1 >= v0 - 1e-9 && uv.1 <= v1 + 1e-9;
- let warm = last.get().and_then(|hint| surface.search_nearest_parameter(p3(x), Some(hint), 20));
- let mut found: Vec<(f64, f64)> = warm.into_iter().collect();
- if !warm.is_some_and(inside) {
- found.extend(surface.search_nearest_parameter(p3(x), None, 100));
- }
- if last.get().is_none() && [u0, u1, v0, v1].iter().all(|x| x.is_finite()) {
- for i in 0..5 {
- for j in 0..5 {
- let hint = (u0 + (u1 - u0) * (i as f64 + 0.5) / 5.0, v0 + (v1 - v0) * (j as f64 + 0.5) / 5.0);
- found.extend(surface.search_nearest_parameter(p3(x), Some(hint), 50));
- }
- }
- }
- let clamped: Vec<(f64, f64)> = found.iter().map(|(u, v)| (u.clamp(u0, u1), v.clamp(v0, v1))).collect();
- found.extend(clamped);
- let d = |uv: &(f64, f64)| from_p3(surface.subs(uv.0, uv.1)).dist(x);
- let uv = found.into_iter().filter(|uv| d(uv).is_finite()).min_by(|a, b| d(a).total_cmp(&d(b)))?;
- last.set(Some(uv));
- let n = surface.normal(uv.0, uv.1);
- Some((from_p3(surface.subs(uv.0, uv.1)), Vec3::new(n.x, n.y, n.z).normalized()?, uv))
-}
-
-/// The strip with parameters in proportion to its lengths across and along (the same surface).
-/// The mesher triangulates a face in its parameters: on a unit square for a strip a few
-/// millimetres wide and tens long, the points of a slanted end fan out into triangles so long
-/// along the curve that they turn over.
-fn in_proportion(surface: &mt::Surface) -> Result {
- use mt::ParametricSurface;
- let fail = || KernelError::Failed("curve blend: strip parameters".into());
- let mt::Surface::NurbsSurface(ns) = surface else { return Err(fail()) };
- let length = |at: &dyn Fn(f64) -> Vec3| (0..32).map(|i| at(i as f64 / 32.0).dist(at((i + 1) as f64 / 32.0))).sum::();
- let across = length(&|u| from_p3(surface.subs(u, 0.5)));
- let along = length(&|v| from_p3(surface.subs(0.5, v)));
- if !(across.is_finite() && along.is_finite() && across > 1e-9 && along > 1e-9) {
- return Err(fail());
- }
- let bs = ns.non_rationalized();
- let (mut uk, mut vk) = bs.knot_vecs().clone();
- uk.transform(across, 0.0);
- vk.transform(along, 0.0);
- let bs = mt::BSplineSurface::try_new((uk, vk), bs.control_points().clone()).map_err(|_| fail())?;
- Ok(mt::Surface::NurbsSurface(mt::NurbsSurface::new(bs)))
-}
-
-/// A chain edge the ball turns about instead of rolling along: an arc of the blend's radius on a
-/// planar side (`side`), curving round the ball (a rounded corner rounded again). The ball's
-/// centre stays at `c`, it touches the planar side only at the arc's centre `o`, and the blend
-/// there is a piece of sphere (of cone, for a chamfer) about the axis through `c` along `axis`.
-#[derive(Clone, Copy, Debug)]
-struct Pivot {
- c: Vec3,
- o: Vec3,
- axis: Vec3,
- side: usize,
-}
-
-/// The circle an edge lies on (centre, radius, axis), if it is an arc of one within `tol`.
-pub(crate) fn circle_of(e: &mt::Edge, tol: f64) -> Option<(Vec3, f64, Vec3)> {
- use mt::{BoundedCurve, ParametricCurve};
- let curve = e.oriented_curve();
- let (t0, t1) = curve.range_tuple();
- let at = |f: f64| from_p3(curve.subs(t0 + (t1 - t0) * f));
- let (a, u, v) = (at(0.0), at(0.5) - at(0.0), at(1.0) - at(0.0));
- let w = u.cross(v);
- if w.len2() < 1e-24 {
- return None;
- }
- let o = a + (v * u.len2() - u * v.len2()).cross(w) * (1.0 / (2.0 * w.len2()));
- let (rho, axis) = (o.dist(a), w.normalized()?);
- (0..=8).map(|i| at(i as f64 / 8.0)).all(|p| (p.dist(o) - rho).abs() <= tol && (p - o).dot(axis).abs() <= tol).then_some((o, rho, axis))
-}
-
-/// The surface the section (homogeneous controls from contact 1 to contact 2) sweeps turning by
-/// `angle` about the axis through `c` along the unit `axis`: rational quadratic arcs in v, a
-/// quarter turn at most each, so it is exact.
-fn revolve(ctrl: [mt::Vector4; 3], c: Vec3, axis: Vec3, angle: f64) -> Option {
- let pieces = ((angle.abs() / std::f64::consts::FRAC_PI_2).ceil() as usize).clamp(1, 8);
- let step = angle / pieces as f64;
- let half = (step / 2.0).cos();
- if !(half.is_finite() && half > 1e-6) {
- return None;
- }
- let rot = |x: Vec3, phi: f64| {
- let (s, co) = phi.sin_cos();
- x * co + axis.cross(x) * s + axis * (axis.dot(x) * (1.0 - co))
- };
- let h = |p: Vec3, w: f64| mt::Vector4::new(p.x * w, p.y * w, p.z * w, w);
- let mut rows = Vec::with_capacity(3);
- for q in ctrl {
- if !(q.w.is_finite() && q.w > 1e-12) {
- return None;
- }
- let x = Vec3::new(q.x / q.w, q.y / q.w, q.z / q.w) - c;
- let along = axis * axis.dot(x);
- let mut row = vec![h(c + x, q.w)];
- for i in 0..pieces {
- let a0 = step * i as f64;
- row.push(h(c + along + rot(x - along, a0 + step / 2.0) * (1.0 / half), q.w * half));
- row.push(h(c + rot(x, a0 + step), q.w));
- }
- rows.push(row);
- }
- let mut knots = vec![0.0; 3];
- for i in 1..pieces {
- let k = i as f64 / pieces as f64;
- knots.extend([k, k]);
- }
- knots.extend([1.0; 3]);
- let bs = mt::BSplineSurface::try_new((mt::KnotVec::bezier_knot(2), mt::KnotVec::from(knots)), rows).ok()?;
- Some(mt::Surface::NurbsSurface(mt::NurbsSurface::new(bs)))
-}
-
-/// Whether the edge is straight: a line, or a curve on the segment between its ends within
-/// `tol` (an earlier blend's contact along a straight edge is a fitted curve).
-pub(crate) fn straight(e: &mt::Edge, tol: f64) -> bool {
- use mt::{BoundedCurve, ParametricCurve};
- let c = e.curve();
- if matches!(c, mt::Curve::Line(_)) {
- return true;
- }
- let (a, b) = (from_p3(e.front().point()), from_p3(e.back().point()));
- let (t0, t1) = c.range_tuple();
- a.dist(b) > tol && (0..=16).all(|i| from_p3(c.subs(t0 + (t1 - t0) * i as f64 / 16.0)).dist_to_segment(a, b) <= tol)
-}
-
-/// Consuming both seams of a side can leave its old boundary and a fitted contact on the
-/// same curve (#1113). They are distinct topological edges but enclose no usable face. Keep
-/// genuine two-edge faces (a lens or lune); refuse only coincident traces, in both directions
-/// since the curves need not have the same parameterisation.
-fn collapsed_boundary(edges: &[mt::Edge], tolerance: f64) -> bool {
- use mt::{BoundedCurve, ParametricCurve};
- let [a, b] = edges else { return false };
- [(a, b), (b, a)].into_iter().all(|(edge, other)| {
- let curve = edge.curve();
- let (lo, hi) = curve.range_tuple();
- (0..=16).all(|k| {
- let p = from_p3(curve.subs(lo + (hi - lo) * f64::from(k) / 16.0));
- crate::blend::on_edge(other, p, tolerance).is_some()
- })
- })
-}
-
-/// A curved seam (an arc of an end face) shortened to the blend's contacts: the part of its
-/// curve between the new ends `a` and `b` (`None` keeps that end), which must lie on it, in
-/// order, short of each other.
-pub(crate) fn trim_curved_seam(seam: &mt::Edge, a: Option, b: Option, size: f64) -> Result {
- // A closed seam (a full circle starting and ending at one vertex) has no "between": which
- // end a contact replaces, and which way round the kept piece runs, are both ambiguous.
- if seam.front() == seam.back() {
- return Err(unsupported("a closed curved edge where the blend ends"));
- }
- use mt::{BoundedCurve, Cut, SearchNearestParameter};
- let mut curve = seam.curve();
- let (lo, hi) = curve.range_tuple();
- let at = |v: &Option, end: f64| -> Result {
- let Some(v) = v else { return Ok(end) };
- // Start from the nearest of a few samples: from the far end of a long arc
- // the search can settle on the opposite side of the circle.
- let q = from_p3(v.point());
- let hint = (0..=32)
- .map(|i| lo + (hi - lo) * i as f64 / 32.0)
- .min_by(|x, y| {
- let d = |t: f64| from_p3(mt::ParametricCurve::subs(&curve, t)).dist(q);
- d(*x).total_cmp(&d(*y))
- })
- .unwrap_or(end);
- let t = curve.search_nearest_parameter(v.point(), hint, 100).ok_or_else(|| unsupported("the blend is larger than the neighbouring faces"))?;
- if !(t.is_finite() && from_p3(mt::ParametricCurve::subs(&curve, t)).dist(from_p3(v.point())) <= size * 1e-5) {
- return Err(too_large("the blend is larger than the neighbouring faces (site 938)"));
- }
- Ok(t)
- };
- let (ta, tb) = (at(&a, lo)?, at(&b, hi)?);
- let margin = (hi - lo) * 1e-9;
- if ta < lo - margin || tb > hi + margin || tb - ta < (hi - lo) * 1e-6 {
- return Err(too_large("the blend is larger than the neighbouring faces (site 945)"));
- }
- if tb < hi {
- let _ = curve.cut(tb);
- }
- let piece = if ta > lo { curve.cut(ta) } else { curve };
- let a = a.unwrap_or_else(|| seam.front().clone());
- let b = b.unwrap_or_else(|| seam.back().clone());
- mt::Edge::try_new(&a, &b, piece).map_err(|e| KernelError::Failed(format!("curve blend: seam: {e}")))
-}
-
-/// A monotone curve's parameter read off a table of its values at uniform parameters (`None` for
-/// an empty table): the fraction of the way through it.
-fn sampled(table: &[f64], along: f64) -> Option {
- if table.len() < 2 || !along.is_finite() {
- return None;
- }
- let x = along.clamp(0.0, 1.0) * (table.len() - 1) as f64;
- let i = (x.floor() as usize).min(table.len() - 2);
- let f = x - i as f64;
- Some(table.get(i)? * (1.0 - f) + table.get(i + 1)? * f)
-}
-
-/// The arc length of `edge` from its front to its back at each of `LENGTH_STEPS + 1` uniform
-/// parameters, accumulated. `None` for an edge that has no length (or runs back over itself).
-fn edge_lengths(edge: &mt::Edge) -> Option> {
- use mt::{BoundedCurve, ParametricCurve};
- let c = edge.oriented_curve();
- let (a, b) = c.range_tuple();
- let mut last = from_p3(c.subs(a));
- let mut total = 0.0;
- let mut out = Vec::with_capacity(LENGTH_STEPS + 1);
- out.push(0.0);
- for i in 1..=LENGTH_STEPS {
- let p = from_p3(c.subs(a + (b - a) * i as f64 / LENGTH_STEPS as f64));
- total += last.dist(p);
- last = p;
- out.push(total);
- }
- (total.is_finite() && total > 1e-12).then_some(out)
-}
-
-/// The radius a law gives at the chain fraction `s`, continued past 0 and 1 at the law's own end
-/// slope. The ball runs on past a chain end (to be cut back there by its end face), and holding
-/// the end radius would kink the strip exactly where the edge begins: a kink a cubic fit spreads
-/// back over the whole blend. Never below a fifth of the end radius, so that a law running down
-/// steeply still has a ball to run on with.
-fn law_beyond(law: &RadiusSpline, s: f64) -> Option {
- if (0.0..=1.0).contains(&s) {
- return Some(law.eval(s));
- }
- let (end, step) = if s < 0.0 { (0.0, s) } else { (1.0, s - 1.0) };
- let h = 1e-3;
- let slope = (law.eval(end + h) - law.eval(end)) / h;
- let r = law.eval(end);
- let r = (r + slope * step).max(0.2 * r);
- (r.is_finite() && r > 0.0).then_some(r)
-}
-
-/// Blend the closed chain of edges (ids in any order) with radius `r`; with what it built from
-/// `solid` (each blend face in place of its chain edge).
-pub(crate) fn curve_blend(solid: &Solid, ids: &[mt::EdgeID], size: f64, r: f64, round: bool) -> Result<(Solid, Rebuild)> {
- curve_blend_with_limit(solid, ids, size, r, round, MAX_SAMPLES)
-}
-
-/// [`curve_blend`] with the blend `chord` wide across, from contact to contact, at every station.
-pub(crate) fn curve_blend_chord(solid: &Solid, ids: &[mt::EdgeID], size: f64, chord: f64, round: bool) -> Result<(Solid, Rebuild)> {
- curve_blend_sized(solid, ids, size, Size::Chord(chord), round, MAX_SAMPLES)
-}
-
-/// [`curve_blend`] with the radius following `law` along the chain (its positions the fraction of
-/// the chain's arc length, from the front of its first edge to the back of its last).
-pub(crate) fn curve_blend_law(solid: &Solid, ids: &[mt::EdgeID], size: f64, law: &RadiusSpline, round: bool) -> Result<(Solid, Rebuild)> {
- curve_blend_sized(solid, ids, size, Size::Law(law), round, MAX_SAMPLES)
-}
-
-fn curve_blend_with_limit(solid: &Solid, ids: &[mt::EdgeID], size: f64, r: f64, round: bool, max_samples: usize) -> Result<(Solid, Rebuild)> {
- curve_blend_sized(solid, ids, size, Size::Constant(r), round, max_samples)
-}
-
-/// Blend the chain of edges (ids in any order) sized by `size`: one radius, a chord width, or a
-/// radius law. With what it built from `solid` (each blend face in place of its chain edge).
-fn curve_blend_sized(solid: &Solid, ids: &[mt::EdgeID], size: f64, size_law: Size<'_>, round: bool, max_samples: usize) -> Result<(Solid, Rebuild)> {
- if !(size.is_finite() && size > 0.0) {
- return Err(KernelError::Invalid("curve blend size and radius must be finite and positive".into()));
- }
- match size_law {
- Size::Constant(r) | Size::Chord(r) => {
- if !(r.is_finite() && r > 1e-6 && r < 1e6) {
- return Err(KernelError::Invalid("curve blend size and radius must be finite and positive".into()));
- }
- }
- Size::Law(law) => {
- let knots = law.knots.len() == law.radii.len() + law.degree + 1;
- if law.radii.len() < 2 || !knots || law.radii.iter().any(|r| !(r.is_finite() && (0.0..1e6).contains(r))) {
- return Err(KernelError::Invalid("a radius law along the edge must be finite and non-negative".into()));
- }
- // A law that runs to zero closes the blend at the edge's end point. The fitted strip
- // pinches to a point there, and the sections' own interpolation cannot follow the last
- // span of it: the straight-edge fillet, which builds that closure exactly, is the way.
- if law.eval(0.0) <= CLOSED || law.eval(1.0) <= CLOSED {
- return Err(unsupported("a radius law that runs to zero along a curved edge"));
- }
- }
- }
- if !(4..=MAX_SAMPLES).contains(&max_samples) {
- return Err(KernelError::Invalid("curve blend section limit is outside the supported range".into()));
- }
- let tol = (size * 1e-7).max(1e-9);
- let shells = solid.boundaries();
- let (si, shell) = shells
- .iter()
- .enumerate()
- .find(|(_, sh)| sh.edge_iter().any(|e| ids.contains(&e.id())))
- .ok_or_else(|| KernelError::Failed("edge not found".into()))?;
- let faces: Vec = shell.face_iter().cloned().collect();
- // Order the chain: edges as stored (absolute direction), each starting where the last ended.
- let mut chain: Vec = Vec::new();
- let all: Vec = {
- let mut seen = std::collections::HashSet::new();
- shell.edge_iter().filter(|e| ids.contains(&e.id()) && seen.insert(e.id())).map(|e| e.absolute_clone()).collect()
- };
- // An open chain starts at a vertex only one of its edges touches.
- let uses = |v: &mt::Vertex| all.iter().filter(|e| e.front() == v || e.back() == v).count();
- let first = match all.iter().find_map(|e| {
- if uses(e.front()) == 1 {
- Some(e.clone())
- } else if uses(e.back()) == 1 {
- Some(e.inverse())
- } else {
- None
- }
- }) {
- Some(e) => e,
- None => all.first().cloned().ok_or_else(|| KernelError::Failed("no edges".into()))?,
- };
- chain.push(first.clone());
- while chain.len() < all.len() {
- let end = chain.last().map(|e| e.back().clone()).ok_or_else(|| KernelError::Failed("chain".into()))?;
- let next = all
- .iter()
- .find(|e| !chain.iter().any(|c| c.id() == e.id()) && (*e.front() == end || *e.back() == end))
- .ok_or_else(|| unsupported("the edges don't form one chain"))?;
- chain.push(if *next.front() == end { next.clone() } else { next.inverse() });
- }
- let closed = chain.first().map(|e| e.front().clone()) == chain.last().map(|e| e.back().clone());
- let n = chain.len();
- // The chain's vertices (n for a closed chain, n + 1 for an open one).
- let mut verts: Vec = chain.iter().map(|e| e.front().clone()).collect();
- if !closed && let Some(e) = chain.last() {
- verts.push(e.back().clone());
- }
- let nv = verts.len();
- // Faces of each edge, split into the two sides.
- let faces_of = |e: &mt::Edge| -> Vec {
- (0..faces.len()).filter(|i| faces.get(*i).is_some_and(|f| f.edge_iter().any(|x| x.id() == e.id()))).collect()
- };
- let mut side1: Vec = Vec::new();
- let mut side2: Vec = Vec::new();
- for (k, e) in chain.iter().enumerate() {
- let fs = faces_of(e);
- let [a, b] = fs[..] else { return Err(unsupported("an edge without two faces")) };
- if k == 0 {
- side1.push(a);
- side2.push(b);
- continue;
- }
- // The side-1 face of this edge is the one whose normal matches side 1 at the joint.
- let p = from_p3(e.front().point());
- let nrm = |fi: usize| faces.get(fi).and_then(|f| project(f, p, None)).map(|x| x.1);
- let prev1 = side1.last().copied().and_then(nrm);
- let (na, nb) = (nrm(a), nrm(b));
- let a_is_1 = match (prev1, na, nb) {
- (Some(x), Some(y), Some(z)) => x.dot(y) >= x.dot(z),
- _ => return Err(KernelError::Failed("blend: normals".into())),
- };
- if a_is_1 {
- side1.push(a);
- side2.push(b);
- } else {
- side1.push(b);
- side2.push(a);
- }
- }
- let s1: Vec<&mt::Face> = side1.iter().filter_map(|i| faces.get(*i)).collect();
- let s2: Vec<&mt::Face> = side2.iter().filter_map(|i| faces.get(*i)).collect();
- // The faces the ball may touch near edges `ks` of the chain: their own, on each side. (The
- // surface of another face of a side, such as a wall's plane past the bend it runs into,
- // may pass nearer than the face the ball actually rolls on.)
- let edge_sides = |ks: &[usize]| -> (Vec<&mt::Face>, Vec<&mt::Face>) {
- let pick = |side: &[usize]| {
- let mut out: Vec = Vec::new();
- for k in ks {
- if let Some(fi) = side.get(*k)
- && !out.contains(fi)
- {
- out.push(*fi);
- }
- }
- out.iter().filter_map(|i| faces.get(*i)).collect::>()
- };
- (pick(&side1), pick(&side2))
- };
- // The chain's edges at vertex k.
- let vertex_edges = |k: usize| -> Vec {
- if closed {
- vec![(k + n - 1) % n, k % n]
- } else if k == 0 {
- vec![0]
- } else if k >= n {
- vec![n - 1]
- } else {
- vec![k - 1, k]
- }
- };
- // Convex or concave, from the first edge as its side-1 face runs it.
- let e0 = chain.first().ok_or_else(|| KernelError::Failed("chain".into()))?;
- let f1 = s1.first().ok_or_else(|| KernelError::Failed("side".into()))?;
- let in_f1 = f1.boundary_iters().into_iter().flatten().find(|e| e.id() == e0.id()).ok_or_else(|| KernelError::Failed("edge use".into()))?;
- let (pm, t1) = {
- use mt::{BoundedCurve, ParametricCurve};
- let c = in_f1.oriented_curve();
- let (a, b) = c.range_tuple();
- let m = (a + b) * 0.5;
- let d = c.der(m);
- (from_p3(c.subs(m)), Vec3::new(d.x, d.y, d.z).normalized().ok_or_else(|| KernelError::Failed("tangent".into()))?)
- };
- let (n1, n2) = match (project(f1, pm, None), s2.first().and_then(|f| project(f, pm, None))) {
- (Some(x), Some(y)) => (x.1, y.1),
- _ => return Err(KernelError::Failed("blend: normals".into())),
- };
- // A knife edge (opposite normals): both faces leave the edge along `w`; the second one lies
- // below the first (against its outward normal) when the cusp is material, above when it is
- // a gap. The cross product of the normals, which tells the other edges apart, is zero here.
- let knife = 1.0 + n1.dot(n2) < KNIFE;
- // The one radius, where the size is one radius (a chord or a law has none).
- let fixed = match size_law {
- Size::Constant(r) => Some(r),
- _ => None,
- };
- // The blend's scale where the size itself is not what matters (the knife edge's probe): the
- // radius asked for, or the law's middle value.
- let scale = match size_law {
- Size::Constant(r) | Size::Chord(r) => r,
- Size::Law(law) => law.eval(0.5).max(1e-6),
- };
- let (convex, cusp) = if knife {
- let w = n1.cross(t1).normalized().ok_or_else(|| KernelError::Failed("blend: cusp direction".into()))?;
- // Second order: from the point of face 1 a little way along `w`, face 2's nearest point.
- let probe = project(f1, pm + w * scale, None)
- .and_then(|(qa, na, _)| s2.first().and_then(|f| project(f, qa, None)).map(|(qb, _, _)| (qb - qa).dot(na)))
- .filter(|depth| depth.abs() > size * 1e-9)
- .ok_or_else(|| unsupported("a knife edge whose faces lie flat on each other"))?;
- // Whether the chain runs along the edge as face 1 uses it decides which way `w` points
- // from the chain's tangent.
- (probe < 0.0, if in_f1.front() == e0.front() { 1.0 } else { -1.0 })
- } else {
- (t1.dot(n1.cross(n2)) > 0.0, 0.0)
- };
- let sigma = if convex { -1.0 } else { 1.0 };
- if n1.dot(n2) > 1.0 - 1e-6 {
- return Err(unsupported("blending a smooth edge"));
- }
- // The chain's arc length, in fractions of its whole, at each station: where the size is one
- // radius it is not read, but the sections take their parameter from it all the same.
- let tables: Vec> = chain.iter().map(|e| edge_lengths(e).unwrap_or_else(|| vec![0.0; LENGTH_STEPS + 1])).collect();
- let total: f64 = tables.iter().filter_map(|t| t.last().copied()).sum();
- if !matches!(size_law, Size::Constant(_)) && !(total.is_finite() && total > 1e-12) {
- return Err(unsupported("a zero-length edge of the chain"));
- }
- let total = if total > 1e-12 { total } else { 1.0 };
- let mut cum: Vec = Vec::with_capacity(n + 1);
- let mut acc = 0.0;
- for table in &tables {
- cum.push(acc);
- acc += table.last().copied().unwrap_or(0.0);
- }
- cum.push(acc);
- // A law that runs around a closed chain meets itself: its two ends must agree there.
- if closed
- && let Size::Law(law) = size_law
- && (law.eval(0.0) - law.eval(1.0)).abs() > 1e-9 * law.radii.iter().copied().fold(1.0_f64, f64::max)
- {
- return Err(KernelError::Invalid("a closed edge chain runs back into itself: give the same radius law at both ends".into()));
- }
- // The law's parameter at `along` of edge `k` (its front to its back).
- let frac_at = |k: usize, along: f64| -> f64 {
- let (Some(table), Some(lo)) = (tables.get(k), cum.get(k)) else { return if k >= n { 1.0 } else { 0.0 } };
- let s = sampled(table, along).unwrap_or(0.0);
- ((lo + s) / total).clamp(0.0, 1.0)
- };
- let sizer = Sizer { size: size_law, tol: tol * 100.0 };
- // Arcs on a planar side that curve round the ball: its centre runs round them at their
- // radius less the blend's. Less than nothing is too large; nothing is a pivot.
- let mut pivots: Vec> = vec![None; n];
- 'pivots: for (k, e) in chain.iter().enumerate() {
- // A size that varies along the edge has no one radius to compare a corner's arc with.
- let Some(r) = fixed else { break 'pivots };
- let Some((o, rho, _)) = circle_of(e, tol * 1e3) else { continue };
- for side in [1, 2] {
- let Some(f) = (if side == 1 { side1.get(k) } else { side2.get(k) }).and_then(|i| faces.get(*i)) else { continue };
- let mt::Surface::Plane(pl) = f.oriented_surface() else { continue };
- let Some(np) = Vec3::new(pl.normal().x, pl.normal().y, pl.normal().z).normalized() else { continue };
- // Into the face (left of the edge as the face runs it, about its outward normal).
- let Some(used) = f.boundary_iters().into_iter().flatten().find(|x| x.id() == e.id()) else { continue };
- let Some((pm, tm)) = ({
- use mt::{BoundedCurve, ParametricCurve};
- let c = used.oriented_curve();
- let (a, b) = c.range_tuple();
- let d = c.der((a + b) * 0.5);
- Vec3::new(d.x, d.y, d.z).normalized().map(|t| (from_p3(c.subs((a + b) * 0.5)), t))
- }) else {
- continue;
- };
- if (o - pm).dot(np.cross(tm)) <= 0.0 {
- continue;
- }
- if rho < r - tol * 1e3 {
- return Err(too_large("the blend is larger than a corner radius (site 1257)"));
- }
- if (rho - r).abs() > tol * 1e3 {
- continue;
- }
- // The ball sits on the planar side at the arc's centre; the other side must be a round
- // about the same axis, the ball touching it all along.
- let c = o + np * (sigma * r);
- let (a1, a2) = edge_sides(&[k]);
- let other = if side == 1 { a2 } else { a1 };
- let reach = other.iter().filter_map(|f| project(f, c, None)).map(|x| x.0.dist(c)).fold(f64::INFINITY, f64::min);
- if (reach - r).abs() <= size * 1e-4 {
- if let Some(slot) = pivots.get_mut(k) {
- *slot = Some(Pivot { c, o, axis: np, side });
- }
- break;
- }
- }
- }
- if pivots.iter().all(Option::is_some) {
- return Err(unsupported("rounding again only rounded corners of the blend's radius"));
- }
- // Seams at the chain's vertices: edges there that aren't in the chain, and their side.
- let chain_ids: Vec = chain.iter().map(|e| e.id()).collect();
- let mut seams: Vec> = Vec::with_capacity(nv);
- // At an open chain's ends: the end face (planar, square to the edge there).
- let mut end_faces: Vec<(usize, usize)> = Vec::new(); // (vertex index, face index)
- // A flat strip on planar sides can end across two planar faces (an earlier chamfer).
- // Their shared seam is shortened to the crossing of the new chamfer plane.
- let mut split_ends: Vec<(usize, usize, usize, mt::Edge)> = Vec::new();
- // Chain ends whose end face is not a plane square to the edge: (vertex, face, point, tangent,
- // the side (1 or 2) the end face is tangent to when it lies along the edge there).
- let mut slanted: Vec<(usize, usize, Vec3, Vec3, Option)> = Vec::new();
- for (k, v) in verts.iter().enumerate() {
- let at_end = !closed && (k == 0 || k == nv - 1);
- let (k1, k2) = {
- let ei = if k == nv - 1 && !closed { n - 1 } else { k.min(n - 1) };
- (side1.get(ei).copied().unwrap_or(usize::MAX), side2.get(ei).copied().unwrap_or(usize::MAX))
- };
- let mut found: Vec<(usize, mt::Edge)> = Vec::new();
- for (fi, f) in faces.iter().enumerate() {
- if !f.vertex_iter().any(|x| x == *v) {
- continue;
- }
- let on_side = side1.contains(&fi) || side2.contains(&fi);
- if !on_side {
- if !at_end || end_faces.iter().filter(|(kk, _)| *kk == k).count() >= 2 {
- return Err(unsupported("a vertex of the edge chain where other faces meet"));
- }
- end_faces.push((k, fi));
- continue;
- }
- for x in f.edge_iter() {
- if chain_ids.contains(&x.id()) || !(*x.front() == *v || *x.back() == *v) || found.iter().any(|(_, y)| y.id() == x.id()) {
- continue;
- }
- let side = if fi == k1 || (side1.contains(&fi) && fi != k2) { 1 } else { 2 };
- found.push((side, x.absolute_clone()));
- }
- }
- if at_end && !end_faces.iter().any(|(kk, _)| *kk == k) {
- return Err(unsupported("an open chain of curved edges must end at a face"));
- }
- let ends: Vec = end_faces.iter().filter(|(kk, _)| *kk == k).map(|(_, fi)| *fi).collect();
- if let [ga, gb] = ends[..] {
- let terminal = chain.get(if k == 0 { 0 } else { n - 1 }).ok_or_else(|| unsupported("chain end"))?;
- let planar = [ga, gb, k1, k2].iter().all(|i| faces.get(*i).and_then(crate::blend::plane_normal).is_some());
- if round || !planar || !straight(terminal, tol * 10.0) {
- return Err(unsupported("a vertex of the edge chain where other faces meet"));
- }
- let shares = |g: usize, side: usize| {
- faces
- .get(g)
- .zip(faces.get(side))
- .is_some_and(|(g, s)| g.edge_iter().any(|e| (e.front() == v || e.back() == v) && s.edge_iter().any(|x| x.id() == e.id())))
- };
- let (ga, gb) = if shares(ga, k1) && shares(gb, k2) {
- (ga, gb)
- } else if shares(gb, k1) && shares(ga, k2) {
- (gb, ga)
- } else {
- return Err(unsupported("the end faces do not meet both sides of the chain"));
- };
- let seam = faces
- .get(ga)
- .and_then(|a| {
- faces.get(gb).and_then(|b| a.edge_iter().find(|e| (e.front() == v || e.back() == v) && b.edge_iter().any(|x| x.id() == e.id())))
- })
- .ok_or_else(|| unsupported("the end faces have no shared seam"))?;
- if !straight(&seam, tol * 10.0) {
- return Err(unsupported("a curved seam between the end faces"));
- }
- // The first face is the one reached by side 1's contact.
- end_faces.retain(|(kk, _)| *kk != k);
- end_faces.extend([(k, ga), (k, gb)]);
- split_ends.push((k, ga, gb, seam.absolute_clone()));
- }
- // At most one seam per side.
- if found.iter().filter(|x| x.0 == 1).count() > 1 || found.iter().filter(|x| x.0 == 2).count() > 1 {
- return Err(unsupported("a vertex of the edge chain where several seams meet"));
- }
- seams.push(found);
- }
- // Sections: at each vertex (a contact on the seam there), then along each edge.
- let tangent_at = |e: &mt::Edge, s: f64| -> Option<(Vec3, Vec3)> {
- use mt::{BoundedCurve, ParametricCurve};
- let c = e.oriented_curve();
- let (a, b) = c.range_tuple();
- let t = a + (b - a) * s;
- let d = c.der(t);
- Some((from_p3(c.subs(t)), Vec3::new(d.x, d.y, d.z).normalized()?))
- };
- let mut vsec: Vec = Vec::with_capacity(nv);
- // The radius each vertex section was solved at (the closed end of a law: zero).
- let mut vradius: Vec = Vec::with_capacity(nv);
- for k in 0..nv {
- let (p, t) = if k < n {
- tangent_at(chain.get(k).ok_or_else(|| KernelError::Failed("edge".into()))?, 0.0)
- } else {
- tangent_at(chain.get(n - 1).ok_or_else(|| KernelError::Failed("edge".into()))?, 1.0)
- }
- .ok_or_else(|| KernelError::Failed("tangent".into()))?;
- let here = seams.get(k).cloned().unwrap_or_default();
- let at_end = end_faces.iter().any(|(kk, _)| *kk == k);
- // Next to a pivot the ball is at its centre, touching the other side square above the
- // vertex.
- let pivoting: Vec = [(k < n).then_some(k), if k > 0 { Some(k - 1) } else { closed.then_some(n - 1) }]
- .into_iter()
- .flatten()
- .filter_map(|i| pivots.get(i).copied().flatten())
- .collect();
- if let Some(pv) = pivoting.first().copied() {
- if at_end || pivoting.iter().any(|x| x.c.dist(pv.c) > tol * 1e3) {
- return Err(unsupported("a rounded corner of the blend's radius where the edge chain ends or turns"));
- }
- let q = pv.c + (p - pv.o);
- vsec.push(if pv.side == 1 { Section { c: pv.c, q1: pv.o, q2: q } } else { Section { c: pv.c, q1: q, q2: pv.o } });
- vradius.push(fixed.unwrap_or_default());
- continue;
- }
- // The law's parameter at this vertex: the front of its edge, or the back of the last
- // edge at an open chain's end.
- let law_s = if k < n { frac_at(k, 0.0) } else { frac_at(n - 1, 1.0) };
- if at_end {
- // A plane square to the edge holds the blend's end section. Any other end face: the
- // blend runs on past the end and is cut back where it meets that face.
- let (_, fi) = end_faces.iter().find(|(kk, _)| *kk == k).copied().unwrap_or_default();
- let g = faces.get(fi).ok_or_else(|| KernelError::Failed("end face".into()))?;
- let square = match g.oriented_surface() {
- mt::Surface::Plane(pl) => {
- let m = pl.normal();
- Vec3::new(m.x, m.y, m.z).normalized().is_some_and(|ng| ng.dot(t).abs() >= 1.0 - 1e-6)
- }
- _ => false,
- };
- // A radius that has run to zero closes the blend at the vertex itself: it does not run
- // on past the end, and the end face keeps the corner it had there.
- let closed_end = matches!(size_law, Size::Law(law) if law.eval(law_s) <= CLOSED);
- if (!square || split_ends.iter().any(|e| e.0 == k)) && !closed_end {
- slanted.push((k, fi, p, t, None));
- }
- }
- let extra = match here.first().filter(|_| !at_end) {
- None => None,
- // A curved seam holds the contact on itself (the chain runs on smoothly across it: a
- // lofted wall's two halves).
- Some((side, seam)) if !straight(seam, tol * 10.0) => Some(Extra::Seam(*side, seam)),
- Some((side, seam)) => {
- let side = *side;
- // The plane through the seam square to that side's surface.
- let o = from_p3(seam.front().point());
- let d = (from_p3(seam.back().point()) - o).normalized().ok_or_else(|| KernelError::Failed("seam".into()))?;
- let fs = if side == 1 { &s1 } else { &s2 };
- // The side's normal at the joint: from its face nearest the joint (any face of a
- // longer side is no guide here).
- let nn = fs
- .iter()
- .filter_map(|f| project(f, p, None))
- .min_by(|a, b| a.0.dist(p).total_cmp(&b.0.dist(p)))
- .map(|x| x.1)
- .ok_or_else(|| KernelError::Failed("seam normal".into()))?;
- Some(Extra::Plane(side, o, d.cross(nn).normalized().ok_or_else(|| KernelError::Failed("seam plane".into()))?))
- }
- };
- // On the faces of the edge from this vertex alone (the last edge's at an open chain's
- // end): the other edge's faces are untrimmed here and can run on near the ball where it no
- // longer is (a wall past the round at a corner, which a ball rolling round it pokes
- // through).
- let (a1, a2) = edge_sides(&[k.min(n - 1)]);
- let (s, r) = sizer.section(&a1, &a2, p, t, law_s, sigma, cusp, extra).ok_or_else(|| sizer.refusal())?;
- // A seam on the other side too must pass through that side's contact.
- if let Some((side, seam)) = here.get(1).filter(|_| !at_end) {
- let q = if *side == 1 { s.q1 } else { s.q2 };
- let (a, b) = (from_p3(seam.front().point()), from_p3(seam.back().point()));
- if !straight(seam, tol * 10.0) || q.dist_to_segment(a, b) > tol * 1e3 {
- return Err(unsupported("seams on both sides of a corner of the edge chain"));
- }
- }
- vsec.push(s);
- vradius.push(r);
- }
- // Past a slanted end: sections of the same rolling ball beyond the end vertex (far to near
- // at the chain's start, near to far at its end), far enough to cross the end face.
- let mut beyond: Vec<(usize, Vec, Vec)> = Vec::new();
- for (k, fi, p, t, tangent) in slanted.iter_mut() {
- let g = faces.get(*fi).ok_or_else(|| KernelError::Failed("end face".into()))?;
- let at = vsec.get(*k).copied().ok_or_else(|| KernelError::Failed("section".into()))?;
- let (_, ng, _) = project(g, *p, None).ok_or_else(|| unsupported("the blend's end on its end face"))?;
- let cos = split_ends
- .iter()
- .find(|e| e.0 == *k)
- .and_then(|(_, _, gb, _)| faces.get(*gb))
- .and_then(crate::blend::plane_normal)
- .map_or(ng.dot(*t).abs(), |nb| ng.dot(*t).abs().min(nb.dot(*t).abs()));
- // An end face along the edge and tangent to one side there (a wall that runs out into
- // the face): the blend meets it along a curve that touches that side's contact at the
- // vertex. Any other end face that close to the edge is refused.
- let (e1, e2) = edge_sides(&vertex_edges(*k));
- *tangent = if cos < TANGENT_END {
- [(1u8, &e1), (2u8, &e2)].into_iter().find_map(|(side, faces)| {
- faces.iter().filter_map(|f| project(f, *p, None)).any(|(_, n, _)| n.dot(ng).abs() > 1.0 - TANGENT_END).then_some(side)
- })
- } else {
- None
- };
- if cos < 0.15 && tangent.is_none() {
- return Err(unsupported("an end face almost along the edge"));
- }
- let width = at.q1.dist(*p).max(at.q2.dist(*p)).max(at.c.dist(*p)) + vradius.get(*k).copied().unwrap_or(scale);
- let reach = 1.5 * width / if tangent.is_some() { 1.0 } else { cos };
- let out = if *k == 0 { -*t } else { *t };
- // The run on past the end only gives the fit its context (the end face cuts it back), but
- // it keeps the law's end slope: the radius is read at the distance past the end.
- let law_s = |d: f64| if *k == 0 { -d / total } else { 1.0 + d / total };
- // Past a tangent end the straight run along the tangent leaves the curved spine: where
- // the ball no longer fits, the run is shortened (it only gives the fit its context).
- let mut list = Vec::with_capacity(EXTENSION);
- let mut laws = Vec::with_capacity(EXTENSION);
- let mut reach = reach;
- // Past the end of a curved edge the planes square to its end tangent cut the ring of
- // centres further and further round it, until a step jumps across the ring (#1255: a
- // knuckle's cap circle with a round as wide as 0.7 of its radius). The run is shortened
- // then, as long as one of its sections still lies wholly past the end face.
- let ng_out = if ng.dot(out) < 0.0 { -ng } else { ng };
- let past = |sec: &Section| [sec.c, sec.q1, sec.q2].iter().all(|x| (*x - *p).dot(ng_out) > tol);
- // A run shortened when its centres jump across the ring (a knuckle's cap circle, #1255)
- // stands if no full-length run works; a size law's own end slope is read at each station's
- // distance past the end.
- let mut fallback: Option> = None;
- for attempt in 0..TANGENT_RETRIES {
- list.clear();
- laws.clear();
- let step = reach / EXTENSION as f64;
- let sections = (1..=EXTENSION).map(|j| {
- let d = step * j as f64;
- let anchor = *p + out * d;
- let s = law_s(d);
- sizer.section(&e1, &e2, anchor, *t, s, sigma, cusp, None).map(|(section, _)| (s, section))
- });
- match sections.collect::>>() {
- Some(all) => {
- let smooth = tangent.is_some()
- || std::iter::once(at.c).chain(all.iter().map(|(_, s)| s.c)).collect::>().windows(2).all(|w| match w {
- [a, b] => a.dist(*b) <= MAX_STEP_STRETCH * step,
- _ => true,
- });
- if smooth {
- // A shortened run must still cross the end face; else the first,
- // full-length run stands.
- if fallback.is_none() || all.iter().any(|(_, s)| past(s)) {
- list = all.iter().map(|(_, s)| *s).collect();
- laws = all.iter().map(|(s, _)| *s).collect();
- }
- break;
- }
- fallback.get_or_insert(all);
- }
- None if tangent.is_none() || fallback.is_some() || attempt + 1 == TANGENT_RETRIES => break,
- None => {}
- }
- reach *= if tangent.is_some() { 0.5 } else { 0.75 };
- }
- if list.is_empty() {
- match fallback {
- // The shortened run stands when the ring's step jumped, whatever its size.
- Some(all) => {
- list = all.iter().map(|(_, s)| *s).collect();
- laws = all.iter().map(|(s, _)| *s).collect();
- }
- // A size asked for beyond what the faces around the end hold is refused as such;
- // one radius past the end is the rolling ball's own failure to fit.
- None => {
- return Err(match size_law {
- Size::Constant(_) => unsupported("the ball doesn't fit past the end of the edge"),
- _ => too_large("the blend is larger than the neighbouring faces (site 1472)"),
- });
- }
- }
- }
- if *k == 0 {
- list.reverse();
- laws.reverse();
- }
- beyond.push((*k, list, laws));
- }
- // Uniform refinement preserves a common spacing across neighbouring patches. Work is
- // capped: a difficult strip returns an error instead of accepting an inaccurate fit.
- let fit_tolerance = (size * 1e-5).clamp(1e-5, 0.001);
- // At a seam the contact lies on the seam plane, which need not be square to the
- // original edge. Its ball centre therefore need not lie in the edge's normal plane.
- // Interpolate that plane's displacement so the interior sections tend to the exact
- // seam sections, rather than leaving a finite jump as sampling gets finer.
- let offsets: Vec<(f64, f64)> = chain
- .iter()
- .enumerate()
- .map(|(k, edge)| {
- let (p0, t0) = tangent_at(edge, 0.0).ok_or_else(|| KernelError::Failed("tangent".into()))?;
- let (p1, t1) = tangent_at(edge, 1.0).ok_or_else(|| KernelError::Failed("tangent".into()))?;
- let start = vsec.get(k).ok_or_else(|| KernelError::Failed("section".into()))?;
- let end = vsec.get((k + 1) % nv).ok_or_else(|| KernelError::Failed("section".into()))?;
- Ok(((start.c - p0).dot(t0), (end.c - p1).dot(t1)))
- })
- .collect::>()?;
- let section_at = |k: usize, edge: &mt::Edge, along: f64| -> Result<(Section, f64)> {
- let (p, t) = tangent_at(edge, along).ok_or_else(|| KernelError::Failed("tangent".into()))?;
- let (start, end) = offsets.get(k).copied().ok_or_else(|| KernelError::Failed("section offset".into()))?;
- let anchor = p + t * (start * (1.0 - along) + end * along);
- let (a1, a2) = edge_sides(&[k]);
- sizer.section(&a1, &a2, anchor, t, frac_at(k, along), sigma, cusp, None).ok_or_else(|| sizer.refusal())
- };
- let mut samples = SAMPLES.min(max_samples);
- let (esec, fits) = loop {
- if n.checked_mul(samples).is_none_or(|count| count > MAX_CHAIN_SAMPLES) {
- return Err(unsupported("curve blend exceeds the section fitting limit"));
- }
- // No guide along a pivot: its sections are the two at its ends.
- let mut guides: Vec> = Vec::with_capacity(n);
- for (k, e) in chain.iter().enumerate() {
- if pivots.get(k).copied().flatten().is_some() {
- guides.push(None);
- continue;
- }
- let mut list = vec![*vsec.get(k).ok_or_else(|| KernelError::Failed("section".into()))?];
- let mut law = vec![frac_at(k, 0.0)];
- let (mut front_beyond, mut back_beyond) = (0usize, 0usize);
- for j in 1..samples - 1 {
- let along = j as f64 / (samples - 1) as f64;
- let (section, _) = section_at(k, e, along)?;
- list.push(section);
- law.push(frac_at(k, along));
- }
- list.push(*vsec.get((k + 1) % nv).ok_or_else(|| KernelError::Failed("section".into()))?);
- law.push(frac_at(k, 1.0));
- for (kv, ext, exts) in &beyond {
- if *kv == k && k == 0 {
- list.splice(0..0, ext.iter().copied());
- law.splice(0..0, exts.iter().copied());
- front_beyond = ext.len();
- } else if *kv == k + 1 && k + 1 == nv - 1 {
- list.extend(ext.iter().copied());
- law.extend(exts.iter().copied());
- back_beyond = ext.len();
- }
- }
- let mut guide = Guide::with_law(list, law)?;
- // The chain's own run: the spliced sections at either end are context for the fit
- // only (the blend is cut back where it meets the end face there).
- let last = guide.lengths.last().copied().unwrap_or(0.0);
- let at = |i: usize| if last > 0.0 { guide.lengths.get(i).copied().unwrap_or(0.0) / last } else { 0.0 };
- guide.span = (at(front_beyond), at(guide.sections.len().saturating_sub(1 + back_beyond)));
- guides.push(Some(guide));
- }
- // Intersection curves inherit their leader's piecewise parameter speed. Fitting
- // those parameters creates oscillations even on a geometrically smooth spine.
- // Resample by distance along the rolling centres, projecting each interpolated
- // centre back onto the exact two offset surfaces before it becomes a section.
- let uniform_section = |k: usize, along: f64| -> Result {
- let guide = guides.get(k).and_then(Option::as_ref).ok_or_else(|| KernelError::Failed("spine guide".into()))?;
- if along == 0.0 {
- return guide.sections.first().copied().ok_or_else(|| KernelError::Failed("section".into()));
- }
- if along == 1.0 {
- return guide.sections.last().copied().ok_or_else(|| KernelError::Failed("section".into()));
- }
- let (anchor, tangent, law_s) = guide.anchor_at(along).ok_or_else(|| unsupported("degenerate rolling-ball spine"))?;
- let (a1, a2) = edge_sides(&[k]);
- sizer
- .section(&a1, &a2, anchor, tangent, law_s, sigma, cusp, None)
- .map(|(section, _)| section)
- .ok_or_else(|| unsupported("the ball doesn't fit along the resampled spine"))
- };
- let esec: Vec> = (0..n)
- .map(|k| match guides.get(k) {
- Some(Some(_)) => (0..samples).map(|j| uniform_section(k, j as f64 / (samples - 1) as f64)).collect::>>(),
- _ => Ok(vec![
- *vsec.get(k).ok_or_else(|| KernelError::Failed("section".into()))?,
- *vsec.get((k + 1) % nv).ok_or_else(|| KernelError::Failed("section".into()))?,
- ]),
- })
- .collect::>()?;
- // Each strip's neighbouring sections at its own spacing (edges of different lengths
- // have differently spaced samples, which makes a uniform interpolation overshoot).
- let length = |k: usize| guides.get(k).and_then(Option::as_ref).and_then(|g| g.lengths.last().copied()).unwrap_or(0.0);
- let rolls = |k: usize| guides.get(k).is_some_and(Option::is_some);
- let mut fits: Vec> = Vec::with_capacity(n);
- for k in 0..n {
- // A pivot's surface is made whole (`revolve`); a strip next to one ends on the joint's
- // section on its own.
- if !rolls(k) {
- fits.push(None);
- continue;
- }
- let h = length(k) / (samples - 1) as f64;
- // A neighbour shorter than two of the strip's steps lends none: its own sections are
- // spaced far closer (a small round beside a long line), and borrowing them made the
- // strip overshoot and fold back on itself past the joint, which its faces' meshes
- // then folded with (#1667). The strip ends on the joint's section on its own.
- let spaced = |nb: usize, from_end: bool| -> Result> {
- let l = length(nb);
- if !(l > 2.0 * h && h > 0.0) {
- return Ok(Vec::new());
- }
- let mut out = Vec::with_capacity(2);
- for j in [1.0, 2.0] {
- out.push(uniform_section(nb, if from_end { 1.0 - j * h / l } else { j * h / l })?);
- }
- if from_end {
- out.reverse();
- }
- Ok(out)
- };
- let (prev, next) = ((k + n - 1) % n, (k + 1) % n);
- let list = esec.get(k).ok_or_else(|| KernelError::Failed("section".into()))?;
- // Not across a joint where the strip's curvature jumps (a line or a wide arc into a
- // small round): a spline smooth through it spreads the jump over the sections beside
- // it, and the error falls only with the square of their spacing. The strip then ends
- // on the joint's section on its own, which the next one shares.
- let smooth = |near: [Option<&Section>; 3], beyond: [Option<&Section>; 3]| match (near, beyond) {
- ([Some(a), Some(b), Some(c)], [Some(x), Some(y), Some(z)]) => !bends([a, b, c], [x, y, z], fit_tolerance),
- _ => false,
- };
- let before = match (closed || k > 0) && rolls(prev) {
- true => {
- let b = spaced(prev, true)?;
- if smooth([list.first(), list.get(1), list.get(2)], [list.first(), b.get(1), b.first()]) { b } else { Vec::new() }
- }
- false => Vec::new(),
- };
- let after = match (closed || k + 1 < n) && rolls(next) {
- true => {
- let a = spaced(next, false)?;
- let m = list.len();
- let tail = [list.last(), m.checked_sub(2).and_then(|i| list.get(i)), m.checked_sub(3).and_then(|i| list.get(i))];
- if smooth(tail, [list.last(), a.first(), a.get(1)]) { a } else { Vec::new() }
- }
- false => Vec::new(),
- };
- let mut fit = crate::guard("fit curve blend", || fit_strip(list, &before, &after, round))?;
- fit.span = guides.get(k).and_then(Option::as_ref).map(|g| g.span).unwrap_or((0.0, 1.0));
- fits.push(Some(fit));
- }
- let mut accurate = true;
- 'edges: for k in 0..n {
- let Some(Some(fit)) = fits.get(k) else { continue };
- for j in 0..samples - 1 {
- for fraction in [0.25, 0.5, 0.75] {
- let along = (j as f64 + fraction) / (samples - 1) as f64;
- // A size that varies along the edge reaches past its ends only for the fit's
- // context (the end face cuts that away), so it is not held to the tolerance
- // there. One radius keeps the check it always had, the whole strip.
- if !matches!(size_law, Size::Constant(_))
- && fits.get(k).and_then(Option::as_ref).is_some_and(|f| along < f.span.0 || along > f.span.1)
- {
- continue;
- }
- let section = uniform_section(k, along)?;
- if !crate::guard("check curve blend fit", || Ok(section_fits(fit, §ion, along, round, sigma, fit_tolerance)))? {
- accurate = false;
- break 'edges;
- }
- }
- }
- }
- if accurate {
- break (esec, fits);
- }
- if samples >= max_samples {
- return Err(KernelError::Failed("curve blend: could not fit the rolling-ball surface within the accuracy and section limits".into()));
- }
- samples = (2 * samples - 1).min(max_samples);
- };
- // Where each extended blend meets its slanted end face: (vertex, edge, cut parameters of
- // the two contacts, the end curve from contact 1 to contact 2).
- let mut caps: Vec<(usize, usize, f64, f64, mt::Curve)> = Vec::new();
- let mut split_caps: Vec<(usize, mt::Edge, Vec3)> = Vec::new();
- for (k, fi, _, _, tangent) in &slanted {
- let ke = if *k == 0 { 0 } else { n - 1 };
- let fit = fits.get(ke).and_then(Option::as_ref).ok_or_else(|| KernelError::Failed("curve blend fit".into()))?;
- let g = faces.get(*fi).ok_or_else(|| KernelError::Failed("end face".into()))?;
- let at = vsec.get(*k).copied().ok_or_else(|| KernelError::Failed("section".into()))?;
- let seam = |s: u8| seams.get(*k).and_then(|l| l.iter().find(|(x, _)| *x as u8 == s)).map(|(_, e)| e);
- let both = [seam(1), seam(2)];
- if let Some((_, ga, gb, middle)) = split_ends.iter().find(|e| e.0 == *k) {
- use mt::{BSplineCurve, KnotVec, ParametricCurve, SearchNearestParameter};
- let fail = || unsupported("the chamfer does not cross both end faces");
- let p = from_p3(verts.get(*k).ok_or_else(fail)?.point());
- let (_, t) = tangent_at(chain.get(ke).ok_or_else(fail)?, if *k == 0 { 0.0 } else { 1.0 }).ok_or_else(fail)?;
- let hit = |q: Vec3, fi: usize| -> Option {
- let normal = faces.get(fi).and_then(crate::blend::plane_normal)?;
- let den = normal.dot(t);
- (den.abs() > 1e-6).then(|| q - t * (normal.dot(q - p) / den))
- };
- let a = hit(at.q1, *ga).ok_or_else(fail)?;
- let b = hit(at.q2, *gb).ok_or_else(fail)?;
- let m = (at.q2 - at.q1).cross(t).normalized().ok_or_else(fail)?;
- let far = if middle.front() == verts.get(*k).ok_or_else(fail)? { middle.back() } else { middle.front() };
- let u = from_p3(far.point()) - p;
- let den = m.dot(u);
- if den.abs() < tol {
- return Err(fail());
- }
- let fraction = m.dot(at.q1 - p) / den;
- let c = p + u * fraction;
- let across = (c - at.q1).dot(at.q2 - at.q1) / (at.q2 - at.q1).len2();
- if !(fraction > 1e-6 && fraction < 1.0 - 1e-6 && across > 1e-6 && across < 1.0 - 1e-6) {
- return Err(fail());
- }
- let parameter = |row: usize, q: Vec3| -> Option {
- let curve = fit.contacts.get(row)?;
- let v = curve.search_nearest_parameter(p3(q), None, 100)?;
- (v > fit.range.0 + 1e-6 && v < fit.range.1 - 1e-6 && from_p3(curve.subs(v)).dist(q) <= fit_tolerance).then_some(v)
- };
- let (ta, tb) = (parameter(0, a).ok_or_else(fail)?, parameter(1, b).ok_or_else(fail)?);
- let curve = BSplineCurve::try_new(KnotVec::from(vec![0.0, 0.0, 0.5, 1.0, 1.0]), vec![p3(a), p3(c), p3(b)])
- .map_err(|e| KernelError::Failed(format!("chamfer end: {e}")))?;
- caps.push((*k, ke, ta, tb, mt::Curve::BSplineCurve(curve)));
- split_caps.push((*k, middle.clone(), c));
- continue;
- }
- let cap = crate::guard("curve blend end", || match tangent {
- Some(side) => tangent_cap(fit, g, *side, both, fit_tolerance),
- None => end_cap(fit, g, &at, both, round, fit_tolerance),
- })?;
- caps.push((*k, ke, cap.0, cap.1, cap.2));
- }
- // Both ends of one edge cut back: the contacts must keep a piece between them.
- if let [(_, 0, s1, s2, _), (_, 0, e1, e2, _)] = &caps[..]
- && n == 1
- && !(s1 + 1e-6 < *e1 && s2 + 1e-6 < *e2)
- {
- return Err(too_large("the blend is larger than the neighbouring faces (site 1668)"));
- }
- crate::guard("curve blend", || {
- let fail = |m: &str| KernelError::Failed(format!("curve blend: {m}"));
- // Vertices and arcs at the chain's vertices.
- let mut v1: Vec = vsec.iter().map(|s| builder::vertex(p3(s.q1))).collect();
- let mut v2: Vec = vsec.iter().map(|s| builder::vertex(p3(s.q2))).collect();
- for (k, _, _, _, curve) in &caps {
- use mt::{BoundedCurve, ParametricCurve};
- let (lo, hi) = curve.range_tuple();
- if let (Some(a), Some(b)) = (v1.get_mut(*k), v2.get_mut(*k)) {
- *a = builder::vertex(curve.subs(lo));
- *b = builder::vertex(curve.subs(hi));
- }
- }
- // A closed section (a radius that has run to zero) has one vertex for both contacts, so
- // the blend face's wire and the side faces' meet there.
- for (k, s) in vsec.iter().enumerate() {
- if !closed_section(s) {
- continue;
- }
- if let Some(v) = v1.get(k).cloned()
- && let Some(slot) = v2.get_mut(k)
- {
- *slot = v;
- }
- }
- // Along a pivot the planar side's contact is one point: one vertex at both its ends.
- for (k, pv) in pivots.iter().enumerate() {
- let Some(pv) = pv else { continue };
- let vs = if pv.side == 1 { &mut v1 } else { &mut v2 };
- if let Some(v) = vs.get(k).cloned()
- && let Some(slot) = vs.get_mut((k + 1) % nv)
- {
- *slot = v;
- }
- }
- // A chain end (a cap, or the section at a square end) on the far end of its seam uses that
- // seam up: that vertex is the end.
- let mut consumed: HashMap = HashMap::new();
- for (k, _) in &end_faces {
- for (side, seam) in seams.get(*k).into_iter().flatten() {
- let Some(old) = verts.get(*k) else { continue };
- let far = if seam.front() == old { seam.back() } else { seam.front() };
- let slot = if *side == 1 { v1.get_mut(*k) } else { v2.get_mut(*k) };
- if let Some(nv) = slot
- && far != old
- && from_p3(far.point()).dist(from_p3(nv.point())) <= fit_tolerance
- {
- *nv = far.clone();
- consumed.insert(seam.id(), far.clone());
- }
- }
- }
- // The section's own radius, where the blend is sized by a law or a chord width (`r` is the
- // one radius of a constant blend, exactly as before).
- let rad = |s: &Section| match size_law {
- Size::Constant(r) => r,
- Size::Chord(_) | Size::Law(_) => s.c.dist(s.q1),
- };
- let mut arcs: Vec> = Vec::with_capacity(nv);
- let mut split_arcs: HashMap> = HashMap::new();
- for (k, s) in vsec.iter().enumerate() {
- let (a, b) = (v1.get(k).ok_or_else(|| fail("vertex"))?, v2.get(k).ok_or_else(|| fail("vertex"))?);
- // A closed section has no arc to run between the contacts: the blend meets itself
- // there, at the edge's end point.
- let e = if closed_section(s) {
- None
- } else if round {
- let m = s.c + ((s.q1 - s.c) + (s.q2 - s.c)).normalized().ok_or_else(|| fail("arc"))? * rad(s);
- Some(builder::circle_arc(a, b, p3(m)))
- } else {
- Some(builder::line(a, b))
- };
- let e = match caps.iter().find(|c| c.0 == k) {
- Some((_, _, _, _, curve)) => Some(mt::Edge::try_new(a, b, curve.clone()).map_err(|e| fail(&e.to_string()))?),
- None => e,
- };
- if let Some((_, _, c)) = split_caps.iter().find(|cap| cap.0 == k) {
- let v = builder::vertex(p3(*c));
- split_arcs.insert(k, vec![builder::line(a, &v), builder::line(&v, b)]);
- }
- arcs.push(e);
- }
- // Outward: toward the ball centre on a concave edge, away on a convex one.
- let oriented = |mut surface: mt::Surface, list: &[Section]| -> Result {
- use mt::{ParametricSurface3D, SearchNearestParameter};
- let s = list.get(list.len() / 2).ok_or_else(|| fail("section"))?;
- let mid = s.c + ((s.q1 - s.c) + (s.q2 - s.c)).normalized().ok_or_else(|| fail("mid"))? * rad(s);
- if let Some((u, v)) = surface.search_nearest_parameter(p3(mid), None, 100) {
- let nn = surface.normal(u, v);
- let want = (s.c - mid) * sigma;
- if Vec3::new(nn.x, nn.y, nn.z).dot(want) < 0.0 {
- surface = mt::Invertible::inverse(&surface);
- }
- }
- Ok(surface)
- };
- // Contact curves and blend faces per edge.
- // (None: the planar side's contact along a pivot, a point.)
- let mut c1: Vec> = Vec::with_capacity(n);
- let mut c2: Vec > = Vec::with_capacity(n);
- let mut blends: Vec = Vec::with_capacity(n);
- for (k, list) in esec.iter().enumerate() {
- let k1 = (k + 1) % nv;
- let (a1, b1, a2, b2) = (v1.get(k), v1.get(k1), v2.get(k), v2.get(k1));
- let (Some(a1), Some(b1), Some(a2), Some(b2)) = (a1, b1, a2, b2) else { return Err(fail("vertex")) };
- if let Some(pv) = pivots.get(k).copied().flatten() {
- // The section at the start turned about the axis to the one at the end; the other
- // side's contact is the circle its end runs on.
- let (s0, s1e) = (list.first().ok_or_else(|| fail("section"))?, list.last().ok_or_else(|| fail("section"))?);
- let (qa, qb) = if pv.side == 1 { (s0.q2, s1e.q2) } else { (s0.q1, s1e.q1) };
- let (a, b) = (qa - pv.c, qb - pv.c);
- let angle = pv.axis.dot(a.cross(b)).atan2(a.dot(b));
- let (sn, cs) = (angle / 2.0).sin_cos();
- let mid = pv.c + a * cs + pv.axis.cross(a) * sn + pv.axis * (pv.axis.dot(a) * (1.0 - cs));
- let surface = section_controls(s0, round).and_then(|ctrl| revolve(ctrl, pv.c, pv.axis, angle)).ok_or_else(|| fail("pivot"))?;
- let (from, to) = if pv.side == 1 { (a2, b2) } else { (a1, b1) };
- let arc = builder::circle_arc(from, to, p3(mid));
- let (e1, e2) = if pv.side == 1 { (None, Some(arc)) } else { (Some(arc), None) };
- c1.push(e1);
- c2.push(e2);
- blends.push(oriented(surface, list)?);
- continue;
- }
- let fit = fits.get(k).and_then(Option::as_ref).ok_or_else(|| fail("fit"))?;
- let [cv1, cv2] = &fit.contacts;
- // Contacts past a slanted end stop at the end curve.
- let (mut cv1, mut cv2) = (cv1.clone(), cv2.clone());
- for (kv, _, t1, t2, _) in caps.iter().filter(|c| c.1 == k) {
- use mt::Cut;
- if *kv == k + 1 {
- let _ = cv1.cut(*t1);
- let _ = cv2.cut(*t2);
- }
- }
- for (kv, _, t1, t2, _) in caps.iter().filter(|c| c.1 == k) {
- use mt::Cut;
- if *kv == k && k == 0 {
- cv1 = cv1.cut(*t1);
- cv2 = cv2.cut(*t2);
- }
- }
- c1.push(Some(mt::Edge::new(a1, b1, cv1)));
- c2.push(Some(mt::Edge::new(a2, b2, cv2)));
- blends.push(oriented(fit.surface.clone(), list)?);
- }
- // Rebuild the side faces: chain edges become contact curves, seams start at contacts.
- let mut subst: HashMap, Option)> = HashMap::new();
- for (k, e) in chain.iter().enumerate() {
- let (Some(x), Some(y)) = (c1.get(k), c2.get(k)) else { return Err(fail("contact")) };
- subst.insert(e.id(), (x.clone(), y.clone()));
- }
- // Seams get new ends at the contacts (an edge between two chain vertices at both).
- let mut ends: HashMap, Option)> = HashMap::new();
- for (k, sm) in seams.iter().enumerate().flat_map(|(k, l)| l.iter().map(move |x| (k, x))) {
- let (side, seam) = sm;
- let v = verts.get(k).cloned().ok_or_else(|| fail("vertex"))?;
- let nv = if *side == 1 { v1.get(k) } else { v2.get(k) }.ok_or_else(|| fail("vertex"))?.clone();
- let slot = ends.entry(seam.id()).or_insert_with(|| (seam.clone(), None, None));
- if *seam.front() == v {
- slot.1 = Some(nv);
- } else {
- slot.2 = Some(nv);
- }
- }
- let mut seam_subst: HashMap = HashMap::new();
- for (k, seam, _) in &split_caps {
- let old = verts.get(*k).ok_or_else(|| fail("end vertex"))?;
- let v = split_arcs.get(k).and_then(|es| es.first()).map(|e| e.back()).ok_or_else(|| fail("end seam"))?;
- seam_subst.insert(seam.id(), crate::blend::retarget(seam, old, v, fit_tolerance)?);
- }
- for (id, (seam, a, b)) in ends {
- if consumed.contains_key(&id) {
- continue;
- }
- // At an end of an open chain the blend may stop past the seam's old end (a slanted end
- // face, or one turning back past the side, as a box side beside a boss joined to it):
- // the seam then runs on along its line or circle, within its planar face.
- let one_end = match (&a, &b) {
- (Some(nv), None) => Some((seam.front().clone(), nv.clone())),
- (None, Some(nv)) => Some((seam.back().clone(), nv.clone())),
- _ => None,
- };
- if let Some((old, nv)) = one_end
- && end_faces.iter().any(|(k, _)| verts.get(*k) == Some(&old))
- {
- let on_tol = (size * 1e-5).max(1e-6);
- let q = from_p3(nv.point());
- if crate::blend::on_edge(&seam, q, on_tol).is_none() {
- let fits = faces
- .iter()
- .filter(|f| f.edge_iter().any(|e| e.id() == id))
- .any(|f| crate::blend::plane_normal(f).is_some() && crate::blend::extension_fits(f, from_p3(old.point()), q, tol));
- if !fits || !crate::blend::on_extension(&seam, q, on_tol) {
- return Err(too_large("the blend is larger than the neighbouring faces (site 1853)"));
- }
- }
- seam_subst.insert(id, crate::blend::retarget(&seam, &old, &nv, on_tol)?);
- continue;
- }
- if !matches!(seam.curve(), mt::Curve::Line(_)) {
- seam_subst.insert(id, trim_curved_seam(&seam, a, b, size)?);
- continue;
- }
- // The new ends must stay on the seam, in order, short of each other.
- let (p0, p1) = (from_p3(seam.front().point()), from_p3(seam.back().point()));
- let at = |v: &mt::Vertex| {
- let q = from_p3(v.point());
- let d = p1 - p0;
- ((q - p0).dot(d) / d.len2().max(1e-300), (q - p0 - d * ((q - p0).dot(d) / d.len2().max(1e-300))).len())
- };
- let (ta, oa) = a.as_ref().map(at).unwrap_or((0.0, 0.0));
- let (tb, ob) = b.as_ref().map(at).unwrap_or((1.0, 0.0));
- if oa > size * 1e-5 || ob > size * 1e-5 || ta < -1e-9 || tb > 1.0 + 1e-9 || tb - ta < 1e-6 {
- return Err(too_large("the blend is larger than the neighbouring faces (site 1873)"));
- }
- let a = a.unwrap_or_else(|| seam.front().clone());
- let b = b.unwrap_or_else(|| seam.back().clone());
- seam_subst.insert(id, builder::line(&a, &b));
- }
- let mut out: Vec = Vec::new();
- let mut rec = Rebuild::default();
- rec.pieces(&seam_subst);
- for (fi, f) in faces.iter().enumerate() {
- let corners: Vec = end_faces.iter().filter(|(_, g)| *g == fi).map(|(k, _)| *k).collect();
- if !corners.is_empty() {
- if corners.iter().any(|k| split_arcs.contains_key(k)) {
- let connectors: Vec = corners
- .iter()
- .flat_map(|k| split_arcs.get(k).cloned().unwrap_or_else(|| arcs.get(*k).cloned().flatten().into_iter().collect()))
- .collect();
- let rebuilt = crate::blend::rebuild_face(f, &seam_subst, &connectors)?;
- rec.face(&rebuilt, f);
- out.push(rebuilt);
- continue;
- }
- // The end face (one or both ends of the chain): its two edges at a chain end now
- // stop at the contacts, with the blend's end arc between them.
- let mut wires = Vec::new();
- for w in f.absolute_boundaries() {
- let mut es: Vec = Vec::new();
- for e in w.edge_iter() {
- let ne = match seam_subst.get(&e.id()) {
- Some(s) => {
- if e.front() == e.absolute_front() {
- s.clone()
- } else {
- s.inverse()
- }
- }
- None => e.clone(),
- };
- // Arriving at an old corner: continue along that end's arc. A seam the
- // blend used up is left out, and the arc starts at its far end.
- let arrives = corners.iter().copied().find(|k| verts.get(*k).is_some_and(|v| *e.back() == *v));
- let used_up = consumed.contains_key(&e.id());
- if !used_up {
- es.push(ne.clone());
- }
- if let Some(k) = arrives {
- // A closed section has no blend arc at the corner: the blend ends at
- // the vertex itself and the end face keeps the corner it had.
- let (Some(arc), Some(a1), Some(a2)) = (arcs.get(k).and_then(Option::as_ref), v1.get(k), v2.get(k)) else {
- continue;
- };
- let to = if used_up { e.front() } else { ne.back() };
- let corner = if to == a1 {
- arc.clone()
- } else if to == a2 {
- arc.inverse()
- } else {
- return Err(fail("end face corner"));
- };
- es.push(corner);
- }
- }
- wires.push(mt::Wire::from(es));
- }
- let rebuilt = crate::heal::absolute_face(f, wires).ok_or_else(|| fail("an end face could not be rebuilt"))?;
- rec.face(&rebuilt, f);
- out.push(rebuilt);
- continue;
- }
- let on1 = side1.contains(&fi);
- let on2 = side2.contains(&fi);
- if !on1 && !on2 && !f.edge_iter().any(|e| seam_subst.contains_key(&e.id())) {
- out.push(f.clone());
- continue;
- }
- let mut wires = Vec::new();
- for w in f.absolute_boundaries() {
- let mut es = Vec::new();
- for e in w.edge_iter() {
- let ne = if let Some((x, y)) = subst.get(&e.id()) {
- // A point along a pivot: the contacts beside it meet there.
- let Some(base) = (if on1 { x } else { y }) else { continue };
- // Same direction as the chain edge, or reversed.
- let chain_e = chain.iter().find(|c| c.id() == e.id()).ok_or_else(|| fail("edge"))?;
- if e.front() == chain_e.front() { base.clone() } else { base.inverse() }
- } else if let Some(s) = seam_subst.get(&e.id()) {
- if e.front() == e.absolute_front() { s.clone() } else { s.inverse() }
- } else if consumed.contains_key(&e.id()) {
- continue;
- } else {
- e.clone()
- };
- es.push(ne);
- }
- if collapsed_boundary(&es, fit_tolerance) {
- return Err(too_large("the blend would consume a neighbouring face"));
- }
- wires.push(mt::Wire::from(es));
- }
- let rebuilt = crate::heal::absolute_face(f, wires).ok_or_else(|| fail("a side face could not be rebuilt"))?;
- rec.face(&rebuilt, f);
- out.push(rebuilt);
- }
- // Blend faces: each runs its side-1 contact the other way from side 1's face.
- for (k, bf) in blends.iter().enumerate() {
- let (Some(e1), Some(e2)) = (c1.get(k), c2.get(k)) else {
- return Err(fail("blend"));
- };
- let ak = arcs.get(k).and_then(Option::as_ref);
- let ak1 = arcs.get((k + 1) % nv).and_then(Option::as_ref);
- let f1i = side1.get(k).ok_or_else(|| fail("side"))?;
- let f1 = faces.get(*f1i).ok_or_else(|| fail("side"))?;
- let chain_e = chain.get(k).ok_or_else(|| fail("edge"))?;
- let used_fwd = f1
- .boundary_iters()
- .into_iter()
- .flatten()
- .find(|e| e.id() == chain_e.id())
- .map(|e| e.front() == chain_e.front())
- .ok_or_else(|| fail("edge use"))?;
- // Side 1 runs the contact forward (as the chain) when it ran the edge forward.
- // A pivot's planar contact is a point: three sides. A closed section has no arc: two.
- let edges: Vec = if used_fwd {
- [e1.as_ref().map(|e| e.inverse()), ak.cloned(), e2.clone(), ak1.map(|e| e.inverse())]
- } else {
- [e1.clone(), ak1.cloned(), e2.as_ref().map(|e| e.inverse()), ak.map(|e| e.inverse())]
- }
- .into_iter()
- .flatten()
- .collect();
- // An arc the chamfer crossed is two lines through the crossing: the blend meets the
- // shortened seam there.
- let wire: mt::Wire = edges
- .into_iter()
- .flat_map(|e| {
- let split = [(k, ak), ((k + 1) % nv, ak1)]
- .into_iter()
- .filter_map(|(i, arc)| arc.map(|arc| (i, arc.clone())))
- .find(|(_, arc)| arc.id() == e.id())
- .and_then(|(i, arc)| split_arcs.get(&i).map(|parts| (arc, parts)));
- match split {
- Some((arc, parts)) if e.orientation() == arc.orientation() => parts.clone(),
- Some((_, parts)) => parts.iter().rev().map(|p| p.inverse()).collect(),
- None => vec![e],
- }
- })
- .collect();
- let face = mt::Face::try_new(vec![wire], bf.clone()).map_err(|e| fail(&e.to_string()))?;
- rec.blend(&face, [chain_e.id()]);
- out.push(face);
- }
- let mut shells = solid.boundaries().clone();
- if let Some(sh) = shells.get_mut(si) {
- *sh = out.into();
- }
- Ok((Solid::try_new(shells).map_err(|e| fail(&format!("invalid solid: {e}")))?, rec))
- })
-}
-
-#[path = "curvecorner.rs"]
-mod corner;
-pub(crate) use corner::{corner_blend_style, param_on};
-// The planar corner builder the G2 corner work left in place of `corner_blend_style`'s sphere.
-#[allow(unused_imports)]
-pub(crate) use corner::corner_blend;
-
-#[cfg(test)]
-#[path = "curveblend_tests.rs"]
-mod tests;
-
-#[cfg(test)]
-#[path = "curveblend_law_tests.rs"]
-mod law_tests;
diff --git a/crates/kernel/src/curveblend_law_tests.rs b/crates/kernel/src/curveblend_law_tests.rs
deleted file mode 100644
index 44495a147..000000000
--- a/crates/kernel/src/curveblend_law_tests.rs
+++ /dev/null
@@ -1,315 +0,0 @@
-//! Chord-width and radius-law blends along curved edges: the width across the blend at every
-//! station, and the radius along the edge, measured on the body the kernel built against values
-//! worked out from the input geometry alone (the two cylinders' axes, the arc's axis).
-
-use mt::{BoundedCurve, ParametricCurve, SearchNearestParameter};
-use solidcraft_geom::Vec3;
-
-use super::*;
-use crate::blend::vtx;
-use crate::blend_variable::{RadiusSpline, fillet_chord, fillet_variable, fillet_variable_points, fillet_variable_spline};
-use crate::{Body, BoolOp, boolean, box_solid, cylinder, fillet, measure, step_export};
-
-/// An oblique boss: a rod of radius 8 whose axis leans 26.57° from the plate's normal, standing on
-/// a 5 mm plate. The edge where its side meets the plate's top plane is an ellipse whose two faces
-/// run from 63° to 117° apart around it.
-fn oblique_boss() -> (Body, Vec3, Vec3) {
- let plate = box_solid(Vec3::new(-40.0, -40.0, 0.0), Vec3::new(40.0, 40.0, 5.0)).unwrap();
- let base = Vec3::new(0.0, 0.0, -10.0);
- let axis = Vec3::new(0.5, 0.0, 1.0).normalized().unwrap();
- let rod = cylinder(base, axis, 8.0, 30.0).unwrap();
- (boolean(&plate, &rod, BoolOp::Union).unwrap().unwrap(), base, axis)
-}
-
-/// A 40 × 40 × 20 box whose front wall is an arc of radius 40 about a Z axis: `concave` cuts a
-/// cylinder away from the front (the wall curves into the part), otherwise the part is the box
-/// within the cylinder (the wall curves out). With the bottom arc's midpoint, the axis's base
-/// point and the side of the wall the material is on (+1 away from the axis, −1 toward it).
-fn arc_walled_box(concave: bool) -> (Body, Vec3, Vec3, f64) {
- let block = box_solid(Vec3::ZERO, Vec3::new(40.0, 40.0, 20.0)).unwrap();
- let (axis, op, side) =
- if concave { (Vec3::new(20.0, -30.0, 0.0), BoolOp::Cut, 1.0) } else { (Vec3::new(20.0, 70.0, 0.0), BoolOp::Intersect, -1.0) };
- let tool = cylinder(axis, Vec3::Z, 40.0, 20.0).unwrap();
- let body = boolean(&block, &tool, op).unwrap().unwrap();
- (body, axis + Vec3::new(0.0, side * 40.0, 0.0), axis, side)
-}
-
-/// The blend face a blend built over `input`: the fitted surface that is on neither of the faces
-/// it runs between (a boolean leaves the curved faces it kept as fitted surfaces themselves).
-fn blend_face(input: &Body, body: &Body) -> Option {
- use mt::ParametricSurface;
- let on_input = |p: Vec3| input.solid.face_iter().any(|f| project(f, p, None).is_some_and(|(q, _, _)| q.dist(p) <= 1e-6));
- body.solid
- .face_iter()
- .filter(|f| matches!(f.oriented_surface(), mt::Surface::NurbsSurface(_)))
- .find(|f| !on_input(from_p3(f.surface().subs(0.5, 0.5))))
- .cloned()
-}
-
-/// The edges of the blend face's boundary, each once, with the point at the middle of it (the
-/// blend is bounded by its two contacts and, at each end, an arc or the curve of an end face).
-fn blend_boundary(input: &Body, body: &Body) -> Vec<(mt::Edge, Vec3)> {
- let Some(f) = blend_face(input, body) else { return Vec::new() };
- let mut out: Vec<(mt::Edge, Vec3)> = Vec::new();
- for w in f.absolute_boundaries() {
- for e in w.edge_iter() {
- if out.iter().any(|(x, _)| x.id() == e.id()) {
- continue;
- }
- let c = e.oriented_curve();
- let (lo, hi) = c.range_tuple();
- out.push((e.absolute_clone(), from_p3(c.subs((lo + hi) * 0.5))));
- }
- }
- out
-}
-
-/// The edges of a contact: the boundary of the blend face whose middle point `side` picks out.
-fn contact(input: &Body, body: &Body, side: &dyn Fn(Vec3) -> bool) -> Vec {
- blend_boundary(input, body).into_iter().filter(|(_, m)| side(*m)).map(|(e, _)| e).collect()
-}
-
-/// The fraction of the way along `edge` (its absolute front to its back) of the point of it
-/// nearest `q`.
-fn along_fraction(edge: &mt::Edge, q: Vec3) -> Option {
- let e = edge.absolute_clone();
- let c = e.oriented_curve();
- let (lo, hi) = c.range_tuple();
- let steps = 512;
- let mut at = vec![from_p3(c.subs(lo))];
- let mut run = vec![0.0];
- for i in 1..=steps {
- let p = from_p3(c.subs(lo + (hi - lo) * i as f64 / steps as f64));
- run.push(run.last().copied()? + at.last().copied()?.dist(p));
- at.push(p);
- }
- let total = *run.last()?;
- let d = |i: usize| at.get(i).map(|p| p.dist(q)).unwrap_or(f64::INFINITY);
- let hint = (0..=steps).min_by(|x, y| d(*x).total_cmp(&d(*y))).unwrap_or(0);
- let t = c.search_nearest_parameter(p3(q), lo + (hi - lo) * hint as f64 / steps as f64, 100)?;
- let i = (((t - lo) / (hi - lo)) * steps as f64).clamp(0.0, steps as f64);
- let (k, f) = (i.floor() as usize, i.fract());
- let (Some(a), Some(b)) = (run.get(k), run.get((k + 1).min(steps))) else { return None };
- Some((a + (b - a) * f) / total)
-}
-
-/// The azimuth of `p` about the Z axis through `axis`.
-fn azimuth(axis: Vec3, p: Vec3) -> f64 {
- (p.y - axis.y).atan2(p.x - axis.x)
-}
-
-/// The point of the curves running round the Z axis through `axis` at the azimuth `phi`.
-fn at_azimuth(edges: &[mt::Edge], axis: Vec3, phi: f64) -> Option {
- let off = |p: Vec3| {
- let mut d = azimuth(axis, p) - phi;
- while d > std::f64::consts::PI {
- d -= std::f64::consts::TAU;
- }
- while d < -std::f64::consts::PI {
- d += std::f64::consts::TAU;
- }
- d
- };
- let (mut best, mut best_d) = (Vec3::ZERO, f64::INFINITY);
- for e in edges {
- let c = e.oriented_curve();
- let (lo, hi) = c.range_tuple();
- let steps = 512;
- let mut at = lo;
- let mut dist = f64::INFINITY;
- for i in 0..=steps {
- let t = lo + (hi - lo) * i as f64 / steps as f64;
- let d = off(from_p3(c.subs(t))).abs();
- if d < dist {
- (at, dist) = (t, d);
- }
- }
- let step = (hi - lo) / steps as f64;
- let (mut x0, mut x1) = ((at - step).max(lo), (at + step).min(hi));
- let g = 0.618_033_988_749_894_9;
- for _ in 0..80 {
- let (a, b) = (x1 - g * (x1 - x0), x0 + g * (x1 - x0));
- if off(from_p3(c.subs(a))).abs() < off(from_p3(c.subs(b))).abs() {
- x1 = b;
- } else {
- x0 = a;
- }
- }
- let t = 0.5 * (x0 + x1);
- let d = off(from_p3(c.subs(t))).abs();
- if d < best_d {
- (best, best_d) = (from_p3(c.subs(t)), d);
- }
- }
- (best_d < 1e-6).then_some(best)
-}
-
-/// A chord fillet along the cylinder-into-plane edge of an oblique boss — the two faces run from
-/// 63° to 117° apart around it. The blend's chain stops at the seams between the patches a boolean
-/// left of the rod's surface, where the end face is tangent to the rod; the cap that cuts the strip
-/// back there is only placed for one radius, so a width that varies along the edge is refused
-/// rather than approximated (the fixed radius of `fillet` along the same edge rolls).
-#[test]
-fn a_chord_fillet_along_an_oblique_boss_edge_is_refused() {
- let (body, _, _) = oblique_boss();
- let pick = Vec3::new(7.5 + 8.944_271_909_999_16, 0.0, 5.0);
- // A fixed radius rolls along the same chain: the edge itself is supported.
- assert!(fillet(&body, &[pick], 2.5).is_ok());
- let e = fillet_chord(&body, &[pick], 4.0).unwrap_err();
- assert!(matches!(e, KernelError::TooLarge(_)), "{e}");
-}
-
-/// A chord fillet along an arc whose two faces meet at a right angle: the width across the blend
-/// is the chord, so the round is the one of radius `chord / √2` (checked against the constant
-/// fillet of that radius) and its two contacts are that far apart at every station.
-#[test]
-fn chord_fillet_along_an_arc_edge() {
- let (chord, r) = (3.0, 3.0 / 2f64.sqrt());
- let (body, mid, axis, _) = arc_walled_box(false);
- let blended = fillet_chord(&body, &[mid], chord).unwrap();
- assert!(blended.validity().is_empty(), "{:?}", blended.validity());
- assert_eq!(blended.unmeshed_faces(), 0);
- let plain = fillet(&body, &[mid], r).unwrap();
- let (made, exact) = (measure(&blended).unwrap().volume, measure(&plain).unwrap().volume);
- assert!((made - exact).abs() < exact * 1e-6, "volume {made} vs {exact}");
- // The contact on the plane and the one on the wall at the same azimuth: the width across.
- let plane = contact(&body, &blended, &|m| m.z.abs() < 1e-6);
- let wall = contact(&body, &blended, &|m| m.z.abs() >= 1e-6);
- assert!(!plane.is_empty() && !wall.is_empty(), "the contacts are not the plane's and the wall's");
- let mid_azimuth = azimuth(axis, mid);
- let mut worst: f64 = 0.0f64;
- let mut stations = 0;
- for i in 1..12 {
- let phi = mid_azimuth + (i as f64 / 12.0 - 0.5) * 0.9;
- let (Some(p), Some(w)) = (at_azimuth(&plane, axis, phi), at_azimuth(&wall, axis, phi)) else { continue };
- stations += 1;
- worst = worst.max((p.dist(w) - chord).abs());
- }
- eprintln!("arc chord {chord}: worst width error {worst:.6} mm at {stations} stations");
- assert!(stations >= 9, "only {stations} stations measured");
- assert!(worst < 0.01, "the width across the blend is {worst} mm off the chord {chord}");
-}
-
-/// A chord fillet on a straight edge between planar faces is still the exact local round: the
-/// same body, bit for bit, as the fillet of the radius the chord gives (a right angle: chord c is
-/// r = c / √2).
-#[test]
-fn chord_fillet_on_a_straight_edge_is_unchanged() {
- let b = box_solid(Vec3::ZERO, Vec3::new(10.0, 20.0, 30.0)).unwrap();
- let (at, chord) = (Vec3::new(10.0, 10.0, 30.0), 4.0);
- let f = fillet_chord(&b, &[at], chord).unwrap();
- let k = fillet(&b, &[at], chord / 2f64.sqrt()).unwrap();
- assert_eq!(step_export(&[&f], "part").unwrap(), step_export(&[&k], "part").unwrap());
- assert_eq!(f.unmeshed_faces(), 0);
-}
-
-/// A variable radius along an arc edge: a ball whose radius is the law's at each station's fraction
-/// of the edge's length rolls along it, and the setback on the planar face — the plane and the
-/// wall meet at a right angle, so it is the section's radius — follows the law from end to end.
-#[test]
-fn variable_radius_along_an_arc_edge_follows_the_law() {
- let (body, mid, axis, _) = arc_walled_box(false);
- let edge = crate::surfaces::edge_near(&body, mid).unwrap();
- // Started from the edge's back end: the law runs the other way, as the positions are from the
- // end nearest `start`.
- let start = vtx(edge.absolute_back());
- // A wider law (2 → 4, the radius doubling over the arc) is out of reach of the fitted strip:
- // the sections' own last spans cannot be held to the fit's accuracy there. That is refused,
- // not approximated.
- for wide in [4.0, 5.0] {
- let e = fillet_variable(&body, mid, start, 2.0, wide).unwrap_err();
- assert!(e.to_string().contains("accuracy and section limits"), "2 -> {wide}: {e}");
- }
- let (r0, r1) = (2.0, 3.4);
- let blended = fillet_variable(&body, mid, start, r0, r1).unwrap();
- assert!(blended.validity().is_empty(), "{:?}", blended.validity());
- assert_eq!(blended.unmeshed_faces(), 0);
- let law = RadiusSpline::through(&[(0.0, r0), (1.0, r1)], false);
- // The law runs from the end nearest `start`: the chain's front here is the far end.
- let want = if vtx(edge.absolute_back()).dist(start) < vtx(edge.absolute_front()).dist(start) { law.reversed() } else { law.clone() };
- // `start` is the chain's back end, so the law is read back to front there: r0 at the back, r1
- // at the front.
- assert!((want.eval(1.0) - r0).abs() < 1e-12 && (want.eval(0.0) - r1).abs() < 1e-12);
- // The blend's contact on the bottom plane is at 40 − r from the axis.
- let plane = contact(&body, &blended, &|m| m.z.abs() < 1e-6);
- assert!(!plane.is_empty(), "no contact on the bottom plane");
- let mut worst: f64 = 0.0;
- let mut stations = 0;
- let mut shown = Vec::new();
- for e in &plane {
- let c = e.oriented_curve();
- let (lo, hi) = c.range_tuple();
- for i in 0..=32 {
- let p = from_p3(c.subs(lo + (hi - lo) * i as f64 / 32.0));
- let measured = 40.0 - (p - axis).len();
- let along = along_fraction(&edge, p).unwrap();
- // Leave the two ends, where the caps cut the contact: the blend closes on the end
- // faces there.
- if !(0.04..=0.96).contains(&along) {
- continue;
- }
- stations += 1;
- if shown.len() < 3 || (0.45..0.55).contains(&along) {
- shown.push((along, measured, want.eval(along)));
- }
- worst = worst.max((measured - want.eval(along)).abs());
- }
- }
- eprintln!("arc variable {r0} -> {r1}: worst radius error {worst:.6} mm at {stations} stations; law vs measured {shown:?}");
- assert!(stations >= 24, "only {stations} stations measured");
- assert!(worst < 0.02, "the section radius is {worst} mm off the law");
- // Wider, still inside what the strip holds: the same body as the exact straight-edge case of
- // that law is not built here, but the radius is the law's at every station measured.
-}
-
-/// A radius law that runs to zero at an end of a curved edge: refused by name. The blend would
-/// close to the edge's end point, but the fitted strip pinches to a point there and the last span
-/// of it cannot be held to the fit's accuracy: the straight-edge fillet, which closes exactly, is
-/// the way (see `variable_radius_down_to_zero_at_one_end`).
-#[test]
-fn a_law_running_to_zero_along_a_curved_edge_is_refused() {
- let (body, mid, _, _) = arc_walled_box(false);
- let edge = crate::surfaces::edge_near(&body, mid).unwrap();
- for start in [vtx(edge.absolute_front()), vtx(edge.absolute_back())] {
- let e = fillet_variable(&body, mid, start, 3.0, 0.0).unwrap_err();
- assert!(e.to_string().contains("runs to zero along a curved edge"), "{e}");
- let law = RadiusSpline { degree: 1, knots: vec![0.0, 0.0, 1.0, 1.0], radii: vec![0.0, 3.0] };
- assert!(fillet_variable_spline(&body, mid, mid, &law).is_err());
- // A law that stays clear of zero along it rolls: the blend is closed, a three-sided face
- // where nothing closes it.
- let made = fillet_variable(&body, mid, start, 3.0, 2.4).unwrap();
- assert!(made.validity().is_empty(), "{:?}", made.validity());
- let mesh = made.mesh(&crate::MeshTolerance::chord(5e-4)).unwrap();
- let about = |o: Vec3| {
- mesh.triangles
- .iter()
- .map(|t| (mesh.positions[t[0] as usize] - o).dot((mesh.positions[t[1] as usize] - o).cross(mesh.positions[t[2] as usize] - o)) / 6.0)
- .sum::()
- };
- assert!((about(Vec3::ZERO) - about(Vec3::new(-100.0, 50.0, 30.0))).abs() < 1e-2, "the mesh is not closed");
- }
-}
-
-/// What a chord or a law the local geometry cannot hold is refused with: an error naming the size,
-/// never a silent approximation and never a panic.
-#[test]
-fn a_chord_or_radius_the_faces_cannot_hold_is_refused() {
- let (body, mid, _, _) = arc_walled_box(false);
- // A chord of 30 across a 40 mm wide wall (r ≈ 21, past the side walls and the block).
- let e = fillet_chord(&body, &[mid], 30.0).unwrap_err();
- assert!(matches!(e, KernelError::TooLarge(_)), "{e}");
- assert!(fillet_chord(&body, &[mid], 3.0 / 2f64.sqrt()).is_ok());
- // A radius law too large for the wall.
- assert!(fillet_variable(&body, mid, Vec3::new(0.0, 30.0, 0.0), 2.0, 30.0).is_err());
- assert!(fillet_variable(&body, mid, Vec3::new(0.0, 30.0, 0.0), 20.0, 20.0).is_err());
- // Non-finite, negative and zero-at-both-ends laws: refused before the geometry is touched.
- let bad = |radii: Vec| RadiusSpline { degree: 1, knots: vec![0.0, 0.0, 1.0, 1.0], radii };
- assert!(fillet_variable_spline(&body, mid, mid, &bad(vec![2.0, f64::NAN])).is_err());
- assert!(fillet_variable_spline(&body, mid, mid, &bad(vec![2.0, f64::INFINITY])).is_err());
- assert!(fillet_variable_spline(&body, mid, mid, &bad(vec![2.0, -1.0])).is_err());
- assert!(fillet_variable_spline(&body, mid, mid, &bad(vec![0.0, 0.0])).is_err());
- assert!(fillet_variable_spline(&body, mid, mid, &RadiusSpline { degree: 1, knots: vec![0.0, 0.5, 1.0], radii: vec![2.0, 3.0] }).is_err());
- assert!(fillet_variable_points(&body, mid, mid, &[(0.0, 2.0), (1.5, 3.0)], false).is_err());
- // An edge the body does not have is refused by name, not approximated.
- assert!(fillet_chord(&body, &[Vec3::new(500.0, 500.0, 500.0)], 3.0).is_err());
-}
diff --git a/crates/kernel/src/curveblend_tests.rs b/crates/kernel/src/curveblend_tests.rs
deleted file mode 100644
index 9e7a63f3b..000000000
--- a/crates/kernel/src/curveblend_tests.rs
+++ /dev/null
@@ -1,731 +0,0 @@
-//! Independent analytic reference: the centre of a ball tangent to two perpendicular
-//! cylinders lies on the intersection of their radius-offset cylinders.
-
-use mt::{BoundedCurve, ParametricCurve, ParametricSurface, ParametricSurface3D, SearchNearestParameter};
-
-use super::*;
-use crate::blend::plane_normal;
-use crate::issue_851_tests::planned_volume;
-use crate::{Body, BoolOp, boolean, cylinder, fillet};
-
-#[test]
-fn issue_1303_chamfer_open_rim_after_end_chamfer() {
- use solidcraft_geom::{Loop2, Plane, Region2, Seg2, Vec2};
- let rim = Region2 {
- outer: Loop2 {
- segs: vec![
- Seg2::Line { a: Vec2::new(31.0, -15.0), b: Vec2::new(31.0, -11.75) },
- Seg2::Line { a: Vec2::new(31.0, -11.75), b: Vec2::new(0.0, -11.75) },
- Seg2::Arc { center: Vec2::ZERO, radius: 11.75, start: -std::f64::consts::FRAC_PI_2, sweep: -std::f64::consts::PI },
- Seg2::Line { a: Vec2::new(0.0, 11.75), b: Vec2::new(31.0, 11.75) },
- Seg2::Line { a: Vec2::new(31.0, 11.75), b: Vec2::new(31.0, 15.0) },
- Seg2::Line { a: Vec2::new(31.0, 15.0), b: Vec2::new(0.0, 15.0) },
- Seg2::Arc { center: Vec2::ZERO, radius: 15.0, start: std::f64::consts::FRAC_PI_2, sweep: std::f64::consts::PI },
- Seg2::Line { a: Vec2::new(0.0, -15.0), b: Vec2::new(31.0, -15.0) },
- ],
- },
- holes: vec![],
- };
- let mut body = crate::extrude(&Plane::XY, &[rim], 0.0, 13.0).unwrap().pop().unwrap();
- // Exact local end bevels, meeting at the four-face vertices (30, +/-11.75, 13).
- body = crate::blend_corner::chamfer(
- &body,
- &[Vec3::new(31.0, 13.375, 13.0), Vec3::new(31.0, -13.375, 13.0), Vec3::new(31.0, 11.75, 8.0), Vec3::new(31.0, -11.75, 8.0)],
- 1.0,
- )
- .unwrap();
- let picks = [Vec3::new(-11.75, 0.0, 13.0), Vec3::new(15.0, 11.75, 13.0), Vec3::new(15.0, -11.75, 13.0)];
- let result = crate::chamfer(&body, &picks, 1.0).unwrap();
- assert!(result.validity().is_empty(), "{:?}", result.validity());
- assert_eq!(result.crossed_face_loops().unwrap(), 0);
- // At height 12 + u, the removed half-ring area is pi/2 * (2*r*u + u^2).
- // The straight strips end at min(31-u, 30+v), 0 <= v <= u. Their integral
- // over 0 <= u <= 1 is 30 + 1/6; this includes both split end sections.
- let expected = 30.0 + 1.0 / 6.0 + std::f64::consts::PI * (11.75 / 2.0 + 1.0 / 6.0);
- let volume = |b: &Body| b.mesh(&crate::MeshTolerance::chord(0.0001)).unwrap().measure().volume;
- let removed = volume(&body) - volume(&result);
- assert!((removed - expected).abs() < 0.02, "removed {removed}, expected {expected}");
- for p in [Vec3::new(30.5, 12.25, 12.5), Vec3::new(30.5, -12.25, 12.5)] {
- assert!(result.solid.vertex_iter().any(|v| from_p3(v.point()).dist(p) < 1e-6));
- }
- for selection in [vec![picks[0]], picks.into_iter().rev().collect()] {
- let other = crate::chamfer(&body, &selection, 1.0).unwrap();
- assert!(other.validity().is_empty(), "{:?}", other.validity());
- assert!((volume(&body) - volume(&other) - expected).abs() < 0.02);
- }
- assert!(crate::chamfer(&body, &picks, 4.0).is_err());
-}
-
-fn tee(scale: f64, origin: Vec3) -> Body {
- let main = cylinder(origin + Vec3::new(-40.0, 0.0, 0.0) * scale, Vec3::X, 15.0 * scale, 80.0 * scale).unwrap();
- let branch = cylinder(origin, Vec3::Z, 10.0 * scale, 35.0 * scale).unwrap();
- boolean(&main, &branch, BoolOp::Union).unwrap().unwrap()
-}
-
-fn analytic_section(theta: f64, scale: f64, origin: Vec3) -> (Vec3, Vec3, Vec3) {
- let centre = Vec3::new(13.0 * theta.cos(), 13.0 * theta.sin(), (324.0 - 169.0 * theta.sin().powi(2)).sqrt());
- let main = Vec3::new(centre.x, centre.y * 15.0 / 18.0, centre.z * 15.0 / 18.0);
- let branch = Vec3::new(centre.x * 10.0 / 13.0, centre.y * 10.0 / 13.0, centre.z);
- (origin + centre * scale, origin + main * scale, origin + branch * scale)
-}
-
-fn nearest_blend(surfaces: &[mt::Surface], point: Vec3) -> (f64, Vec3) {
- surfaces
- .iter()
- .filter_map(|s| {
- let (u, v) = s.search_nearest_parameter(p3(point), None, 100)?;
- let actual = from_p3(s.subs(u, v));
- let n = s.normal(u, v);
- Some((actual.dist(point), Vec3::new(n.x, n.y, n.z).normalized()?))
- })
- .min_by(|a, b| a.0.total_cmp(&b.0))
- .unwrap()
-}
-
-fn distance_to_analytic_arc(theta: f64, point: Vec3) -> f64 {
- let (centre, main, branch) = analytic_section(theta, 1.0, Vec3::ZERO);
- let a = (main - centre).normalized().unwrap();
- let b = (branch - centre).normalized().unwrap();
- let plane = a.cross(b).normalized().unwrap();
- let radial = point - centre;
- let projected = radial - plane * radial.dot(plane);
- let direction = projected.normalized().unwrap();
- let angle = a.dot(b).clamp(-1.0, 1.0).acos();
- let from_main = a.dot(direction).clamp(-1.0, 1.0).acos();
- let from_branch = b.dot(direction).clamp(-1.0, 1.0).acos();
- if (from_main + from_branch - angle).abs() < 1e-7 { point.dist(centre + direction * 3.0) } else { point.dist(main).min(point.dist(branch)) }
-}
-
-fn distance_to_analytic_band(point: Vec3) -> f64 {
- // The arc's XY azimuth stays between its two contacts' azimuths. Their difference
- // for this tee is less than 0.1 rad; bracket generously around the query azimuth.
- let azimuth = point.y.atan2(point.x);
- let (mut lo, mut hi) = (azimuth - 0.3, azimuth + 0.3);
- for _ in 0..55 {
- let a = lo + (hi - lo) * 0.38196601125;
- let b = lo + (hi - lo) * 0.61803398875;
- if distance_to_analytic_arc(a, point) < distance_to_analytic_arc(b, point) {
- hi = b;
- } else {
- lo = a;
- }
- }
- distance_to_analytic_arc((lo + hi) * 0.5, point)
-}
-
-#[test]
-fn fitted_contact_edges_coincide_with_their_surface_boundaries() {
- let sections: Vec> = (0..4)
- .map(|k| {
- (0..SAMPLES)
- .map(|i| {
- let theta = std::f64::consts::FRAC_PI_2 * (k as f64 + i as f64 / (SAMPLES - 1) as f64);
- let (c, q1, q2) = analytic_section(theta, 1.0, Vec3::ZERO);
- Section { c, q1, q2 }
- })
- .collect()
- })
- .collect();
- for k in 0..sections.len() {
- let fit = crate::guard("contact consistency", || fit_sections(§ions, k, true, true)).unwrap();
- for (side, curve) in fit.contacts.iter().enumerate() {
- let (lo, hi) = curve.range_tuple();
- for i in 0..=200 {
- let parameter = lo + (hi - lo) * i as f64 / 200.0;
- let edge = from_p3(curve.subs(parameter));
- let surface = from_p3(fit.surface.subs(side as f64, parameter));
- assert!(edge.dist(surface) < 1e-9, "contact-to-surface gap {}", edge.dist(surface));
- }
- }
- }
-}
-
-#[test]
-fn rolling_ball_matches_analytic_tee_and_contacts() {
- for (scale, origin) in [(1.0, Vec3::ZERO), (0.25, Vec3::new(23.0, -17.0, 9.0))] {
- let body = tee(scale, origin);
- let point = origin + Vec3::new(0.0, 10.0, 125f64.sqrt()) * scale;
- let blend = fillet(&body, &[point], 3.0 * scale).unwrap();
- assert!(blend.validity().is_empty(), "{:?}", blend.validity());
- let surfaces: Vec<_> = blend.solid.face_iter().map(|f| f.oriented_surface()).filter(|s| matches!(s, mt::Surface::NurbsSurface(_))).collect();
- assert!(!surfaces.is_empty());
- let mut distance: f64 = 0.0;
- let mut tangent_angle: f64 = 0.0;
- for i in 0..96 {
- // Offset the angular samples from patch seams; contact endpoints are tested below.
- let theta = std::f64::consts::TAU * (i as f64 + 0.37) / 96.0;
- let (centre, main, branch) = analytic_section(theta, scale, origin);
- let a = (main - centre).normalized().unwrap();
- let b = (branch - centre).normalized().unwrap();
- let angle = a.dot(b).clamp(-1.0, 1.0).acos();
- for fraction in [0.0, 0.25, 0.5, 0.75, 1.0] {
- // Spherical linear interpolation of the radial unit vectors, independent of
- // the production rational control-point construction and fitting parameters.
- let radial = (a * ((1.0 - fraction) * angle).sin() + b * (fraction * angle).sin()) / angle.sin();
- let exact = centre + radial * (3.0 * scale);
- let (error, normal) = nearest_blend(&surfaces, exact);
- distance = distance.max(error);
- if fraction == 0.0 || fraction == 1.0 {
- let want = (centre - exact).normalized().unwrap();
- tangent_angle = tangent_angle.max(normal.dot(want).abs().min(1.0).acos().to_degrees());
- }
- }
- }
- assert!(distance <= 0.005, "scale {scale}: analytic surface deviation {distance} mm");
- assert!(tangent_angle <= 0.5, "scale {scale}: contact normals differ by {tangent_angle} degrees");
-
- // The reverse direction uses points on the actual trimmed face mesh, so an
- // untrimmed neighbouring surface cannot conceal an overshooting blend patch.
- let mesh = blend.mesh(&crate::MeshTolerance::chord(0.002)).unwrap();
- let mut reverse_distance: f64 = 0.0;
- let mut probes = 0;
- for point in mesh.positions.iter().step_by(19) {
- let p = (*point - origin) / scale;
- if (p.x * p.x + p.y * p.y).sqrt() <= 10.000001
- || (p.y * p.y + p.z * p.z).sqrt() <= 15.000001
- || !(10.0..20.0).contains(&p.z)
- || p.x.abs() > 16.0
- {
- continue;
- }
- probes += 1;
- reverse_distance = reverse_distance.max(distance_to_analytic_band(p) * scale);
- }
- assert!(probes > 300, "only {probes} trimmed surface points checked");
- assert!(reverse_distance <= 0.005, "scale {scale}: reverse analytic deviation {reverse_distance} mm");
- eprintln!("scale {scale}: surface {distance:.9} mm, reverse {reverse_distance:.9} mm, contact normals {tangent_angle:.6} degrees");
-
- let mut contact_count = 0;
- for edge in Body::unique_edges(&blend.solid) {
- let curve = edge.oriented_curve();
- let (lo, hi) = curve.range_tuple();
- let endpoints = [from_p3(curve.subs(lo)), from_p3(curve.subs(hi))].map(|p| (p - origin) / scale);
- if endpoints.iter().any(|p| !(9.0..20.0).contains(&p.z) || p.x.abs() > 16.0) {
- continue;
- }
- let branch = endpoints.iter().all(|p| ((p.x * p.x + p.y * p.y).sqrt() - 10.0).abs() < 1e-5);
- let main = endpoints.iter().all(|p| ((p.y * p.y + p.z * p.z).sqrt() - 15.0).abs() < 1e-5);
- if !branch && !main {
- continue;
- }
- contact_count += 1;
- for i in 0..=200 {
- let p = (from_p3(curve.subs(lo + (hi - lo) * i as f64 / 200.0)) - origin) / scale;
- let radius_error = if branch { ((p.x * p.x + p.y * p.y).sqrt() - 10.0).abs() } else { ((p.y * p.y + p.z * p.z).sqrt() - 15.0).abs() };
- assert!(radius_error * scale <= 0.002, "supporting cylinder deviation {} mm", radius_error * scale);
- }
- }
- assert!(contact_count >= 4, "only {contact_count} contacts checked");
- }
-}
-
-#[test]
-fn rolling_ball_refinement_cap_returns_an_error_and_preserves_input() {
- let body = tee(1.0, Vec3::ZERO);
- let solid = body.deep_copy();
- let ids: Vec<_> = Body::unique_edges(&solid)
- .iter()
- .filter(|edge| {
- let curve = edge.oriented_curve();
- let (lo, hi) = curve.range_tuple();
- let p = from_p3(curve.subs((lo + hi) * 0.5));
- p.z > 10.0 && ((p.x * p.x + p.y * p.y).sqrt() - 10.0).abs() < 0.01 && ((p.y * p.y + p.z * p.z).sqrt() - 15.0).abs() < 0.01
- })
- .map(mt::Edge::id)
- .collect();
- assert!(!ids.is_empty());
- let before = crate::step_export(&[&body], "unchanged").unwrap();
- let input_before = crate::step_export(&[&Body::new(solid.clone()).unwrap()], "unchanged").unwrap();
- // Four sections deliberately undersample the saddle; production starts at 24.
- let error = crate::guard("limited rolling ball", || curve_blend_with_limit(&solid, &ids, body.size(), 3.0, true, 4)).unwrap_err();
- assert!(error.to_string().contains("accuracy and section limits"), "{error}");
- assert_eq!(crate::step_export(&[&body], "unchanged").unwrap(), before);
- assert_eq!(crate::step_export(&[&Body::new(solid.clone()).unwrap()], "unchanged").unwrap(), input_before);
-}
-
-/// Plan-view construction of a round between two overlapping circles (a concave vertical edge
-/// where two Z cylinders meet): the ball centre `f`, the circle and fillet arc angles, and the
-/// area the round fills in, all independent of the kernel.
-struct Gap {
- /// Points along the round's arc in plan, contacts included.
- arc: Vec,
- /// Arc angles on circle 1, circle 2 and the fillet between the corner and the contacts.
- angles: [f64; 3],
- area: f64,
-}
-
-fn gap(c1: Vec3, r1: f64, c2: Vec3, r2: f64, corner: Vec3, r: f64) -> Gap {
- // The ball centre is r from both circles, on the corner's side of the centre line.
- let (a, b) = (r1 + r, r2 + r);
- let d = c1.dist(c2);
- let u = (c2 - c1) * (1.0 / d);
- let along = (a * a - b * b + d * d) / (2.0 * d);
- let mut side = Vec3::new(-u.y, u.x, 0.0);
- if (corner - c1).dot(side) < 0.0 {
- side = side * -1.0;
- }
- let f = c1 + u * along + side * (a * a - along * along).sqrt();
- let (t1, t2) = (c1 + (f - c1) * (r1 / a), c2 + (f - c2) * (r2 / b));
- let angle = |c: Vec3, p: Vec3, q: Vec3| (p - c).normalized().unwrap().dot((q - c).normalized().unwrap()).clamp(-1.0, 1.0).acos();
- let angles = [angle(c1, t1, corner), angle(c2, corner, t2), angle(f, t2, t1)];
- // Shoelace over the three short arcs: circle 1 to the corner, circle 2 on, fillet back.
- let mut ring = Vec::new();
- for (c, p, q) in [(c1, t1, corner), (c2, corner, t2), (f, t2, t1)] {
- let (p0, q0) = (p - c, q - c);
- let (a0, a1) = (p0.y.atan2(p0.x), q0.y.atan2(q0.x));
- let mut sweep = a1 - a0;
- while sweep > std::f64::consts::PI {
- sweep -= std::f64::consts::TAU;
- }
- while sweep < -std::f64::consts::PI {
- sweep += std::f64::consts::TAU;
- }
- let rr = p0.len();
- for i in 0..20_000 {
- let t = a0 + sweep * i as f64 / 20_000.0;
- ring.push(c + Vec3::new(t.cos(), t.sin(), 0.0) * rr);
- }
- }
- let area = ring.iter().map(|p| solidcraft_geom::Vec2::new(p.x, p.y)).collect::>().signed_area().abs();
- let (p, q) = ((t1 - f).normalized().unwrap(), (t2 - f).normalized().unwrap());
- let arc = (0..=8).map(|i| angles[2] * i as f64 / 8.0).map(|t| f + (p * ((angles[2] - t).sin()) + q * t.sin()) * (r / angles[2].sin())).collect();
- Gap { arc, angles, area }
-}
-
-#[test]
-fn rolling_ball_along_a_straight_edge_between_cylinders_trims_curved_end_seams() {
- // Two Z cylinders crossing square to each other: the vertical lines where they meet are
- // concave edges between two curved faces, and the blend ends on the planar caps, where the
- // seams are arcs.
- let (r1, r2, h, r) = (17.0, 9.5, 10.0, 6.0);
- let (c1, c2) = (Vec3::ZERO, Vec3::new(r1, r2, 0.0));
- let a = cylinder(c1, Vec3::Z, r1, h).unwrap();
- let b = cylinder(c2, Vec3::Z, r2, h).unwrap();
- let body = boolean(&a, &b, BoolOp::Union).unwrap().unwrap();
- // The corner: one of the two points where the circles cross.
- let d = c1.dist(c2);
- let u = (c2 - c1) * (1.0 / d);
- let along = (r1 * r1 - r2 * r2 + d * d) / (2.0 * d);
- let corner = c1 + u * along + Vec3::new(-u.y, u.x, 0.0) * (r1 * r1 - along * along).sqrt();
- let g = gap(c1, r1, c2, r2, corner, r);
- let blend = fillet(&body, &[corner + Vec3::Z * (h / 2.0)], r).unwrap();
- assert!(blend.validity().is_empty(), "{:?}", blend.validity());
- // One blend face; the edge is replaced by two contact lines and two end arcs.
- let (before, after) = (crate::measure(&body).unwrap(), crate::measure(&blend).unwrap());
- assert_eq!((after.faces, after.edges, after.vertices), (before.faces + 1, before.edges + 3, before.vertices + 2), "{before:?} -> {after:?}");
- // The round fills the gap over the full height. The caps gain it twice; the walls lose
- // their arcs to the contacts and gain the round.
- let (m0, m1) = (body.mesh(&crate::MeshTolerance::chord(0.0005)).unwrap().measure(), blend.mesh(&crate::MeshTolerance::chord(0.0005)).unwrap().measure());
- let volume = h * g.area;
- assert!((m1.volume - m0.volume - volume).abs() < volume * 3e-3, "added volume {} vs {volume}", m1.volume - m0.volume);
- let [a1, a2, af] = g.angles;
- let area = 2.0 * g.area + h * (r * af - r1 * a1 - r2 * a2);
- assert!((m1.area - m0.area - area).abs() < area.abs() * 3e-3, "added area {} vs {area}", m1.area - m0.area);
- // The round is the analytic arc at every height, from contact to contact.
- let surfaces: Vec<_> = blend.solid.face_iter().map(|f| f.oriented_surface()).filter(|s| matches!(s, mt::Surface::NurbsSurface(_))).collect();
- let mut worst: f64 = 0.0;
- for z in [0.0, 0.25, 0.5, 0.75, 1.0] {
- for p in &g.arc {
- worst = worst.max(nearest_blend(&surfaces, *p + Vec3::Z * (h * z)).0);
- }
- }
- assert!(worst < 1e-3, "blend surface is {worst} mm off the analytic round");
-}
-
-#[test]
-fn closed_curved_seam_is_not_supported() {
- // A closed seam (one edge starting and ending at the same vertex, as a full cap circle can
- // be in imported geometry) has no "between" two contacts, so trimming it is refused rather
- // than guessed.
- let body = cylinder(Vec3::ZERO, Vec3::Z, 10.0, 5.0).unwrap();
- let arc = body.solid.edge_iter().find(|e| !matches!(e.curve(), mt::Curve::Line(_))).expect("a cap arc");
- let circle = mt::Edge::new_unchecked(arc.front(), arc.front(), arc.curve());
- assert_eq!(circle.front(), circle.back());
- // Contacts on the circle itself: a third and two thirds of the way round.
- let (lo, hi) = circle.curve().range_tuple();
- let on = |f: f64| mt::Vertex::new(circle.curve().subs(lo + (hi - lo) * f));
- for (a, b) in [(Some(on(1.0 / 3.0)), None), (None, Some(on(2.0 / 3.0))), (Some(on(1.0 / 3.0)), Some(on(2.0 / 3.0))), (None, None)] {
- let err = trim_curved_seam(&circle, a, b, 20.0).unwrap_err();
- assert!(err.to_string().contains("not supported yet: a closed curved edge"), "{err}");
- }
-}
-
-#[test]
-fn rolling_ball_past_the_end_seam_is_too_large_and_reduces() {
- // The crossing cylinders of the test above with the small one's centre inside the large
- // one: a round of 3 would reach past the end of the cap arc it trims, so it is too large
- // (a smaller one fits), and the largest that fits is the analytic round over the full height
- // (checked on its surface: its added volume is too small beside the body's to measure).
- let (r1, r2, d, h) = (17.0, 9.5, 12.0, 10.0);
- let (c1, c2) = (Vec3::ZERO, Vec3::new(d, 0.0, 0.0));
- let body = boolean(&cylinder(c1, Vec3::Z, r1, h).unwrap(), &cylinder(c2, Vec3::Z, r2, h).unwrap(), BoolOp::Union).unwrap().unwrap();
- let along = (r1 * r1 - r2 * r2 + d * d) / (2.0 * d);
- let corner = Vec3::new(along, (r1 * r1 - along * along).sqrt(), 0.0);
- let at = [corner + Vec3::Z * (h / 2.0)];
- let e = fillet(&body, &at, 3.0).unwrap_err();
- assert!(matches!(e, KernelError::TooLarge(_)), "{e}");
- let (r, blend) = crate::fillet_max(&body, &at, 3.0).unwrap();
- assert!(r > 1.5 && r < 3.0, "{r}");
- assert!(blend.validity().is_empty(), "{:?}", blend.validity());
- let g = gap(c1, r1, c2, r2, corner, r);
- let surfaces: Vec<_> = blend.solid.face_iter().map(|f| f.oriented_surface()).filter(|s| matches!(s, mt::Surface::NurbsSurface(_))).collect();
- let mut worst: f64 = 0.0;
- for z in [0.0, 0.25, 0.5, 0.75, 1.0] {
- for p in &g.arc {
- worst = worst.max(nearest_blend(&surfaces, *p + Vec3::Z * (h * z)).0);
- }
- }
- assert!(worst < 1e-3, "blend surface is {worst} mm off the analytic round at r {r}");
-}
-
-#[test]
-fn a_refused_edge_is_not_rolled_again_after_blends_far_from_it() {
- // The crossing cylinders' seam refuses a round of 3 (too large). A bar joined to them has
- // two straight edges at its far end that round on their own. Each blend there leaves the
- // seam's surroundings as they were, so the seam is tried once, not once per blend, and the
- // refusal is the same.
- let (r1, r2, d, h) = (17.0, 9.5, 12.0, 10.0);
- let body = boolean(&cylinder(Vec3::ZERO, Vec3::Z, r1, h).unwrap(), &cylinder(Vec3::new(d, 0.0, 0.0), Vec3::Z, r2, h).unwrap(), BoolOp::Union)
- .unwrap()
- .unwrap();
- let bar = crate::box_solid(Vec3::new(-80.0, -5.0, 0.0), Vec3::new(-10.0, 5.0, h)).unwrap();
- let body = boolean(&body, &bar, BoolOp::Union).unwrap().unwrap();
- let along = (r1 * r1 - r2 * r2 + d * d) / (2.0 * d);
- let seam = Vec3::new(along, (r1 * r1 - along * along).sqrt(), h / 2.0);
- let ends = [Vec3::new(-80.0, -5.0, h / 2.0), Vec3::new(-80.0, 5.0, h / 2.0)];
- crate::blend::ROLLS.with(|n| n.set(0));
- let e = fillet(&body, &[seam, ends[0], ends[1]], 3.0).unwrap_err();
- assert!(matches!(e, KernelError::TooLarge(_)), "{e}");
- let rolls = crate::blend::ROLLS.with(|n| n.get());
- assert_eq!(rolls, 1, "the seam was rolled {rolls} times");
- // The far edges alone still round.
- assert!(fillet(&body, &ends, 3.0).is_ok());
-}
-
-/// At a knife edge (the plane and the wall's normals opposite) the ball's centre is the same
-/// whichever face is side 1: `r` inside the plane and `r` outside the wall's cylinder.
-#[test]
-fn knife_edge_ball_centre_does_not_depend_on_the_side_order() {
- const R: f64 = 21.0;
- let tip = Vec3::new(62.0 + 1.0 / 6.0, 0.0, 5.0);
- let slab = crate::box_solid(Vec3::new(0.0, -R, 0.0), Vec3::new(tip.x, 0.0, 10.0)).unwrap();
- let disc = cylinder(Vec3::new(tip.x, -R, 0.0), Vec3::Z, R, 10.0).unwrap();
- let body = boolean(&slab, &disc, BoolOp::Cut).unwrap().unwrap();
- let faces: Vec<&mt::Face> = body.solid.face_iter().collect();
- let plane = faces.iter().copied().find(|f| plane_normal(f).is_some_and(|n| n.y > 0.99)).unwrap();
- let wall = faces.iter().copied().find(|f| plane_normal(f).is_none()).unwrap();
- for r in [0.5, 2.0, 5.0] {
- let centre = Vec3::new(tip.x - (4.0 * R * r).sqrt(), -r, tip.z);
- // `cusp` is +1 when n1 × t points into the cusp: the wall's normal is −y, the plane's +y.
- for (f1, f2, cusp) in [(wall, plane, 1.0), (plane, wall, -1.0)] {
- let s = solve(&[f1], &[f2], tip, Vec3::Z, r, -1.0, cusp, None, 1e-6).unwrap();
- assert!(s.c.dist(centre) < 1e-6, "r={r} cusp={cusp}: centre {:?}, expected {centre:?}", s.c);
- }
- }
-}
-
-/// #896: the seams where rounds run into the faces beside them are picked to be rounded again.
-/// The faces meet tangentially there, so there is nothing to round: the refusal says so, rather
-/// than that blending such an edge isn't supported yet.
-#[test]
-fn a_smooth_seam_is_refused_as_having_no_corner() {
- let b = crate::box_solid(Vec3::ZERO, Vec3::new(150.0, 200.0, 70.0)).unwrap();
- let mut edges = Vec::new();
- for (x, y) in [(0.0, 0.0), (150.0, 0.0), (0.0, 200.0), (150.0, 200.0)] {
- edges.push(Vec3::new(x, y, 35.0));
- }
- for (a, z) in [(0.0, 0.0), (150.0, 0.0), (0.0, 70.0), (150.0, 70.0)] {
- edges.push(Vec3::new(a, 100.0, z));
- }
- for (y, z) in [(0.0, 0.0), (200.0, 0.0), (0.0, 70.0), (200.0, 70.0)] {
- edges.push(Vec3::new(75.0, y, z));
- }
- let rounded = fillet(&b, &edges, 10.0).unwrap();
- // The seam on the top face beside the round of the edge along y at x = 0, and the seam
- // with the end face x = 0 beside the round of the top edge along y.
- for seam in [Vec3::new(10.0, 100.0, 70.0), Vec3::new(0.0, 100.0, 60.0)] {
- for chamfer in [false, true] {
- let r = if chamfer { crate::chamfer(&rounded, &[seam], 1.0) } else { fillet(&rounded, &[seam], 1.0) };
- match r {
- Err(KernelError::Invalid(m)) => assert!(m.contains("smooth") && m.contains("no corner"), "{m}"),
- other => panic!("{seam:?}: {:?}", other.map(|_| "a body")),
- }
- }
- }
- // A sharp edge of a box with one round still takes a fillet beside the round's seams.
- let one = fillet(&crate::box_solid(Vec3::ZERO, Vec3::new(40.0, 30.0, 20.0)).unwrap(), &[Vec3::new(40.0, 30.0, 10.0)], 5.0).unwrap();
- assert!(fillet(&one, &[Vec3::new(20.0, 0.0, 20.0)], 1.0).is_ok());
- assert!(matches!(fillet(&one, &[Vec3::new(35.0, 30.0, 10.0)], 1.0), Err(KernelError::Invalid(_))));
-}
-
-/// A 40 × 40 × 20 box whose front wall is an arc of radius 40 about a Z axis: `concave` cuts a
-/// cylinder away from the front (the wall curves into the part), otherwise the part is the box
-/// within the cylinder (the wall curves out). The arc meets the planar side walls x = 0 and
-/// x = 40 at an angle, not square. With the bottom arc's midpoint, the axis's base point and the
-/// side of the wall the material is on (+1 away from the axis, −1 toward it).
-fn arc_walled_box(concave: bool) -> (Body, Vec3, Vec3, f64) {
- let block = crate::box_solid(Vec3::ZERO, Vec3::new(40.0, 40.0, 20.0)).unwrap();
- let (axis, op, side) =
- if concave { (Vec3::new(20.0, -30.0, 0.0), BoolOp::Cut, 1.0) } else { (Vec3::new(20.0, 70.0, 0.0), BoolOp::Intersect, -1.0) };
- let tool = cylinder(axis, Vec3::Z, 40.0, 20.0).unwrap();
- let body = boolean(&block, &tool, op).unwrap().unwrap();
- (body, axis + Vec3::new(0.0, side * 40.0, 0.0), axis, side)
-}
-
-/// Volume the blend removes along the bottom arc: the corner's cross-section at each distance
-/// ρ from the axis (`depth(x)`, x ∈ [0, size] from the wall into the material), times the arc
-/// of radius ρ between the side walls.
-fn removed_volume(side: f64, size: f64, depth: impl Fn(f64) -> f64) -> f64 {
- let steps = 4000;
- let h = size / steps as f64;
- (0..=steps)
- .map(|i| {
- let x = i as f64 * h;
- let rho = 40.0 + side * x;
- let w = if i == 0 || i == steps {
- 1.0
- } else if i % 2 == 1 {
- 4.0
- } else {
- 2.0
- };
- w * depth(x) * 2.0 * rho * (20.0 / rho).asin()
- })
- .sum::()
- * h
- / 3.0
-}
-
-#[test]
-fn rolling_ball_along_an_arc_ends_in_side_walls_at_an_angle() {
- // The bottom edge of an arc wall ends in the side walls at an angle (#556). The round is the
- // torus about the cylinder's axis (centre circle of radius 40 ± r at height r), trimmed by
- // the side walls; the chamfer is the cone between the two contacts.
- let r = 2.0;
- for concave in [true, false] {
- let (body, mid, axis, side) = arc_walled_box(concave);
- let v0 = planned_volume(&body);
- for round in [true, false] {
- let what = format!("{} {}", if concave { "concave" } else { "convex" }, if round { "fillet" } else { "chamfer" });
- let blend = if round { fillet(&body, &[mid], r) } else { crate::chamfer(&body, &[mid], r) }.unwrap_or_else(|e| panic!("{what}: {e}"));
- assert!(blend.validity().is_empty(), "{what}: {:?}", blend.validity());
- let volume = planned_volume(&blend);
- let removed =
- if round { removed_volume(side, r, |x| r - (r * r - (r - x) * (r - x)).max(0.0).sqrt()) } else { removed_volume(side, r, |x| r - x) };
- assert!((v0 - volume - removed).abs() < removed * 3e-3, "{what}: removed {} vs {removed}", v0 - volume);
- // The blend face stays between the side walls and, for the round, on the torus.
- let surfaces: Vec<_> =
- blend.solid.face_iter().map(|f| f.oriented_surface()).filter(|s| matches!(s, mt::Surface::NurbsSurface(_))).collect();
- assert!(!surfaces.is_empty(), "{what}: no blend face");
- let mesh = blend.mesh(&crate::MeshTolerance::chord(0.0005)).unwrap();
- let (lo, hi) = mesh.positions.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), p| (lo.min(p.x), hi.max(p.x)));
- assert!(lo > -1e-3 && hi < 40.0 + 1e-3, "{what}: the blend runs past the side walls: x {lo}..{hi}");
- if round {
- // Sections of the round across the arc: the quarter circle about the centre
- // ring (radius 40 ± r about the axis, at height r) from contact to contact.
- let ring = 40.0 + side * r;
- let mut worst: f64 = 0.0;
- for i in 0..=40 {
- let x = 40.0 * i as f64 / 40.0;
- for a in 1..8 {
- let t = std::f64::consts::FRAC_PI_2 * a as f64 / 8.0;
- let (rho, z) = (ring - side * r * t.cos(), r - r * t.sin());
- let dx = x - axis.x;
- let dy = (rho * rho - dx * dx).sqrt() * if concave { 1.0 } else { -1.0 };
- let p = Vec3::new(x, axis.y + dy, z);
- worst = worst.max(nearest_blend(&surfaces, p).0);
- }
- }
- assert!(worst < 1e-3, "{what}: blend surface is {worst} mm off the torus");
- }
- }
- }
-}
-
-#[test]
-fn rolling_ball_past_a_slanted_end_face_is_too_large_and_reduces() {
- // On the outward-curving wall a round of 4 would run its bottom contact into the back face
- // before it reaches the side wall (the contact circle of radius 36 meets x = 0 at y ≈ 40.07):
- // too large, and the largest that fits rounds the edge.
- let (body, mid, _, _) = arc_walled_box(false);
- let e = fillet(&body, &[mid], 4.0).unwrap_err();
- assert!(matches!(e, KernelError::TooLarge(_)), "{e}");
- let (r, blend) = crate::fillet_max(&body, &[mid], 4.0).unwrap();
- assert!(r > 3.0 && r < 4.0, "{r}");
- assert!(blend.validity().is_empty(), "{:?}", blend.validity());
-}
-
-#[test]
-fn rolling_ball_runs_into_a_knife_edge_tip() {
- // The corner of a block outside a cylinder of radius 21 about (21, −21): its wall meets the
- // back face y = 0 tangentially at (21, 0) and the left face x = 0 at (0, −21), knife-edge
- // tips at both ends of the arc. The round of the bottom arc runs into both, cut off by the
- // end faces' planes, which touch the wall contact at the tips without crossing it: at
- // distance ρ from the axis it runs from x = 0 to y = 0, ρ (asin(21 / ρ) − acos(21 / ρ)).
- let block = crate::box_solid(Vec3::new(0.0, -21.0, 0.0), Vec3::new(21.0, 0.0, 10.0)).unwrap();
- let body = boolean(&block, &cylinder(Vec3::new(21.0, -21.0, -1.0), Vec3::Z, 21.0, 12.0).unwrap(), BoolOp::Cut).unwrap().unwrap();
- let mid = Vec3::new(21.0 - 21.0 * std::f64::consts::FRAC_1_SQRT_2, -21.0 + 21.0 * std::f64::consts::FRAC_1_SQRT_2, 0.0);
- let r = 2.0;
- let blend = fillet(&body, &[mid], r).unwrap();
- assert!(blend.validity().is_empty(), "{:?}", blend.validity());
- let (n, h) = (4000, r / 4000.0);
- let removed = (0..=n)
- .map(|i| {
- let x = i as f64 * h;
- let rho = 21.0 + x;
- let w = if i == 0 || i == n {
- 1.0
- } else if i % 2 == 1 {
- 4.0
- } else {
- 2.0
- };
- w * (r - (r * r - (r - x) * (r - x)).max(0.0).sqrt()) * rho * ((21.0 / rho).asin() - (21.0 / rho).acos())
- })
- .sum::()
- * h
- / 3.0;
- let got = planned_volume(&body) - planned_volume(&blend);
- assert!((got - removed).abs() < removed * 5e-3, "removed {got} vs {removed}");
-}
-
-#[test]
-fn rolling_ball_turns_about_a_rounded_corner_of_its_radius() {
- // The box with the inward-curving wall, its 60° corner at x = 0 rounded (r 2) first. The
- // bottom edges then run: the side wall's, the corner round's (an arc of radius 2) and the
- // arc wall's into the slanted side wall at x = 40. Rounded again with r 2 the ball can't
- // roll round the corner: it turns about one point there, and the blend is a piece of sphere.
- // It is what the rolling round tends to as its radius tends to the corner's, too large past
- // it, and its mesh is closed.
- let (body, _, _, _) = arc_walled_box(true);
- let body = fillet(&body, &[Vec3::new(0.0, 4.641016151377546, 10.0)], 2.0).unwrap();
- // The corner round's centre is 4 from the corner along its bisector, (2, 8.105): its arc's
- // middle is 2 back toward the corner.
- let ends = [Vec3::new(0.0, 25.0, 0.0), Vec3::new(1.0, 6.373, 0.0), Vec3::new(20.0, 10.0, 0.0)];
- let v0 = planned_volume(&body);
- let removed = |r: f64| {
- let b = fillet(&body, &ends, r).unwrap_or_else(|e| panic!("r {r}: {e}"));
- assert!(b.validity().is_empty(), "r {r}: {:?}", b.validity());
- v0 - planned_volume(&b)
- };
- let (a, b, at) = (removed(1.96), removed(1.98), removed(2.0));
- let expected = 2.0 * b - a;
- assert!((at - expected).abs() < expected * 2e-3, "removed {at} at r 2, {a} and {b} before it");
- let e = fillet(&body, &ends, 2.5).unwrap_err();
- assert!(matches!(e, KernelError::TooLarge(_)), "{e}");
- let (r, _) = crate::fillet_max(&body, &ends, 2.5).unwrap();
- assert!(r > 1.5 && r <= 2.0 + 1e-9, "{r}");
-}
-
-#[test]
-fn rolling_ball_along_a_straight_edge_ends_in_a_curved_face() {
- // The box with the inward-curving wall: the bottom edge of the side wall x = 0 runs from the
- // back to the curved wall (#556). The round of radius 2 along it is cut off by that wall:
- // at d from the side wall it runs from y = −30 + √(40² − (d − 20)²) to the back at y = 40.
- let (body, _, _, _) = arc_walled_box(true);
- let r = 2.0;
- for round in [true, false] {
- let blend =
- if round { fillet(&body, &[Vec3::new(0.0, 25.0, 0.0)], r) } else { crate::chamfer(&body, &[Vec3::new(0.0, 25.0, 0.0)], r) }.unwrap();
- assert!(blend.validity().is_empty(), "{:?}", blend.validity());
- let (n, h) = (4000, r / 4000.0);
- let removed = (0..=n)
- .map(|i| {
- let d = i as f64 * h;
- let w = if i == 0 || i == n {
- 1.0
- } else if i % 2 == 1 {
- 4.0
- } else {
- 2.0
- };
- let depth = if round { r - (r * r - (r - d) * (r - d)).max(0.0).sqrt() } else { r - d };
- w * depth * (40.0 - (-30.0 + (1600.0 - (d - 20.0) * (d - 20.0)).sqrt()))
- })
- .sum::()
- * h
- / 3.0;
- let (m0, m1) = (body.mesh(&crate::MeshTolerance::chord(0.0005)).unwrap(), blend.mesh(&crate::MeshTolerance::chord(0.0005)).unwrap());
- let got = m0.measure().volume - m1.measure().volume;
- assert!((got - removed).abs() < removed * 3e-3, "round {round}: removed {got} vs {removed}");
- let volume_about = |o: Vec3| {
- let at = |i: u32| m1.positions[i as usize] - o;
- m1.triangles.iter().map(|t| at(t[0]).dot(at(t[1]).cross(at(t[2]))) / 6.0).sum::()
- };
- let shift = volume_about(Vec3::ZERO) - volume_about(Vec3::new(-100.0, 50.0, 30.0));
- assert!(shift.abs() < 1e-2, "round {round}: the mesh is not closed (volume moves {shift} with the origin)");
- }
-}
-
-#[test]
-fn chamfer_a_chain_of_a_line_and_an_arc_into_a_slanted_end() {
- // A 40 × 40 block, 20 high, whose front runs straight for 20 and then along an arc of
- // radius 29 about (20, 29), tangent to it, up to (40, 8): the right face meets the arc at an
- // angle. The top front chain chamfered by 2 (the planes' and the cone's sections are 2 × 2
- // corners, 2 − w high at w in from the edge): 2 a millimetre along the line, and along the
- // arc out to the right face, at each distance ρ from its axis, the height times the arc of
- // radius ρ inside x ≤ 40.
- use solidcraft_geom::{Loop2, Plane, Region2, Seg2, Vec2};
- let start = -std::f64::consts::FRAC_PI_2;
- let end = (-21.0f64).atan2(20.0);
- let segs = vec![
- Seg2::Line { a: Vec2::new(0.0, 0.0), b: Vec2::new(20.0, 0.0) },
- Seg2::Arc { center: Vec2::new(20.0, 29.0), radius: 29.0, start, sweep: end - start },
- Seg2::Line { a: Vec2::new(40.0, 8.0), b: Vec2::new(40.0, 40.0) },
- Seg2::Line { a: Vec2::new(40.0, 40.0), b: Vec2::new(0.0, 40.0) },
- Seg2::Line { a: Vec2::new(0.0, 40.0), b: Vec2::new(0.0, 0.0) },
- ];
- let body = crate::extrude(&Plane::XY, &[Region2 { outer: Loop2 { segs }, holes: vec![] }], 0.0, 20.0).unwrap().pop().unwrap();
- let volume = |b: &Body| b.mesh(&crate::MeshTolerance::chord(0.0005)).unwrap().measure().volume;
- let made = crate::chamfer(&body, &[Vec3::new(10.0, 0.0, 20.0)], 2.0).unwrap();
- let n = 2000;
- let h = 2.0 / n as f64;
- let arc = (0..=n)
- .map(|i| {
- let rho = 27.0 + i as f64 * h;
- let w = if i == 0 || i == n { 1.0 } else { [2.0, 4.0][i % 2] };
- w * (rho - 27.0) * rho * (20.0 / rho).asin()
- })
- .sum::()
- * h
- / 3.0;
- let want = 40.0 + arc;
- let got = volume(&body) - volume(&made);
- assert!((got - want).abs() < want * 1e-3, "removed {got} vs {want}");
-}
-
-/// #1667: an R1 round around the end of a long bar whose four long edges are R5. The chain is
-/// 290 mm lines and quarter turns of 7.85 mm, so the lines' sections are spaced far wider than
-/// the turns'; borrowing the turns' sections for the lines' ends made their strips overshoot and
-/// fold back past the joints, the strips' meshes folded with them, and the measured volume came
-/// out thousands of mm³ off. The R1 pipe is exact: the corner's section, `1 - π/4`, along the
-/// lines, and round each turn's axis at the section's centroid (Pappus).
-#[test]
-fn round_along_long_lines_and_small_turns_measures_its_volume() {
- use std::f64::consts::{FRAC_PI_2, FRAC_PI_4};
- let (w, d, h) = (300.0, 60.0, 40.0);
- let bar = crate::build::box_solid(Vec3::new(-w / 2.0, 0.0, 0.0), Vec3::new(w / 2.0, d, h)).unwrap();
- let long = [Vec3::new(-w / 2.0, d / 2.0, 0.0), Vec3::new(w / 2.0, d / 2.0, 0.0), Vec3::new(-w / 2.0, d / 2.0, h), Vec3::new(w / 2.0, d / 2.0, h)];
- let rounded = fillet(&bar, &long, 5.0).unwrap();
- // The rolling ball along the end face's loop (the exact blends would take this loop; a
- // loop next to free-form faces, as in the issue, comes here).
- let ids: Vec = crate::body::Body::unique_edges(&rounded.solid)
- .into_iter()
- .filter(|e| [e.front(), e.back()].iter().all(|v| crate::blend::vtx(v).y.abs() < 1e-9))
- .map(|e| e.id())
- .collect();
- assert_eq!(ids.len(), 8);
- let (solid, _) = crate::guard("test", || curve_blend(&rounded.solid, &ids, rounded.size(), 1.0, true)).unwrap();
- let body = Body::new(solid).unwrap();
- assert!(body.validity().is_empty(), "{:?}", body.validity());
- let section = 1.0 - FRAC_PI_4;
- // The section's centroid lies this far from its corner along each side.
- let inset = (5.0 / 6.0 - FRAC_PI_4) / section;
- let lines = 2.0 * (w - 10.0) + 2.0 * (h - 10.0);
- let turns = 4.0 * FRAC_PI_2 * (5.0 - inset);
- let want = w * d * h - 4.0 * 25.0 * section * d - section * (lines + turns);
- let m = crate::measure(&body).unwrap();
- assert!((m.volume - want).abs() < 1e-5 * want, "{} vs {want}", m.volume);
- // Centred across the bar, as the part is.
- assert!(m.centroid.x.abs() < 1e-3, "centre of mass x {}", m.centroid.x);
-}
diff --git a/crates/kernel/src/curvecorner.rs b/crates/kernel/src/curvecorner.rs
deleted file mode 100644
index a3dbc8892..000000000
--- a/crates/kernel/src/curvecorner.rs
+++ /dev/null
@@ -1,1246 +0,0 @@
-//! Corners where rolling-ball blends meet on faces of any surface (the arc wall of an extruded
-//! profile and the edges round it): what [`crate::blend_corner`] does for straight edges between
-//! planes, with each blend fitted as in the parent module.
-//!
-//! Each blended edge's strip (its rolling-ball sections, fitted) runs a little past both ends.
-//! Every end vertex has three faces and three edges. There:
-//! - one blended edge: the strip ends where the third face cuts it, between where its contacts
-//! cross the other two edges;
-//! - two: the strips cut each other along a crease, from where their contacts cross on the face
-//! they share to the third edge. When one strip's contact
-//! reaches further along the third edge, the other's ends on the crease alone and the first
-//! runs on beyond it to end on the other's third face;
-//! - three (one radius): each strip ends at its section through the ball touching all three
-//! faces, and a piece of that ball's sphere fills the corner.
-
-use std::cell::Cell;
-use std::collections::{HashMap, HashSet};
-
-use solidcraft_geom::Vec3;
-use truck_modeling::{self as mt, builder};
-
-use super::{
- Guide, MAX_SAMPLES, SAMPLES, Section, fit_sections, in_proportion, knife_convex, knife_start, nearest_on, project, section_fits, solve_from,
- unsupported,
-};
-use crate::blend::{too_large, vtx};
-use crate::body::{Solid, from_p3, p3, v3};
-use crate::bridge::Frame;
-use crate::record::Rebuild;
-use crate::{KernelError, Result};
-
-fn fail(m: &str) -> KernelError {
- KernelError::Failed(format!("blend corner: {m}"))
-}
-
-/// One blended edge's strip: the fitted rolling-ball surface (u across, from the contact with
-/// side `fa` at 0 to side `fb`'s at 1; v along the edge from its front, running on past both
-/// ends), its contacts (in v) and its sections.
-struct Strip {
- edge: mt::Edge,
- fa: usize,
- fb: usize,
- surface: mt::Surface,
- contacts: [mt::Curve; 2],
- /// v of the sections at the edge's front and back vertex.
- ends: [f64; 2],
- /// +1 when the surface's normal points out of the material, −1 when into it.
- flip: f64,
- /// −1 for a convex edge (the ball inside the material), +1 for a concave one.
- sigma: f64,
- /// Sections with their v.
- sections: Vec<(f64, Section)>,
-}
-
-impl Strip {
- fn row(&self, f: usize) -> Result {
- if f == self.fa {
- Ok(0)
- } else if f == self.fb {
- Ok(1)
- } else {
- Err(fail("a face beside a blend"))
- }
- }
-
- fn contact(&self, f: usize) -> Result<&mt::Curve> {
- self.contacts.get(self.row(f)?).ok_or_else(|| fail("contact"))
- }
-
- /// u of the contact with face `f`.
- fn u(&self, f: usize) -> Result {
- self.row(f).map(|i| i as f64)
- }
-
- fn at(&self, u: f64, v: f64) -> Vec3 {
- use mt::ParametricSurface;
- from_p3(self.surface.subs(u, v))
- }
-
- /// The edge's own stretch of v.
- fn own(&self) -> (f64, f64) {
- let [a, b] = self.ends;
- (a.min(b), a.max(b))
- }
-
- /// v of the edge's end at `v`, and +1 when the strip runs on past it toward larger v.
- fn end_at(&self, v: &mt::Vertex) -> (f64, f64) {
- let [a, b] = self.ends;
- if self.edge.front() == v { (a, -1.0) } else { (b, 1.0) }
- }
-
- /// The strip's nearest point to `x` (u and v within it): from the section whose ball is
- /// nearest, by Gauss-Newton steps kept within the strip.
- fn nearest(&self, x: Vec3) -> Option<(f64, f64)> {
- use mt::ParametricSurface;
- let (v0, s0) = self.sections.iter().min_by(|a, b| a.1.c.dist(x).total_cmp(&b.1.c.dist(x)))?;
- let (a, b, w) = (s0.q1 - s0.c, s0.q2 - s0.c, x - s0.c);
- let angle = |p: Vec3, q: Vec3| (p.dot(q) / (p.len() * q.len()).max(1e-300)).clamp(-1.0, 1.0).acos();
- let total = angle(a, b);
- let mut uv = ((angle(a, w) / total.max(1e-12)).clamp(0.0, 1.0), *v0);
- let dist = |uv: (f64, f64)| from_p3(self.surface.subs(uv.0, uv.1)).dist(x);
- let mut d = dist(uv);
- for _ in 0..50 {
- let p = from_p3(self.surface.subs(uv.0, uv.1));
- let (su, sv) = (self.surface.uder(uv.0, uv.1), self.surface.vder(uv.0, uv.1));
- let (su, sv) = (Vec3::new(su.x, su.y, su.z), Vec3::new(sv.x, sv.y, sv.z));
- let r = x - p;
- let (a11, a12, a22) = (su.dot(su), su.dot(sv), sv.dot(sv));
- let (b1, b2) = (su.dot(r), sv.dot(r));
- let det = a11 * a22 - a12 * a12;
- if !(det.abs() > 1e-300) {
- break;
- }
- let (mut du, mut dv) = ((b1 * a22 - b2 * a12) / det, (a11 * b2 - a12 * b1) / det);
- let mut moved = false;
- for _ in 0..30 {
- let next = ((uv.0 + du).clamp(0.0, 1.0), (uv.1 + dv).clamp(0.0, 1.0));
- let dn = dist(next);
- if dn <= d {
- moved = (next.0 - uv.0).abs() + (next.1 - uv.1).abs() > 1e-15;
- uv = next;
- d = dn;
- break;
- }
- du *= 0.5;
- dv *= 0.5;
- }
- if !moved {
- break;
- }
- }
- Some(uv)
- }
-}
-
-/// Signed distance from a surface, positive out of the material; each search starts where the
-/// last ended (the points asked about come in small steps). A strip's is measured to its
-/// nearest point within it: past a contact, to the contact along the face there.
-enum Away<'a> {
- Face(Box<(mt::Surface, Cell>)>),
- Strip(&'a Strip),
-}
-
-impl<'a> Away<'a> {
- fn face(f: &mt::Face) -> Self {
- Away::Face(Box::new((f.oriented_surface(), Cell::new(None))))
- }
-
- fn strip(s: &'a Strip) -> Self {
- Away::Strip(s)
- }
-
- fn at(&self, x: Vec3) -> Option {
- use mt::{ParametricSurface, ParametricSurface3D, SearchNearestParameter};
- match self {
- Away::Face(face) if matches!(face.0, mt::Surface::Plane(_)) => nearest_on(&face.0, &face.1, x).map(|(q, n, _)| (x - q).dot(n)),
- Away::Face(face) => {
- let (surface, last) = (&face.0, &face.1);
- // The nearest of the search from the last answer, a fresh one and either kept
- // within the surface's parameters: past them a conic's patch runs on round to
- // its far side, where a search can settle.
- let (ru, rv) = surface.try_range_tuple();
- let ((u0, u1), (v0, v1)) = (ru.unwrap_or((f64::NEG_INFINITY, f64::INFINITY)), rv.unwrap_or((f64::NEG_INFINITY, f64::INFINITY)));
- let inside = |uv: (f64, f64)| uv.0 >= u0 - 1e-9 && uv.0 <= u1 + 1e-9 && uv.1 >= v0 - 1e-9 && uv.1 <= v1 + 1e-9;
- let warm = last.get().and_then(|h| surface.search_nearest_parameter(p3(x), Some(h), 20));
- let mut found: Vec<(f64, f64)> = warm.into_iter().collect();
- if !warm.is_some_and(inside) {
- found.extend(surface.search_nearest_parameter(p3(x), None, 100));
- }
- let clamped: Vec<(f64, f64)> = found.iter().map(|(u, v)| (u.clamp(u0, u1), v.clamp(v0, v1))).collect();
- found.extend(clamped);
- let d = |uv: &(f64, f64)| from_p3(surface.subs(uv.0, uv.1)).dist(x);
- let uv = found.into_iter().filter(|uv| d(uv).is_finite()).min_by(|a, b| d(a).total_cmp(&d(b)))?;
- last.set(Some(uv));
- let q = from_p3(surface.subs(uv.0, uv.1));
- let n = surface.normal(uv.0, uv.1);
- Some((x - q).dot(Vec3::new(n.x, n.y, n.z).normalized()?))
- }
- Away::Strip(s) => {
- let (u, v) = s.nearest(x)?;
- let q = from_p3(s.surface.subs(u, v));
- let n = s.surface.normal(u, v);
- Some((x - q).dot(Vec3::new(n.x, n.y, n.z).normalized()?) * s.flip)
- }
- }
- }
-}
-
-/// Unit direction along a curve at `t`.
-fn tangent(c: &mt::Curve, t: f64) -> Option {
- use mt::ParametricCurve;
- let d = c.der(t);
- Vec3::new(d.x, d.y, d.z).normalized()
-}
-
-/// Nearest parameter on `c` to `x`, started from the nearest of a few samples.
-/// The radius of edge `e` seen along the unit `axis`: its points, moved along the axis into one
-/// plane, all on one circle (within `tol`).
-fn radius_along(e: &mt::Edge, axis: Vec3, tol: f64) -> Option {
- use mt::{BoundedCurve, ParametricCurve};
- let curve = e.curve();
- let (t0, t1) = curve.range_tuple();
- let at = |f: f64| {
- let p = from_p3(curve.subs(t0 + (t1 - t0) * f));
- p - axis * axis.dot(p)
- };
- let (a, u, v) = (at(0.0), at(0.5) - at(0.0), at(1.0) - at(0.0));
- let w = u.cross(v);
- if w.len2() < 1e-24 || w.normalized()?.dot(axis).abs() < 1.0 - 1e-6 {
- return None;
- }
- let o = a + (v * u.len2() - u * v.len2()).cross(w) * (1.0 / (2.0 * w.len2()));
- let rho = o.dist(a);
- (0..=16).map(|i| at(i as f64 / 16.0)).all(|p| (p.dist(o) - rho).abs() <= tol).then_some(rho)
-}
-
-/// The parameter of `c`'s point nearest `x`: the nearest of 65 samples, refined where that
-/// comes nearer.
-pub(crate) fn param_on(c: &mt::Curve, x: Vec3) -> Option {
- use mt::{BoundedCurve, ParametricCurve, SearchNearestParameter};
- let (lo, hi) = c.range_tuple();
- let d = |t: f64| from_p3(c.subs(t)).dist(x);
- let hint = (0..=64).map(|i| lo + (hi - lo) * i as f64 / 64.0).min_by(|a, b| d(*a).total_cmp(&d(*b)))?;
- let t = c.search_nearest_parameter(p3(x), hint, 100).unwrap_or(hint).clamp(lo, hi);
- Some(if d(t) <= d(hint) { t } else { hint })
-}
-
-/// Where curve `a` crosses curve `b` on face `f`, both lying in it: its parameter on `a` and
-/// the point. Of several, the one within `own` (a range of `a`'s parameter) nearest `near`.
-fn cross(a: &mt::Curve, b: &mt::Curve, f: &mt::Face, near: Vec3, own: (f64, f64), tol: f64) -> Option<(f64, Vec3)> {
- use mt::{BoundedCurve, ParametricCurve, SearchNearestParameter};
- let (a0, a1) = a.range_tuple();
- let (b0, b1) = b.range_tuple();
- let surface = f.oriented_surface();
- let last = Cell::new(None);
- let hint = Cell::new(None::);
- // Signed distance across `b` in the face, and how far `b`'s nearest point is.
- // `b` sampled once (an intersection curve is slow to evaluate).
- let along_b: Vec<(f64, Vec3)> = (0..=64).map(|i| b0 + (b1 - b0) * i as f64 / 64.0).map(|t| (t, from_p3(b.subs(t)))).collect();
- let lateral = |s: f64| -> Option<(f64, f64)> {
- let x = from_p3(a.subs(s));
- // From the last answer when that is still nearest, else from the nearest sample of `b`
- // (a search from the far end of a short arc can stay there).
- let d = |t: f64| from_p3(b.subs(t)).dist(x);
- let warm = hint.get().map(|h| b.search_nearest_parameter(p3(x), h, 50).unwrap_or(h).clamp(b0, b1));
- let (start, ds) = along_b.iter().map(|(t, p)| (*t, p.dist(x))).min_by(|p, q| p.1.total_cmp(&q.1))?;
- let t = match warm {
- Some(w) if d(w) <= ds => w,
- _ => {
- let cold = b.search_nearest_parameter(p3(x), start, 50).unwrap_or(start).clamp(b0, b1);
- match warm {
- Some(w) if d(w) <= d(cold).min(ds) => w,
- _ if d(cold) <= ds => cold,
- _ => start,
- }
- }
- };
- hint.set(Some(t));
- let y = from_p3(b.subs(t));
- let (_, n, _) = nearest_on(&surface, &last, y)?;
- let m = n.cross(tangent(b, t)?).normalized()?;
- Some(((x - y).dot(m), x.dist(y)))
- };
- let steps = 256;
- let samples: Vec<(f64, Option<(f64, f64)>)> = (0..=steps)
- .map(|i| {
- let s = a0 + (a1 - a0) * i as f64 / steps as f64;
- (s, lateral(s))
- })
- .collect();
- // Only where `a` comes within a sample's step of `b` (elsewhere the side flips only round
- // an end of `b`).
- let step = samples.windows(2).map(|w| from_p3(a.subs(w[1].0)).dist(from_p3(a.subs(w[0].0)))).fold(0.0, f64::max);
- let close = |d: f64| d <= 2.0 * step + tol;
- let mut found: Vec<(f64, Vec3)> = Vec::new();
- for w in samples.windows(2) {
- let [(s0, Some((h0, d0))), (s1, Some((h1, d1)))] = w else { continue };
- if h1.abs() <= tol && *d1 <= tol {
- found.push((*s1, from_p3(a.subs(*s1))));
- continue;
- }
- if (*h0 < 0.0) == (*h1 < 0.0) || !(close(*d0) || close(*d1)) {
- continue;
- }
- let (mut lo, mut hi, glo) = (*s0, *s1, *h0);
- hint.set(None);
- for _ in 0..60 {
- let m = (lo + hi) * 0.5;
- let Some((hm, _)) = lateral(m) else { break };
- if (hm < 0.0) == (glo < 0.0) {
- lo = m;
- } else {
- hi = m;
- }
- }
- let s = (lo + hi) * 0.5;
- hint.set(None);
- if lateral(s).is_some_and(|(_, d)| d <= tol) {
- found.push((s, from_p3(a.subs(s))));
- }
- }
- if let Some((s, Some((h, d)))) = samples.first()
- && h.abs() <= tol
- && *d <= tol
- {
- found.push((*s, from_p3(a.subs(*s))));
- }
- // Touching without crossing: through an end of `b` (an edge the blend uses up to its far
- // vertex), where the side `b` is measured from turns over. Where the distance comes down
- // to nothing.
- for w in samples.windows(3) {
- let [(s0, Some((_, d0))), (_, Some((_, d1))), (s2, Some((_, d2)))] = w else { continue };
- if !(d1 <= d0 && d1 <= d2 && close(*d1)) {
- continue;
- }
- let gap = |s: f64| {
- hint.set(None);
- lateral(s).map_or(f64::INFINITY, |x| x.1)
- };
- let (mut lo, mut hi) = (*s0, *s2);
- for _ in 0..80 {
- let (x, y) = (lo + (hi - lo) * 0.381_966, lo + (hi - lo) * 0.618_034);
- if gap(x) < gap(y) {
- hi = y;
- } else {
- lo = x;
- }
- }
- let s = (lo + hi) * 0.5;
- if gap(s) <= tol && !found.iter().any(|f| (f.0 - s).abs() <= (a1 - a0) * 1e-6) {
- found.push((s, from_p3(a.subs(s))));
- }
- }
- let slack = (a1 - a0) * 1e-6;
- let outside = |s: f64| s < own.0 - slack || s > own.1 + slack;
- found.into_iter().min_by(|x, y| outside(x.0).cmp(&outside(y.0)).then(x.1.dist(near).total_cmp(&y.1.dist(near))))
-}
-
-/// Where curve `c` crosses `side`'s surface: its parameter and the point; of several, the one
-/// nearest `near`.
-fn reach(c: &mt::Curve, side: &Away, near: Vec3, tol: f64) -> Option<(f64, Vec3)> {
- use mt::{BoundedCurve, ParametricCurve};
- let (lo, hi) = c.range_tuple();
- let g = |s: f64| side.at(from_p3(c.subs(s))).filter(|x| x.is_finite());
- let steps = 256;
- let samples: Vec<(f64, Option)> = (0..=steps)
- .map(|i| {
- let s = lo + (hi - lo) * i as f64 / steps as f64;
- (s, g(s))
- })
- .collect();
- let mut found: Vec<(f64, Vec3)> = Vec::new();
- for w in samples.windows(2) {
- let [(s0, Some(g0)), (s1, Some(g1))] = w else { continue };
- if (*g0 < 0.0) == (*g1 < 0.0) {
- continue;
- }
- let (mut a, mut b, ga) = (*s0, *s1, *g0);
- for _ in 0..60 {
- let m = (a + b) * 0.5;
- let Some(gm) = g(m) else { break };
- if (gm < 0.0) == (ga < 0.0) {
- a = m;
- } else {
- b = m;
- }
- }
- let s = (a + b) * 0.5;
- if g(s).is_some_and(|x| x.abs() <= tol) {
- found.push((s, from_p3(c.subs(s))));
- }
- }
- found.into_iter().min_by(|x, y| x.1.dist(near).total_cmp(&y.1.dist(near)))
-}
-
-/// The curve on strip `s` from `a` to `b` (each u, v and point) where `side` changes sign (it is
-/// negative in the material kept): for each u between, the v where it does nearest a guess
-/// between the ends, stepping toward `out` (+1: larger v) while inside. Interpolated by chord
-/// length through u spaced closer toward the ends; between its points it stays on the strip and
-/// on the surface.
-fn trace(s: &Strip, a: (f64, f64, Vec3), b: (f64, f64, Vec3), side: &Away, out: f64, tolerance: f64) -> Result {
- use mt::ParametricCurve;
- let beyond = || too_large("the blend is larger than the neighbouring faces");
- let (ua, va, pa) = a;
- let (ub, vb, pb) = b;
- let f = |u: f64, v: f64| side.at(s.at(u, v)).unwrap_or(f64::NAN);
- let root = |frac: f64| -> Option<(f64, f64)> {
- let u = ua + (ub - ua) * frac;
- let guess = (va + (vb - va) * frac).clamp(0.0, 1.0);
- // Steps in proportion to the distance from the nearer end, where the curve is known: a
- // face tangent to a contact there (a knife-edge tip) crosses the strip only within a
- // window that narrows toward it.
- let step = (vb - va).abs().max(1e-3) * frac.min(1.0 - frac).clamp(1e-6, 0.5) / 8.0;
- let g = f(u, guess);
- if !g.is_finite() {
- return None;
- }
- let dir = if g < 0.0 { out } else { -out };
- let mut prev = (guess, g);
- for i in 1..=4096 {
- let v = (guess + dir * step * i as f64).clamp(0.0, 1.0);
- let cur = (v, f(u, v));
- if !cur.1.is_finite() {
- return None;
- }
- if (prev.1 < 0.0) != (cur.1 < 0.0) {
- let (mut x, mut y) = (prev, cur);
- for _ in 0..60 {
- let m = (x.0 + y.0) * 0.5;
- let fm = f(u, m);
- if (fm < 0.0) == (x.1 < 0.0) {
- x = (m, fm);
- } else {
- y = (m, fm);
- }
- }
- return Some((u, (x.0 + y.0) * 0.5));
- }
- if v <= 0.0 || v >= 1.0 {
- return None;
- }
- prev = cur;
- }
- None
- };
- let across = |t: f64| (1.0 - (std::f64::consts::PI * t).cos()) * 0.5;
- let mut m = 8;
- loop {
- let mut pts = vec![pa];
- for i in 1..m {
- let (u, v) = root(across(i as f64 / m as f64)).ok_or_else(beyond)?;
- pts.push(s.at(u, v));
- }
- pts.push(pb);
- let (curve, params) = crate::build::interpolate_cubic_chordal(&pts).ok_or_else(|| fail("end curve"))?;
- let mut accurate = true;
- for (i, w) in params.windows(2).enumerate() {
- let (Some(t0), Some(t1)) = (w.first(), w.get(1)) else { continue };
- root(across((i as f64 + 0.5) / m as f64)).ok_or_else(beyond)?;
- let x = from_p3(curve.subs((t0 + t1) * 0.5));
- let on = s.nearest(x).map(|(a, b)| s.at(a, b).dist(x));
- let off = side.at(x).map(f64::abs);
- if !(on.is_some_and(|d| d <= tolerance) && off.is_some_and(|d| d <= tolerance)) {
- accurate = false;
- break;
- }
- }
- if accurate {
- return Ok(mt::Curve::BSplineCurve(curve));
- }
- if m >= 256 {
- return Err(fail("could not fit where the blends meet"));
- }
- m *= 2;
- }
-}
-
-/// Convex (−1) or concave (+1): from the edge's direction as its first face runs it and the
-/// faces' outward normals at its middle. At a knife edge (normals opposite), also the
-/// direction both faces run on from it.
-fn convexity(faces: &[mt::Face], e: &mt::Edge, fa: usize, fb: usize, r: f64) -> Result<(f64, Option)> {
- use mt::{BoundedCurve, ParametricCurve};
- let (Some(f1), Some(f2)) = (faces.get(fa), faces.get(fb)) else { return Err(fail("face")) };
- let used = f1.boundary_iters().into_iter().flatten().find(|x| x.id() == e.id()).ok_or_else(|| fail("edge use"))?;
- let c = used.oriented_curve();
- let (a, b) = c.range_tuple();
- let pm = from_p3(c.subs((a + b) * 0.5));
- let t = tangent(&c, (a + b) * 0.5).ok_or_else(|| fail("tangent"))?;
- let (Some(n1), Some(n2)) = (project(f1, pm, None).map(|x| x.1), project(f2, pm, None).map(|x| x.1)) else { return Err(fail("normals")) };
- if n1.dot(n2) > 1.0 - 1e-6 {
- return Err(unsupported("blending a smooth edge"));
- }
- if n1.dot(n2) < -1.0 + 1e-6 {
- let into = n1.cross(t).normalized().ok_or_else(|| fail("normals"))?;
- return match knife_convex(f1, f2, pm, into, r) {
- Some(true) => Ok((-1.0, Some(into))),
- _ => Err(unsupported("blending a knife edge inside the material (a crack)")),
- };
- }
- Ok((if t.dot(n1.cross(n2)) > 0.0 { -1.0 } else { 1.0 }, None))
-}
-
-/// The strip of edge `e` between faces `fa` and `fb`, running on past each end as far as the
-/// ball still fits, up to `reach`.
-#[allow(clippy::too_many_arguments)]
-fn strip(
- faces: &[mt::Face],
- e: &mt::Edge,
- (fa, fb): (usize, usize),
- r: f64,
- round: bool,
- (sigma, knife): (f64, Option),
- reach: f64,
- tol: f64,
- fit_tol: f64,
-) -> Result {
- use mt::{BoundedCurve, ParametricCurve, ParametricSurface3D, SearchNearestParameter};
- let (Some(f1), Some(f2)) = (faces.get(fa), faces.get(fb)) else { return Err(fail("face")) };
- let (o1, o2) = ([f1], [f2]);
- let curve = e.curve();
- let (t0, t1) = curve.range_tuple();
- let at = |s: f64| -> Option<(Vec3, Vec3)> {
- let t = t0 + (t1 - t0) * s;
- Some((from_p3(curve.subs(t)), tangent(&curve, t)?))
- };
- // At a knife edge each ball starts where the last one was, beside it (the first where the
- // faces are a diameter apart): the edge itself is no start.
- let offset: Cell> = Cell::new(None);
- let ball = |p: Vec3, t: Vec3| -> Option {
- let start = match (knife, offset.get()) {
- (None, _) => None,
- (Some(_), Some(o)) => Some(p + o),
- (Some(into), None) => Some(knife_start(&o1, &o2, p, t, into, r)?),
- };
- let s = solve_from(&o1, &o2, p, t, r, sigma, 0.0, None, tol * 100.0, start)?;
- if knife.is_some() {
- offset.set(Some(s.c - p));
- }
- Some(s)
- };
- // Along the edge, then on along its curve past its ends (a line runs straight on, a conic's
- // arc round its circle) while the ball fits.
- let mut raw: Vec = Vec::new();
- let (p0, _) = at(0.0).ok_or_else(|| fail("tangent"))?;
- let n = 32;
- let mut along = Vec::with_capacity(n + 1);
- for i in 0..=n {
- let (p, t) = at(i as f64 / n as f64).ok_or_else(|| fail("tangent"))?;
- along.push(ball(p, t).ok_or_else(|| unsupported("the ball doesn't fit along the edge"))?);
- }
- let length = (0..n).filter_map(|i| Some(at(i as f64 / n as f64)?.0.dist(at((i + 1) as f64 / n as f64)?.0))).sum::();
- if !(length.is_finite() && length > tol) {
- return Err(fail("edge length"));
- }
- let past = |sign: f64| -> Vec {
- let mut list = Vec::new();
- for k in 1..=16 {
- let s = (sign * reach * k as f64 / 16.0) / length;
- match at(if sign < 0.0 { s } else { 1.0 + s }).filter(|(p, t)| p.is_finite() && t.is_finite()).and_then(|(p, t)| ball(p, t)) {
- Some(x) => list.push(x),
- None => break,
- }
- }
- list
- };
- let after = past(1.0);
- offset.set(along.first().map(|s| s.c - p0));
- let before = past(-1.0);
- raw.extend(before.iter().rev().copied());
- let first = raw.len();
- raw.extend(along);
- let last = raw.len() - 1;
- raw.extend(after);
- let guide = Guide::new(raw)?;
- let total = guide.lengths.last().copied().ok_or_else(|| fail("spine"))?;
- let ends = [
- guide.lengths.get(first).copied().ok_or_else(|| fail("spine"))? / total,
- guide.lengths.get(last).copied().ok_or_else(|| fail("spine"))? / total,
- ];
- let uniform = |along: f64| -> Result {
- if along <= 0.0 {
- return guide.sections.first().copied().ok_or_else(|| fail("section"));
- }
- if along >= 1.0 {
- return guide.sections.last().copied().ok_or_else(|| fail("section"));
- }
- let (anchor, t) = guide.anchor(along).ok_or_else(|| unsupported("degenerate rolling-ball spine"))?;
- solve_from(&o1, &o2, anchor, t, r, sigma, 0.0, None, tol * 100.0, None)
- .ok_or_else(|| unsupported("the ball doesn't fit along the resampled spine"))
- };
- let mut samples = SAMPLES;
- let (list, fit) = loop {
- let list: Vec = (0..samples).map(|j| uniform(j as f64 / (samples - 1) as f64)).collect::>()?;
- let fit = crate::guard("fit corner blend", || fit_sections(std::slice::from_ref(&list), 0, false, round))?;
- let mut accurate = true;
- 'check: for j in 0..samples - 1 {
- for fraction in [0.25, 0.5, 0.75] {
- let along = (j as f64 + fraction) / (samples - 1) as f64;
- if !section_fits(&fit, &uniform(along)?, along, round, sigma, fit_tol) {
- accurate = false;
- break 'check;
- }
- }
- }
- if accurate {
- break (list, fit);
- }
- if samples >= MAX_SAMPLES {
- return Err(fail("could not fit the rolling-ball surface"));
- }
- samples = (2 * samples - 1).min(MAX_SAMPLES);
- };
- // Outward: toward the ball centre on a concave edge, away on a convex one.
- let mid = list.get(list.len() / 2).ok_or_else(|| fail("section"))?;
- let m = mid.c + ((mid.q1 - mid.c) + (mid.q2 - mid.c)).normalized().ok_or_else(|| fail("section"))? * r;
- let (u, v) = fit.surface.search_nearest_parameter(p3(m), Some((0.5, 0.5)), 100).ok_or_else(|| fail("orientation"))?;
- let nn = fit.surface.normal(u, v);
- let flip = if Vec3::new(nn.x, nn.y, nn.z).dot((mid.c - m) * sigma) < 0.0 { -1.0 } else { 1.0 };
- let sections = list.iter().enumerate().map(|(j, s)| (j as f64 / (samples - 1) as f64, *s)).collect();
- let [c1, c2] = fit.contacts;
- Ok(Strip { edge: e.clone(), fa, fb, surface: fit.surface, contacts: [c1, c2], ends, flip, sigma, sections })
-}
-
-/// The point a radius from all three faces (inside the material for a convex corner), from
-/// `start`, and its contacts with them.
-fn corner_ball(faces: [&mt::Face; 3], start: Vec3, r: f64, sigma: f64, tol: f64) -> Option<(Vec3, [Vec3; 3])> {
- let mut c = start;
- for _ in 0..100 {
- let mut rows = [[0.0; 3]; 3];
- let mut rhs = [0.0; 3];
- let mut qs = [Vec3::ZERO; 3];
- let mut worst: f64 = 0.0;
- for (((f, row), b), q) in faces.iter().zip(rows.iter_mut()).zip(rhs.iter_mut()).zip(qs.iter_mut()) {
- let (x, n, _) = project(f, c, None)?;
- let g = (c - x).dot(n) - sigma * r;
- *row = [n.x, n.y, n.z];
- *b = -g;
- *q = x;
- worst = worst.max(g.abs());
- }
- let d = crate::polyhedron::solve3_pub(rows, rhs)?;
- let dc = Vec3::new(d[0], d[1], d[2]);
- if worst < tol && dc.len() < tol {
- return Some((c, qs));
- }
- c += dc;
- if !c.is_finite() {
- return None;
- }
- }
- None
-}
-
-/// Flip a surface so that its normal near `at` points along `outward`.
-fn orient(mut surf: mt::Surface, at: Vec3, outward: Vec3) -> mt::Surface {
- use mt::{ParametricSurface3D, SearchNearestParameter};
- if let Some((u, v)) = surf.search_nearest_parameter(p3(at), None, 100) {
- let n = surf.normal(u, v);
- if Vec3::new(n.x, n.y, n.z).dot(outward) < 0.0 {
- surf = mt::Invertible::inverse(&surf);
- }
- }
- surf
-}
-
-/// Where a blend's contact ends at a vertex where it ends alone: crossing the edge there (its
-/// parameter and the point), or past that edge's far vertex `w`, crossing the next edge `g` of
-/// its face there (`h`: the third edge at `w`, between the faces `f4` beyond and the vertex's
-/// third face).
-enum Reached {
- Edge(f64, Vec3),
- Past { t: f64, p: Vec3, w: mt::Vertex, g: mt::EdgeID, h: mt::EdgeID, f4: usize },
-}
-
-/// A face of the shell being rebuilt, a strip, or a corner's sphere.
-#[derive(Clone, Copy, PartialEq)]
-enum Owner {
- Face(usize),
- Strip(mt::EdgeID),
- Patch,
-}
-
-/// Edges from `from` to `to` through the pool edges of `owner`.
-fn connect(from: &mt::Vertex, to: &mt::Vertex, pool: &[(mt::Edge, Vec)], owner: Owner) -> Result> {
- let mut out = Vec::new();
- let mut used: HashSet = HashSet::new();
- let mut cur = from.clone();
- for _ in 0..=pool.len() {
- if &cur == to {
- return Ok(out);
- }
- let next = pool.iter().filter(|(e, o)| o.contains(&owner) && !used.contains(&e.id())).find_map(|(e, _)| {
- if e.front() == &cur {
- Some(e.clone())
- } else if e.back() == &cur {
- Some(e.inverse())
- } else {
- None
- }
- });
- let Some(e) = next else { break };
- used.insert(e.id());
- cur = e.back().clone();
- out.push(e);
- }
- Err(fail("a boundary does not close"))
-}
-
-/// The strip's own station nearest the corner ball `c`: the section where the strip stops against
-/// that ball, where its direction of leave and its curvature are read.
-fn corner_station(strip: &Strip, c: Vec3) -> Option {
- strip.sections.iter().min_by(|a, b| a.1.c.dist(c).total_cmp(&b.1.c.dist(c))).map(|x| x.0)
-}
-
-/// One side of a G2 corner: the corner ball's own section arc of radius `r` about `c`, from its
-/// contact `q_from` to its contact `q_to`, each station carrying the direction the corner patch
-/// leaves the blend in (towards the corner's apex) and the blend's own curvature across it, read
-/// from `strip` where the ball stops against it. A rolling ball's section is a circular arc about
-/// its own centre wherever the edge runs, so this arc is the blend's section curve itself, and its
-/// ends are the ball's contacts exactly — the sides close the loop whatever the fit's station
-/// spacing is.
-fn g2_side(strip: &Strip, c: Vec3, r: f64, q_from: Vec3, q_to: Vec3, apex: Vec3) -> Result> {
- use mt::ParametricSurface;
- /// Stations across one section: enough for the patch's cubic cross-sections, few enough to
- /// keep the corner's own patch small.
- const STATIONS: usize = 9;
- let vec_of = |d: mt::Vector3| Vec3::new(d.x, d.y, d.z);
- let v = corner_station(strip, c).ok_or_else(|| fail("corner section"))?;
- let a = (q_from - c).normalized().ok_or_else(|| fail("corner contact"))?;
- let b = (q_to - c).normalized().ok_or_else(|| fail("corner contact"))?;
- let dot = a.dot(b).clamp(-1.0, 1.0);
- let w = (b - a * dot).normalized().ok_or_else(|| fail("corner contact"))?;
- let theta = dot.acos();
- // The blend's own direction of leave and curvature across the seam, at its corner station.
- let speed = vec_of(strip.surface.vder(0.5, v)).len();
- if !(speed > 1e-30) {
- return Err(unsupported("a corner section of no width"));
- }
- let leave = vec_of(strip.surface.vder(0.5, v)) * (1.0 / speed);
- let bend = vec_of(strip.surface.vvder(0.5, v)) * (1.0 / (speed * speed));
- if !(leave.is_finite() && bend.is_finite() && theta.is_finite() && r.is_finite()) {
- return Err(unsupported("a corner section that is not finite"));
- }
- let mut out = Vec::with_capacity(STATIONS);
- for k in 0..STATIONS {
- let t = theta * k as f64 / (STATIONS - 1) as f64;
- let p = c + (a * t.cos() + w * t.sin()) * r;
- // The patch leaves the blend towards the material the corner caps, so the sign is the one
- // towards the corner's apex (the blends' own v direction runs away from the vertex).
- let leave = if leave.dot(apex - p) < 0.0 { -leave } else { leave };
- if !(p.is_finite() && leave.is_finite() && bend.is_finite()) {
- return Err(unsupported("a corner section that is not finite"));
- }
- out.push(Frame { p, leave, bend, bend_change: Vec3::ZERO });
- }
- Ok(out)
-}
-
-/// Blend the edges `ids` of `solid` with radius `r` (a chamfer's distance), rebuilding the
-/// corners at their ends; with what it built from `solid`.
-pub(crate) fn corner_blend(solid: &Solid, ids: &[mt::EdgeID], size: f64, r: f64, round: bool) -> Result<(Solid, Rebuild)> {
- corner_blend_style(solid, ids, size, r, round, false)
-}
-
-/// [`corner_blend`]; with `g2`, the corners where three blends meet are G2 patches
-/// ([`crate::corner_g2`]) instead of pieces of the rolling ball's sphere.
-pub(crate) fn corner_blend_style(solid: &Solid, ids: &[mt::EdgeID], size: f64, r: f64, round: bool, g2: bool) -> Result<(Solid, Rebuild)> {
- if !(size.is_finite() && size > 0.0 && r.is_finite() && r > 0.0) {
- return Err(KernelError::Invalid("blend size and radius must be finite and positive".into()));
- }
- if ids.is_empty() || ids.len() > 64 {
- return Err(KernelError::Invalid("select 1…64 edges".into()));
- }
- let tol = (size * 1e-7).max(1e-9);
- let fit_tol = (size * 1e-5).clamp(1e-5, 0.001);
- let shells = solid.boundaries();
- let si = shells.iter().position(|sh| sh.edge_iter().any(|e| ids.contains(&e.id()))).ok_or_else(|| fail("edge not found"))?;
- let shell = shells.get(si).ok_or_else(|| fail("shell"))?;
- if ids.iter().any(|id| !shell.edge_iter().any(|e| e.id() == *id)) {
- return Err(unsupported("blends on separate lumps in one go"));
- }
- let faces: Vec = shell.face_iter().cloned().collect();
- let edges: HashMap = shell.edge_iter().map(|e| (e.id(), e.absolute_clone())).collect();
- let mut on_edge: HashMap> = HashMap::new();
- let mut at_vertex: HashMap, Vec)> = HashMap::new();
- for (fi, f) in faces.iter().enumerate() {
- for e in f.edge_iter() {
- let list = on_edge.entry(e.id()).or_default();
- if !list.contains(&fi) {
- list.push(fi);
- }
- for v in [e.front(), e.back()] {
- let a = at_vertex.entry(v.id()).or_default();
- a.0.insert(e.id());
- if !a.1.contains(&fi) {
- a.1.push(fi);
- }
- }
- }
- }
- let face_with = |a: mt::EdgeID, b: mt::EdgeID| -> Result {
- let fa = on_edge.get(&a).cloned().unwrap_or_default();
- let fb = on_edge.get(&b).cloned().unwrap_or_default();
- fa.into_iter().find(|f| fb.contains(f)).ok_or_else(|| fail("faces"))
- };
- let face = |fi: usize| faces.get(fi).ok_or_else(|| fail("face"));
-
- // The vertices at the blended edges' ends: three faces, three edges.
- let mut touched: HashMap = HashMap::new();
- let mut sides: HashMap)> = HashMap::new();
- for id in ids {
- let e = edges.get(id).ok_or_else(|| fail("edge"))?;
- if e.front() == e.back() {
- return Err(unsupported("blending a closed edge at a corner"));
- }
- let fs = on_edge.get(id).cloned().unwrap_or_default();
- let [fa, fb] = fs[..] else { return Err(unsupported("the edge is not between two faces")) };
- let (sigma, knife) = convexity(&faces, e, fa, fb, r)?;
- sides.insert(*id, (fa, fb, sigma, knife));
- touched.insert(e.front().id(), e.front().clone());
- touched.insert(e.back().id(), e.back().clone());
- }
- for vid in touched.keys() {
- let (eids, fids) = at_vertex.get(vid).ok_or_else(|| fail("vertex"))?;
- if eids.len() != 3 || fids.len() != 3 {
- return Err(unsupported("blends ending where more than three edges meet"));
- }
- let chosen: Vec<&mt::EdgeID> = eids.iter().filter(|id| sides.contains_key(id)).collect();
- if chosen.len() >= 2 && chosen.iter().any(|id| sides.get(*id).is_none_or(|s| s.2 > 0.0)) {
- return Err(unsupported("concave blends meeting at a corner"));
- }
- if chosen.len() == 3 && !round {
- return Err(unsupported("three chamfers at one corner"));
- }
- // A blended edge running on smoothly into one that isn't: the blend follows it there
- // (a chain round the corner, blended elsewhere), unless it is an earlier round's arc of
- // this radius, which the blend ends in. Round a smaller one the ball can't.
- let v = touched.get(vid).ok_or_else(|| fail("vertex"))?;
- let leaves = |e: &mt::Edge| {
- use mt::BoundedCurve;
- let c = e.curve();
- let (t0, t1) = c.range_tuple();
- tangent(&c, if e.front() == v { t0 } else { t1 }).map(|d| if e.front() == v { d } else { -d })
- };
- for id in &chosen {
- let Some(d) = edges.get(*id).and_then(leaves) else { continue };
- for g in eids.iter().filter(|g| !sides.contains_key(*g)) {
- let Some(e) = edges.get(g) else { continue };
- if !leaves(e).is_some_and(|x| x.dot(d) < -1.0 + 1e-6) {
- continue;
- }
- // The earlier round's end may also be where it meets a curved face: a circle only
- // seen along the round's axis, which its contact with the third face runs along.
- let third = eids.iter().find(|x| *x != *id && *x != g).and_then(|x| edges.get(x)).and_then(leaves);
- let seen = super::circle_of(e, tol * 1e3).map(|c| c.1).or_else(|| third.and_then(|a| radius_along(e, a, tol * 1e3)));
- match seen {
- Some(rho) if (rho - r).abs() <= tol * 1e3 => {}
- Some(rho) if rho < r => return Err(too_large("the blend is larger than a corner radius")),
- _ => return Err(unsupported("a blend running on smoothly into an edge not blended")),
- }
- }
- }
- }
-
- crate::guard("blend corners", || {
- // The strips.
- let mut strips: HashMap = HashMap::new();
- for id in ids {
- let (Some(e), Some((fa, fb, sigma, knife))) = (edges.get(id), sides.get(id).copied()) else { return Err(fail("edge")) };
- strips.insert(*id, strip(&faces, e, (fa, fb), r, round, (sigma, knife), 8.0 * r, tol, fit_tol)?);
- }
- let strip_of = |id: &mt::EdgeID| strips.get(id).ok_or_else(|| fail("strip"));
- // New end points: (edge, vertex, the face of a blended edge's contact).
- let mut endpt: HashMap<(mt::EdgeID, mt::VertexID, Option), mt::Vertex> = HashMap::new();
- let mut pool: HashMap)>> = HashMap::new();
- let mut patches: Vec<(mt::Face, Vec)> = Vec::new();
- // Edges a blend uses up to their far vertex (an earlier round's edge, when the radii
- // are equal): left out, the blend ends at that vertex.
- let mut consumed: HashSet = HashSet::new();
- // Vertices a blend takes in (an earlier round's corner past the end of its edge).
- let mut gone: HashMap = HashMap::new();
- // In a fixed order (by position): the work and the result don't depend on hashing.
- let mut order_v: Vec<(&mt::VertexID, &mt::Vertex)> = touched.iter().collect();
- order_v.sort_by(|a, b| {
- let (p, q) = (vtx(a.1), vtx(b.1));
- p.x.total_cmp(&q.x).then(p.y.total_cmp(&q.y)).then(p.z.total_cmp(&q.z))
- });
- for (vid, vert) in order_v {
- let v = vtx(vert);
- let (eids, _) = at_vertex.get(vid).ok_or_else(|| fail("vertex"))?;
- let mut chosen: Vec = eids.iter().filter(|id| sides.contains_key(id)).copied().collect();
- let rest: Vec = eids.iter().filter(|id| !sides.contains_key(id)).copied().collect();
- chosen.sort_by_key(|id| ids.iter().position(|x| x == id));
- let curve_of = |id: &mt::EdgeID| edges.get(id).map(|e| e.curve()).ok_or_else(|| fail("edge"));
- // The new end on edge `id` at `p`: its far vertex when the blend reaches it.
- // A contact (`along`: the curves arriving there, and where) that runs into that
- // vertex along another of its edges would leave a face no wider than nothing: refused.
- let at_end = |id: &mt::EdgeID, p: Vec3, along: &[(&mt::Curve, f64, usize)]| -> Result<(mt::Vertex, bool)> {
- let far = edges.get(id).map(|e| if e.front().id() == *vid { e.back().clone() } else { e.front().clone() });
- let Some(w) = far.filter(|w| vtx(w).dist(p) <= fit_tol * 10.0 && !touched.contains_key(&w.id())) else {
- return Ok((builder::vertex(p3(p)), false));
- };
- let others = at_vertex.get(&w.id()).map(|x| x.0.iter().filter(|g| *g != id).copied().collect::>()).unwrap_or_default();
- for g in others {
- use mt::BoundedCurve;
- let Some(e) = edges.get(&g) else { continue };
- let c = e.curve();
- let (t0, t1) = c.range_tuple();
- let leaves = tangent(&c, if e.front() == &w { t0 } else { t1 });
- let of = on_edge.get(&g).cloned().unwrap_or_default();
- if along
- .iter()
- .filter(|(_, _, f)| of.contains(f))
- .filter_map(|(c, t, _)| tangent(c, *t))
- .any(|d| leaves.is_some_and(|l| l.dot(d).abs() > 1.0 - 1e-6))
- {
- return Err(unsupported("a blend that runs along an edge where it ends"));
- }
- }
- Ok((w, true))
- };
- let mut ending = |id: &mt::EdgeID, p: Vec3, along: &[(&mt::Curve, f64, usize)]| -> Result {
- let (w, used) = at_end(id, p, along)?;
- if used {
- consumed.insert(*id);
- }
- Ok(w)
- };
- let list = pool.entry(*vid).or_default();
- match (&chosen[..], &rest[..]) {
- ([e1], [e2, e3]) => {
- let s1 = strip_of(e1)?;
- let (f12, f31, f23) = (face_with(*e1, *e2)?, face_with(*e1, *e3)?, face_with(*e2, *e3)?);
- let (_, out) = s1.end_at(vert);
- let (c12, c31) = (s1.contact(f12)?, s1.contact(f31)?);
- let none = || too_large("the blend is larger than the neighbouring faces");
- // Each contact crosses its edge at the vertex, or runs past that edge's far
- // end (the blend takes in that corner, an earlier round's) to the next edge of
- // its face there.
- let side = |ei: &mt::EdgeID, fi: usize| -> Result {
- let c = s1.contact(fi)?;
- if let Some((t, p)) = cross(c, &curve_of(ei)?, face(fi)?, v, s1.own(), fit_tol) {
- return Ok(Reached::Edge(t, p));
- }
- // Only an earlier round's corner: the third face runs on smoothly from a
- // side at the vertex (else the blend would wrap round a corner of the part).
- let normal = |f: usize| face(f).ok().and_then(|g| project(g, v, None)).map(|x| x.1);
- let smooth = normal(f23).is_some_and(|n| [f12, f31].iter().any(|f| normal(*f).is_some_and(|m| m.dot(n) > 1.0 - 1e-6)));
- if !smooth {
- return Err(none());
- }
- let e = edges.get(ei).ok_or_else(|| fail("edge"))?;
- let w = if e.front().id() == *vid { e.back().clone() } else { e.front().clone() };
- let (ws, wf) = at_vertex.get(&w.id()).ok_or_else(|| fail("vertex"))?;
- if touched.contains_key(&w.id()) || ws.len() != 3 || wf.len() != 3 || ws.iter().any(|x| sides.contains_key(x)) {
- return Err(none());
- }
- let on = |f: usize| ws.iter().filter(|x| *x != ei).find(|x| on_edge.get(*x).is_some_and(|fs| fs.contains(&f))).copied();
- let (Some(g), Some(h)) = (on(fi), on(f23)) else { return Err(none()) };
- let f4 = face_with(g, h)?;
- let (t, p) = cross(c, &curve_of(&g)?, face(fi)?, v, s1.own(), fit_tol).ok_or_else(none)?;
- // Through that far vertex itself: the contact reaches the edge's end there
- // (touching it where it runs in tangent to the contact, as at a knife-edge
- // tip).
- if p.dist(vtx(&w)) <= fit_tol * 10.0 {
- return Ok(Reached::Edge(t, vtx(&w)));
- }
- Ok(Reached::Past { t, p, w, g, h, f4 })
- };
- match (side(e2, f12)?, side(e3, f31)?) {
- (Reached::Edge(v2, p2), Reached::Edge(v3, p3_)) => {
- let (a, b) = (ending(e2, p2, &[(c12, v2, f12)])?, ending(e3, p3_, &[(c31, v3, f31)])?);
- endpt.insert((*e2, *vid, None), a.clone());
- endpt.insert((*e1, *vid, Some(f12)), a.clone());
- endpt.insert((*e3, *vid, None), b.clone());
- endpt.insert((*e1, *vid, Some(f31)), b.clone());
- let end = Away::face(face(f23)?);
- let c = trace(s1, (s1.u(f12)?, v2, p2), (s1.u(f31)?, v3, p3_), &end, out, fit_tol)?;
- list.push((mt::Edge::new(&a, &b, c), vec![Owner::Face(f23), Owner::Strip(*e1)]));
- }
- (r2, r3) => {
- // The end runs from the edge reached across the third face to where
- // it crosses the edge `h` from the corner taken in, then across the
- // face beyond (`f4`) to the next edge `g`.
- let ((ed, fd, td, pd), (ex, fx, past)) = match (r2, r3) {
- (Reached::Edge(t, p), past @ Reached::Past { .. }) => ((e2, f12, t, p), (e3, f31, past)),
- (past @ Reached::Past { .. }, Reached::Edge(t, p)) => ((e3, f31, t, p), (e2, f12, past)),
- _ => return Err(unsupported("a blend running past both edges where it ends")),
- };
- let Reached::Past { t: tx, p: px, w, g, h, f4 } = past else { return Err(fail("corner")) };
- let a = ending(ed, pd, &[(s1.contact(fd)?, td, fd)])?;
- let b = builder::vertex(p3(px));
- let (_, y) = reach(&curve_of(&h)?, &Away::strip(s1), vtx(&w), fit_tol).ok_or_else(none)?;
- let (u_y, v_y) = s1.nearest(y).ok_or_else(none)?;
- if s1.at(u_y, v_y).dist(y) > fit_tol * 10.0 {
- return Err(none());
- }
- let yv = builder::vertex(p3(y));
- consumed.insert(*ex);
- gone.insert(w.id(), w.clone());
- endpt.insert((*ed, *vid, None), a.clone());
- endpt.insert((*e1, *vid, Some(fd)), a.clone());
- endpt.insert((*e1, *vid, Some(fx)), b.clone());
- endpt.insert((g, w.id(), None), b.clone());
- endpt.insert((h, w.id(), None), yv.clone());
- let first = trace(s1, (s1.u(fd)?, td, pd), (u_y, v_y, y), &Away::face(face(f23)?), out, fit_tol)?;
- let second = trace(s1, (u_y, v_y, y), (s1.u(fx)?, tx, px), &Away::face(face(f4)?), out, fit_tol)?;
- list.push((mt::Edge::new(&a, &yv, first), vec![Owner::Face(f23), Owner::Strip(*e1)]));
- list.push((mt::Edge::new(&yv, &b, second), vec![Owner::Face(f4), Owner::Strip(*e1)]));
- }
- }
- }
- ([ea, eb], [e3]) => {
- let (sa, sb) = (strip_of(ea)?, strip_of(eb)?);
- let fab = face_with(*ea, *eb)?;
- let (fa3, fb3) = (face_with(*ea, *e3)?, face_with(*eb, *e3)?);
- let c3 = curve_of(e3)?;
- let none = || too_large("the blend is larger than the neighbouring faces");
- // Where the contacts cross on the shared face, and each reaches the third edge.
- let (va_q, q) = cross(sa.contact(fab)?, sb.contact(fab)?, face(fab)?, v, sa.own(), fit_tol).ok_or_else(none)?;
- let vb_q = param_on(sb.contact(fab)?, q).ok_or_else(none)?;
- let (va_x, xa) = cross(sa.contact(fa3)?, &c3, face(fa3)?, v, sa.own(), fit_tol).ok_or_else(none)?;
- let (vb_x, xb) = cross(sb.contact(fb3)?, &c3, face(fb3)?, v, sb.own(), fit_tol).ok_or_else(none)?;
- let qv = builder::vertex(p3(q));
- endpt.insert((*ea, *vid, Some(fab)), qv.clone());
- endpt.insert((*eb, *vid, Some(fab)), qv.clone());
- if xa.dist(xb) <= fit_tol * 10.0 {
- // The crease runs to the third edge.
- let x = (xa + xb) * 0.5;
- let xv = ending(e3, x, &[(sa.contact(fa3)?, va_x, fa3), (sb.contact(fb3)?, vb_x, fb3)])?;
- endpt.insert((*e3, *vid, None), xv.clone());
- endpt.insert((*ea, *vid, Some(fa3)), xv.clone());
- endpt.insert((*eb, *vid, Some(fb3)), xv.clone());
- let (_, out) = sa.end_at(vert);
- let c = trace(sa, (sa.u(fab)?, va_q, q), (sa.u(fa3)?, va_x, x), &Away::strip(sb), out, fit_tol)?;
- list.push((mt::Edge::new(&qv, &xv, c), vec![Owner::Strip(*ea), Owner::Strip(*eb)]));
- } else {
- // The strip reaching further along the third edge (`big`) runs on past
- // the crease to end on the other's third face.
- let (big, small, ebig, esmall, fbig3, fsmall3, x, vbig_x) =
- if xa.dist(v) > xb.dist(v) { (sa, sb, *ea, *eb, fa3, fb3, xa, va_x) } else { (sb, sa, *eb, *ea, fb3, fa3, xb, vb_x) };
- let vs_q = if esmall == *ea { va_q } else { vb_q };
- let (vs_y, y) = reach(small.contact(fsmall3)?, &Away::strip(big), v, fit_tol).ok_or_else(none)?;
- let (u_y, v_y) = big.nearest(y).ok_or_else(none)?;
- if big.at(u_y, v_y).dist(y) > fit_tol * 10.0 {
- return Err(unsupported("blends this different at one corner"));
- }
- let xv = ending(e3, x, &[(big.contact(fbig3)?, vbig_x, fbig3)])?;
- let yv = builder::vertex(p3(y));
- endpt.insert((*e3, *vid, None), xv.clone());
- endpt.insert((ebig, *vid, Some(fbig3)), xv.clone());
- endpt.insert((esmall, *vid, Some(fsmall3)), yv.clone());
- let (_, out_s) = small.end_at(vert);
- let (_, out_b) = big.end_at(vert);
- let crease = trace(small, (small.u(fab)?, vs_q, q), (small.u(fsmall3)?, vs_y, y), &Away::strip(big), out_s, fit_tol)?;
- let section = trace(big, (u_y, v_y, y), (big.u(fbig3)?, vbig_x, x), &Away::face(face(fsmall3)?), out_b, fit_tol)?;
- list.push((mt::Edge::new(&qv, &yv, crease), vec![Owner::Strip(*ea), Owner::Strip(*eb)]));
- list.push((mt::Edge::new(&yv, &xv, section), vec![Owner::Face(fsmall3), Owner::Strip(ebig)]));
- }
- }
- ([e1, e2, e3], []) => {
- let s1 = strip_of(e1)?;
- let (f12, f23, f31) = (face_with(*e1, *e2)?, face_with(*e2, *e3)?, face_with(*e3, *e1)?);
- // The corner ball, from the first strip's section nearest the vertex.
- let (v1, _) = s1.end_at(vert);
- let start = s1
- .sections
- .iter()
- .min_by(|a, b| (a.0 - v1).abs().total_cmp(&(b.0 - v1).abs()))
- .map(|x| x.1.c)
- .ok_or_else(|| fail("section"))?;
- let (c, [q12, q23, q31]) = corner_ball([face(f12)?, face(f23)?, face(f31)?], start, r, s1.sigma, tol * 100.0)
- .ok_or_else(|| unsupported("the ball doesn't fit in the corner"))?;
- let (v12, v23, v31) = (builder::vertex(p3(q12)), builder::vertex(p3(q23)), builder::vertex(p3(q31)));
- for (e, f, x) in [(e1, f12, &v12), (e2, f12, &v12), (e2, f23, &v23), (e3, f23, &v23), (e3, f31, &v31), (e1, f31, &v31)] {
- endpt.insert((*e, *vid, Some(f)), x.clone());
- }
- let arc = |a: &mt::Vertex, b: &mt::Vertex| -> Result {
- let m = c + ((vtx(a) - c) + (vtx(b) - c)).normalized().ok_or_else(|| fail("corner arc"))? * r;
- Ok(builder::circle_arc(a, b, p3(m)))
- };
- let (a1, a2, a3) = (arc(&v12, &v31)?, arc(&v12, &v23)?, arc(&v23, &v31)?);
- // A sphere with its poles and seam away from the patch.
- let n = |f: usize, q: Vec3| face(f).ok().and_then(|g| project(g, q, None)).map(|x| x.1).unwrap_or(Vec3::Z);
- let out = (n(f12, q12) + n(f23, q23) + n(f31, q31)).normalized().unwrap_or(Vec3::Z);
- let side = out.any_perp();
- let (np, sp, back) = (c + side * r, c - side * r, c - out * r);
- if g2 {
- // A G2 patch on the blends' own end sections, gathered at the ball's pole
- // (the point the sphere's meridians are built through above). Each side is
- // the strip's section through the ball's contact with the face it shares
- // with the previous strip; the strips run on past their edges, so that
- // station is found by projecting the contact point, not taken from the
- // edge's own end.
- let s2 = strip_of(e2)?;
- let s3 = strip_of(e3)?;
- // The cap's own pole: the ball's point nearest the corner (the sphere
- // patch's `back` above is its opposite pole, where the meridian starts).
- let apex = c + out * r;
- // Side 1 runs from the ball's contact with the face it shares with e3
- // round to the one it shares with e2, and so on round the loop: each
- // side's last station is the next side's first, at that contact.
- let sides = [g2_side(s1, c, r, q31, q12, apex)?, g2_side(s2, c, r, q12, q23, apex)?, g2_side(s3, c, r, q23, q31, apex)?];
- let _patch = crate::corner_g2::corner_g2_patch(&sides, apex)?;
- // Sewing the patch into the shell is not done yet: it brings its own
- // boundary vertices where the strips' contacts end at the ball's contacts
- // (`v12`/`v23`/`v31`), and a truck vertex is its allocation, not its point,
- // so the rebuilt shell does not close there (rewrapping the section curves
- // onto the contacts is the missing step). Refused rather than left open:
- // the rolling ball fills the corner instead.
- return Err(unsupported(
- "a G2 corner sewn between these blends (the patch's section curves do not join the blends' contacts yet)",
- ));
- }
- let meridian = builder::circle_arc(&builder::vertex(p3(np)), &builder::vertex(p3(sp)), p3(back));
- let surf = mt::Surface::RevolutedCurve(mt::Processor::new(mt::RevolutedCurve::by_revolution(
- meridian.oriented_curve(),
- p3(c),
- v3(side),
- )));
- let surf = orient(surf, c + out * r, out * -s1.sigma);
- let wire: mt::Wire = vec![a2.clone(), a3.clone(), a1.inverse()].into();
- let patch = mt::Face::try_new(vec![wire], surf).map_err(|e| fail(&format!("corner patch: {e}")))?;
- patches.push((patch, vec![*e1, *e2, *e3]));
- list.push((a1, vec![Owner::Strip(*e1), Owner::Patch]));
- list.push((a2, vec![Owner::Strip(*e2), Owner::Patch]));
- list.push((a3, vec![Owner::Strip(*e3), Owner::Patch]));
- }
- _ => return Err(unsupported("this corner")),
- }
- }
-
- // Rebuilt edges: contacts per (edge, face), shortened edges per edge.
- let end_of =
- |id: mt::EdgeID, v: &mt::Vertex, f: Option| -> mt::Vertex { endpt.get(&(id, v.id(), f)).cloned().unwrap_or_else(|| v.clone()) };
- let mut lines: HashMap<(mt::EdgeID, Option), mt::Edge> = HashMap::new();
- let mut line_of = |e: &mt::Edge, f: Option| -> Result {
- use mt::Cut;
- if let Some(x) = lines.get(&(e.id(), f)) {
- return Ok(x.clone());
- }
- let abs = e.absolute_clone();
- let (a, b) = (end_of(e.id(), abs.front(), f), end_of(e.id(), abs.back(), f));
- let x = match (f, strips.get(&e.id())) {
- (Some(fi), Some(s)) => {
- // The contact between its new ends.
- let c = s.contact(fi)?;
- let none = || too_large("the blend is larger than the neighbouring faces");
- let (ta, tb) = (param_on(c, vtx(&a)).ok_or_else(none)?, param_on(c, vtx(&b)).ok_or_else(none)?);
- if tb - ta < 1e-9 {
- return Err(too_large("the blend is larger than the neighbouring faces"));
- }
- let mut piece = c.clone();
- let _ = piece.cut(tb);
- let piece = piece.cut(ta);
- mt::Edge::try_new(&a, &b, piece).map_err(|e| fail(&format!("contact: {e}")))?
- }
- _ => {
- let orig = vtx(abs.back()) - vtx(abs.front());
- if (vtx(&b) - vtx(&a)).dot(orig) <= size * 1e-9 * orig.len() {
- return Err(too_large("the blend is larger than the neighbouring faces"));
- }
- if matches!(abs.curve(), mt::Curve::Line(_)) {
- builder::line(&a, &b)
- } else {
- let moved = |n: &mt::Vertex, o: &mt::Vertex| (n != o).then(|| n.clone());
- super::trim_curved_seam(&abs, moved(&a, abs.front()), moved(&b, abs.back()), size)?
- }
- }
- };
- lines.insert((e.id(), f), x.clone());
- Ok(x)
- };
- let changed = |v: &mt::Vertex| touched.contains_key(&v.id()) || gone.contains_key(&v.id());
- let moved = |e: &mt::Edge| changed(e.front()) || changed(e.back());
- let everywhere: Vec<(mt::Edge, Vec)> = pool.values().flatten().cloned().collect();
- let mut rec = Rebuild::default();
- let mut out: Vec = Vec::with_capacity(faces.len() + strips.len() + patches.len());
- for (fi, f) in faces.iter().enumerate() {
- if !f.vertex_iter().any(|v| changed(&v)) {
- out.push(f.clone());
- continue;
- }
- let mut wires = Vec::new();
- for w in f.boundaries() {
- let olds: Vec = w.edge_iter().filter(|e| !consumed.contains(&e.id())).cloned().collect();
- let mut news = Vec::with_capacity(olds.len());
- for e in &olds {
- let ne = if strips.contains_key(&e.id()) {
- line_of(e, Some(fi))?
- } else if moved(e) {
- let piece = line_of(e, None)?;
- rec.piece(&piece, e);
- piece
- } else {
- news.push(e.clone());
- continue;
- };
- news.push(if e.front() == e.absolute_front() { ne } else { ne.inverse() });
- }
- let n = news.len();
- let mut ws = Vec::new();
- for i in 0..n {
- let (Some(a), Some(b)) = (news.get(i), news.get((i + 1) % n)) else { continue };
- ws.push(a.clone());
- if a.back() != b.front() {
- ws.extend(connect(a.back(), b.front(), &everywhere, Owner::Face(fi))?);
- }
- }
- wires.push(mt::Wire::from(ws));
- }
- let rebuilt = mt::Face::try_new(wires, f.oriented_surface()).map_err(|e| fail(&format!("face: {e}")))?;
- rec.face(&rebuilt, f);
- out.push(rebuilt);
- }
- // The strips: back along the first face's contact, round the front corner, along the
- // second's, round the back corner.
- for id in ids {
- let (Some(s), Some(e)) = (strips.get(id), edges.get(id)) else { continue };
- let (va, vb) = (e.front(), e.back());
- let a_forward = faces.get(s.fa).is_some_and(|f| f.boundaries().iter().any(|w| w.edge_iter().any(|x| x.id() == *id && x.front() == va)));
- let la = line_of(e, Some(s.fa))?;
- let lb = line_of(e, Some(s.fb))?;
- let (first, second) = if a_forward { (la.inverse(), lb) } else { (lb.inverse(), la) };
- let p1 = pool.get(&va.id()).map(|x| &x[..]).unwrap_or(&[]);
- let p2 = pool.get(&vb.id()).map(|x| &x[..]).unwrap_or(&[]);
- let mut w = vec![first.clone()];
- w.extend(connect(first.back(), second.front(), p1, Owner::Strip(*id))?);
- w.push(second.clone());
- w.extend(connect(second.back(), first.front(), p2, Owner::Strip(*id))?);
- let surface = if s.flip < 0.0 { mt::Invertible::inverse(&s.surface) } else { s.surface.clone() };
- let surface = in_proportion(&surface)?;
- let blend = mt::Face::try_new(vec![w.into()], surface).map_err(|e| fail(&format!("blend face: {e}")))?;
- rec.blend(&blend, [*id]);
- out.push(blend);
- }
- // Corner patches run each section opposite to its strip.
- for (mut p, corner) in patches {
- let uses = |f: &mt::Face, id: mt::EdgeID| {
- f.boundaries().iter().flat_map(|w| w.edge_iter().cloned().collect::>()).find(|x| x.id() == id).map(|x| x.front().id())
- };
- let flip = p
- .boundaries()
- .first()
- .and_then(|w| w.edge_iter().next())
- .and_then(|pe| out.iter().find_map(|f| uses(f, pe.id())).map(|front| front == pe.front().id()));
- if flip == Some(true) {
- let surf = p.oriented_surface();
- let wires: Vec = p.boundaries().iter().map(|w| w.inverse()).collect();
- p = mt::Face::try_new(wires, surf).map_err(|e| fail(&format!("corner patch: {e}")))?;
- }
- rec.blend(&p, corner);
- out.push(p);
- }
- let mut shells = solid.boundaries().clone();
- if let Some(sh) = shells.get_mut(si) {
- *sh = out.into();
- }
- let res = Solid::try_new(shells).map_err(|e| fail(&format!("invalid solid: {e}")))?;
- Ok((res, rec))
- })
-}
-
-#[cfg(test)]
-#[path = "curvecorner_tests.rs"]
-mod tests;
diff --git a/crates/kernel/src/curvecorner_tests.rs b/crates/kernel/src/curvecorner_tests.rs
index 947b20032..af199c53c 100644
--- a/crates/kernel/src/curvecorner_tests.rs
+++ b/crates/kernel/src/curvecorner_tests.rs
@@ -275,9 +275,9 @@ fn rounds_together_in_any_order() {
}
}
-/// The blends this part needs the corner build for (and the back edge, rolled into the tip) at
+/// The blends this part has corners in (and the back edge, rounded into the tip) at
/// 0.01 and 100 times the part's size, the radius scaled with it: they take off what they take at
-/// full size, scaled by the cube, so the build's tolerances and limits follow the model's size.
+/// full size, scaled by the cube, so the tolerances and limits follow the model's size.
#[test]
fn corner_blends_hold_at_any_scale() {
let cases: [(&str, Vec>); 6] = [
diff --git a/crates/kernel/src/loopblend.rs b/crates/kernel/src/loopblend.rs
deleted file mode 100644
index 89b21a2ef..000000000
--- a/crates/kernel/src/loopblend.rs
+++ /dev/null
@@ -1,959 +0,0 @@
-//! Blending a whole boundary loop of a planar face whose neighbours are walls standing
-//! perpendicular to it (planes, and cylinders with axes along the face normal): a pocket floor,
-//! the top outline of an extruded plate. Lines and arcs can meet tangentially or at mitred sharp
-//! corners. The face shrinks by the radius, the walls are trimmed by it, and each loop edge
-//! gets a blend face: a cylinder (or plane, for a chamfer) along a line, a torus (or cone) along
-//! an arc, all meeting along the profile curves at the joints. Sharp joints at perpendicular
-//! curved walls follow the intersections of the exact offsets, fitted within tolerance.
-//! A chamfer may also set back by different distances on the face and up the walls (two
-//! distances, or a distance and an angle: [`loop_chamfer_sides`]).
-
-use std::collections::HashMap;
-
-use solidcraft_geom::Vec3;
-use truck_modeling::{self as mt, builder};
-
-use crate::blend::{ChamferSide, too_large};
-use crate::body::{Solid, from_p3, p3, v3};
-use crate::record::Rebuild;
-use crate::{KernelError, Result};
-
-fn unsupported(msg: &str) -> KernelError {
- KernelError::Failed(format!("not supported yet: {msg}"))
-}
-
-#[derive(Clone, Copy, Debug)]
-enum Seg {
- Line {
- a: Vec3,
- b: Vec3,
- },
- /// Arc from `a` to `b` about `c` turning by `angle` about `axis` (right hand, angle > 0).
- Arc {
- a: Vec3,
- c: Vec3,
- axis: Vec3,
- angle: f64,
- mid: Vec3,
- },
-}
-
-impl Seg {
- fn start(&self) -> Vec3 {
- match *self {
- Seg::Line { a, .. } | Seg::Arc { a, .. } => a,
- }
- }
- fn end(&self) -> Vec3 {
- match *self {
- Seg::Line { b, .. } => b,
- Seg::Arc { a, c, axis, angle, .. } => turn(a, c, axis, angle),
- }
- }
- /// Unit tangent (direction of travel) at a point of the segment.
- fn tangent(&self, p: Vec3) -> Option {
- match *self {
- Seg::Line { a, b } => (b - a).normalized(),
- Seg::Arc { c, axis, .. } => axis.cross(p - c).normalized(),
- }
- }
-}
-
-/// Intersection of two inward offsets nearest their shared corner, in the face plane.
-fn offset_joint(prev: &Seg, cur: &Seg, n: Vec3, d: f64) -> Option {
- let p = cur.start();
- let line_circle = |line: &Seg, arc: &Seg| {
- let Seg::Arc { a, c, .. } = *arc else { return None };
- let tangent = line.tangent(p)?;
- let origin = p + n.cross(tangent) * d;
- let radius = a.dist(c) + n.cross(arc.tangent(p)?).dot((p - c).normalized()?) * d;
- let foot = origin + tangent * (c - origin).dot(tangent);
- let height2 = radius * radius - foot.dist(c).powi(2);
- if !(radius > 0.0 && height2 >= 0.0) {
- return None;
- }
- let (a, b) = (foot + tangent * height2.sqrt(), foot - tangent * height2.sqrt());
- Some(if a.dist(p) < b.dist(p) { a } else { b })
- };
- match (prev, cur) {
- (Seg::Line { .. }, Seg::Arc { .. }) => line_circle(prev, cur),
- (Seg::Arc { .. }, Seg::Line { .. }) => line_circle(cur, prev),
- (Seg::Arc { a: a0, c: c0, .. }, Seg::Arc { a: a1, c: c1, .. }) => {
- let delta = *c1 - *c0;
- let distance = delta.len();
- let axis = delta.normalized()?;
- let r0 = a0.dist(*c0) + n.cross(prev.tangent(p)?).dot((p - *c0).normalized()?) * d;
- let r1 = a1.dist(*c1) + n.cross(cur.tangent(p)?).dot((p - *c1).normalized()?) * d;
- let along = (r0 * r0 - r1 * r1 + distance * distance) / (2.0 * distance);
- let height2 = r0 * r0 - along * along;
- if !(r0 > 0.0 && r1 > 0.0 && height2 >= 0.0) {
- return None;
- }
- let foot = *c0 + axis * along;
- let across = n.cross(axis) * height2.sqrt();
- let (a, b) = (foot + across, foot - across);
- Some(if a.dist(p) < b.dist(p) { a } else { b })
- }
- _ => None,
- }
-}
-
-/// A curved-wall joint is generally not planar. Fit its exact offset slices rather than
-/// projecting a circular section onto a tangent mitre and revolving that distorted section.
-/// `(r, rw)`: the round's radius (`rw` unused), or a chamfer's setbacks on the face and up the wall.
-fn offset_profile(prev: &Seg, cur: &Seg, n: Vec3, side: f64, (r, rw): (f64, f64), round: bool, tol: f64) -> Result {
- use mt::ParametricCurve;
- let point = |u: f64| {
- let (d, h) = if round {
- let (sin, cos) = (u * std::f64::consts::FRAC_PI_2).sin_cos();
- (r * (1.0 - sin), r * (1.0 - cos))
- } else {
- (r * (1.0 - u), rw * u)
- };
- offset_joint(prev, cur, n, d).map(|p| p + n * (side * h))
- };
- for count in [8, 16, 32, 64, 128] {
- let pts = (0..=count)
- .map(|i| point(f64::from(i) / f64::from(count)))
- .collect::>>()
- .ok_or_else(|| too_large("the blend's offset walls do not meet"))?;
- let curve = crate::build::interpolate_cubic(&pts).ok_or_else(|| unsupported("curved corner profile"))?;
- if (0..count).all(|i| {
- let u = (f64::from(i) + 0.5) / f64::from(count);
- point(u).is_some_and(|p| p.dist(from_p3(curve.subs(u))) <= tol)
- }) {
- return Ok(mt::Curve::BSplineCurve(curve));
- }
- }
- Err(unsupported("could not fit the curved corner within tolerance"))
-}
-
-/// The exact shape of an oriented loop edge (a line, or an arc found from samples).
-fn seg_of(e: &mt::Edge, tol: f64) -> Option {
- use mt::{BoundedCurve, ParametricCurve};
- let (a, b) = (from_p3(e.front().point()), from_p3(e.back().point()));
- let c = e.oriented_curve();
- let (t0, t1) = c.range_tuple();
- let pts: Vec = (0..=16).map(|k| from_p3(c.subs(t0 + (t1 - t0) * k as f64 / 16.0))).collect();
- let closed = a.dist(b) < tol;
- if !closed && pts.iter().all(|p| p.dist_to_segment(a, b) < tol) {
- return Some(Seg::Line { a, b });
- }
- let m = *pts.get(8)?;
- // A closed edge (a full circle): fit through points a third of the way round.
- let (b_fit, m_fit) = if closed { (*pts.get(5)?, *pts.get(11)?) } else { (b, m) };
- let (u, v) = (b_fit - a, m_fit - a);
- let w = u.cross(v);
- let d = 2.0 * w.len2();
- if d < 1e-300 {
- return None;
- }
- let centre = a + (v.cross(w) * u.len2() + w.cross(u) * v.len2()) * (1.0 / d);
- let r = centre.dist(a);
- if !pts.iter().all(|p| (p.dist(centre) - r).abs() < tol) {
- return None;
- }
- // Turning direction: the travel at a is axis × (a − c).
- let t_a = (*pts.get(1)? - a).normalized()?;
- let mut axis = w.normalized()?;
- if axis.cross(a - centre).dot(t_a) < 0.0 {
- axis = -axis;
- }
- let (ra, rb) = ((a - centre).normalized()?, (b - centre).normalized()?);
- let mut angle = ra.dot(rb).clamp(-1.0, 1.0).acos();
- if ra.cross(rb).dot(axis) < 0.0 {
- angle = std::f64::consts::TAU - angle;
- }
- if closed {
- angle = std::f64::consts::TAU;
- }
- Some(Seg::Arc { a, c: centre, axis, angle, mid: m })
-}
-
-/// Whether an edge is a straight segment: a line, or a curve whose points all lie on the chord
-/// (the contact lines of a rolling-ball blend between parallel walls are such curves).
-fn is_straight(e: &mt::Edge, tol: f64) -> bool {
- use mt::{BoundedCurve, ParametricCurve};
- if matches!(e.curve(), mt::Curve::Line(_)) {
- return true;
- }
- let (a, b) = (from_p3(e.absolute_front().point()), from_p3(e.absolute_back().point()));
- if a.dist(b) < tol {
- return false;
- }
- let c = e.curve();
- let (t0, t1) = c.range_tuple();
- (0..=16).all(|k| from_p3(c.subs(t0 + (t1 - t0) * k as f64 / 16.0)).dist_to_segment(a, b) < tol)
-}
-
-/// `p` turned about the line (c, axis) by `ang`.
-fn turn(p: Vec3, c: Vec3, axis: Vec3, ang: f64) -> Vec3 {
- let k = axis.normalized().unwrap_or(Vec3::Z);
- let v = p - c;
- let (s, co) = ang.sin_cos();
- c + v * co + k.cross(v) * s + k * (k.dot(v) * (1.0 - co))
-}
-
-/// Split full circles in two halves (an edge needs two ends).
-fn pieces(segs: &[Seg]) -> Vec<(usize, Seg)> {
- let mut out = Vec::new();
- for (i, s) in segs.iter().enumerate() {
- match *s {
- Seg::Arc { a, c, axis, angle, .. } if angle > std::f64::consts::TAU - 1e-9 => {
- let h = std::f64::consts::PI;
- let a2 = turn(a, c, axis, h);
- out.push((i, Seg::Arc { a, c, axis, angle: h, mid: turn(a, c, axis, h / 2.0) }));
- out.push((i, Seg::Arc { a: a2, c, axis, angle: h, mid: turn(a, c, axis, 1.5 * h) }));
- }
- _ => out.push((i, *s)),
- }
- }
- out
-}
-
-fn plane_normal(f: &mt::Face) -> Option {
- match f.oriented_surface() {
- mt::Surface::Plane(p) => {
- let n = p.normal();
- Vec3::new(n.x, n.y, n.z).normalized()
- }
- _ => None,
- }
-}
-
-/// Outward normal of a face at a point on it.
-fn face_normal(f: &mt::Face, p: Vec3) -> Option {
- use mt::{ParametricSurface3D, SearchNearestParameter, SearchParameter};
- let s = f.oriented_surface();
- let (u, v) = s.search_parameter(p3(p), None, 100).or_else(|| s.search_nearest_parameter(p3(p), None, 100))?;
- let n = s.normal(u, v);
- Vec3::new(n.x, n.y, n.z).normalized()
-}
-
-/// Blend `edges` (by id) if they form a boundary loop or neighbouring run of a planar face with
-/// perpendicular walls, with what it built from `solid` (each blend face in place of its loop
-/// edge). `None` when the edges are not such a loop.
-pub(crate) fn loop_blend(solid: &Solid, edge_ids: &[mt::EdgeID], size: f64, r: f64, round: bool) -> Option> {
- loop_blend_sized(solid, edge_ids, size, Sizing::Equal { r, round })
-}
-
-/// [`loop_blend`] as a chamfer of `d1` on its first face and the second side by `side`. The
-/// first face is the one facing up most (the planar face or its wall, decided as for a straight
-/// edge, see [`crate::chamfer_sides`]), the other one with `flip`.
-pub(crate) fn loop_chamfer_sides(
- solid: &Solid,
- edge_ids: &[mt::EdgeID],
- size: f64,
- d1: f64,
- side: ChamferSide,
- flip: bool,
-) -> Option> {
- loop_blend_sized(solid, edge_ids, size, Sizing::Sides { d1, side, flip })
-}
-
-/// How large a loop blend is.
-#[derive(Clone, Copy, Debug)]
-enum Sizing {
- /// A round of radius `r` (`round`), or an equal-distance chamfer of `r`.
- Equal { r: f64, round: bool },
- /// A chamfer of `d1` on its first face, the second side by `side` ([`loop_chamfer_sides`]).
- Sides { d1: f64, side: ChamferSide, flip: bool },
-}
-
-fn loop_blend_sized(solid: &Solid, edge_ids: &[mt::EdgeID], size: f64, sizing: Sizing) -> Option> {
- match crate::guard("loop blend", || Ok(loop_blend_inner(solid, edge_ids, size, sizing))) {
- Ok(result) => result,
- Err(error) => Some(Err(error)),
- }
-}
-
-fn loop_blend_inner(solid: &Solid, edge_ids: &[mt::EdgeID], size: f64, sizing: Sizing) -> Option> {
- #[cfg(test)]
- assert!(crate::guarded(), "loop selection must run inside the kernel guard");
- let tol = (size * 1e-6).max(1e-7);
- for (si, shell) in solid.boundaries().iter().enumerate() {
- let faces: Vec<&mt::Face> = shell.face_iter().collect();
- for (fi, f) in faces.iter().enumerate() {
- let Some(n) = plane_normal(f) else { continue };
- for (wi, w) in f.boundaries().iter().enumerate() {
- let ids: Vec = w.edge_iter().map(|e| e.id()).collect();
- if !edge_ids.iter().all(|e| ids.contains(e)) {
- continue;
- }
- if ids.len() == edge_ids.len() {
- return Some(build(solid, si, &faces, fi, wi, n, size, tol, sizing, None));
- }
- // A run of neighbouring edges of the loop (its ends meet unblended edges).
- let m = ids.len();
- let inside = |i: usize| ids.get(i % m).is_some_and(|x| edge_ids.contains(x));
- let starts: Vec = (0..m).filter(|i| inside(*i) && !inside(*i + m - 1)).collect();
- if let [s0] = starts[..]
- && (0..edge_ids.len()).all(|j| inside(s0 + j))
- {
- return Some(build(solid, si, &faces, fi, wi, n, size, tol, sizing, Some((s0, edge_ids.len()))));
- }
- }
- }
- }
- None
-}
-
-#[allow(clippy::too_many_arguments)]
-fn build(
- solid: &Solid,
- si: usize,
- faces: &[&mt::Face],
- fi: usize,
- wi: usize,
- n: Vec3,
- size: f64,
- tol: f64,
- sizing: Sizing,
- run: Option<(usize, usize)>,
-) -> Result<(Solid, Rebuild)> {
- #[cfg(test)]
- assert!(crate::guarded(), "loop construction must run inside the kernel guard");
- // `r`: the round's radius or the equal chamfer's size; an unequal chamfer's first distance
- // (its setbacks come from `frame`).
- let (r, round, sides) = match sizing {
- Sizing::Equal { r, round } => (r, round, None),
- Sizing::Sides { d1, side, flip } => (d1, false, Some((side, flip))),
- };
- let f = faces.get(fi).ok_or_else(|| KernelError::Failed("face".into()))?;
- let wire = f.boundaries().get(wi).cloned().ok_or_else(|| KernelError::Failed("loop".into()))?;
- let all_edges: Vec = wire.edge_iter().cloned().collect();
- // The blended edges in loop order: the whole loop, or a run of it (open).
- let open = run.is_some();
- let edges: Vec = match run {
- None => all_edges,
- Some((s0, len)) => (0..len).filter_map(|j| all_edges.get((s0 + j) % all_edges.len().max(1)).cloned()).collect(),
- };
- let edge_segs: Vec = edges
- .iter()
- .map(|e| seg_of(e, (size * 1e-5).max(1e-6)))
- .collect::>()
- .ok_or_else(|| unsupported("loop edges must be lines or arcs"))?;
- // Pieces: the loop's edges, full circles in halves; each knows its edge.
- let split = pieces(&edge_segs);
- let owner: Vec = split.iter().map(|x| x.0).collect();
- let segs: Vec = split.iter().map(|x| x.1).collect();
- let k = segs.len();
- // Joints: k round a whole loop; k + 1 along a run (its two ends included).
- let nj = if open { k + 1 } else { k };
- let nxt = |i: usize| if open { i + 1 } else { (i + 1) % k };
- // Joints: smooth, or sharp where the walls meet in one straight seam (the blends
- // then meet in a mitre). A loop can therefore mix lines and arcs at its corners.
- let mut mitre = vec![false; nj];
- for i in 0..k {
- if open && i == 0 {
- continue;
- }
- let (Some(prev), Some(cur)) = (segs.get((i + k - 1) % k), segs.get(i)) else { continue };
- let p = cur.start();
- let (Some(ta), Some(tb)) = (prev.tangent(p), cur.tangent(p)) else { return Err(unsupported("degenerate loop edge")) };
- if ta.dot(tb) < 1.0 - 1e-6 {
- if ta.dot(tb) < -1.0 + 1e-3 {
- return Err(unsupported("blending a loop with sharp corners next to arcs"));
- }
- if let Some(x) = mitre.get_mut(i) {
- *x = true;
- }
- }
- }
- // Walls: the other face of each edge, perpendicular to the face; all on one side.
- let mut walls: Vec = Vec::with_capacity(k);
- let mut side = 0.0;
- for (oi, s) in owner.iter().zip(&segs) {
- let e = edges.get(*oi).ok_or_else(|| KernelError::Failed("edge".into()))?;
- let wf = faces
- .iter()
- .position(|g| !std::ptr::eq(*g, *f) && g.edge_iter().any(|x| x.id() == e.id()))
- .ok_or_else(|| unsupported("an edge with one face"))?;
- let mid = match *s {
- Seg::Line { a, b } => (a + b) * 0.5,
- Seg::Arc { mid, .. } => mid,
- };
- let g = faces.get(wf).ok_or_else(|| KernelError::Failed("wall".into()))?;
- let gn = face_normal(g, mid).ok_or_else(|| unsupported("wall normal"))?;
- if gn.dot(n).abs() > 1.0 - 1e-6 {
- return Err(unsupported("a wall tangent to the face"));
- }
- // Into the face from the loop: left of travel.
- let m = n.cross(s.tangent(mid).ok_or_else(|| unsupported("tangent"))?);
- let sd = if gn.dot(m) > 0.0 { 1.0 } else { -1.0 };
- if side != 0.0 && sd != side {
- return Err(unsupported("a loop that is partly convex and partly concave"));
- }
- side = sd;
- walls.push(wf);
- }
- // A run ends in the cross-section through its end vertex: the face there must hold it (a
- // plane square to the run). One at an angle cuts the blend's two contacts at different
- // places, which the rolling-ball blend handles.
- if open {
- let ends = [
- (edges.first().map(|e| e.front().clone()), segs.first().map(|s| (s.start(), *s))),
- (edges.last().map(|e| e.back().clone()), segs.last().map(|s| (s.end(), *s))),
- ];
- for (v, seg) in ends {
- let (Some(v), Some((p, s))) = (v, seg) else { return Err(KernelError::Failed("run end".into())) };
- let t = s.tangent(p).ok_or_else(|| unsupported("degenerate loop edge"))?;
- let square = faces
- .iter()
- .enumerate()
- .filter(|(gi, g)| *gi != fi && !walls.contains(gi) && g.vertex_iter().any(|x| x == v))
- .all(|(_, g)| plane_normal(g).is_some_and(|gn| gn.dot(t).abs() > 1.0 - 1e-6));
- if !square {
- return Err(unsupported("a run of edges ending at a face at an angle"));
- }
- }
- }
- // Cross-section at a loop point: into the face (m) and up the wall (t, away from the edge,
- // up a concave wall and down a convex one). The ball of radius r touches both at the
- // setback s = r / tan(φ/2), φ the angle between m and t; its centre is on the bisector.
- let into = |s: &Seg, p: Vec3| -> Vec3 { s.tangent(p).map(|t| n.cross(t)).unwrap_or(Vec3::ZERO) };
- let up = |i: usize, p: Vec3| -> Option {
- let s = segs.get(i)?;
- let g = faces.get(*walls.get(i)?)?;
- let gn = face_normal(g, p)?;
- let t = s.tangent(p)?.cross(gn).normalized()?;
- Some(if t.dot(n * side) < 0.0 { -t } else { t })
- };
- // An unequal chamfer: whether its first side is the planar face (else the walls). As for a
- // straight edge, that is the one facing up most (a curved wall by its mean normal along each
- // edge), the other with `flip`; it must be the same all round the loop.
- let face_first = match sides {
- None => true,
- Some((_, flip)) => {
- use mt::{BoundedCurve, ParametricCurve};
- let up = Vec3::new(1e-6, 1e-3, 1.0);
- let face_up = n.dot(up);
- let mut first: Option = None;
- for (pi, oi) in owner.iter().enumerate() {
- if pi > 0 && owner.get(pi - 1) == Some(oi) {
- continue;
- }
- let (Some(e), Some(g)) = (edges.get(*oi), walls.get(pi).and_then(|w| faces.get(*w))) else {
- return Err(KernelError::Failed("loop edge".into()));
- };
- let c = e.curve();
- let (t0, t1) = c.range_tuple();
- let ups: Vec =
- (0..=8).filter_map(|j| face_normal(g, from_p3(c.subs(t0 + (t1 - t0) * f64::from(j) / 8.0))).map(|gn| gn.dot(up))).collect();
- if ups.is_empty() {
- return Err(unsupported("wall normal"));
- }
- let wall_up = ups.iter().sum::() / ups.len() as f64;
- let mine = (face_up >= wall_up) != flip;
- if first.is_some_and(|x| x != mine) {
- return Err(unsupported(
- "an unequal chamfer round a loop whose first face changes along it (the face faces up more than some walls and less than others)",
- ));
- }
- first = Some(mine);
- }
- first.unwrap_or(true)
- }
- };
- // Into the face (m), up the wall (t), the setbacks along each and the distance from the edge
- // to a round's centre.
- let frame = |i: usize, p: Vec3| -> Option<(Vec3, Vec3, f64, f64, f64)> {
- let s = segs.get(i)?;
- let (m, t) = (into(s, p), up(i, p)?);
- let phi = m.dot(t).clamp(-1.0, 1.0).acos();
- if !(phi > 1e-3 && phi < std::f64::consts::PI - 1e-3) {
- return None;
- }
- let (sf, sw) = match sides {
- None => {
- let sb = if round { r / (phi / 2.0).tan() } else { r };
- (sb, sb)
- }
- Some((cs, _)) => {
- let d2 = match cs {
- ChamferSide::Distance(d) => d,
- // The triangle edge–A–B: angle φ at the edge, `a` at A (on the first side).
- ChamferSide::Angle(a) => {
- let den = (phi + a).sin();
- if den <= 1e-9 {
- return None;
- }
- r * a.sin() / den
- }
- };
- if face_first { (r, d2) } else { (d2, r) }
- }
- };
- Some((m, t, sf, sw, r / (phi / 2.0).sin()))
- };
- if let Some((ChamferSide::Angle(a), _)) = sides {
- for (i, s) in segs.iter().enumerate() {
- let p = s.start();
- if let Some(t) = up(i, p)
- && (into(s, p).dot(t).clamp(-1.0, 1.0).acos() + a).sin() <= 1e-9
- {
- return Err(KernelError::Invalid("that chamfer angle runs past the other face".into()));
- }
- }
- }
- // The straight seam between the walls at a sharp joint (direction away from the face).
- let seam_dir = |i: usize, p: Vec3| -> Option {
- let o = owner.get(i)?;
- let v = edges.get(*o)?.front().clone();
- let loop_ids: Vec = edges.iter().map(|e| e.id()).collect();
- let mut dirs = Vec::new();
- for g in faces {
- for e in g.edge_iter() {
- if loop_ids.contains(&e.id()) || !(*e.front() == v || *e.back() == v) {
- continue;
- }
- let other = if *e.front() == v { e.back().clone() } else { e.front().clone() };
- if let Some(d) = (from_p3(other.point()) - p).normalized()
- && !dirs.iter().any(|x: &Vec3| x.dot(d) > 1.0 - 1e-9)
- {
- dirs.push(d);
- }
- }
- }
- match dirs[..] {
- [d] => Some(d),
- _ => None,
- }
- };
- let mut pa = Vec::with_capacity(nj);
- let mut pb = Vec::with_capacity(nj);
- let mut centres = Vec::with_capacity(nj);
- let mut curved_joint = vec![false; nj];
- // Joint i: the start of piece i (the end of the last piece for a run's far end).
- let joint_point = |i: usize| if i < k { segs.get(i).map(|s| s.start()) } else { segs.last().map(|s| s.end()) };
- for i in 0..nj {
- let p = joint_point(i).unwrap_or_default();
- let (m, t, sb, sbw, dc) = frame(i.min(k - 1), p).ok_or_else(|| unsupported("the face and wall meet at an angle the blend can't take"))?;
- centres.push(p + (m + t).normalized().unwrap_or(m) * dc);
- if !mitre.get(i).copied().unwrap_or(false) {
- pa.push(p + m * sb);
- pb.push(p + t * sbw);
- continue;
- }
- // Sharp joint: the face rails meet where the two offset lines cross; the wall rails
- // meet on the seam.
- let ip = (i + k - 1) % k;
- let (m0, t0, sb0, sbw0, _) = frame(ip, p).ok_or_else(|| unsupported("the face and wall meet at an angle the blend can't take"))?;
- let (Some(d0), Some(d1)) = (segs.get(ip).and_then(|x| x.tangent(p)), segs.get(i).and_then(|x| x.tangent(p))) else {
- return Err(unsupported("degenerate loop edge"));
- };
- let x = d0.cross(d1);
- let lam = ((m * sb - m0 * sb0).cross(d1)).dot(x) / x.len2();
- let exact = (matches!(segs.get(ip), Some(Seg::Arc { .. })) || matches!(segs.get(i), Some(Seg::Arc { .. })))
- && t.dot(n * side) > 1.0 - 1e-9
- && t0.dot(n * side) > 1.0 - 1e-9;
- if exact {
- let (Some(prev), Some(cur)) = (segs.get(ip), segs.get(i)) else { return Err(unsupported("corner segments")) };
- pa.push(
- offset_joint(prev, cur, n, if sides.is_some() { sb } else { r }).ok_or_else(|| too_large("the blend's offset walls do not meet"))?,
- );
- if let Some(slot) = curved_joint.get_mut(i) {
- *slot = true;
- }
- } else {
- pa.push(p + m0 * sb0 + d0 * lam);
- }
- let e = seam_dir(i, p).ok_or_else(|| unsupported("a sharp corner without one straight seam"))?;
- let (h0, h1) = (e.dot(t0), e.dot(t));
- if h0 < 1e-6 || h1 < 1e-6 || (sbw0 / h0 - sbw / h1).abs() > tol * 10.0 {
- return Err(unsupported("a sharp corner whose walls meet the blend differently"));
- }
- pb.push(p + e * (sbw / h1));
- }
- // Sharp joints between straight rim edges can extend beyond the old corner.
- // Equal wall slopes reach this path instead of the corner builder, and must
- // also reject an extension through the outer wall or another hole.
- for (i, q) in pa.iter().enumerate() {
- // Smooth arc transitions and open-run ends retain their existing checks.
- if !mitre.get(i).copied().unwrap_or(false) {
- continue;
- }
- let p = joint_point(i).ok_or_else(|| unsupported("degenerate loop joint"))?;
- if !crate::blend::extension_fits(f, p, *q, size * 1e-7) {
- return Err(too_large("the blend is larger than the neighbouring faces"));
- }
- }
- // The offset arcs must not turn inside out; an arc of exactly the blend's radius shrinks
- // to a point (a rounded corner rounded again: the blend there is a sphere).
- let mut collapsed = vec![false; k.max(nj)];
- for (i, s) in segs.iter().enumerate() {
- if let Seg::Arc { a, c, .. } = *s {
- let toward = into(s, a).dot(c - a) > 0.0;
- // An unequal chamfer's offset on the face; it never ends in a point (a cone's apex).
- if sides.is_some() {
- let reach = frame(i, a).map(|x| x.2).ok_or_else(|| unsupported("the face and wall meet at an angle the blend can't take"))?;
- if toward && a.dist(c) <= reach + tol * 10.0 {
- return Err(too_large("the chamfer is larger than a corner radius"));
- }
- continue;
- }
- if toward && (a.dist(c) - r).abs() <= tol * 10.0 && !mitre.get(i).copied().unwrap_or(true) && !mitre.get(nxt(i)).copied().unwrap_or(true)
- {
- if let Some(x) = collapsed.get_mut(i) {
- *x = true;
- }
- } else if toward && a.dist(c) <= r + tol {
- return Err(too_large("the blend is larger than a corner radius"));
- }
- }
- }
- if collapsed.iter().all(|x| *x) {
- return Err(too_large("the blend is larger than a corner radius"));
- }
- let mut va: Vec = pa.iter().map(|p| builder::vertex(p3(*p))).collect();
- // A collapsed piece starts and ends at one vertex.
- for i in 0..k {
- if collapsed.get(i).copied().unwrap_or(false)
- && let Some(v) = va.get(i).cloned()
- && let Some(slot) = va.get_mut(nxt(i))
- {
- *slot = v;
- }
- }
- // Model vertices at the joints (the second half of a circle starts at none).
- let mut joint_vertex: Vec> = (0..k)
- .map(|i| if i == 0 || owner.get(i) != owner.get(i - 1) { owner.get(i).and_then(|o| edges.get(*o)).map(|e| e.front().clone()) } else { None })
- .collect();
- if open {
- joint_vertex.push(edges.last().map(|e| e.back().clone()));
- }
- let loop_ids: Vec = edges.iter().map(|e| e.id()).collect();
- let on_face = |e: &mt::Edge| f.edge_iter().any(|x| x.id() == e.id());
- // A blend as tall as its walls uses them up: each wall seam ends exactly where the
- // wall-side rail would, at a vertex of the walls' far boundary, which becomes the rail.
- let wall_end: Vec> = joint_vertex
- .iter()
- .zip(&pb)
- .map(|(v, target)| {
- let v = v.as_ref()?;
- faces.iter().flat_map(|g| g.edge_iter()).find_map(|e| {
- if loop_ids.contains(&e.id()) || on_face(&e) || !(e.front() == v || e.back() == v) || !matches!(e.curve(), mt::Curve::Line(_)) {
- return None;
- }
- let other = if e.front() == v { e.back().clone() } else { e.front().clone() };
- (from_p3(other.point()).dist(*target) <= tol * 10.0).then_some(other)
- })
- })
- .collect();
- let used_up = wall_end.iter().filter(|x| x.is_some()).count();
- if used_up > 0 && (used_up != nj || open) {
- return Err(unsupported("the blend uses up only part of the walls"));
- }
- let walls_used_up = used_up > 0;
- let vb: Vec = match walls_used_up {
- true => wall_end.into_iter().flatten().collect(),
- false => pb.iter().map(|p| builder::vertex(p3(*p))).collect(),
- };
- let centre = |i: usize| centres.get(i).copied().unwrap_or_default();
- let profile_mid = |i: usize| {
- let (Some(p), c) = (joint_point(i), centre(i)) else { return Vec3::ZERO };
- c + (p - c).normalized().unwrap_or(n) * r
- };
- // Profiles at the joints (face side → wall side).
- let mut profiles: Vec = Vec::with_capacity(nj);
- for i in 0..nj {
- let (Some(a), Some(b)) = (va.get(i), vb.get(i)) else { return Err(KernelError::Failed("joint".into())) };
- if curved_joint.get(i).copied().unwrap_or(false) {
- let (Some(prev), Some(cur)) = (segs.get((i + k - 1) % k), segs.get(i)) else { return Err(unsupported("corner segments")) };
- let setbacks = match sides {
- None => (r, r),
- Some(_) => joint_point(i).and_then(|p| frame(i.min(k - 1), p)).map(|x| (x.2, x.3)).ok_or_else(|| unsupported("frame"))?,
- };
- let curve = offset_profile(prev, cur, n, side, setbacks, round, (setbacks.0.min(setbacks.1) * 1e-7).max(1e-9))?;
- profiles.push(mt::Edge::try_new(a, b, curve).map_err(|e| KernelError::Failed(format!("curved corner: {e}")))?);
- continue;
- }
- if !round {
- profiles.push(builder::line(a, b));
- continue;
- }
- if !mitre.get(i).copied().unwrap_or(false) {
- profiles.push(builder::circle_arc(a, b, p3(profile_mid(i))));
- continue;
- }
- // Mitre: the cross-section circle of this edge's blend where it passes the face-side
- // point, slid along the edge onto the mitre plane (an ellipse arc, on both blends).
- let p = segs.get(i).map(|x| x.start()).unwrap_or_default();
- let d1 = segs.get(i).and_then(|x| x.tangent(p)).ok_or_else(|| unsupported("tangent"))?;
- let (pa_i, pb_i) = (from_p3(a.point()), from_p3(b.point()));
- let lam = (pa_i - p).dot(d1);
- let (_, t, sb, _, _) = frame(i, p).ok_or_else(|| unsupported("frame"))?;
- let cc = centre(i) + d1 * lam;
- let q = p + t * sb + d1 * lam;
- let mid = cc + ((pa_i - cc) + (q - cc)).normalized().unwrap_or(t) * r;
- // q projects onto the wall rail at pb_i; fitting through pb_i before projection
- // would distort the circular cross-section at mixed line/arc corners.
- let arc = builder::circle_arc(&builder::vertex(p3(pa_i)), &builder::vertex(p3(q)), p3(mid));
- let nb = (pa_i - p).cross(pb_i - p).normalized().ok_or_else(|| unsupported("mitre plane"))?;
- let den = d1.dot(nb);
- if den.abs() < 1e-9 {
- return Err(unsupported("mitre plane along the edge"));
- }
- // x ↦ x − d1 ((x − p)·nb) / (d1·nb), column-major.
- let col = |j: usize| {
- let ej = [Vec3::X, Vec3::Y, Vec3::Z][j];
- ej - d1 * (ej.dot(nb) / den)
- };
- let (c0, c1, c2) = (col(0), col(1), col(2));
- let tr = d1 * (p.dot(nb) / den);
- let mat = mt::Matrix4::new(c0.x, c0.y, c0.z, 0.0, c1.x, c1.y, c1.z, 0.0, c2.x, c2.y, c2.z, 0.0, tr.x, tr.y, tr.z, 1.0);
- let mut curve = arc.curve();
- mt::Transformed::transform_by(&mut curve, mat);
- profiles.push(mt::Edge::new(a, b, curve));
- }
- let rail = |vs: &[mt::Vertex], i: usize, offset: &dyn Fn(Vec3, &Seg) -> Vec3| -> Option {
- let s = segs.get(i)?;
- if std::ptr::eq(vs, va.as_slice()) && collapsed.get(i).copied().unwrap_or(false) {
- return None;
- }
- let (a, b) = (vs.get(i)?, vs.get(nxt(i))?);
- Some(match *s {
- Seg::Line { .. } => builder::line(a, b),
- Seg::Arc { mid, .. } => builder::circle_arc(a, b, p3(offset(mid, s))),
- })
- };
- let piece_of = |s: &Seg| segs.iter().position(|x| std::ptr::eq(x, s)).unwrap_or(0);
- let face_off = |p: Vec3, s: &Seg| {
- let i = piece_of(s);
- frame(i, p).map(|(m, _, sb, _, _)| p + m * sb).unwrap_or(p)
- };
- let wall_off = |p: Vec3, s: &Seg| {
- let i = piece_of(s);
- frame(i, p).map(|(_, t, _, sbw, _)| p + t * sbw).unwrap_or(p)
- };
- let face_rails: Vec> = (0..k).map(|i| rail(&va, i, &face_off)).collect();
- if face_rails.iter().zip(&collapsed).any(|(r, c)| r.is_none() && !c) {
- return Err(KernelError::Failed("rail".into()));
- }
- let wall_rails: Vec = if walls_used_up {
- // Each piece's wall rail is the wall's far edge between the joints, where the offset
- // rail lies (checked at the piece's middle).
- (0..k)
- .map(|i| -> Result {
- let (Some(a), Some(b), Some(s), Some(wf)) = (vb.get(i), vb.get(nxt(i)), segs.get(i), walls.get(i)) else {
- return Err(KernelError::Failed("rail".into()));
- };
- let mid = match *s {
- Seg::Line { a, b } => (a + b) * 0.5,
- Seg::Arc { mid, .. } => mid,
- };
- let want = wall_off(mid, s);
- let g = faces.get(*wf).ok_or_else(|| KernelError::Failed("wall".into()))?;
- g.edge_iter()
- .find(|e| (e.front() == a && e.back() == b) || (e.front() == b && e.back() == a))
- .filter(|e| crate::blend::edge_mid(e).is_some_and(|m| m.dist(want) <= tol * 10.0))
- .map(|e| if e.front() == a { e.clone() } else { e.inverse() })
- .ok_or_else(|| unsupported("the blend uses up walls whose far edge is not where the blend ends"))
- })
- .collect::>()?
- } else {
- (0..k).map(|i| rail(&vb, i, &wall_off)).collect::>().ok_or_else(|| KernelError::Failed("rail".into()))?
- };
- // Seams between neighbouring walls at the joints get shorter.
- // At a run's ends the face's next loop edges stop at the face-side point.
- let mut seam_subst: HashMap = HashMap::new();
- let mut seam_ends: HashMap, Option)> = HashMap::new();
- for (i, v) in joint_vertex.iter().enumerate() {
- let Some(v) = v else { continue };
- for g in faces {
- for e in g.edge_iter() {
- if loop_ids.contains(&e.id()) || !(e.front() == v || e.back() == v) {
- continue;
- }
- // Once per edge and joint (an edge between both ends of a run is met twice).
- if seam_ends.get(&e.id()).is_some_and(|x: &(mt::Edge, Option, Option)| {
- (x.0.absolute_front() == v && x.1.is_some()) || (x.0.absolute_back() == v && x.2.is_some())
- }) {
- continue;
- }
- let (fa, fb) = (e.absolute_front().clone(), e.absolute_back().clone());
- let other = if &fa == v { &fb } else { &fa };
- if !is_straight(&e, (size * 1e-5).max(1e-6)) {
- return Err(unsupported("the wall seams must be straight"));
- }
- let face_side = on_face(&e);
- // A used-up wall goes, seams and all.
- if walls_used_up && !face_side {
- continue;
- }
- let target = if face_side { pa.get(i) } else { pb.get(i) }.copied().unwrap_or_default();
- let along = (from_p3(other.point()) - from_p3(v.point())).dot(target - from_p3(v.point()));
- let reach = (target - from_p3(v.point())).len2();
- if along <= reach + tol {
- return Err(too_large(if face_side { "the blend is longer than the next edge" } else { "the blend is taller than the walls" }));
- }
- let nb = if face_side { va.get(i) } else { vb.get(i) }.ok_or_else(|| KernelError::Failed("joint".into()))?;
- let slot = seam_ends.entry(e.id()).or_insert_with(|| (e.absolute_clone(), None, None));
- if &fa == v {
- slot.1 = Some(nb.clone());
- } else {
- slot.2 = Some(nb.clone());
- }
- }
- }
- }
- for (id, (e, a, b)) in seam_ends {
- let a = a.unwrap_or_else(|| e.absolute_front().clone());
- let b = b.unwrap_or_else(|| e.absolute_back().clone());
- if from_p3(a.point()).dist(from_p3(b.point())) < tol * 10.0 {
- return Err(too_large("the blend is longer than the next edge"));
- }
- seam_subst.insert(id, builder::line(&a, &b));
- }
- // Rebuild faces.
- let idx_of = |id: mt::EdgeID| loop_ids.iter().position(|x| *x == id);
- let rebuild = |g: &mt::Face, rails: &[Option]| -> Result {
- let mut wires = Vec::new();
- for w in g.absolute_boundaries() {
- let mut es = Vec::new();
- for e in w.edge_iter() {
- if let Some(i) = idx_of(e.id()) {
- // Rails run in loop order; an edge used the other way takes them reversed.
- let mine: Vec<&mt::Edge> = owner.iter().zip(rails).filter(|(o, _)| **o == i).filter_map(|(_, r)| r.as_ref()).collect();
- let same = edges.get(i).is_some_and(|le| le.orientation() == e.orientation());
- if same {
- es.extend(mine.into_iter().cloned());
- } else {
- es.extend(mine.into_iter().rev().map(|r| r.inverse()));
- }
- continue;
- }
- let ne = if let Some(s) = seam_subst.get(&e.id()) {
- if e.front() == e.absolute_front() { s.clone() } else { s.inverse() }
- } else {
- e.clone()
- };
- es.push(ne);
- }
- // A run's end: the face's edge and the wall's seam now stop at the two ends of the
- // end profile, which closes the gap between them.
- if open {
- let mut fixed: Vec = Vec::with_capacity(es.len() + 2);
- let m = es.len();
- for j in 0..m {
- let (Some(cur), Some(next)) = (es.get(j), es.get((j + 1) % m)) else { continue };
- fixed.push(cur.clone());
- if cur.back() == next.front() {
- continue;
- }
- for ji in [0, nj - 1] {
- let (Some(a), Some(b), Some(pr)) = (va.get(ji), vb.get(ji), profiles.get(ji)) else { continue };
- if cur.back() == a && next.front() == b {
- fixed.push(pr.clone());
- } else if cur.back() == b && next.front() == a {
- fixed.push(pr.inverse());
- }
- }
- }
- es = fixed;
- }
- wires.push(mt::Wire::from(es));
- }
- crate::heal::absolute_face(g, wires).ok_or_else(|| KernelError::Failed("loop blend: a face could not be rebuilt".into()))
- };
- let mut out: Vec = Vec::new();
- let mut rec = Rebuild::default();
- rec.pieces(&seam_subst);
- for (gi, g) in faces.iter().enumerate() {
- let rebuilt = if gi == fi {
- rebuild(g, &face_rails)?
- } else if walls.contains(&gi) {
- if walls_used_up {
- continue;
- }
- let wr: Vec> = wall_rails.iter().cloned().map(Some).collect();
- rebuild(g, &wr)?
- } else if g.edge_iter().any(|e| seam_subst.contains_key(&e.id())) {
- rebuild(g, &[])?
- } else {
- (*g).clone()
- };
- rec.face(&rebuilt, g);
- out.push(rebuilt);
- }
- // Blend faces.
- use mt::{ParametricSurface3D, SearchNearestParameter};
- for i in 0..k {
- let (Some(s), Some(pr), Some(pr_next), Some(fr), Some(wr)) =
- (segs.get(i), profiles.get(i), profiles.get(nxt(i)), face_rails.get(i), wall_rails.get(i))
- else {
- continue;
- };
- let swept: mt::Shell = match *s {
- Seg::Line { a, b } => {
- // The cross-section at the start, swept along the whole edge and beyond (the
- // face may reach past the edge's ends at a mitre).
- let d = (b - a).normalized().ok_or_else(|| unsupported("degenerate loop edge"))?;
- let (_, t, sb, sbw, _) = frame(i, a).ok_or_else(|| unsupported("frame"))?;
- let m = into(s, a);
- let ext = size;
- let back = d * -ext;
- let (fa, wa) = (builder::vertex(p3(a + m * sb + back)), builder::vertex(p3(a + t * sbw + back)));
- let base = if round { builder::circle_arc(&fa, &wa, p3(profile_mid(i) + back)) } else { builder::line(&fa, &wa) };
- vec![builder::tsweep(&base, v3(b - a + d * (2.0 * ext)))].into()
- }
- Seg::Arc { .. } if collapsed.get(i).copied().unwrap_or(false) => {
- // A sphere about the profile's centre, its poles well away from the corner
- // patch (a pole inside a face's corner confuses the meshing).
- let c = centre(i);
- let corners = [from_p3(pr.front().point()), from_p3(pr.back().point()), from_p3(pr_next.back().point())];
- let g = corners.iter().fold(Vec3::ZERO, |acc, q| acc + (*q - c).normalized().unwrap_or(Vec3::ZERO));
- let g = g.normalized().ok_or_else(|| unsupported("sphere corner"))?;
- let w = g.any_perp();
- let (top, eq, bottom) = (builder::vertex(p3(c + w * r)), p3(c + g * r), builder::vertex(p3(c - w * r)));
- let meridian = builder::circle_arc(&top, &bottom, eq);
- builder::rsweep(&meridian, p3(c), v3(w), mt::Rad(std::f64::consts::TAU))
- }
- Seg::Arc { c, axis, angle, .. }
- if !curved_joint.get(i).copied().unwrap_or(false) && !curved_joint.get(nxt(i)).copied().unwrap_or(false) =>
- {
- builder::rsweep(pr, p3(c), v3(axis), mt::Rad(angle))
- }
- Seg::Arc { a, c, axis, angle, .. } => {
- // Sweep a radial section, not the shared corner curve: the latter can be
- // nonplanar and would change the round's radius all along this edge.
- let (_, t, sb, sbw, _) = frame(i, a).ok_or_else(|| unsupported("frame"))?;
- let (fa, wa) = (builder::vertex(p3(a + into(s, a) * sb)), builder::vertex(p3(a + t * sbw)));
- let base = if round { builder::circle_arc(&fa, &wa, p3(profile_mid(i))) } else { builder::line(&fa, &wa) };
- builder::rsweep(&base, p3(c), v3(axis), mt::Rad(angle))
- }
- };
- let mut surf = swept.face_iter().next().map(|x| x.oriented_surface()).ok_or_else(|| KernelError::Failed("blend surface".into()))?;
- // Outward: toward the profile centre on a concave loop, away from it on a convex one.
- // An unequal chamfer's profile has no centre: its middle, away from the edge on a concave
- // loop (where the chamfer fills) and toward it on a convex one.
- let (c, mid) = (centre(i), profile_mid(i));
- let (mid, outward) = match (sides, joint_point(i)) {
- (Some(_), Some(p)) => {
- let m = (from_p3(pr.front().point()) + from_p3(pr.back().point())) * 0.5;
- (m, (m - p) * side)
- }
- _ => (mid, (c - mid) * side),
- };
- if let Some((u, v)) = surf.search_nearest_parameter(p3(mid), None, 100) {
- let nn = surf.normal(u, v);
- if Vec3::new(nn.x, nn.y, nn.z).dot(outward) < 0.0 {
- surf = mt::Invertible::inverse(&surf);
- }
- }
- let w: mt::Wire = match fr {
- Some(fr) => vec![fr.inverse(), pr.clone(), wr.clone(), pr_next.inverse()].into(),
- None => vec![pr.clone(), wr.clone(), pr_next.inverse()].into(),
- };
- let face = mt::Face::try_new(vec![w.clone()], surf.clone()).map_err(|e| KernelError::Failed(format!("blend face: {e}")))?;
- // In place of the loop edge this piece runs along (a full circle's two halves both).
- rec.blend(&face, owner.get(i).and_then(|o| edges.get(*o)).map(|e| e.id()));
- out.push(face);
- }
- let mut shells = solid.boundaries().clone();
- if let Some(sh) = shells.get_mut(si) {
- *sh = out.into();
- }
- let solid = Solid::try_new(shells).map_err(|e| KernelError::Failed(format!("loop blend produced an invalid solid: {e}")))?;
- Ok((solid, rec))
-}