* claim: #2570 * Loft: a circle lofted to a non-star-shaped profile is split once round (#2570) A circle section was split at the lead section's vertex directions, kept in the lead's order and forced to increase by whole turns. A non-star-shaped lead (a C, a comb) turns back on itself, so the circle wound round many times and closed with a negative arc: self-crossing walls and a huge mesh (which froze the web build while meshing it). The circle is now split exactly once round: at the lead's directions when they go round once in order (clockwise on a plane facing the other way), otherwise at the lead's perimeter fractions, evenly as the fallback. Every arc is finite and positive and they total one turn; the unbounded loop is gone. Section preparation is split out as loft_section_loops so the resampled sections can be checked.
This commit is contained in:
+36
-10
@@ -1986,6 +1986,19 @@ fn loft_reversed(sections: &[(Plane, Loop2)]) -> Result<bool> {
|
||||
}
|
||||
|
||||
fn loft_numbered_wires(sections: &[(Plane, NumberedLoop)], reversed: bool) -> Result<(Vec<mt::Wire>, Vec<Vec<Vec<usize>>>)> {
|
||||
let mut wires: Vec<mt::Wire> = Vec::new();
|
||||
// Per section, the profile segments under each of its wire's edges.
|
||||
let mut edge_sources: Vec<Vec<Vec<usize>>> = Vec::new();
|
||||
for (p, r) in loft_section_loops(sections, reversed)? {
|
||||
wires.push(uniform_wire(&p, &r.lp)?);
|
||||
edge_sources.push(r.from);
|
||||
}
|
||||
Ok((wires, edge_sources))
|
||||
}
|
||||
|
||||
/// The sections of a loft as the wires are built from them: in loft order, oriented alike,
|
||||
/// re-split to the same number of segments and started where they line up best.
|
||||
pub(crate) fn loft_section_loops(sections: &[(Plane, NumberedLoop)], reversed: bool) -> Result<Vec<(Plane, NumberedLoop)>> {
|
||||
let n = sections.iter().map(|(_, l)| l.lp.segs.len()).max().unwrap_or(0);
|
||||
if n == 0 || n > MAX_SEGS {
|
||||
return Err(KernelError::Invalid("empty section".into()));
|
||||
@@ -2019,18 +2032,32 @@ fn loft_numbered_wires(sections: &[(Plane, NumberedLoop)], reversed: bool) -> Re
|
||||
let lead = oriented.iter().max_by_key(|(_, l)| l.lp.segs.len()).ok_or_else(|| KernelError::Invalid("no sections".into()))?;
|
||||
let lead_c = lead.0.to_world(lead.1.lp.centroid());
|
||||
let lead_dirs: Vec<Vec3> = lead.1.lp.segs.iter().map(|s| lead.0.to_world(s.start()) - lead_c).collect();
|
||||
let mut wires: Vec<mt::Wire> = Vec::new();
|
||||
// Per section, the profile segments under each of its wire's edges.
|
||||
let mut edge_sources: Vec<Vec<Vec<usize>>> = Vec::new();
|
||||
// The share of the lead's perimeter before each of its vertices: where a circle section
|
||||
// breaks when the lead's vertex directions do not go round in order.
|
||||
let lead_len: f64 = lead.1.lp.segs.iter().map(Seg2::length).sum();
|
||||
let fractions: Vec<f64> = lead
|
||||
.1
|
||||
.lp
|
||||
.segs
|
||||
.iter()
|
||||
.scan(0.0, |before, s| {
|
||||
let f = *before / lead_len;
|
||||
*before += s.length();
|
||||
Some(f)
|
||||
})
|
||||
.collect();
|
||||
let mut out: Vec<(Plane, NumberedLoop)> = Vec::new();
|
||||
for (p, l) in &oriented {
|
||||
let c = l.lp.centroid();
|
||||
// Break angles: the lead section's vertex directions seen in this plane.
|
||||
let angles: Vec<f64> = lead_dirs.iter().map(|d| Vec2::new(d.dot(p.x), d.dot(p.y)).angle()).collect();
|
||||
let mut r = l.resample(n, &angles);
|
||||
// Circle resampling creates increasing local angles. An antiparallel sketch
|
||||
// plane must run clockwise locally to keep the same winding in world space.
|
||||
// Curving a run through a right angle does not reverse a section's winding.
|
||||
if parallel && p.normal().dot(n0) < 0.0 {
|
||||
// plane must run clockwise locally to keep the same winding in world space (the lead's
|
||||
// directions go round clockwise there). Curving a run through a right angle does not
|
||||
// reverse a section's winding.
|
||||
let flip = parallel && p.normal().dot(n0) < 0.0;
|
||||
let mut r = l.resample(n, &angles, &fractions, flip);
|
||||
if flip {
|
||||
r = r.oriented(true);
|
||||
}
|
||||
// Start where every vertex lines up best with the lead's vertex of the same number (the
|
||||
@@ -2045,10 +2072,9 @@ fn loft_numbered_wires(sections: &[(Plane, NumberedLoop)], reversed: bool) -> Re
|
||||
if let Some(k) = (0..m).min_by(|a, b| fit(*b).total_cmp(&fit(*a))) {
|
||||
r.rotate_left(k);
|
||||
}
|
||||
wires.push(uniform_wire(p, &r.lp)?);
|
||||
edge_sources.push(r.from);
|
||||
out.push((*p, r));
|
||||
}
|
||||
Ok((wires, edge_sources))
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Ruled faces between each two neighbouring section wires; each comes from the section edges
|
||||
|
||||
@@ -85,9 +85,13 @@ impl NumberedLoop {
|
||||
NumberedLoop { lp: pieces, from }
|
||||
}
|
||||
|
||||
/// Re-split into exactly `n` segments: a full circle gets breaks at `angles` (or evenly),
|
||||
/// other loops split their longest segments in half.
|
||||
pub(crate) fn resample(&self, n: usize, angles: &[f64]) -> NumberedLoop {
|
||||
/// Re-split into exactly `n` segments, other loops split their longest segments in half. A
|
||||
/// full circle is split once round (one turn, every arc a positive sweep) to follow a lead
|
||||
/// loop: at the lead's vertex directions `angles` when they go round in order (counter-
|
||||
/// clockwise, or clockwise when `clockwise`), otherwise from the first of them at the lead's
|
||||
/// perimeter `fractions` (the share of the lead's length before each vertex; evenly when
|
||||
/// those are unusable).
|
||||
pub(crate) fn resample(&self, n: usize, angles: &[f64], fractions: &[f64], clockwise: bool) -> NumberedLoop {
|
||||
let lp = &self.lp;
|
||||
let circle = lp.segs.iter().all(|s| matches!(s, Seg2::Arc { .. }))
|
||||
&& lp.segs.windows(2).all(|w| match (w.first(), w.get(1)) {
|
||||
@@ -96,22 +100,15 @@ impl NumberedLoop {
|
||||
}
|
||||
_ => false,
|
||||
});
|
||||
if circle && let Some(Seg2::Arc { center, radius, .. }) = lp.segs.first().copied() {
|
||||
let mut a: Vec<f64> =
|
||||
if angles.len() == n { angles.to_vec() } else { (0..n).map(|i| std::f64::consts::TAU * i as f64 / n as f64).collect() };
|
||||
// Keep the given order but make them increase.
|
||||
for i in 1..a.len() {
|
||||
let Some(prev) = a.get(i - 1).copied() else { continue };
|
||||
if let Some(x) = a.get_mut(i) {
|
||||
while *x <= prev {
|
||||
*x += std::f64::consts::TAU;
|
||||
}
|
||||
}
|
||||
}
|
||||
let segs: Vec<Seg2> = (0..n)
|
||||
if circle
|
||||
&& n > 0
|
||||
&& let Some(Seg2::Arc { center, radius, .. }) = lp.segs.first().copied()
|
||||
{
|
||||
let a = circle_breaks(n, angles, fractions, clockwise);
|
||||
let segs: Vec<Seg2> = (0..a.len())
|
||||
.filter_map(|i| {
|
||||
let s = *a.get(i)?;
|
||||
let e = if i + 1 < n { *a.get(i + 1)? } else { a.first()? + std::f64::consts::TAU };
|
||||
let e = if i + 1 < a.len() { *a.get(i + 1)? } else { a.first()? + std::f64::consts::TAU };
|
||||
Some(Seg2::Arc { center, radius, start: s, sweep: e - s })
|
||||
})
|
||||
.collect();
|
||||
@@ -190,6 +187,65 @@ impl NumberedRegion {
|
||||
}
|
||||
}
|
||||
|
||||
/// The smallest arc a circle is split into (radians).
|
||||
const MIN_SWEEP: f64 = 1e-9;
|
||||
|
||||
/// `n` increasing break angles of one turn round a circle (each step and the closing step back
|
||||
/// to the first, one turn on, positive) for a circle following a lead loop: `angles` (the lead's
|
||||
/// vertex directions) when they go round once in order in the lead's direction (counter-clockwise,
|
||||
/// or clockwise when `clockwise`), otherwise from the first of them at the lead's perimeter
|
||||
/// `fractions`, or evenly. A non-star-shaped lead's directions turn back on themselves: forcing
|
||||
/// them to increase wound the circle round many times (#2570).
|
||||
fn circle_breaks(n: usize, angles: &[f64], fractions: &[f64], clockwise: bool) -> Vec<f64> {
|
||||
use std::f64::consts::TAU;
|
||||
let sign = if clockwise { -1.0 } else { 1.0 };
|
||||
// Angles measured in the lead's direction of travel.
|
||||
let along: Vec<f64> = angles.iter().map(|a| sign * a).collect();
|
||||
let run = (along.len() == n).then(|| one_turn(&along)).flatten().unwrap_or_else(|| {
|
||||
let start = along.first().copied().filter(|a| a.is_finite()).unwrap_or(0.0);
|
||||
let even = || (0..n).map(|i| i as f64 / n as f64).collect::<Vec<f64>>();
|
||||
let f = if usable_fractions(n, fractions) { fractions.to_vec() } else { even() };
|
||||
f.iter().map(|f| start + TAU * f).collect()
|
||||
});
|
||||
let mut breaks: Vec<f64> = run.into_iter().map(|a| sign * a).collect();
|
||||
if clockwise {
|
||||
breaks.reverse();
|
||||
}
|
||||
breaks
|
||||
}
|
||||
|
||||
/// `along` unwrapped into one increasing turn (each step the shortest positive one), or `None`
|
||||
/// when they do not go round once in order.
|
||||
fn one_turn(along: &[f64]) -> Option<Vec<f64>> {
|
||||
let mut out: Vec<f64> = Vec::with_capacity(along.len());
|
||||
for &x in along {
|
||||
if !x.is_finite() {
|
||||
return None;
|
||||
}
|
||||
let next = match out.last() {
|
||||
Some(&prev) => {
|
||||
let step = (x - prev).rem_euclid(std::f64::consts::TAU);
|
||||
if step <= MIN_SWEEP {
|
||||
return None;
|
||||
}
|
||||
prev + step
|
||||
}
|
||||
None => x,
|
||||
};
|
||||
out.push(next);
|
||||
}
|
||||
let (first, last) = (*out.first()?, *out.last()?);
|
||||
(last - first < std::f64::consts::TAU - MIN_SWEEP).then_some(out)
|
||||
}
|
||||
|
||||
/// `fractions` are `n` finite, strictly increasing shares of a turn from 0, all under one.
|
||||
fn usable_fractions(n: usize, fractions: &[f64]) -> bool {
|
||||
fractions.len() == n
|
||||
&& fractions.first().is_some_and(|f| f.abs() < MIN_SWEEP)
|
||||
&& fractions.windows(2).all(|w| matches!(w, [a, b] if b - a > MIN_SWEEP))
|
||||
&& fractions.last().is_some_and(|f| f.is_finite() && *f < 1.0 - MIN_SWEEP)
|
||||
}
|
||||
|
||||
/// Every number of `sets`, once each, in order.
|
||||
fn union<'a>(sets: impl IntoIterator<Item = &'a [usize]>) -> Vec<usize> {
|
||||
sets.into_iter().flatten().copied().collect::<BTreeSet<usize>>().into_iter().collect()
|
||||
|
||||
@@ -2964,6 +2964,53 @@ fn loft_pairs_the_vertices_of_matching_non_convex_sections() {
|
||||
assert!(m.centroid.x.abs() < 0.05, "centre of mass x {}", m.centroid.x);
|
||||
}
|
||||
|
||||
/// #2570: a circle lofted to a C-shaped outline. Seen from its centroid the C's vertices turn
|
||||
/// back on themselves; the circle was still split at those directions, forced to increase by
|
||||
/// whole turns, so it wound round several times (a closing arc of negative sweep), the walls
|
||||
/// crossed and the mesh grew huge. The circle is now split once round, in both section orders
|
||||
/// and from a plane facing the other way.
|
||||
#[test]
|
||||
fn loft_circle_to_non_star_profile_splits_circle_once() {
|
||||
let c = Loop2::polygon(&[
|
||||
Vec2::new(0.0, 0.0),
|
||||
Vec2::new(30.0, 0.0),
|
||||
Vec2::new(30.0, 8.0),
|
||||
Vec2::new(8.0, 8.0),
|
||||
Vec2::new(8.0, 22.0),
|
||||
Vec2::new(30.0, 22.0),
|
||||
Vec2::new(30.0, 30.0),
|
||||
Vec2::new(0.0, 30.0),
|
||||
]);
|
||||
let circle = (Plane::XY, Loop2::circle(Vec2::ZERO, 20.0));
|
||||
let up = (Plane::XY.offset(48.0), c.clone());
|
||||
let down = (Plane::new(Vec3::new(0.0, 0.0, 48.0), Vec3::Y, Vec3::X).unwrap(), c);
|
||||
for secs in [vec![circle.clone(), up.clone()], vec![up, circle.clone()], vec![circle, down]] {
|
||||
let numbered: Vec<(Plane, crate::numbered::NumberedLoop)> =
|
||||
secs.iter().map(|(p, _)| *p).zip(crate::numbered::number_loops(secs.iter().map(|(_, l)| l))).collect();
|
||||
for reversed in [false, true] {
|
||||
let loops = crate::build::loft_section_loops(&numbered, reversed).unwrap();
|
||||
let arcs: Vec<f64> = loops
|
||||
.iter()
|
||||
.flat_map(|(_, r)| r.lp.segs.iter())
|
||||
.filter_map(|s| match s {
|
||||
Seg2::Arc { sweep, .. } => Some(*sweep),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(arcs.len(), 8, "{arcs:?}");
|
||||
assert!(arcs.iter().all(|w| w.is_finite() && w.abs() > 1e-9), "{arcs:?}");
|
||||
// One way round: every arc the same way, one turn in all.
|
||||
assert!(arcs.iter().all(|w| w.signum() == arcs[0].signum()), "{arcs:?}");
|
||||
let total: f64 = arcs.iter().sum();
|
||||
assert!((total.abs() - std::f64::consts::TAU).abs() < 1e-9, "{total} {arcs:?}");
|
||||
}
|
||||
let body = loft(&secs).unwrap();
|
||||
assert!(measure(&body).unwrap().volume > 0.0);
|
||||
let mesh = body.tessellate(0.05).unwrap();
|
||||
assert!(mesh.triangles.len() < 4000, "{} triangles", mesh.triangles.len());
|
||||
}
|
||||
}
|
||||
|
||||
/// Two cylinders crossing at right angles need the kernel's own intersection: with no tries
|
||||
/// left the boolean fails at once, a budget inside another uses the outer one's up, and none
|
||||
/// lingers after.
|
||||
|
||||
Reference in New Issue
Block a user