use super::Tube;
use crate::Vec3;
#[derive(Clone, Copy, Debug)]
pub struct TrimPoint {
pub sigma: f64,
pub psi: f64,
pub mate_time: f64,
pub point: Vec3,
}
pub struct Lattice {
pub sigmas: Vec<f64>,
pub psis: Vec<f64>,
pub per_chunk: usize,
pub per_quarter: usize,
}
impl Lattice {
pub fn new(chunks: [usize; 4], per_chunk: usize, per_quarter: usize) -> Lattice {
let mut sigmas = Vec::new();
for (chart, &count) in chunks.iter().enumerate() {
for c in 0..count {
for k in 0..per_chunk {
sigmas.push(chart as f64 + (c as f64 + k as f64 / per_chunk as f64) / count as f64);
}
}
}
let quarters = 4 * per_quarter;
let psis = (0..quarters).map(|k| std::f64::consts::TAU * k as f64 / quarters as f64).collect();
Lattice { sigmas, psis, per_chunk, per_quarter }
}
}
impl Tube {
pub fn k_at(&self, sigma: f64, psi: f64) -> Option<Vec3> {
let chart = (sigma.floor() as i64).rem_euclid(4) as usize;
self.k_point(chart, sigma - sigma.floor(), psi)
}
pub(super) fn own_time(&self, sigma: f64) -> f64 {
let chart = (sigma.floor() as i64).rem_euclid(4) as usize;
let s = sigma - sigma.floor();
match chart {
0 => self.from + (self.to - self.from) * s,
1 => self.to,
2 => self.to - (self.to - self.from) * s,
_ => self.from,
}
}
pub fn far_depth(&self, q: Vec3, own: f64, window: f64, tolerance: f64) -> (f64, f64) {
self.far_depth_until(q, own, window, tolerance, f64::NEG_INFINITY)
}
pub fn far_depth_until(&self, q: Vec3, own: f64, window: f64, tolerance: f64, stop: f64) -> (f64, f64) {
let speed = self.reach_speed(q);
let mut spans: Vec<(f64, f64)> = Vec::new();
let (a, b) = (own - window, own + window);
if a > self.from {
spans.push((self.from, a.min(self.to)));
}
if b < self.to {
spans.push((b.max(self.from), self.to));
}
let mut best = (f64::INFINITY, own);
let mut stack: Vec<(f64, f64)> = Vec::new();
for (lo, hi) in spans {
let count = 256usize;
let h = (hi - lo) / count as f64;
stack.extend((0..count).map(|k| (lo + h * k as f64, lo + h * (k + 1) as f64)));
}
while let Some((lo, hi)) = stack.pop() {
let (fl, fh) = (self.reach(q, lo), self.reach(q, hi));
if fl < best.0 {
best = (fl, lo);
}
if fh < best.0 {
best = (fh, hi);
}
if best.0 < stop {
return best;
}
if fl.min(fh) - speed * (hi - lo) * 0.5 >= best.0 - tolerance || hi - lo <= 1e-13 * (self.to - self.from) {
continue;
}
let m = 0.5 * (lo + hi);
stack.push((lo, m));
stack.push((m, hi));
}
best
}
pub fn own_basin(&self, q: Vec3, own: f64, window: f64) -> (f64, f64) {
let range = self.to - self.from;
let noise = 1e-13 * (self.major + self.minor);
let side = |sign: f64| -> f64 {
let mut before = 0.0f64;
let mut last = (0.0f64, self.reach(q, own));
let mut h = 1e-7 * range;
let _ = window;
while h <= 2.0 * range {
let mut t = own + sign * h;
let past = t < self.from || t > self.to;
if past {
let end = if sign > 0.0 { self.to - own } else { own - self.from };
if !(end > last.0) {
return end + 1e-12 * range;
}
h = end;
t = own + sign * h;
}
let value = self.reach(q, t);
if past && !(value < last.1 - noise) {
return h + 1e-12 * range;
}
if value < last.1 - noise {
let (mut a, mut b) = (before, h);
let ratio = 0.5 * (5f64.sqrt() - 1.0);
for _ in 0..60 {
if b - a <= 1e-15 * range {
break;
}
let (c, d) = (b - ratio * (b - a), a + ratio * (b - a));
if self.reach(q, own + sign * c) > self.reach(q, own + sign * d) {
b = d;
} else {
a = c;
}
}
return 0.5 * (a + b);
}
before = last.0;
last = (h, value);
h *= 2.0;
}
2.0 * range
};
(own - side(-1.0), own + side(1.0))
}
pub fn far_depth_sampled(&self, q: Vec3, own: f64, window: f64, count: usize) -> (f64, f64) {
let mut times: Vec<f64> = Vec::with_capacity(count + 1);
let (lo, hi) = self.own_basin(q, own, window);
for k in 0..=count {
let t = self.from + (self.to - self.from) * k as f64 / count as f64;
if t <= lo || t >= hi {
times.push(t);
}
}
if lo > self.from && lo < self.to {
times.push(lo);
}
if hi > self.from && hi < self.to {
times.push(hi);
}
times.sort_by(f64::total_cmp);
let values: Vec<f64> = times.iter().map(|&t| self.reach(q, t)).collect();
let n = times.len();
if n == 0 {
return (f64::INFINITY, own);
}
let mut best = (f64::INFINITY, own);
for k in 0..n {
if values[k] < best.0 {
best = (values[k], times[k]);
}
}
let mut minima: Vec<usize> = (0..n).filter(|&k| (k == 0 || values[k] <= values[k - 1]) && (k + 1 == n || values[k] <= values[k + 1])).collect();
minima.sort_by(|&x, &y| values[x].total_cmp(&values[y]));
let ratio = 0.5 * (5f64.sqrt() - 1.0);
for &k in minima.iter().take(5) {
let (mut a, mut b) = (times[k.saturating_sub(1)], times[(k + 1).min(n - 1)]);
if a < hi && b > lo && (a - own).abs() > 0.0 {
if times[k] <= lo { b = b.min(lo); } else { a = a.max(hi); }
}
for _ in 0..80 {
if b - a <= 1e-14 * (self.to - self.from) {
break;
}
let (c, d) = (b - ratio * (b - a), a + ratio * (b - a));
if self.reach(q, c) < self.reach(q, d) {
b = d;
} else {
a = c;
}
}
let t = 0.5 * (a + b);
let value = self.reach(q, t);
if value < best.0 {
best = (value, t);
}
}
best
}
pub fn far_depth_near(&self, q: Vec3, own: f64, window: f64, guess: f64, span: f64) -> (f64, f64) {
let lo = (guess - span).max(self.from);
let hi = (guess + span).min(self.to);
let (left, right) = self.own_basin(q, own, window);
let allowed = |t: f64| t <= left || t >= right;
let mut best = (f64::INFINITY, guess);
let mut best_k = None;
let count = 16;
let samples: Vec<f64> = (0..=count).map(|k| lo + (hi - lo) * k as f64 / count as f64).collect();
let mut values = vec![f64::INFINITY; count + 1];
for (k, &t) in samples.iter().enumerate() {
if allowed(t) {
values[k] = self.reach(q, t);
if values[k] < best.0 {
best = (values[k], t);
best_k = Some(k);
}
}
}
let Some(k) = best_k else { return self.far_depth_sampled(q, own, window, 1024) };
if (k == 0 && lo > self.from) || (k == count && hi < self.to) {
return self.far_depth_sampled(q, own, window, 1024);
}
let (mut a, mut b) = (samples[k.saturating_sub(1)], samples[(k + 1).min(count)]);
if !allowed(a) { a = samples[k]; }
if !allowed(b) { b = samples[k]; }
let (mut x, mut fx) = (best.1, best.0);
let ratio = 0.5 * (3.0 - 5f64.sqrt());
for _ in 0..40 {
if b - a <= 1e-13 * (self.to - self.from) {
break;
}
let (fa, fb) = (self.reach(q, a), self.reach(q, b));
let denominator = (x - a) * (fx - fb) - (x - b) * (fx - fa);
let mut u = if denominator.abs() > 0.0 { x - 0.5 * ((x - a) * (x - a) * (fx - fb) - (x - b) * (x - b) * (fx - fa)) / denominator } else { f64::NAN };
if !(u > a && u < b) || (u - x).abs() < 1e-15 * (self.to - self.from) {
u = if x - a > b - x { x - ratio * (x - a) } else { x + ratio * (b - x) };
}
let fu = self.reach(q, u);
if fu < fx {
if u < x { b = x; } else { a = x; }
x = u;
fx = fu;
} else if u < x {
a = u;
} else {
b = u;
}
}
if fx < best.0 { (fx, x) } else { best }
}
pub fn beyond(&self, q: Vec3, own: f64, window: f64, level: f64, budget: usize) -> Option<bool> {
let speed = self.reach_speed(q);
let mut stack: Vec<(f64, f64)> = Vec::new();
let (lo, hi) = (own - window, own + window);
for (a, b) in [(self.from, lo.min(self.to)), (hi.max(self.from), self.to)] {
if b > a {
let count = 64usize;
let h = (b - a) / count as f64;
stack.extend((0..count).map(|k| (a + h * k as f64, a + h * (k + 1) as f64)));
}
}
let mut spent = 0usize;
while let Some((a, b)) = stack.pop() {
let (fa, fb) = (self.reach(q, a), self.reach(q, b));
if fa < level || fb < level {
return Some(false);
}
if fa.min(fb) - speed * (b - a) * 0.5 >= level {
continue;
}
spent += 1;
if spent > budget || b - a <= 1e-12 * (self.to - self.from) {
return None;
}
let m = 0.5 * (a + b);
stack.push((a, m));
stack.push((m, b));
}
Some(true)
}
pub(super) fn trim_value(&self, sigma: f64, psi: f64, window: f64, tolerance: f64) -> Option<(f64, f64, Vec3)> {
let q = self.k_at(sigma, psi)?;
let _ = tolerance;
let (depth, time) = self.far_depth_sampled(q, self.own_time(sigma), window, 1024);
Some((depth - self.minor, time, q))
}
}
impl Tube {
pub(crate) fn touching_times(&self, q: Vec3, tolerance: f64) -> Vec<f64> {
let (range, count) = (self.to - self.from, 2048usize);
let at = |k: usize| self.from + range * k as f64 / count as f64;
let values: Vec<f64> = (0..=count).map(|k| self.reach(q, at(k))).collect();
let ratio = 0.5 * (5f64.sqrt() - 1.0);
let mut times: Vec<f64> = Vec::new();
for k in 0..=count {
let left = k == 0 || values[k] <= values[k - 1];
let right = k == count || values[k] <= values[k + 1];
if !(left && right) {
continue;
}
let (mut a, mut b) = (at(k.saturating_sub(1)), at((k + 1).min(count)));
for _ in 0..100 {
if b - a <= 1e-15 * range {
break;
}
let (c, d) = (b - ratio * (b - a), a + ratio * (b - a));
if self.reach(q, c) < self.reach(q, d) {
b = d;
} else {
a = c;
}
}
let t = 0.5 * (a + b);
if (self.reach(q, t) - self.minor).abs() <= tolerance && times.iter().all(|u| (u - t).abs() > 1e-3 * range) {
times.push(t);
}
}
times
}
pub fn mate_of(&self, q: Vec3, time: f64) -> Option<(f64, f64)> {
if let Some(found) = self.mate_at(q, time) {
return Some(found);
}
let range = self.to - self.from;
let spread = range / 512.0;
let (mut lo, mut hi) = ((time - spread).max(self.from), (time + spread).min(self.to));
let ratio = 0.5 * (5f64.sqrt() - 1.0);
let (mut a, mut b) = (hi - ratio * (hi - lo), lo + ratio * (hi - lo));
let (mut fa, mut fb) = (self.reach(q, a), self.reach(q, b));
for _ in 0..80 {
if !(hi - lo > 1e-15 * range) {
break;
}
if fa <= fb {
hi = b;
(b, fb) = (a, fa);
a = hi - ratio * (hi - lo);
fa = self.reach(q, a);
} else {
lo = a;
(a, fa) = (b, fb);
b = lo + ratio * (hi - lo);
fb = self.reach(q, b);
}
}
let refined = 0.5 * (lo + hi);
if !((self.reach(q, refined) - self.minor).abs() <= 1e-6 * self.minor) {
return None;
}
if let Some(found) = self.mate_at(q, refined) {
return Some(found);
}
if !((refined - self.from) > 1e-6 * range && (self.to - refined) > 1e-6 * range) {
return None;
}
let local = self.motion.pose(refined).invert(q).sub(self.centre);
let psi = local.dot(self.y).atan2(local.dot(self.x)).rem_euclid(std::f64::consts::TAU);
let frame = self.frame(refined, psi)?;
let sigma = if q.sub(frame.point).dot(frame.normal) >= 0.0 { (refined - self.from) / range } else { 2.0 + (self.to - refined) / range };
Some((sigma, psi))
}
fn mate_at(&self, q: Vec3, time: f64) -> Option<(f64, f64)> {
let local = self.motion.pose(time).invert(q).sub(self.centre);
let psi = local.dot(self.y).atan2(local.dot(self.x)).rem_euclid(std::f64::consts::TAU);
let frame = self.frame(time, psi)?;
let offset = q.sub(frame.point);
let (along_n, along_lead) = (offset.dot(frame.normal), offset.dot(frame.lead));
let range = self.to - self.from;
let on_sheet = along_lead.abs() <= 1e-6 * self.minor;
let near_end = (self.to - time) <= 1e-6 * range;
let near_start = (time - self.from) <= 1e-6 * range;
let sigma = if !on_sheet && near_end && along_lead > 0.0 {
1.0 + along_lead.atan2(along_n).clamp(0.0, std::f64::consts::PI) / std::f64::consts::PI
} else if !on_sheet && near_start && along_lead < 0.0 {
3.0 + (-along_lead).atan2(-along_n).clamp(0.0, std::f64::consts::PI) / std::f64::consts::PI
} else if !on_sheet {
return None; } else if along_n >= 0.0 {
(time - self.from) / range
} else {
2.0 + (self.to - time) / range
};
Some((sigma, psi))
}
}
pub fn trim_loops(tube: &Tube, lattice: &Lattice, window: f64, tolerance: f64) -> Result<Vec<Vec<TrimPoint>>, String> {
trim_loops_charted(tube, lattice, window, tolerance, &[], &[]).map(|(loops, _)| loops)
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Jump {
pub chart: usize,
pub run: usize,
pub forward: bool,
}
#[allow(clippy::type_complexity)]
pub fn trim_loops_charted(
tube: &Tube,
lattice: &Lattice,
window: f64,
tolerance: f64,
charts: &[super::chart::TubeChart],
rims: &[super::chart::Rim],
) -> Result<(Vec<Vec<TrimPoint>>, Vec<Vec<Option<Jump>>>), String> {
let (rows, columns) = (lattice.sigmas.len(), lattice.psis.len());
let held = |sigma: f64, psi: f64| charts.iter().any(|c| c.holds(sigma, psi));
let sigma_at = |i: usize| -> f64 { if i == rows { 4.0 } else { lattice.sigmas[i] } };
let psi_at = |j: usize| -> f64 { if j == columns { std::f64::consts::TAU } else { lattice.psis[j] } };
let mut values = vec![vec![f64::NAN; columns]; rows];
for i in 0..rows {
for j in 0..columns {
if held(lattice.sigmas[i], lattice.psis[j]) {
continue;
}
let q = tube.k_at(lattice.sigmas[i], lattice.psis[j]).ok_or("K is singular at a lattice station")?;
let own = tube.own_time(lattice.sigmas[i]);
let tie = 1e-9 * (tube.major + tube.minor);
let near = tube.own_read(q, own, window, tie);
if matches!(near, super::fold::OwnRead::Tie) {
return Err(format!("a station's own-time read ties at (σ {:.6}, ψ {:.6})", lattice.sigmas[i], lattice.psis[j]));
}
let depth = if let super::fold::OwnRead::Covered(_) = near {
tube.minor * (1.0 - 1e-3)
} else {
match tube.beyond(q, own, window, tube.minor, 4096) {
Some(true) => tube.minor * (1.0 + 1e-3),
Some(false) => tube.minor * (1.0 - 1e-3),
None => tube.far_depth_sampled(q, own, window, 1024).0,
}
};
let g = depth - tube.minor;
if g.abs() <= tolerance {
return Err(format!("a lattice station ties at (σ {:.6}, ψ {:.6})", lattice.sigmas[i], lattice.psis[j]));
}
values[i][j] = g;
}
}
let covered = |i: usize, j: usize| values[i % rows][j % columns] < 0.0;
let mut crossings: std::collections::HashMap<(usize, usize, u8), TrimPoint> = std::collections::HashMap::new();
let mut solve = |i: usize, j: usize, along: u8| -> Result<TrimPoint, String> {
if let Some(found) = crossings.get(&(i, j, along)) {
return Ok(*found);
}
let (s0, p0) = (sigma_at(i), psi_at(j));
let (s1, p1) = if along == 0 { (sigma_at(i + 1), p0) } else { (s0, psi_at(j + 1)) };
let at = |f: f64| (s0 + (s1 - s0) * f, p0 + (p1 - p0) * f);
let sign0 = values[i % rows][j % columns] < 0.0;
let covered_end = if sign0 { 0.0 } else { 1.0 };
let (cs, cp) = at(covered_end);
let range = tube.to - tube.from;
let guess = if charts.is_empty() {
tube.trim_value(cs, cp, window, tolerance).ok_or("K is singular on a lattice edge")?.1
} else {
let q = tube.k_at(cs.rem_euclid(4.0), cp.rem_euclid(std::f64::consts::TAU)).ok_or("K is singular on a lattice edge")?;
super::chart::chart_far(tube, q, tube.own_time(cs.rem_euclid(4.0)), window, None, range).1
};
let near = |s: f64, p: f64| -> Option<(f64, f64, Vec3)> {
let (s, p) = (s.rem_euclid(4.0), p.rem_euclid(std::f64::consts::TAU));
let q = tube.k_at(s, p)?;
let (depth, time) = if charts.is_empty() {
tube.far_depth_near(q, tube.own_time(s), window, guess, 0.01 * range)
} else {
super::chart::chart_far(tube, q, tube.own_time(s), window, Some(guess), range)
};
Some((depth - tube.minor, time, q))
};
let (mut lo, mut hi) = (0.0f64, 1.0f64);
for _ in 0..48 {
let mid = 0.5 * (lo + hi);
let (s, p) = at(mid);
let (g, _, _) = near(s, p).ok_or("K is singular on a lattice edge")?;
if (g < 0.0) == sign0 {
lo = mid;
} else {
hi = mid;
}
}
let (s, p) = at(0.5 * (lo + hi));
let (_, time, point) = near(s, p).ok_or("K is singular on a lattice edge")?;
let found = TrimPoint { sigma: s, psi: p, mate_time: time, point };
crossings.insert((i, j, along), found);
Ok(found)
};
type Key = (usize, usize, u8);
let mut links: std::collections::HashMap<Key, Vec<Key>> = std::collections::HashMap::new();
for i in 0..rows {
for j in 0..columns {
if held(0.5 * (sigma_at(i) + sigma_at(i + 1)), 0.5 * (psi_at(j) + psi_at(j + 1))) {
continue;
}
let corners = [covered(i, j), covered(i + 1, j), covered(i + 1, j + 1), covered(i, j + 1)];
let keys: [Key; 4] = [(i, j, 0), ((i + 1) % rows, j, 1), (i, (j + 1) % columns, 0), (i, j, 1)];
let cut = [corners[0] != corners[1], corners[1] != corners[2], corners[3] != corners[2], corners[0] != corners[3]];
let cuts: Vec<usize> = (0..4).filter(|&e| cut[e]).collect();
match cuts.as_slice() {
[] => {}
[a, b] => {
links.entry(keys[*a]).or_default().push(keys[*b]);
links.entry(keys[*b]).or_default().push(keys[*a]);
}
_ => return Err(format!("a saddle cell at (σ {:.6}, ψ {:.6})", sigma_at(i), psi_at(j))),
}
}
}
let mut jumps: std::collections::HashMap<(Key, Key), Jump> = std::collections::HashMap::new();
let mut rim_at: std::collections::HashMap<Key, TrimPoint> = std::collections::HashMap::new();
for (c, rim) in rims.iter().enumerate() {
for k in 0..rim.closed.len() {
let pieces = rim.pieces.get(rim.runs.len() + k).ok_or("a chart's closed curve has no pieces")?;
if pieces.is_empty() || pieces.iter().any(|q| rim.edges.get(q.edge).is_none_or(|e| e.outside.is_some())) {
return Err("a chart holds a closed trim curve whose mate side is outside it (not yet taken)".into());
}
}
let mut keys_of: Vec<Key> = Vec::with_capacity(rim.crossings.len());
for crossing in &rim.crossings {
let mut best: Option<(f64, Key)> = None;
let dangling: Vec<Key> = links.iter().filter(|(_, v)| v.len() == 1).map(|(k, _)| *k).collect();
for key in dangling {
let found = solve(key.0, key.1, key.2)?;
let d = found.point.sub(crossing.at.point).length();
if best.is_none_or(|b| d < b.0) {
best = Some((d, key));
}
}
let (d, key) = best.ok_or("a rim crossing has no trim run outside its box")?;
if !(d <= 0.05 * (tube.major + tube.minor)) {
return Err(format!("a rim crossing lies {d:.2e} from the nearest trim run outside its box"));
}
rim_at.insert(key, crossing.at);
keys_of.push(key);
}
for (r, run) in rim.runs.iter().enumerate() {
let [a, b] = run.ends;
let (ka, kb) = (keys_of[a], keys_of[b]);
links.entry(ka).or_default().push(kb);
links.entry(kb).or_default().push(ka);
jumps.insert((ka, kb), Jump { chart: c, run: r, forward: true });
jumps.insert((kb, ka), Jump { chart: c, run: r, forward: false });
}
}
let mut seen: std::collections::HashSet<Key> = std::collections::HashSet::new();
let mut loop_jumps: Vec<Vec<Option<Jump>>> = Vec::new();
let mut loops = Vec::new();
let mut keys: Vec<Key> = links.keys().copied().collect();
keys.sort();
for start in keys {
if seen.contains(&start) {
continue;
}
let mut chain = vec![start];
seen.insert(start);
let mut previous = start;
let mut current = links[&start][0];
while current != start {
if !seen.insert(current) {
return Err("a trim curve branches".into());
}
chain.push(current);
let next = links[¤t].iter().copied().find(|k| *k != previous).ok_or("a trim curve ends")?;
previous = current;
current = next;
}
let mut points = Vec::with_capacity(chain.len());
for &(i, j, along) in &chain {
points.push(match rim_at.get(&(i, j, along)) {
Some(at) => *at,
None => solve(i, j, along)?,
});
}
loop_jumps.push((0..chain.len()).map(|k| jumps.get(&(chain[k], chain[(k + 1) % chain.len()])).copied()).collect());
loops.push(points);
}
Ok((loops, loop_jumps))
}
fn path_near(path: &[(f64, f64)], point: (f64, f64), cell_gap: &dyn Fn((f64, f64), (f64, f64)) -> f64) -> bool {
if path.iter().any(|q| cell_gap(*q, point) <= 1.5) {
return true;
}
path.windows(2).any(|w| {
let unwrap = |value: f64, near: f64, period: f64| value + ((near - value) / period).round() * period;
let b = (unwrap(w[1].0, w[0].0, 4.0), unwrap(w[1].1, w[0].1, std::f64::consts::TAU));
[0.25, 0.5, 0.75].iter().any(|f| cell_gap((w[0].0 + (b.0 - w[0].0) * f, w[0].1 + (b.1 - w[0].1) * f), point) <= 1.5)
})
}
#[derive(Clone, Copy, Debug)]
struct Node {
sigma: f64,
psi: f64,
point: Vec3,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
enum Mark {
Corner(usize, usize),
Split(usize, usize),
Chart(usize, usize),
}
#[derive(Clone, Debug)]
struct Piece {
marks: [Mark; 2],
domain: Vec<(f64, f64)>,
edge: (usize, usize),
forward: bool,
}
#[allow(clippy::too_many_arguments)]
pub fn trimmed_tube(
tube: &Tube,
chunks: [usize; 4],
lattice: &Lattice,
per_chunk: usize,
per_quarter: usize,
loops: &[Vec<TrimPoint>],
window: f64,
fit: f64,
cuts: (&[f64], &[f64]),
charts: &[super::chart::TubeChart],
rims: &[super::chart::Rim],
loop_jumps: &[Vec<Option<Jump>>],
) -> Result<crate::BrepSolid, String> {
let in_chart = |sigma: f64, psi: f64| charts.iter().any(|c| c.holds(sigma, psi));
use std::f64::consts::{FRAC_PI_2, TAU};
let tolerance = 1e-12 * tube.minor;
let edge_fit = crate::KernelTolerances::for_scale(tube.major + tube.minor, 1e-7).intersection_fit.max(fit);
let mut rows: Vec<(usize, f64, f64)> = Vec::new();
for (chart, &count) in chunks.iter().enumerate() {
for c in 0..count {
rows.push((chart, c as f64 / count as f64, (c + 1) as f64 / count as f64));
}
}
let chunk_bounds: Vec<f64> = rows.iter().map(|(chart, s0, _)| *chart as f64 + s0).chain(std::iter::once(4.0)).collect();
let chunk_of = |sigma: f64| -> usize {
let s = sigma.rem_euclid(4.0);
(chunk_bounds.partition_point(|b| *b <= s).max(1) - 1).min(chunk_bounds.len() - 2)
};
let mut cut_rows: Vec<(usize, f64, f64)> = Vec::with_capacity(rows.len());
for &(chart, s0, s1) in &rows {
let mut inner: Vec<f64> = cuts.0.iter().map(|c| c.rem_euclid(4.0) - chart as f64).filter(|c| *c > s0 + 1e-12 && *c < s1 - 1e-12).collect();
inner.sort_by(f64::total_cmp);
inner.dedup_by(|x, y| (*x - *y).abs() <= 1e-12);
let mut from = s0;
for c in inner {
cut_rows.push((chart, from, c));
from = c;
}
cut_rows.push((chart, from, s1));
}
let rows = cut_rows;
let sigma_bounds: Vec<f64> = rows.iter().map(|(chart, s0, _)| *chart as f64 + s0).chain(std::iter::once(4.0)).collect();
let row_of = |sigma: f64| -> usize {
let s = sigma.rem_euclid(4.0);
(sigma_bounds.partition_point(|b| *b <= s).max(1) - 1).min(rows.len() - 1)
};
let mut psi_bounds: Vec<f64> = (0..4).map(|q| q as f64 * FRAC_PI_2).chain(cuts.1.iter().map(|c| c.rem_euclid(TAU))).collect();
psi_bounds.sort_by(f64::total_cmp);
psi_bounds.dedup_by(|x, y| (*x - *y).abs() <= 1e-12);
let columns = psi_bounds.len();
let psi_end = |b: usize| if b + 1 < columns { psi_bounds[b + 1] } else { TAU };
let column_of = |psi: f64| -> usize { (psi_bounds.partition_point(|b| *b <= psi.rem_euclid(TAU)).max(1) - 1).min(columns - 1) };
let unwrap = |value: f64, near: f64, period: f64| value + ((near - value) / period).round() * period;
let cell_sigma = |sigma: f64| {
let a = chunk_of(sigma);
(chunk_bounds[a + 1] - chunk_bounds[a]) / per_chunk as f64
};
let cell_psi = TAU / (4 * per_quarter) as f64;
let g_at = |sigma: f64, psi: f64| -> Option<(f64, f64, Vec3)> {
if charts.is_empty() {
return tube.trim_value(sigma.rem_euclid(4.0), psi.rem_euclid(TAU), window, tolerance);
}
let (sigma, psi) = (sigma.rem_euclid(4.0), psi.rem_euclid(TAU));
let q = tube.k_at(sigma, psi)?;
let (depth, time) = super::chart::chart_far(tube, q, tube.own_time(sigma), window, None, tube.to - tube.from);
Some((depth - tube.minor, time, q))
};
let range = tube.to - tube.from;
let g_near = |sigma: f64, psi: f64, guess: f64| -> Option<(f64, f64, Vec3)> {
let (sigma, psi) = (sigma.rem_euclid(4.0), psi.rem_euclid(TAU));
let q = tube.k_at(sigma, psi)?;
let (depth, time) = if charts.is_empty() {
tube.far_depth_near(q, tube.own_time(sigma), window, guess, 0.01 * range)
} else {
super::chart::chart_far(tube, q, tube.own_time(sigma), window, Some(guess), range)
};
Some((depth - tube.minor, time, q))
};
let contour_within = |a: (f64, f64), b: (f64, f64), f: f64, guess: f64, cells: f64| -> Result<(f64, f64, f64, Vec3), String> {
let c = (a.0 + (b.0 - a.0) * f, a.1 + (b.1 - a.1) * f);
let (ds, dp) = (cell_sigma(c.0), cell_psi);
let (cs, cp) = ((b.0 - a.0) / ds, (b.1 - a.1) / dp);
let length = cs.hypot(cp);
let (ns, np) = if length > 0.0 { (-cp / length, cs / length) } else { (1.0, 0.0) };
let at = |lambda: f64| (c.0 + lambda * ns * ds, c.1 + lambda * np * dp);
let search = |global: bool| -> Result<(f64, f64, f64, Vec3), String> {
let read = |s: f64, p: f64| if global { g_at(s, p) } else { g_near(s, p, guess) };
let sign = |lambda: f64| -> Result<bool, String> {
let (s, p) = at(lambda);
Ok(read(s, p).ok_or("K is singular near a trim curve")?.0 < 0.0)
};
let (mut lo, mut hi) = (-cells, cells);
let (mut slo, shi) = (sign(lo)?, sign(hi)?);
if slo == shi {
let here = sign(0.0)?;
let mut lambda = cells * 2f64.powi(-20);
let mut found = None;
while lambda <= cells {
if sign(lambda)? != here {
found = Some((0.0, lambda));
break;
}
if sign(-lambda)? != here {
found = Some((-lambda, 0.0));
break;
}
lambda *= 2.0;
}
if let Some((a0, a1)) = found {
(lo, hi, slo) = (a0, a1, sign(a0)?);
}
}
if slo == sign(hi)? {
return Err(format!("a trim curve leaves its cell (across {cells} cells) at (σ {:.6}, ψ {:.6}) on the chord from (σ {:.6}, ψ {:.6}) to (σ {:.6}, ψ {:.6}) at {f}", c.0, c.1, a.0, a.1, b.0, b.1));
}
for _ in 0..30 {
let mid = 0.5 * (lo + hi);
if sign(mid)? == slo {
lo = mid;
} else {
hi = mid;
}
}
let (s, p) = at(0.5 * (lo + hi));
let (_, time, point) = read(s, p).ok_or("K is singular near a trim curve")?;
Ok((s, p, time, point))
};
search(false).or_else(|_| search(true))
};
let contour = |a: (f64, f64), b: (f64, f64), f: f64, guess: f64| -> Result<(f64, f64, f64, Vec3), String> { contour_within(a, b, f, guess, 1.0) };
let mate_read = |point: Vec3, time: f64, sigma: f64| -> Option<((f64, f64), f64)> {
if let Some(m) = tube.mate_of(point, time) {
return Some((m, time));
}
if let Some(m) = charts.iter().find_map(|c| c.mate_of(tube, point, time)) {
return Some((m, time));
}
let _ = tolerance;
let (depth, exact) = tube.far_depth_sampled(point, tube.own_time(sigma.rem_euclid(4.0)), window, 1024);
let found = tube.mate_of(point, exact).map(|m| (m, exact));
found
};
let size = tube.major + tube.minor;
let follow = |point: Vec3, from: (f64, f64)| -> Option<(f64, f64)> {
let (mut s, mut p) = from;
let h = 1e-7;
for _ in 0..30 {
let at = tube.k_at(s.rem_euclid(4.0), p.rem_euclid(TAU))?;
let r = at.sub(point);
if r.length() <= 1e-10 * size {
return Some((s, p));
}
let ks = tube.k_at((s + h).rem_euclid(4.0), p.rem_euclid(TAU))?.sub(tube.k_at((s - h).rem_euclid(4.0), p.rem_euclid(TAU))?).scale(0.5 / h);
let kp = tube.k_at(s.rem_euclid(4.0), (p + h).rem_euclid(TAU))?.sub(tube.k_at(s.rem_euclid(4.0), (p - h).rem_euclid(TAU))?).scale(0.5 / h);
let (a, b, c) = (ks.dot(ks), ks.dot(kp), kp.dot(kp));
let (u, v) = (-ks.dot(r), -kp.dot(r));
let det = a * c - b * b;
if !(det.abs() > 1e-30) {
return None;
}
let (ds, dp) = ((c * u - b * v) / det, (a * v - b * u) / det);
if !(ds.is_finite() && dp.is_finite()) {
return None;
}
s += ds;
p += dp;
}
let at = tube.k_at(s.rem_euclid(4.0), p.rem_euclid(TAU))?;
(at.sub(point).length() <= 1e-9 * size).then_some((s, p))
};
let wrap = |a: f64, b: f64, period: f64| {
let d = (a - b).rem_euclid(period);
d.min(period - d)
};
let domain_gap = |a: (f64, f64), b: (f64, f64)| wrap(a.0, b.0, 4.0).hypot(wrap(a.1, b.1, TAU));
let cell_gap = |a: (f64, f64), b: (f64, f64)| (wrap(a.0, b.0, 4.0) / cell_sigma(a.0)).hypot(wrap(a.1, b.1, TAU) / cell_psi);
let mut curves: Vec<(Vec<TrimPoint>, bool, [bool; 2])> = Vec::new();
let mut kept_mates: Vec<Vec<(f64, f64)>> = Vec::new();
let mut twins: Vec<Vec<TrimPoint>> = Vec::new();
let rim_far: Vec<TrimPoint> = rims
.iter()
.flat_map(|rim| rim.crossings.iter())
.filter_map(|c| {
let (m, _) = mate_read(c.at.point, c.at.mate_time, c.at.sigma)?;
Some(TrimPoint { sigma: m.0.rem_euclid(4.0), psi: m.1.rem_euclid(TAU), mate_time: tube.own_time(c.at.sigma), point: c.at.point })
})
.collect();
for (li, l) in loops.iter().enumerate() {
let n = l.len();
if n < 2 {
return Err("a trim loop of fewer than two points".into());
}
let trace76 = std::env::var("BREP_TUBE_TRACE_LOOPS").is_ok();
if trace76 && li == 0 {
for (c, chart) in charts.iter().enumerate() {
let (cs, cp) = chart.cuts();
eprintln!("T76 chart {c}: sigma cuts {cs:?} psi cuts {cp:?}");
for x in &rims[c].crossings {
let far = mate_read(x.at.point, x.at.mate_time, x.at.sigma).map(|(m, _)| m);
eprintln!("T76 crossing ({:.6}, {:.6}) far {far:?}", x.at.sigma, x.at.psi);
}
}
}
if trace76 {
eprintln!("T76 loop {li}: {n} points, from ({:.6}, {:.6})", l[0].sigma, l[0].psi);
for p in l.iter().filter(|p| p.sigma > 0.45 && p.sigma < 0.65 && p.psi > 5.9 && p.psi < 6.3) { eprintln!("T76 pt ({:.6}, {:.6}) t {:.5}", p.sigma, p.psi, p.mate_time); }
}
let no_jumps = vec![None; n];
let jump_after: &[Option<Jump>] = loop_jumps.get(li).map(|v| v.as_slice()).unwrap_or(&no_jumps);
let along_chord = |a: TrimPoint, b: TrimPoint, q: (f64, f64)| -> (f64, f64) {
let (ds, dp) = (cell_sigma(a.sigma), cell_psi);
let v = ((unwrap(b.sigma, a.sigma, 4.0) - a.sigma) / ds, (unwrap(b.psi, a.psi, TAU) - a.psi) / dp);
let w = ((unwrap(q.0, a.sigma, 4.0) - a.sigma) / ds, (unwrap(q.1, a.psi, TAU) - a.psi) / dp);
let vv = v.0 * v.0 + v.1 * v.1;
if !(vv > 0.0) {
return (0.0, w.0.hypot(w.1));
}
let t = (w.0 * v.0 + w.1 * v.1) / vv;
(t, (w.0 - t * v.0).hypot(w.1 - t * v.1))
};
let mut forced: Vec<Option<TrimPoint>> = vec![None; n];
for far in &rim_far {
let mut best: Option<(f64, usize)> = None;
for i in 0..n {
if jump_after[i].is_some() {
continue;
}
let (t, d) = along_chord(l[i], l[(i + 1) % n], (far.sigma, far.psi));
if (0.0..=1.0).contains(&t) && d <= 0.5 && best.is_none_or(|x| d < x.0) {
best = Some((d, i));
}
}
if let Some((_, i)) = best {
if trace76 { eprintln!("T76 far ({:.6}, {:.6}) forced after {i}", far.sigma, far.psi); }
forced[i] = Some(*far);
}
}
let mates: Vec<Option<(f64, f64)>> = l.iter().map(|p| mate_read(p.point, p.mate_time, p.sigma).map(|(m, _)| m)).collect();
let gaps: Vec<f64> = (0..n).map(|i| mates[i].map(|m| cell_gap((l[i].sigma, l[i].psi), m)).unwrap_or(f64::INFINITY)).collect();
let walk = |i: usize| -> Result<TrimPoint, String> {
let p0 = l[i];
let guess = p0.mate_time;
let g = |s: f64, p: f64| -> Result<f64, String> {
g_near(s, p, guess).map(|x| x.0).ok_or_else(|| format!("K is singular near a cusp at (σ {s:.9}, ψ {p:.9}); start (σ {:.9}, ψ {:.9})", p0.sigma, p0.psi))
};
let (ds, dp) = (cell_sigma(p0.sigma), cell_psi);
let gap_of = |s: f64, p: f64| -> Result<(f64, TrimPoint), String> {
let (_, time, point) = g_near(s, p, guess).ok_or("K is singular near a cusp")?;
let gap = mate_read(point, time, s).map(|(m, _)| domain_gap(m, (s, p))).unwrap_or(f64::INFINITY);
Ok((gap, TrimPoint { sigma: s.rem_euclid(4.0), psi: p.rem_euclid(TAU), mate_time: time, point }))
};
let correct = |s: f64, p: f64, gs: f64, gp: f64, reach: f64| -> Result<Option<(f64, f64)>, String> {
let length = gs.hypot(gp);
if !(length.is_finite() && length > 0.0) || !(s.is_finite() && p.is_finite()) {
return Ok(None);
}
let (us, up) = (gs / length, gp / length);
let at = |lambda: f64| (s + lambda * us * ds, p + lambda * up * dp);
let (a0, a1) = (at(-reach), at(reach));
let (f0, f1) = (g(a0.0, a0.1)?, g(a1.0, a1.1)?);
if (f0 < 0.0) == (f1 < 0.0) {
return Ok(None);
}
let (mut lo, mut hi) = (-reach, reach);
for _ in 0..40 {
let mid = 0.5 * (lo + hi);
let (x, y) = at(mid);
if (g(x, y)? < 0.0) == (f0 < 0.0) {
lo = mid;
} else {
hi = mid;
}
}
Ok(Some(at(0.5 * (lo + hi))))
};
let gradient = |s: f64, p: f64, h: f64| -> Result<(f64, f64), String> {
let gs = (g(s + h * ds, p)? - g(s - h * ds, p)?) / (2.0 * h);
let gp = (g(s, p + h * dp)? - g(s, p - h * dp)?) / (2.0 * h);
Ok((gs, gp))
};
let (mut s0, mut q0) = (p0.sigma, p0.psi);
let (mut best, mut best_point) = gap_of(s0, q0)?;
let mut step: f64 = 0.25;
let mut direction = 0.0f64;
let mut steps = 0usize;
while step > 1e-9 && steps < 2000 {
steps += 1;
let (gs, gp) = gradient(s0, q0, (0.1 * step).max(1e-7))?;
let (ts, tp) = (-gp, gs);
let length = ts.hypot(tp);
if !(length.is_finite() && length > 0.0) {
break;
}
let mut moved = false;
let order: [f64; 2] = if direction < 0.0 { [-1.0, 1.0] } else { [1.0, -1.0] };
for sign in order {
let (ps, pp) = (s0 + sign * step * ts / length * ds, q0 + sign * step * tp / length * dp);
let Some((cs, cp)) = correct(ps, pp, gs, gp, (2.0 * step).max(1e-6))? else { continue };
let (gap, point) = gap_of(cs, cp)?;
if gap < best {
best = gap;
best_point = point;
s0 = cs;
q0 = cp;
direction = sign;
moved = true;
break;
}
}
if !moved {
step *= 0.5;
}
}
Ok(best_point)
};
let cusp: Vec<bool> = (0..n).map(|i| gaps[i] < 4.0 && gaps[i] <= gaps[(i + n - 1) % n] && gaps[i] <= gaps[(i + 1) % n]).collect();
let jump = |i: usize| -> bool {
let j = (i + 1) % n;
match (mates[i], mates[j]) {
(Some(a), Some(b)) => !cusp[i] && !cusp[j] && cell_gap(a, b) > 4.0 + 4.0 * cell_gap((l[i].sigma, l[i].psi), (l[j].sigma, l[j].psi)),
_ => false,
}
};
let junction = |i: usize| -> Result<Option<(TrimPoint, TrimPoint)>, String> {
let j = (i + 1) % n;
let (a, b) = (l[i], l[j]);
let pa = (a.sigma, a.psi);
let pb = (unwrap(b.sigma, pa.0, 4.0), unwrap(b.psi, pa.1, TAU));
let (ma, mb) = (mates[i].ok_or("a mate is singular [j]")?, mates[j].ok_or("a mate is singular [j]")?);
let read = |f: f64, guess: f64| -> Result<(TrimPoint, Option<(f64, f64)>), String> {
let (s, p, time, point) = contour(pa, pb, f, guess).map_err(|e| format!("{e} [junction]"))?;
let m = mate_read(point, time, s).map(|(m, _)| m);
Ok((TrimPoint { sigma: s.rem_euclid(4.0), psi: p.rem_euclid(TAU), mate_time: time, point }, m))
};
let (mut lo, mut hi) = (0.0f64, 1.0f64);
let (mut left, mut right) = (a, b);
let (mut left_mate, mut right_mate) = (Some(ma), Some(mb));
for _ in 0..40 {
let mid = 0.5 * (lo + hi);
let (point, m) = read(mid, left.mate_time)?;
let follows_a = m.is_some_and(|m| cell_gap(m, ma) <= cell_gap(m, mb));
if follows_a {
lo = mid;
left = point;
left_mate = m;
} else {
hi = mid;
right = point;
right_mate = m;
}
}
match (left_mate, right_mate) {
(Some(x), Some(y)) if cell_gap(x, y) <= 0.05 => Ok(None),
_ => Ok(Some((left, right))),
}
};
let junctions: Vec<Option<(TrimPoint, TrimPoint)>> = (0..n).map(|i| if jump(i) { junction(i).unwrap_or(None) } else { None }).collect();
let walked: Vec<Option<TrimPoint>> = (0..n)
.map(|i| -> Result<Option<TrimPoint>, String> {
if !cusp[i] {
return Ok(None);
}
let w = walk(i)?;
let closed = mate_read(w.point, w.mate_time, w.sigma).is_some_and(|(m, _)| cell_gap(m, (w.sigma, w.psi)) <= 0.05);
if trace76 {
eprintln!("T76 walk from {i} ({:.6}, {:.6}) reached ({:.6}, {:.6}) mate {:?} closed {closed}", l[i].sigma, l[i].psi, w.sigma, w.psi, mate_read(w.point, w.mate_time, w.sigma).map(|x| x.0));
}
Ok(closed.then_some(w))
})
.collect::<Result<_, _>>()?;
let mut walked = walked;
{
let on_seam = |sigma: f64| {
let f = sigma.rem_euclid(1.0);
f.min(1.0 - f) <= 1e-6
};
let along: Vec<Option<f64>> = (0..n)
.map(|i| {
let m = mates[i]?;
let (k, d) = (0..n).map(|k| (k, cell_gap(m, (l[k].sigma, l[k].psi)))).min_by(|x, y| x.1.total_cmp(&y.1))?;
if d > 1.5 {
return None;
}
let mut steps = (k as i64 - i as i64).rem_euclid(n as i64);
if steps > n as i64 / 2 {
steps -= n as i64;
}
Some(steps as f64)
})
.collect();
for i in 0..n {
let j = (i + 1) % n;
if trace76 && n < 60 {
eprintln!("T76 fold scan {i}: along {:?} {:?} gaps {:.3} mate {:?} walked {} cand {}", along[i], along[j], gaps[i], mates[i], walked[i].is_some(), cusp[i]);
}
let (Some(x), Some(y)) = (along[i], along[j]) else { continue };
if !(x.abs() <= 3.0 && y.abs() <= 3.0 && x * y <= 0.0 && x != y) || walked[i].is_some() || walked[j].is_some() {
continue;
}
if (1..=3).any(|d| walked[(i + n - d % n) % n].is_some() || walked[(j + d) % n].is_some()) {
continue;
}
if x == 0.0 && !along[(i + n - 1) % n].is_some_and(|p| p * y < 0.0) || y == 0.0 && !along[(j + 1) % n].is_some_and(|q| q * x < 0.0) {
continue;
}
let (a, b) = (l[i], l[j]);
let pa = (a.sigma, a.psi);
let pb = (unwrap(b.sigma, pa.0, 4.0), unwrap(b.psi, pa.1, TAU));
let (cs, cp) = ((pb.0 - pa.0) / cell_sigma(pa.0), (pb.1 - pa.1) / cell_psi);
let offset = |f: f64, guess: f64| -> Option<(f64, f64, TrimPoint, (f64, f64))> {
let (s, p, time, point) = contour(pa, pb, f, guess).ok()?;
let (m, _) = mate_read(point, time, s)?;
let m = (unwrap(m.0, s, 4.0), unwrap(m.1, p, TAU));
let ahead = ((m.0 - s) / cell_sigma(s)) * cs + ((m.1 - p) / cell_psi) * cp;
Some((ahead, cell_gap(m, (s, p)), TrimPoint { sigma: s.rem_euclid(4.0), psi: p.rem_euclid(TAU), mate_time: time, point }, m))
};
let (o0, o1) = (offset(0.0, a.mate_time), offset(1.0, b.mate_time));
if trace76 {
eprintln!("T76 fold try {i}: h0 {:?} h1 {:?}", o0.as_ref().map(|o| (o.0, o.1)), o1.as_ref().map(|o| (o.0, o.1)));
}
let (Some((h0, ..)), Some((h1, ..))) = (o0, o1) else { continue };
if (h0 < 0.0) == (h1 < 0.0) {
continue;
}
let (mut lo, mut hi, mut guess) = (0.0f64, 1.0f64, a.mate_time);
let mut last = None;
let mut sides: [Option<(f64, TrimPoint, (f64, f64))>; 2] = [None, None];
for _ in 0..50 {
let mid = 0.5 * (lo + hi);
let Some((h, gap, point, m)) = offset(mid, guess) else { break };
guess = point.mate_time;
last = Some((gap, point));
if (h < 0.0) == (h0 < 0.0) {
lo = mid;
sides[0] = Some((gap, point, m));
} else {
hi = mid;
sides[1] = Some((gap, point, m));
}
}
let apart = sides.iter().flatten().filter(|x| x.0 > 0.05).max_by(|x, y| x.0.total_cmp(&y.0)).copied();
let fallen = sides.iter().flatten().any(|x| x.0 <= 0.05);
let (before, after) = (along[(i + n - 1) % n], along[(j + 1) % n]);
let fallen = fallen && matches!((before, after), (Some(p), Some(q)) if p * q < 0.0 && (p > 0.0) == (x > y));
if let Some((gap, point, m)) = apart {
if gap <= 1.0 && fallen {
let own = (unwrap(point.sigma, pa.0, 4.0), unwrap(point.psi, pa.1, TAU));
let m = (unwrap(m.0, own.0, 4.0), unwrap(m.1, own.1, TAU));
if let Ok((s, p, time, at)) = contour(own, m, 0.5, point.mate_time) {
last = Some((0.0, TrimPoint { sigma: s.rem_euclid(4.0), psi: p.rem_euclid(TAU), mate_time: time, point: at }));
}
}
}
if trace76 {
eprintln!("T76 fold bisect {i}: lo {lo} hi {hi} last {:?}", last.as_ref().map(|(g, p)| (*g, p.sigma, p.psi)));
}
if let Some((gap, point)) = last {
let reached = walked.iter().flatten().any(|w| cell_gap((w.sigma, w.psi), (point.sigma, point.psi)) <= 1.0);
if gap <= 0.05 && !on_seam(point.sigma) && !reached {
walked[i] = Some(point);
}
}
}
}
for w in walked.iter_mut() {
let Some(p) = *w else { continue };
let seam = p.sigma.round();
if (p.sigma - seam).abs() > 1e-5 || p.sigma == seam {
continue;
}
let read = |psi: f64| g_near(seam, psi, p.mate_time);
let reach = 0.02 * cell_psi;
let (Some(f0), Some(f1)) = (read(p.psi - reach).map(|x| x.0), read(p.psi + reach).map(|x| x.0)) else { continue };
if (f0 < 0.0) == (f1 < 0.0) {
continue;
}
let (mut lo, mut hi) = (p.psi - reach, p.psi + reach);
for _ in 0..60 {
let mid = 0.5 * (lo + hi);
match read(mid) {
Some(x) if (x.0 < 0.0) == (f0 < 0.0) => lo = mid,
Some(_) => hi = mid,
None => break,
}
}
let psi = 0.5 * (lo + hi);
if let Some((_, time, point)) = read(psi) {
*w = Some(TrimPoint { sigma: seam.rem_euclid(4.0), psi: psi.rem_euclid(TAU), mate_time: time, point });
}
}
let mut seen: Vec<(f64, f64)> = Vec::new();
for w in walked.iter_mut() {
if let Some(p) = *w {
if seen.iter().any(|q| cell_gap(*q, (p.sigma, p.psi)) <= 1e-3) {
*w = None;
} else {
seen.push((p.sigma, p.psi));
}
}
}
let cusp: Vec<bool> = walked.iter().map(|w| w.is_some()).collect();
let events = (0..n).any(|i| cusp[i] || junctions[i].is_some() || jump_after[i].is_some() || forced[i].is_some());
if trace76 {
for i in 0..n { if cusp[i] || junctions[i].is_some() || jump_after[i].is_some() || forced[i].is_some() { eprintln!("T76 event at {i} ({:.6}, {:.6}): cusp {} junction {} jump {} forced {}", l[i].sigma, l[i].psi, cusp[i], junctions[i].is_some(), jump_after[i].is_some(), forced[i].is_some()); } }
}
if !events {
let middle = (l[n / 2].sigma, l[n / 2].psi);
if trace76 {
let mm: Vec<String> = (0..n).step_by((n / 8).max(1)).map(|i| match mates[i] { Some(m) => format!("({:.4}, {:.4}){}", m.0, m.1, if in_chart(m.0.rem_euclid(4.0), m.1.rem_euclid(TAU)) { "C" } else { "" }), None => "-".into() }).collect();
eprintln!("T76 no events: own ({:.6}, {:.6})..({:.6}, {:.6}) mates {mm:?} twin_of {:?}", l[0].sigma, l[0].psi, l[n / 2].sigma, l[n / 2].psi, kept_mates.iter().position(|path| path_near(path, middle, &cell_gap)));
}
if let Some(k) = kept_mates.iter().position(|path| path_near(path, middle, &cell_gap)) {
twins[k].extend(l.iter().copied());
continue;
}
kept_mates.push(mates.iter().flatten().copied().collect());
twins.push(Vec::new());
curves.push((l.clone(), false, [false, false]));
continue;
}
let mut sequence: Vec<(TrimPoint, u8)> = Vec::with_capacity(n + 8);
for i in 0..n {
let into = jump_after[(i + n - 1) % n].is_some();
let out = jump_after[i].is_some();
if into && out {
sequence.push((l[i], 3));
sequence.push((l[i], 2));
} else if out {
sequence.push((l[i], 2));
} else if into {
sequence.push((l[i], 3));
} else if cusp[i] {
sequence.push((walked[i].expect("walked"), 1));
} else {
sequence.push((l[i], 0));
}
if out {
continue;
}
let far_first = match (junctions[i], forced[i]) {
(Some((left, _)), Some(far)) => along_chord(l[i], l[(i + 1) % n], (far.sigma, far.psi)).0 < along_chord(l[i], l[(i + 1) % n], (left.sigma, left.psi)).0,
_ => false,
};
if let (true, Some(far)) = (far_first, forced[i]) {
sequence.push((far, 2));
sequence.push((far, 3));
}
if let Some((left, right)) = junctions[i] {
sequence.push((left, 2));
sequence.push((right, 3));
}
if let (false, Some(far)) = (far_first, forced[i]) {
sequence.push((far, 2));
sequence.push((far, 3));
}
}
let first = sequence.iter().position(|(_, c)| *c == 1 || *c == 3).ok_or("a trim loop's cuts start no arc")?;
sequence.rotate_left(first);
let total = sequence.len();
let mut k = 0;
while k < total {
let (start, start_cut) = sequence[k];
let mut arc = vec![start];
let mut j = k + 1;
let end_cut = loop {
let (point, cut) = sequence[j % total];
if cut == 1 || cut == 2 {
arc.push(point);
break cut;
}
if cut == 3 {
return Err("a junction's next arc starts before the last ends".into());
}
arc.push(point);
j += 1;
if j > k + total {
return Err("a trim loop's arc never ends".into());
}
};
k = if end_cut == 1 { j } else { j + 1 };
if arc.len() < 2 || arc.iter().all(|p| p.point.sub(arc[0].point).length() <= 1e-12 * size) {
continue;
}
let arc_mates: Vec<(f64, f64)> = arc.iter().filter_map(|p| mate_read(p.point, p.mate_time, p.sigma).map(|(m, _)| m)).collect();
if trace76 {
let (a0, a1) = (arc[0], arc[arc.len() - 1]);
let mm = arc_mates.get(arc_mates.len() / 2).copied().unwrap_or((f64::NAN, f64::NAN));
eprintln!("T76 arc {} pts ({:.6}, {:.6}) -> ({:.6}, {:.6}) cuts {start_cut}/{end_cut}, middle mate ({:.6}, {:.6}) in_chart {}", arc.len(), a0.sigma, a0.psi, a1.sigma, a1.psi, mm.0, mm.1, in_chart(mm.0.rem_euclid(4.0), mm.1.rem_euclid(TAU)));
for (p, m) in arc.iter().zip(arc_mates.iter()) { eprintln!("T76 ({:.6}, {:.6}) mate ({:.6}, {:.6})", p.sigma, p.psi, m.0, m.1); }
}
let mate_middle = match arc_mates.len() {
0 | 1 => None,
2 => {
let (x, y) = (arc_mates[0], arc_mates[1]);
let y = (unwrap(y.0, x.0, 4.0), unwrap(y.1, x.1, TAU));
(cell_gap((x.0.rem_euclid(4.0), x.1.rem_euclid(TAU)), (y.0.rem_euclid(4.0), y.1.rem_euclid(TAU))) <= 4.0).then_some((0.5 * (x.0 + y.0), 0.5 * (x.1 + y.1)))
}
n => Some(arc_mates[n / 2]),
};
if mate_middle.is_some_and(|m| in_chart(m.0.rem_euclid(4.0), m.1.rem_euclid(TAU))) {
if trace76 { eprintln!("T76 -> chart run's mate side (dropped)"); }
continue;
}
let middle = (arc[arc.len() / 2].sigma, arc[arc.len() / 2].psi);
if let Some(k) = kept_mates.iter().position(|path| path_near(path, middle, &cell_gap)) {
if trace76 { eprintln!("T76 -> twin of curve {k}"); }
twins[k].extend(arc.iter().copied());
continue;
}
if trace76 { eprintln!("T76 -> kept as curve {}", curves.len()); }
kept_mates.push(arc_mates);
twins.push(Vec::new());
curves.push((arc, true, [start_cut == 1, end_cut == 1]));
if k >= total {
break;
}
}
}
struct Dense {
own: Vec<(f64, f64)>,
mate: Vec<(f64, f64)>,
point: Vec<Vec3>,
split: Vec<bool>,
time: Vec<f64>,
}
let mut dense_loops: Vec<(usize, Dense, bool)> = Vec::new();
let trace_stages = std::env::var("BREP_TUBE_TRACE_STAGES").is_ok();
for (k, (l, open, cusps)) in curves.iter().enumerate() {
let (open, cusps) = (*open, *cusps);
if trace_stages {
eprintln!("TS dense curve {k}: {} points, open {open}", l.len());
}
let mut dense = Dense { own: Vec::new(), mate: Vec::new(), point: Vec::new(), split: Vec::new(), time: Vec::new() };
let n = l.len();
let mut previous: Option<(f64, f64)> = None;
let mut last: Option<((f64, f64), (f64, f64))> = None;
let twin = &twins[k];
let on_twin = |point: Vec3, own: (f64, f64)| -> Option<(f64, f64)> {
let near = twin.iter().filter(|t| cell_gap((t.sigma, t.psi), own) > 0.05).min_by(|a, b| a.point.sub(point).length().total_cmp(&b.point.sub(point).length()))?;
let m = follow(point, (near.sigma, near.psi))?;
Some((m.0.rem_euclid(4.0), m.1.rem_euclid(TAU)))
};
let junction_mate = |a: TrimPoint, b: TrimPoint| -> Option<((f64, f64), f64)> {
let own_time = tube.own_time(a.sigma);
let range = tube.to - tube.from;
let nb = on_twin(b.point, (b.sigma, b.psi))?;
if cell_gap(nb, (b.sigma, b.psi)) <= 1.0 {
return None;
}
tube.touching_times(a.point, 1e-3 * size)
.into_iter()
.filter(|t| (t - own_time).abs() > 1e-3 * range)
.filter_map(|t| tube.mate_of(a.point, t).map(|m| (m, t)))
.filter(|(m, _)| cell_gap(*m, nb) <= 2.0 && cell_gap(*m, (a.sigma, a.psi)) > 1.0)
.min_by(|x, y| cell_gap(x.0, nb).total_cmp(&cell_gap(y.0, nb)))
};
let mate_next_read = |point: Vec3, time: f64, own: (f64, f64), last: Option<((f64, f64), (f64, f64))>| -> Option<((f64, f64), f64)> {
if let Some(m) = on_twin(point, own).filter(|m| cell_gap(*m, own) > 1e-4) {
return Some((m, tube.own_time(m.0)));
}
if let Some((lo, lm)) = last {
let apart = cell_gap(lo, lm);
if apart > 0.05 {
if let Some(m) = follow(point, lm) {
let m = (m.0.rem_euclid(4.0), m.1.rem_euclid(TAU));
if cell_gap(m, own) > 0.25 * apart.min(2.0) {
return Some((m, tube.own_time(m.0)));
}
}
}
}
mate_read(point, time, own.0)
};
let mate_next = |point: Vec3, time: f64, own: (f64, f64), last: Option<((f64, f64), (f64, f64))>| -> Option<((f64, f64), f64)> {
let read = mate_next_read(point, time, own, last)?;
if let Some((lo, lm)) = last {
let step = cell_gap(lo, own);
if cell_gap(read.0, lm) > 3.0 + 3.0 * step {
if let Some(m) = follow(point, lm) {
let m = (m.0.rem_euclid(4.0), m.1.rem_euclid(TAU));
if cell_gap(m, lm) <= 3.0 + 3.0 * step && cell_gap(m, own) > 1e-4 {
return Some((m, tube.own_time(m.0)));
}
}
}
}
Some(read)
};
for i in 0..n {
if open && i + 1 == n {
let a = l[i];
let pa = match previous {
Some(p) => (unwrap(a.sigma, p.0, 4.0), unwrap(a.psi, p.1, TAU)),
None => (a.sigma, a.psi),
};
let across = if cusps[1] && n >= 2 { junction_mate(a, l[n - 2]) } else { None };
let (mate, time) = if let Some(m) = across { m } else if cusps[1] { (pa, a.mate_time) } else { mate_read(a.point, a.mate_time, a.sigma).ok_or("a mate is singular [5]")? };
dense.own.push(pa);
dense.point.push(a.point);
dense.mate.push(mate);
dense.split.push(true);
dense.time.push(time);
break;
}
let (a, b) = (l[i], l[(i + 1) % n]);
if domain_gap((a.sigma, a.psi), (b.sigma, b.psi)) <= 1e-12 && !(open && i + 2 == n) && !(open && i == 0) {
continue;
}
let pa = match previous {
Some(p) => (unwrap(a.sigma, p.0, 4.0), unwrap(a.psi, p.1, TAU)),
None => (a.sigma, a.psi),
};
let pb = (unwrap(b.sigma, pa.0, 4.0), unwrap(b.psi, pa.1, TAU));
let on_sigma_side = sigma_bounds.iter().any(|s| wrap(*s, a.sigma, 4.0) <= 1e-12);
let on_psi_side = psi_bounds.iter().any(|q| wrap(*q, a.psi, TAU) <= 1e-12);
dense.own.push(pa);
dense.point.push(a.point);
let across = if open && i == 0 && cusps[0] && n >= 2 { junction_mate(a, l[1]) } else { None };
let (mate, time) = if let Some(m) = across { m } else if open && i == 0 && cusps[0] { (pa, a.mate_time) } else { mate_next(a.point, a.mate_time, (a.sigma, a.psi), last).ok_or("a mate is singular [1]")? };
last = Some(((a.sigma, a.psi), mate));
dense.mate.push(mate);
dense.split.push(on_sigma_side || on_psi_side || (open && i == 0));
dense.time.push(time);
let fractions: &[f64] = if domain_gap(pa, pb) <= 1e-12 { &[] } else { &[0.25, 0.5, 0.75] };
for &f in fractions {
let (s, p, time, point) = contour(pa, pb, f, time).map_err(|e| format!("{e} [densify]"))?;
dense.own.push((unwrap(s, pa.0, 4.0), unwrap(p, pa.1, TAU)));
dense.point.push(point);
let (mate, time) = mate_next(point, time, (s.rem_euclid(4.0), p.rem_euclid(TAU)), last).ok_or("a mate is singular [2]")?;
last = Some(((s.rem_euclid(4.0), p.rem_euclid(TAU)), mate));
dense.mate.push(mate);
dense.split.push(false);
dense.time.push(time);
}
previous = Some(pa);
}
{
let len = dense.mate.len();
let wrapped = |x: (f64, f64)| (x.0.rem_euclid(4.0), x.1.rem_euclid(TAU));
for q in 1..len.saturating_sub(1) {
let (a, m, b) = (wrapped(dense.mate[q - 1]), wrapped(dense.mate[q]), wrapped(dense.mate[q + 1]));
let step = cell_gap(wrapped(dense.own[q - 1]), wrapped(dense.own[q + 1]));
let tol = 3.0 + 3.0 * step;
if cell_gap(a, b) <= tol && cell_gap(m, a) > tol && cell_gap(m, b) > tol && !dense.split[q] {
if let Some(fixed) = follow(dense.point[q], a) {
let fixed = wrapped(fixed);
if cell_gap(fixed, a) <= tol {
dense.mate[q] = fixed;
dense.time[q] = tube.own_time(fixed.0);
}
}
}
}
}
for i in 1..dense.mate.len() {
let before = dense.mate[i - 1];
dense.mate[i] = (unwrap(dense.mate[i].0, before.0, 4.0), unwrap(dense.mate[i].1, before.1, TAU));
}
let mut i = 0;
let split_cap = 2 * dense.own.len() + 64;
let mut splits = 0usize;
while i < dense.own.len() {
if splits > split_cap {
return Err(format!("a trim curve's mates cross patch sides more than {split_cap} times"));
}
if open && i + 1 >= dense.own.len() {
break;
}
let j = (i + 1) % dense.own.len();
let (ma, mb) = (dense.mate[i], dense.mate[j]);
let mb = (unwrap(mb.0, ma.0, 4.0), unwrap(mb.1, ma.1, TAU));
let crossing = |x: f64, y: f64, bounds: &[f64], period: f64| -> Option<f64> {
bounds.iter().flat_map(|b| (-2..=2).map(move |w| b + w as f64 * period)).find(|b| (x - b) * (y - b) < 0.0 && (x - b).abs() > 1e-12 && (y - b).abs() > 1e-12)
};
let found = crossing(ma.0, mb.0, &sigma_bounds, 4.0).map(|b| (0, b)).or_else(|| crossing(ma.1, mb.1, &psi_bounds, TAU).map(|b| (1, b)));
let found = found.filter(|_| cell_gap((ma.0.rem_euclid(4.0), ma.1.rem_euclid(TAU)), (mb.0.rem_euclid(4.0), mb.1.rem_euclid(TAU))) <= 3.0 + 3.0 * cell_gap(dense.own[i], dense.own[j]));
if let Some((axis, bound)) = found {
let (oa, ob) = (dense.own[i], dense.own[j]);
let ob = (unwrap(ob.0, oa.0, 4.0), unwrap(ob.1, oa.1, TAU));
let guess = dense.time[i];
let mate_coord = |f: f64| -> Result<(f64, (f64, f64), (f64, f64), Vec3), String> {
let (s, p, time, point) = contour(oa, ob, f, guess).map_err(|e| format!("{e} [mate-split]"))?;
let here = (s.rem_euclid(4.0), p.rem_euclid(TAU));
let near_ma = |m: &(f64, f64)| cell_gap((m.0.rem_euclid(4.0), m.1.rem_euclid(TAU)), (ma.0.rem_euclid(4.0), ma.1.rem_euclid(TAU))) <= 3.0 + cell_gap(oa, ob);
let apart = |m: &(f64, f64)| cell_gap((m.0.rem_euclid(4.0), m.1.rem_euclid(TAU)), here) > 1e-4;
let followed = follow(point, ma).filter(|m| apart(m) && near_ma(m)).or_else(|| on_twin(point, here).filter(|m| apart(m) && near_ma(m)));
let m = match followed {
Some(m) => m,
None => mate_read(point, time, s).ok_or("a mate is singular [3]")?.0,
};
let m = (unwrap(m.0, ma.0, 4.0), unwrap(m.1, ma.1, TAU));
Ok((if axis == 0 { m.0 } else { m.1 } - bound, (unwrap(s, oa.0, 4.0), unwrap(p, oa.1, TAU)), m, point))
};
let (mut lo, mut hi) = (0.0f64, 1.0f64);
let start = if axis == 0 { ma.0 } else { ma.1 } - bound;
for _ in 0..50 {
let mid = 0.5 * (lo + hi);
if (mate_coord(mid)?.0 < 0.0) == (start < 0.0) {
lo = mid;
} else {
hi = mid;
}
}
let (_, own, mut mate, point) = mate_coord(0.5 * (lo + hi))?;
if axis == 0 {
mate.0 = bound;
} else {
mate.1 = bound;
}
let near_cusp = |q: usize| cell_gap((dense.own[q].0.rem_euclid(4.0), dense.own[q].1.rem_euclid(TAU)), (own.0.rem_euclid(4.0), own.1.rem_euclid(TAU))) <= 0.1;
let last = dense.own.len() - 1;
if open && ((cusps[0] && near_cusp(0)) || (cusps[1] && near_cusp(last))) {
i += 1;
continue;
}
dense.own.insert(i + 1, own);
dense.mate.insert(i + 1, mate);
dense.point.insert(i + 1, point);
dense.split.insert(i + 1, true);
dense.time.insert(i + 1, guess);
splits += 1;
}
i += 1;
}
if !dense.split.iter().any(|s| *s) {
return Err("a trim loop never crosses a patch side".into());
}
dense_loops.push((k, dense, open));
}
let regular_loops = dense_loops.len();
if trace_stages {
eprintln!("TS chart runs");
}
let mut chart_runs: Vec<(usize, usize)> = Vec::new();
for (c, rim) in rims.iter().enumerate() {
for (r, edge) in rim.edges.iter().enumerate() {
let Some(outside) = edge.outside.as_ref() else { continue };
let n = edge.points.len();
if n < 2 || outside.len() != n {
return Err("a chart edge has too few points".into());
}
let side_of = |pm: (f64, f64), m: (f64, f64)| -> Option<(u8, f64)> {
let across = |x: f64, y: f64, bounds: &[f64], period: f64| -> Option<f64> {
bounds.iter().flat_map(|b| (-2..=2).map(move |w| b + w as f64 * period)).find(|b| (x - b) * (y - b) < 0.0 && (x - b).abs() > 1e-12 && (y - b).abs() > 1e-12)
};
across(pm.0, m.0, &sigma_bounds, 4.0).map(|b| (0, b)).or_else(|| across(pm.1, m.1, &psi_bounds, TAU).map(|b| (1, b)))
};
let mut dense = Dense { own: Vec::new(), mate: Vec::new(), point: Vec::new(), split: Vec::new(), time: Vec::new() };
for k in 0..n {
let m = (outside[k].sigma, outside[k].psi);
let m = match dense.mate.last() {
Some(pm) => (unwrap(m.0, pm.0, 4.0), unwrap(m.1, pm.1, TAU)),
None => m,
};
if let Some(&pm) = dense.mate.last() {
if let Some((axis, bound)) = side_of(pm, m) {
let (ca, cb) = if axis == 0 { (pm.0, m.0) } else { (pm.1, m.1) };
let f = (bound - ca) / (cb - ca);
let mut at = (pm.0 + (m.0 - pm.0) * f, pm.1 + (m.1 - pm.1) * f);
if axis == 0 {
at.0 = bound;
} else {
at.1 = bound;
}
let point = tube.k_at(at.0.rem_euclid(4.0), at.1.rem_euclid(TAU)).ok_or("K is singular on a chart edge's mate side")?;
dense.own.push(at);
dense.mate.push(at);
dense.point.push(point);
dense.split.push(true);
dense.time.push(outside[k].mate_time);
}
}
dense.own.push(m);
dense.mate.push(m);
dense.point.push(edge.points[k]);
dense.split.push(k == 0 || k + 1 == n);
dense.time.push(outside[k].mate_time);
}
dense_loops.push((usize::MAX, dense, true));
chart_runs.push((c, r));
}
}
let _ = (fit, lattice);
struct Raw {
own_patch: (usize, usize),
mate_patch: (usize, usize),
own: Vec<(f64, f64)>,
mate: Vec<(f64, f64)>,
points: Vec<Vec3>,
times: Vec<f64>,
marks: [Mark; 2],
chart: bool,
source: usize,
}
let mut raws: Vec<Raw> = Vec::new();
#[allow(unused_mut)]
for (index, (_, dense, open)) in dense_loops.iter().enumerate() {
let n = dense.own.len();
let first = dense.split.iter().position(|s| *s).unwrap();
let mut start = first;
loop {
if *open && start + 1 >= n {
break; }
let mut end = (start + 1) % n;
let mut own = vec![dense.own[start]];
let mut mate = vec![dense.mate[start]];
let mut points = vec![dense.point[start]];
let mut times = vec![dense.time[start]];
loop {
let last = *own.last().unwrap();
let o = dense.own[end];
own.push((unwrap(o.0, last.0, 4.0), unwrap(o.1, last.1, TAU)));
let lm = *mate.last().unwrap();
let m = dense.mate[end];
mate.push((unwrap(m.0, lm.0, 4.0), unwrap(m.1, lm.1, TAU)));
points.push(dense.point[end]);
times.push(dense.time[end]);
if dense.split[end] {
break;
}
end = (end + 1) % n;
}
let middle = own.len() / 2;
let (om, mm) = (own[middle], mate[middle]);
let (om, mm) = if own.len() == 2 { ((0.5 * (own[0].0 + own[1].0), 0.5 * (own[0].1 + own[1].1)), (0.5 * (mate[0].0 + mate[1].0), 0.5 * (mate[0].1 + mate[1].1))) } else { (om, mm) };
raws.push(Raw {
own_patch: (row_of(om.0), column_of(om.1)),
mate_patch: (row_of(mm.0), column_of(mm.1)),
own,
mate,
points,
times,
marks: [Mark::Split(index, start), Mark::Split(index, end)],
chart: index >= regular_loops,
source: index,
});
start = end;
if start == first || (*open && start + 1 >= n) {
break;
}
}
}
{
let weld = 1e-7 * (tube.major + tube.minor);
let mut names: Vec<(Mark, Vec3)> = Vec::new();
for raw in raws.iter_mut() {
for end in 0..2 {
let Mark::Split(l, i) = raw.marks[end] else { continue };
let point = dense_loops[l].1.point[i];
match names.iter().find(|(_, q)| q.sub(point).length() <= weld) {
Some((name, _)) => raw.marks[end] = *name,
None => names.push((raw.marks[end], point)),
}
}
}
}
if trace_stages {
eprintln!("TS refine {} raws", raws.len());
}
for (raw_index, raw) in raws.iter_mut().enumerate() {
if trace_stages {
eprintln!("TS raw {raw_index}: {} points, source {}, own ({:.6}, {:.6})", raw.points.len(), raw.source, raw.own[0].0, raw.own[0].1);
}
if raw.chart {
continue;
}
let mut good = vec![false; raw.points.len() - 1];
let mut settled = false;
for _round in 0..32 {
if raw.points.len() > 4096 {
return Err(format!("a trim edge does not settle within the fit {edge_fit:.1e} (over 4096 stations)"));
}
if trace_stages && _round < 6 {
for k in 0..raw.own.len() {
eprintln!("TS round {_round} k {k} own ({:.6}, {:.6}) mate ({:.6}, {:.6}) t {:.5} good {}", raw.own[k].0, raw.own[k].1, raw.mate[k].0, raw.mate[k].1, raw.times[k], k < good.len() && good[k]);
}
}
let mut params = vec![0.0];
for pair in raw.points.windows(2) {
params.push(params.last().unwrap() + pair[1].sub(pair[0]).length().max(1e-300));
}
let total = *params.last().unwrap();
let params: Vec<f64> = params.iter().map(|t| t / total).collect();
let curve = crate::interpolate_curve(&raw.points, 3.min(raw.points.len() - 1), ¶ms)?;
let path = |line: &[(f64, f64)]| crate::interpolate_curve(&line.iter().map(|(x, y)| Vec3::new(*x, *y, 0.0)).collect::<Vec<_>>(), 3.min(line.len() - 1), ¶ms);
let (own_path, mate_path) = (path(&raw.own)?, path(&raw.mate)?);
let last = raw.own.len() - 1;
let folds = [0, last].iter().any(|&k| cell_gap((raw.own[k].0.rem_euclid(4.0), raw.own[k].1.rem_euclid(TAU)), (raw.mate[k].0.rem_euclid(4.0), raw.mate[k].1.rem_euclid(TAU))) <= 1e-6);
let apart = |path: &crate::NurbsCurve, t: f64| -> f64 {
match (path.evaluate(t), curve.evaluate(t)) {
(Ok(q), Ok(c)) => tube.k_at(q.x.rem_euclid(4.0), q.y.rem_euclid(TAU)).map(|p| p.sub(c).length()).unwrap_or(0.0),
_ => 0.0,
}
};
let mut inserts: Vec<(usize, (f64, f64), (f64, f64), f64, Vec3)> = Vec::new();
for (k, fraction) in (0..raw.points.len() - 1).filter(|k| !good[*k]).flat_map(|k| [0.25, 0.5, 0.75].map(|f| (k, f))) {
let guess = tube.own_time(raw.mate[k].0.rem_euclid(4.0));
let (s_mid, p_mid, time, target) = match contour(raw.own[k], raw.own[k + 1], fraction, guess) {
Ok(found) => found,
Err(_) if fraction != 0.5 => continue,
Err(e) => return Err(format!("{e} [refine]")),
};
let (lo, hi) = (params[k], params[k + 1]);
let distance = |t: f64| curve.evaluate(t).map(|p| p.sub(target).length()).unwrap_or(f64::INFINITY);
let mut best = (f64::INFINITY, lo);
for j in 0..=32 {
let t = lo + (hi - lo) * j as f64 / 32.0;
let d = distance(t);
if d < best.0 {
best = (d, t);
}
}
let step = (hi - lo) / 32.0;
let (mut a, mut b) = ((best.1 - step).max(lo), (best.1 + step).min(hi));
let ratio = 0.5 * (5f64.sqrt() - 1.0);
for _ in 0..60 {
let (c, d) = (b - ratio * (b - a), a + ratio * (b - a));
if distance(c) < distance(d) {
b = d;
} else {
a = c;
}
}
let miss_here = distance(0.5 * (a + b)).min(best.0);
let miss_here = if fraction == 0.5 {
let own_miss = 2.0 * apart(&own_path, 0.5 * (lo + hi));
let mate_miss = if folds { 0.0 } else { 2.0 * apart(&mate_path, 0.5 * (lo + hi)) };
miss_here.max(own_miss).max(mate_miss)
} else {
miss_here
};
if miss_here > edge_fit && fraction == 0.5 || miss_here > edge_fit && !inserts.iter().any(|i| i.0 == k + 1) {
if trace_stages && _round < 6 {
eprintln!("TS miss {miss_here:.3e} at gap {k} fraction {fraction} mid ({s_mid:.6}, {p_mid:.6})");
}
let (s_mid, p_mid, time, target) = if fraction == 0.5 { (s_mid, p_mid, time, target) } else { contour(raw.own[k], raw.own[k + 1], 0.5, guess)? };
let own = (unwrap(s_mid, raw.own[k].0, 4.0), unwrap(p_mid, raw.own[k].1, TAU));
let (m, _) = mate_read(target, time, s_mid).ok_or("a mate is singular [4]")?;
let mate = (unwrap(m.0, raw.mate[k].0, 4.0), unwrap(m.1, raw.mate[k].1, TAU));
if !inserts.iter().any(|i| i.0 == k + 1) {
inserts.push((k + 1, own, mate, time, target));
}
}
}
if inserts.is_empty() {
if good.iter().all(|g| !g) {
settled = true;
break;
}
good.iter_mut().for_each(|g| *g = false);
continue;
}
let split: std::collections::HashSet<usize> = inserts.iter().map(|i| i.0 - 1).collect();
let mut next_good = Vec::with_capacity(good.len() + inserts.len());
for k in 0..good.len() {
if split.contains(&k) {
next_good.push(false);
next_good.push(false);
} else {
next_good.push(true);
}
}
good = next_good;
for (at, own, mate, time, point) in inserts.into_iter().rev() {
raw.own.insert(at, own);
raw.mate.insert(at, mate);
raw.times.insert(at, time);
raw.points.insert(at, point);
}
}
if !settled {
return Err(format!("a trim edge does not settle within the fit {edge_fit:.1e} in 32 rounds"));
}
}
let patch_box = |a: usize, b: usize| -> ([f64; 2], [f64; 2]) { ([sigma_bounds[a], sigma_bounds[a + 1]], [psi_bounds[b], psi_end(b)]) };
let localise = |line: &[(f64, f64)], a: usize, b: usize| -> Vec<(f64, f64)> {
let (su, pv) = patch_box(a, b);
let m = line[line.len() / 2];
let (ds, dp) = (((0.5 * (su[0] + su[1]) - m.0) / 4.0).round() * 4.0, ((0.5 * (pv[0] + pv[1]) - m.1) / TAU).round() * TAU);
line.iter().map(|(x, y)| (x + ds, y + dp)).collect()
};
let kept_left = |line: &[(f64, f64)]| -> Result<bool, String> {
let k = (line.len() / 2).max(1).min(line.len() - 1);
let (a, b) = (line[k - 1], line[k]);
let (ds, dp) = (cell_sigma(a.0), cell_psi);
let (cs, cp) = ((b.0 - a.0) / ds, (b.1 - a.1) / dp);
let length = cs.hypot(cp);
if !(length > 0.0) {
return Err("a trim piece has no length".into());
}
let m = (0.5 * (a.0 + b.0), 0.5 * (a.1 + b.1));
let left = (m.0 - 0.05 * cp / length * ds, m.1 + 0.05 * cs / length * dp);
Ok(g_at(left.0, left.1).ok_or("K is singular near a trim curve")?.0 >= 0.0)
};
let mut held: std::collections::HashMap<(usize, usize), Vec<Piece>> = std::collections::HashMap::new();
for (e, raw) in raws.iter().enumerate() {
let own_forward = if raw.chart { !kept_left(&localise(&raw.mate, raw.mate_patch.0, raw.mate_patch.1))? } else { kept_left(&localise(&raw.own, raw.own_patch.0, raw.own_patch.1))? };
for (side, (patch, line)) in [(raw.own_patch, &raw.own), (raw.mate_patch, &raw.mate)].into_iter().enumerate() {
if raw.chart && side == 0 {
continue;
}
let mut domain = localise(line, patch.0, patch.1);
let mut marks = raw.marks;
let forward = if side == 0 { own_forward } else { !own_forward };
if !forward {
domain.reverse();
marks.swap(0, 1);
}
held.entry(patch).or_default().push(Piece { marks, domain, edge: (0, e), forward });
}
}
use crate::topology::{CoedgeRecord, EdgeRecord, FaceRecord, LoopRecord, ShellRecord, VertexRecord};
let mut next = 1u64;
let mut id = || {
next += 1;
next - 1
};
let mut vertices: Vec<VertexRecord> = Vec::new();
let mut vertex_ids: std::collections::HashMap<Mark, u64> = std::collections::HashMap::new();
let mut vertex = |mark: Mark, point: Vec3, id: &mut dyn FnMut() -> u64| -> u64 {
*vertex_ids.entry(mark).or_insert_with(|| {
let vid = id();
vertices.push(VertexRecord { id: vid, point });
vid
})
};
let mark_point = |mark: Mark| -> Result<Vec3, String> {
match mark {
Mark::Corner(a, b) => tube.k_at(sigma_bounds[a % rows.len()], psi_bounds[b % columns]).ok_or_else(|| "K is singular at a corner".to_string()),
Mark::Split(l, i) => Ok(dense_loops[l].1.point[i]),
Mark::Chart(c, k) => Ok(rims[c].vertices[k]),
}
};
let curve_through = |points: &[Vec3]| -> Result<crate::NurbsCurve, String> {
let mut params = vec![0.0];
for pair in points.windows(2) {
params.push(params.last().unwrap() + pair[1].sub(pair[0]).length().max(1e-300));
}
let total = *params.last().unwrap();
let params: Vec<f64> = params.iter().map(|t| t / total).collect();
crate::interpolate_curve(points, 3.min(points.len() - 1), ¶ms)
};
let chord_parameters = |points: &[Vec3]| -> Vec<f64> {
let mut params = vec![0.0];
for pair in points.windows(2) {
params.push(params.last().unwrap() + pair[1].sub(pair[0]).length().max(1e-300));
}
let total = *params.last().unwrap();
params.iter().map(|t| t / total).collect()
};
let station_pcurve = |uv: &[Vec3], edge_points: &[Vec3], forward: bool| -> Result<crate::NurbsCurve, String> {
let mut params = chord_parameters(edge_points);
if !forward {
params = params.iter().rev().map(|t| 1.0 - t).collect();
}
crate::interpolate_curve(uv, 3.min(uv.len() - 1), ¶ms)
};
let same_parameter = |surface: &crate::NurbsSurface, curve: &crate::NurbsCurve, t0: f64, t1: f64, forward: bool, uv: &[Vec3]| -> Result<crate::NurbsCurve, String> {
let path = curve_through(uv)?;
let [q0, q1] = path.domain()?;
let lift = |c: &crate::NurbsCurve, q: f64| -> Option<Vec3> {
let p = c.evaluate(q).ok()?;
surface.evaluate_extended(p.x, p.y).ok()
};
let edge_at = |fraction: f64| if forward { t0 + (t1 - t0) * fraction } else { t1 - (t1 - t0) * fraction };
let off = |c: &crate::NurbsCurve| -> f64 {
let Ok([c0, c1]) = c.domain() else { return f64::INFINITY };
(0..67)
.map(|k| {
let f = (k as f64 + 0.5) / 67.0;
match (lift(c, c0 + (c1 - c0) * f), curve.evaluate(edge_at(f))) {
(Some(a), Ok(b)) => a.sub(b).length(),
_ => f64::INFINITY,
}
})
.fold(0.0, f64::max)
};
let mut best: Option<(f64, crate::NurbsCurve)> = None;
let mut count = (2 * (uv.len() - 1)).clamp(8, 400);
loop {
let mut stations = Vec::with_capacity(count + 1);
let mut last = q0;
for j in 0..=count {
let fraction = j as f64 / count as f64;
if j == 0 || j == count {
stations.push(path.evaluate(if j == 0 { q0 } else { q1 })?);
continue;
}
let t = edge_at(fraction);
let target = curve.evaluate(t)?;
let h = 1e-4 * (t1 - t0);
let tangent = curve.evaluate((t + h).min(t0.max(t1)))?.sub(curve.evaluate((t - h).max(t0.min(t1)))?);
let tangent = if forward { tangent } else { tangent.scale(-1.0) };
let ahead = |q: f64| lift(&path, q).map(|p| p.sub(target).dot(tangent));
let guess = (q0 + (q1 - q0) * fraction).max(last);
let step = (q1 - q0) / count as f64;
let (mut a, mut b) = (guess, (guess + 0.25 * step).min(q1));
if b <= a {
a = (b - 0.25 * step).max(q0);
}
let (mut fa, mut fb) = (ahead(a).ok_or("a pcurve station is off its face")?, ahead(b).ok_or("a pcurve station is off its face")?);
for _ in 0..24 {
if !(fb - fa).is_finite() || (fb - fa).abs() <= 1e-300 || (b - a).abs() <= 1e-14 * (q1 - q0) {
break;
}
let next = (b - fb * (b - a) / (fb - fa)).clamp(last, q1);
a = b;
fa = fb;
b = next;
fb = ahead(b).ok_or("a pcurve station is off its face")?;
}
last = b.clamp(last, q1);
stations.push(path.evaluate(last)?);
}
let params: Vec<f64> = (0..=count).map(|j| j as f64 / count as f64).collect();
if let Ok(matched) = crate::interpolate_curve(&stations, 3, ¶ms) {
let miss = off(&matched);
if best.as_ref().is_none_or(|b| miss < b.0) {
best = Some((miss, matched));
}
}
if best.as_ref().is_some_and(|b| b.0 <= 5e-7) || count >= 1600 {
break;
}
count *= 2;
}
match best {
Some((miss, matched)) if miss <= off(&path) => Ok(matched),
_ => Ok(path),
}
};
let mut edges: Vec<EdgeRecord> = Vec::new();
let mut piece_edges: std::collections::HashMap<usize, u64> = std::collections::HashMap::new();
let mut side_edges: std::collections::HashMap<(u8, usize, usize, Mark, Mark), (u64, Mark)> = std::collections::HashMap::new();
let mut faces: Vec<FaceRecord> = Vec::new();
let mut face_charts: Vec<usize> = Vec::new();
let mut fits: std::collections::HashMap<(usize, usize), crate::NurbsSurface> = std::collections::HashMap::new();
let mut orient_by: Option<(usize, [f64; 2], [f64; 2])> = None;
for a in 0..rows.len() {
for b in 0..columns {
let (su, pv) = patch_box(a, b);
if trace_stages {
eprintln!("TS patch ({a}, {b})");
}
if in_chart(0.5 * (su[0] + su[1]), 0.5 * (pv[0] + pv[1])) {
continue;
}
let pieces = held.remove(&(a, b)).unwrap_or_default();
if std::env::var("BREP_TUBE_TRACE_PATCH").ok().is_some_and(|v| v == format!("{a},{b}")) {
eprintln!("TP patch ({a}, {b}): sigma {:?} psi {:?}", su, pv);
for (k, p) in pieces.iter().enumerate() {
eprintln!("TP piece {k}: {:?} -> {:?} from ({:.6}, {:.6}) to ({:.6}, {:.6}) n {} edge {:?} forward {}", p.marks[0], p.marks[1], p.domain[0].0, p.domain[0].1, p.domain.last().unwrap().0, p.domain.last().unwrap().1, p.domain.len(), p.edge, p.forward);
}
}
let whole = pieces.is_empty();
if pieces.is_empty() {
let (g, _, _) = g_at(0.5 * (su[0] + su[1]), 0.5 * (pv[0] + pv[1])).ok_or("K is singular")?;
if g < 0.0 {
continue; }
}
let chart = rows[a].0;
let surface = match fits.get(&(a, b)) {
Some(found) => found.clone(),
None => {
let (surface, ..) = super::fit_patch(tube, chart, [rows[a].1, rows[a].2], pv, fit).map_err(|e| e.message)?;
fits.insert((a, b), surface.clone());
surface
}
};
let position = |(x, y): (f64, f64)| -> Result<f64, String> {
let (fx, fy) = ((x - su[0]) / (su[1] - su[0]), (y - pv[0]) / (pv[1] - pv[0]));
let near = |v: f64, t: f64| (v - t).abs() <= 1e-7;
Ok(if near(fy, 0.0) {
fx.clamp(0.0, 1.0)
} else if near(fx, 1.0) {
1.0 + fy.clamp(0.0, 1.0)
} else if near(fy, 1.0) {
2.0 + (1.0 - fx).clamp(0.0, 1.0)
} else if near(fx, 0.0) {
3.0 + (1.0 - fy).clamp(0.0, 1.0)
} else {
return Err(format!("a trim piece ends inside patch ({a}, {b}) at ({fx:.6}, {fy:.6})"));
})
};
let at_position = |t: f64| -> (f64, f64) {
let f = t - t.floor();
match t.floor() as i64 {
0 => (su[0] + (su[1] - su[0]) * f, pv[0]),
1 => (su[1], pv[0] + (pv[1] - pv[0]) * f),
2 => (su[1] - (su[1] - su[0]) * f, pv[1]),
_ => (su[0], pv[1] - (pv[1] - pv[0]) * f),
}
};
let mut chains: Vec<Vec<usize>> = Vec::new();
{
let near = |x: (f64, f64), y: (f64, f64)| (x.0 - y.0).hypot(x.1 - y.1);
let next_after = |tail: Mark, at: (f64, f64), taken: &[bool]| -> Option<usize> {
(0..pieces.len()).filter(|&k| !taken[k] && pieces[k].marks[0] == tail).min_by(|&x, &y| near(pieces[x].domain[0], at).total_cmp(&near(pieces[y].domain[0], at)))
};
let ends: std::collections::HashSet<Mark> = pieces.iter().map(|p| p.marks[1]).collect();
let mut taken = vec![false; pieces.len()];
for k in 0..pieces.len() {
if taken[k] || (ends.contains(&pieces[k].marks[0]) && position(pieces[k].domain[0]).is_err()) {
continue;
}
let mut chain = vec![k];
taken[k] = true;
let mut tail = pieces[k].marks[1];
while position(*pieces[*chain.last().unwrap()].domain.last().unwrap()).is_err() {
let at = *pieces[*chain.last().unwrap()].domain.last().unwrap();
let next = match next_after(tail, at, &taken) {
Some(next) => next,
None if pieces.iter().any(|p| p.marks[0] == tail) => return Err(format!("a trim run closes inside patch ({a}, {b})")),
None => return Err(format!("a trim run stops inside patch ({a}, {b})")),
};
taken[next] = true;
chain.push(next);
tail = pieces[next].marks[1];
}
chains.push(chain);
}
if taken.iter().any(|t| !t) {
return Err(format!("a trim run of patch ({a}, {b}) never reaches its sides"));
}
}
let corners = [Mark::Corner(a, b), Mark::Corner((a + 1) % rows.len(), b), Mark::Corner((a + 1) % rows.len(), (b + 1) % columns), Mark::Corner(a, (b + 1) % columns)];
let mut stops: Vec<(f64, Mark)> = (0..4).map(|k| (k as f64, corners[k])).collect();
for chain in &chains {
let (first, last) = (&pieces[chain[0]], &pieces[*chain.last().unwrap()]);
stops.push((position(first.domain[0])?, first.marks[0]));
stops.push((position(*last.domain.last().unwrap())?, last.marks[1]));
}
stops.sort_by(|x, y| x.0.total_cmp(&y.0));
stops.dedup_by(|x, y| (x.0 - y.0).abs() <= 1e-9 && x.1 == y.1);
#[derive(Clone, Copy)]
enum Run {
Piece(usize),
Side(f64, f64),
}
let mut segments: Vec<(Mark, Mark, Run)> = pieces.iter().enumerate().map(|(k, p)| (p.marks[0], p.marks[1], Run::Piece(k))).collect();
let _ = &chains;
for k in 0..stops.len() {
let (t0, m0) = stops[k];
let (mut t1, m1) = stops[(k + 1) % stops.len()];
if t1 <= t0 {
t1 += 4.0;
}
if t1 - t0 <= 1e-12 {
continue;
}
let middle = at_position((0.5 * (t0 + t1)).rem_euclid(4.0));
if g_at(middle.0, middle.1).ok_or("K is singular")?.0 >= 0.0 {
segments.push((m0, m1, Run::Side(t0, t1)));
}
}
let trace_patch = std::env::var("BREP_TUBE_TRACE_PATCH").ok().is_some_and(|v| v == format!("{a},{b}"));
if trace_patch {
for (t, m) in &stops {
eprintln!("TP stop {t:.6} {m:?}");
}
for (m0, m1, run) in &segments {
if let Run::Side(t0, t1) = run {
eprintln!("TP side {t0:.6}..{t1:.6} {m0:?} -> {m1:?}");
}
}
}
let mut used = vec![false; segments.len()];
for start in 0..segments.len() {
if used[start] {
continue;
}
let mut chain = vec![start];
used[start] = true;
let ends_of = |k: usize| -> ((f64, f64), (f64, f64)) {
match segments[k].2 {
Run::Piece(i) => (pieces[i].domain[0], *pieces[i].domain.last().unwrap()),
Run::Side(t0, t1) => (at_position(t0.rem_euclid(4.0)), at_position(t1.rem_euclid(4.0))),
}
};
let gap = |x: (f64, f64), y: (f64, f64)| (x.0 - y.0).hypot(x.1 - y.1);
let first = segments[start].0;
let first_at = ends_of(start).0;
let mut tail = segments[start].1;
let mut tail_at = ends_of(start).1;
while !(tail == first && gap(tail_at, first_at) <= 1e-6) {
let next = (0..segments.len())
.filter(|&k| !used[k] && segments[k].0 == tail)
.min_by(|&x, &y| gap(ends_of(x).0, tail_at).total_cmp(&gap(ends_of(y).0, tail_at)));
let next = match next {
Some(next) => next,
None if tail == first => break,
None => {
if trace_patch {
eprintln!("TP stuck at {tail:?} ({:.6}, {:.6}), loop from {first:?} ({:.6}, {:.6}), chain {}", tail_at.0, tail_at.1, first_at.0, first_at.1, chain.len());
}
return Err(format!("a face loop of patch ({a}, {b}) does not close"));
}
};
tail_at = ends_of(next).1;
used[next] = true;
chain.push(next);
tail = segments[next].1;
}
let mut coedges = Vec::new();
for &k in &chain {
let (m0, m1, run) = segments[k];
let v0 = vertex(m0, mark_point(m0)?, &mut id);
let v1 = vertex(m1, mark_point(m1)?, &mut id);
match run {
Run::Piece(index) => {
let piece = &pieces[index];
let e = piece.edge.1;
let edge_id = match piece_edges.get(&e) {
Some(found) => *found,
None => {
let raw = &raws[e];
let curve = curve_through(&raw.points)?;
let [t0, t1] = curve.domain()?;
let eid = id();
let (s0, s1) = (vertex(raw.marks[0], mark_point(raw.marks[0])?, &mut id), vertex(raw.marks[1], mark_point(raw.marks[1])?, &mut id));
edges.push(EdgeRecord { id: eid, curve, t0, t1, start_vertex_id: s0, end_vertex_id: s1, degenerate: false, name: None });
if trace_stages {
eprintln!("TS edge {eid} raw {e} source {} chart {} n {} own ({:.6}, {:.6}) -> ({:.6}, {:.6}) mate ({:.6}, {:.6}) -> ({:.6}, {:.6})", raw.source, raw.chart, raw.points.len(), raw.own[0].0, raw.own[0].1, raw.own[raw.own.len() - 1].0, raw.own[raw.own.len() - 1].1, raw.mate[0].0, raw.mate[0].1, raw.mate[raw.mate.len() - 1].0, raw.mate[raw.mate.len() - 1].1);
}
piece_edges.insert(e, eid);
eid
}
};
let chart = rows[a].0 as f64;
let uv: Vec<Vec3> = piece.domain.iter().map(|(x, y)| Vec3::new(x - chart, *y, 0.0)).collect();
let record = edges.iter().find(|r| r.id == edge_id).ok_or("a trim piece has no edge")?;
let pcurve = if uv.len() == raws[e].points.len() && uv.len() >= 2 {
station_pcurve(&uv, &raws[e].points, piece.forward)?
} else {
same_parameter(&surface, &record.curve, record.t0, record.t1, piece.forward, &uv)?
};
coedges.push(CoedgeRecord { id: id(), edge_id, forward: piece.forward, pcurve });
}
Run::Side(t0, t1) => {
let side = t0.floor() as i64;
let (pa, pb) = (at_position(t0.rem_euclid(4.0)), at_position(if t1 - t1.floor() == 0.0 && t1.floor() as i64 == side + 1 { t1 - 1e-15 } else { t1.rem_euclid(4.0) }));
let pb = if t1 >= (side + 1) as f64 - 1e-15 { at_position(((side + 1) as f64 - 1e-15).rem_euclid(4.0)) } else { pb };
let pb = if t1 >= (side + 1) as f64 - 1e-15 { match side { 0 => (su[1], pv[0]), 1 => (su[1], pv[1]), 2 => (su[0], pv[1]), _ => (su[0], pv[0]) } } else { pb };
let key_line: (u8, usize, usize) = match side {
0 => (1, a, b),
1 => (0, (a + 1) % rows.len(), b),
2 => (1, a, (b + 1) % columns),
_ => (0, a, b),
};
let (lo, hi) = if m0 <= m1 { (m0, m1) } else { (m1, m0) };
let key = (key_line.0, key_line.1, key_line.2, lo, hi);
let (edge_id, edge_start) = match side_edges.get(&key) {
Some(found) => *found,
None => {
let local = rows[a].0 as f64;
let (iso, from_t, to_t) = match side {
0 | 2 => (surface.iso_curve_v(pa.1)?, pa.0 - local, pb.0 - local),
_ => (surface.iso_curve_u(pa.0 - local)?, pa.1, pb.1),
};
let (lo_t, hi_t) = (from_t.min(to_t), from_t.max(to_t));
let [d0, d1] = iso.domain()?;
let mut piece_curve = iso;
if lo_t > d0 + 1e-9 {
piece_curve = piece_curve.split(lo_t)?.1;
}
let [_, e1] = piece_curve.domain()?;
if hi_t < e1 - 1e-9 {
piece_curve = piece_curve.split(hi_t)?.0;
}
let curve = if from_t > to_t { piece_curve.reversed()? } else { piece_curve };
let [c0, c1] = curve.domain()?;
let eid = id();
edges.push(EdgeRecord { id: eid, curve, t0: c0, t1: c1, start_vertex_id: v0, end_vertex_id: v1, degenerate: false, name: None });
side_edges.insert(key, (eid, m0));
(eid, m0)
}
};
let chart = rows[a].0 as f64;
let pcurve = crate::make_line(Vec3::new(pa.0 - chart, pa.1, 0.0), Vec3::new(pb.0 - chart, pb.1, 0.0))?;
coedges.push(CoedgeRecord { id: id(), edge_id, forward: edge_start == m0, pcurve });
}
}
}
let surface = surface.clone();
if whole && chart == 0 && orient_by.is_none() {
orient_by = Some((faces.len(), [rows[a].1, rows[a].2], pv));
}
faces.push(FaceRecord { id: id(), surface, same_sense: true, loops: vec![LoopRecord { id: id(), coedges }], name: None });
if trace_stages {
let f = faces.last().unwrap();
eprintln!("TS face {} patch ({a}, {b}) coedges {:?}", f.id, f.loops[0].coedges.iter().map(|c| (c.id, c.edge_id, c.forward)).collect::<Vec<_>>());
}
face_charts.push(chart);
}
}
}
{
use super::chart::ChartEnd;
let weld = 1e-7 * (tube.major + tube.minor);
let mark_at = |point: Vec3| -> Option<Mark> { raws.iter().flat_map(|r| r.marks).find(|m| mark_point(*m).is_ok_and(|q| q.sub(point).length() <= weld)) };
let near_index = |bounds: &[f64], v: f64, period: f64| bounds.iter().position(|b| { let d = (b - v).rem_euclid(period); d.min(period - d) <= 1e-9 });
let along = |points: &[Vec3], p: Vec3| -> f64 {
let mut best = (f64::INFINITY, 0.0);
let mut total = 0.0;
for w in points.windows(2) {
let d = w[1].sub(w[0]);
let l2 = d.dot(d);
let f = if l2 > 0.0 { (p.sub(w[0]).dot(d) / l2).clamp(0.0, 1.0) } else { 0.0 };
let dist = w[0].add(d.scale(f)).sub(p).length();
if dist < best.0 {
best = (dist, total + f * l2.sqrt());
}
total += l2.sqrt();
}
best.1
};
let pcurve_between = |side: &super::chart::ChartSide, from: f64, to: f64| -> Vec<Vec3> {
let mut lengths = vec![0.0];
for w in side.points.windows(2) {
lengths.push(lengths.last().unwrap() + w[1].sub(w[0]).length());
}
let at = |s: f64| -> (f64, f64) {
let k = lengths.partition_point(|x| *x <= s).clamp(1, lengths.len() - 1);
let (l0, l1) = (lengths[k - 1], lengths[k]);
let f = if l1 > l0 { ((s - l0) / (l1 - l0)).clamp(0.0, 1.0) } else { 0.0 };
let (a, b) = (side.pcurve[k - 1], side.pcurve[k]);
(a.0 + (b.0 - a.0) * f, a.1 + (b.1 - a.1) * f)
};
let (lo, hi) = (from.min(to), from.max(to));
let mut out = vec![at(lo)];
for (k, l) in lengths.iter().enumerate() {
if *l > lo && *l < hi {
out.push(side.pcurve[k]);
}
}
out.push(at(hi));
if from > to {
out.reverse();
}
out.into_iter().map(|(u, v)| Vec3::new(u, v, 0.0)).collect()
};
let mut internal_edges: std::collections::HashMap<(usize, usize), u64> = std::collections::HashMap::new();
for (c, chart) in charts.iter().enumerate() {
let rim = &rims[c];
if trace_stages {
eprintln!("TS chart {c} faces");
}
for cf in chart.faces(tube, rim, window, fit)? {
let mut loops = Vec::new();
for sides in std::iter::once(&cf.sides).chain(cf.holes.iter()) {
let mut coedges = Vec::new();
for side in sides {
let side_length = side.points.windows(2).map(|w| w[1].sub(w[0]).length()).sum::<f64>();
match side.edge {
Some((r, with)) if rim.edges[r].outside.is_some() => {
let li = regular_loops + chart_runs.iter().position(|x| *x == (c, r)).ok_or("a chart face uses an edge not built")?;
let mut run_raws: Vec<usize> = (0..raws.len()).filter(|&e| raws[e].source == li).collect();
if !with {
run_raws.reverse();
}
for e in run_raws {
let edge_id = match piece_edges.get(&e) {
Some(found) => *found,
None => {
let raw = &raws[e];
let curve = curve_through(&raw.points)?;
let [t0, t1] = curve.domain()?;
let eid = id();
let (s0, s1) = (vertex(raw.marks[0], mark_point(raw.marks[0])?, &mut id), vertex(raw.marks[1], mark_point(raw.marks[1])?, &mut id));
edges.push(EdgeRecord { id: eid, curve, t0, t1, start_vertex_id: s0, end_vertex_id: s1, degenerate: false, name: None });
piece_edges.insert(e, eid);
eid
}
};
let raw = &raws[e];
let (p0, p1) = if with { (raw.points[0], *raw.points.last().unwrap()) } else { (*raw.points.last().unwrap(), raw.points[0]) };
let (s0, s1) = (along(&side.points, p0), along(&side.points, p1));
let _ = side_length;
let record = edges.iter().find(|r| r.id == edge_id).ok_or("a chart run has no edge")?;
let pcurve = same_parameter(&cf.surface, &record.curve, record.t0, record.t1, with, &pcurve_between(side, s0, s1))?;
coedges.push(CoedgeRecord { id: id(), edge_id, forward: with, pcurve });
}
}
Some((r, with)) => {
let edge_id = match internal_edges.get(&(c, r)) {
Some(found) => *found,
None => {
let edge = &rim.edges[r];
let curve = curve_through(&edge.points)?;
let [t0, t1] = curve.domain()?;
let mark_of = |e: ChartEnd| -> Result<Mark, String> {
match e {
ChartEnd::Vertex(k) => Ok(Mark::Chart(c, k)),
ChartEnd::Crossing(i) => mark_at(rim.crossings[i].at.point).ok_or_else(|| "a rim crossing has no vertex".to_string()),
_ => Err("an internal chart edge ends on a box side".into()),
}
};
let (m0, m1) = (mark_of(edge.ends[0])?, mark_of(edge.ends[1])?);
let eid = id();
let (s0, s1) = (vertex(m0, mark_point(m0)?, &mut id), vertex(m1, mark_point(m1)?, &mut id));
edges.push(EdgeRecord { id: eid, curve, t0, t1, start_vertex_id: s0, end_vertex_id: s1, degenerate: false, name: None });
internal_edges.insert((c, r), eid);
eid
}
};
let record = edges.iter().find(|r| r.id == edge_id).ok_or("an internal chart edge has no record")?;
let uv: Vec<Vec3> = side.pcurve.iter().map(|(u, v)| Vec3::new(*u, *v, 0.0)).collect();
let edge_points = &rim.edges[r].points;
let n = edge_points.len();
let same = n == side.points.len() && n == uv.len() && n >= 2 && (0..n).all(|k| side.points[k].sub(edge_points[if with { k } else { n - 1 - k }]).length() <= 1e-12);
let pcurve = if same {
let mut ordered = edge_points.clone();
if !with {
ordered.reverse();
}
crate::interpolate_curve(&uv, 3.min(n - 1), &chord_parameters(&ordered))?
} else {
same_parameter(&cf.surface, &record.curve, record.t0, record.t1, with, &uv)?
};
coedges.push(CoedgeRecord { id: id(), edge_id, forward: with, pcurve });
}
None => {
let end_of = |e: ChartEnd| -> Result<(Mark, (f64, f64)), String> {
match e {
ChartEnd::Crossing(i) => {
let at = rim.crossings[i].at;
Ok((mark_at(at.point).ok_or("a rim crossing has no vertex")?, (at.sigma.rem_euclid(4.0), at.psi.rem_euclid(TAU))))
}
ChartEnd::Corner { plus, corner } => {
let d = chart.corner(plus, corner);
let d = (d.0.rem_euclid(4.0), d.1.rem_euclid(TAU));
let a = near_index(&sigma_bounds, d.0, 4.0).ok_or("a box corner off the patch grid")?;
let b = near_index(&psi_bounds, d.1, TAU).ok_or("a box corner off the patch grid")?;
Ok((Mark::Corner(a % rows.len(), b % columns), d))
}
ChartEnd::Vertex(k) => Ok((Mark::Chart(c, k), (0.0, 0.0))),
ChartEnd::Closed(_) => Err("a closed chart side (not yet taken)".into()),
}
};
let ((m0, d0), (m1, d1)) = (end_of(side.ends[0])?, end_of(side.ends[1])?);
let e1 = (unwrap(d1.0, d0.0, 4.0), unwrap(d1.1, d0.1, TAU));
let along_psi = (d0.0 - e1.0).abs() <= 1e-9;
let (from, to, bounds, period): (f64, f64, &[f64], f64) = if along_psi { (d0.1, e1.1, &psi_bounds[..], TAU) } else { (d0.0, e1.0, &sigma_bounds[..rows.len()], 4.0) };
let fixed = if along_psi {
near_index(&sigma_bounds, d0.0, 4.0).ok_or("a box side off the patch grid")? % rows.len()
} else {
near_index(&psi_bounds, d0.1, TAU).ok_or("a box side off the patch grid")? % columns
};
let mut stops: Vec<(f64, Mark)> = vec![(0.0, m0)];
if (to - from).abs() > 1e-12 {
let mut inner: Vec<(f64, Mark)> = Vec::new();
for (k, bound) in bounds.iter().enumerate() {
for turn in -1..=1 {
let f = (bound + turn as f64 * period - from) / (to - from);
if f > 1e-9 && f < 1.0 - 1e-9 {
inner.push((f, if along_psi { Mark::Corner(fixed, k) } else { Mark::Corner(k, fixed) }));
}
}
}
inner.sort_by(|x, y| x.0.total_cmp(&y.0));
stops.extend(inner);
}
stops.push((1.0, m1));
let uv: Vec<Vec3> = side.pcurve.iter().map(|(u, v)| Vec3::new(*u, *v, 0.0)).collect();
let full = curve_through(&uv)?;
let [q0, q1] = full.domain()?;
let nearest = |target: Vec3, a: f64, b: f64| -> f64 {
let distance = |q: f64| full.evaluate(q).ok().and_then(|p| cf.surface.evaluate_extended(p.x, p.y).ok()).map(|p| p.sub(target).length()).unwrap_or(f64::INFINITY);
let mut best = (f64::INFINITY, a);
for j in 0..=64 {
let q = a + (b - a) * j as f64 / 64.0;
let d = distance(q);
if d < best.0 {
best = (d, q);
}
}
let step = (b - a).abs() / 64.0;
let (lo_q, hi_q) = (a.min(b), a.max(b));
let (mut x0, mut x1) = ((best.1 - step).max(lo_q), (best.1 + step).min(hi_q));
let ratio = 0.5 * (5f64.sqrt() - 1.0);
for _ in 0..60 {
let (x, y) = (x1 - ratio * (x1 - x0), x0 + ratio * (x1 - x0));
if distance(x) < distance(y) {
x1 = y;
} else {
x0 = x;
}
}
0.5 * (x0 + x1)
};
let mut cuts_q = vec![q0];
for (_, mark) in &stops[1..stops.len() - 1] {
let last = *cuts_q.last().unwrap();
cuts_q.push(nearest(mark_point(*mark)?, last, q1));
}
cuts_q.push(q1);
for (w, q) in stops.windows(2).zip(cuts_q.windows(2)) {
let ((f0, k0), (f1, k1)) = (w[0], w[1]);
let f = 0.5 * (f0 + f1);
let mid = (d0.0 + (e1.0 - d0.0) * f, d0.1 + (e1.1 - d0.1) * f);
let key_line: (u8, usize, usize) = if along_psi { (0, fixed, column_of(mid.1)) } else { (1, row_of(mid.0), fixed) };
let (lo, hi) = if k0 <= k1 { (k0, k1) } else { (k1, k0) };
let (edge_id, edge_start) = *side_edges.get(&(key_line.0, key_line.1, key_line.2, lo, hi)).ok_or_else(|| {
let on_line: Vec<_> = side_edges.keys().filter(|k| k.0 == key_line.0 && k.1 == key_line.1 && k.2 == key_line.2).map(|k| (k.3, k.4)).collect();
format!("a chart face's box side has no patch edge (chart {c}, line {key_line:?}, ends {:?} at {d0:?} -> {d1:?}, marks {lo:?}..{hi:?}; the line's edges {on_line:?})", side.ends)
})?;
let forward = edge_start == k0;
let record = edges.iter().find(|e| e.id == edge_id).ok_or("a chart face's box side has no patch edge")?;
let edge_at = |fraction: f64| if forward { record.t0 + (record.t1 - record.t0) * fraction } else { record.t1 - (record.t1 - record.t0) * fraction };
let mut count = 24;
let pcurve = loop {
let mut stations = Vec::with_capacity(count + 1);
let mut at = q[0];
for j in 0..=count {
let t = edge_at(j as f64 / count as f64);
at = if j == 0 { q[0] } else if j == count { q[1] } else { nearest(record.curve.evaluate(t)?, at, q[1]) };
stations.push(full.evaluate(at)?);
}
let params: Vec<f64> = (0..=count).map(|j| j as f64 / count as f64).collect();
let fitted = crate::interpolate_curve(&stations, 3, ¶ms)?;
let miss = (0..67)
.map(|k| {
let f = (k as f64 + 0.5) / 67.0;
match (fitted.evaluate(f).ok().and_then(|p| cf.surface.evaluate_extended(p.x, p.y).ok()), record.curve.evaluate(edge_at(f))) {
(Some(a), Ok(b)) => a.sub(b).length(),
_ => f64::INFINITY,
}
})
.fold(0.0, f64::max);
if miss <= 5e-7 || count >= 768 {
break fitted;
}
count *= 2;
};
coedges.push(CoedgeRecord { id: id(), edge_id, forward, pcurve });
}
}
}
}
loops.push(LoopRecord { id: id(), coedges });
}
faces.push(FaceRecord { id: id(), surface: cf.surface.clone(), same_sense: true, loops, name: None });
if trace_stages {
let f = faces.last().unwrap();
eprintln!("TS face {} chart face loops {:?}", f.id, f.loops.iter().map(|l| l.coedges.iter().map(|c| (c.id, c.edge_id, c.forward)).collect::<Vec<_>>()).collect::<Vec<_>>());
}
face_charts.push(usize::MAX);
}
}
}
let mut owner: std::collections::BTreeMap<u64, Vec<usize>> = std::collections::BTreeMap::new();
for (f, face) in faces.iter().enumerate() {
for coedge in face.loops.iter().flat_map(|l| &l.coedges) {
owner.entry(coedge.edge_id).or_default().push(f);
}
}
let mut group: Vec<usize> = (0..faces.len()).collect();
fn find(group: &mut [usize], x: usize) -> usize {
let mut r = x;
while group[r] != r {
r = group[r];
}
group[x] = r;
r
}
for users in owner.values() {
for pair in users.windows(2) {
let (x, y) = (find(&mut group, pair[0]), find(&mut group, pair[1]));
group[x] = y;
}
}
let mut shells: std::collections::BTreeMap<usize, Vec<FaceRecord>> = std::collections::BTreeMap::new();
for (f, face) in faces.into_iter().enumerate() {
let root = find(&mut group, f);
shells.entry(root).or_default().push(face);
}
let shells: Vec<ShellRecord> = shells.into_values().map(|faces| ShellRecord { id: id(), faces }).collect();
let genus = shells.len() as i64;
let _ = face_charts;
let weld = 1e-7 * (tube.major + tube.minor);
let mut alias: std::collections::HashMap<u64, u64> = std::collections::HashMap::new();
let mut kept_vertices: Vec<VertexRecord> = Vec::with_capacity(vertices.len());
for v in vertices.into_iter() {
match kept_vertices.iter().find(|k| k.point.sub(v.point).length() <= weld) {
Some(k) => {
alias.insert(v.id, k.id);
}
None => kept_vertices.push(v),
}
}
let vertices = kept_vertices;
let mut edges = edges;
for e in edges.iter_mut() {
if let Some(&to) = alias.get(&e.start_vertex_id) {
e.start_vertex_id = to;
}
if let Some(&to) = alias.get(&e.end_vertex_id) {
e.end_vertex_id = to;
}
}
let mut solid = crate::BrepSolid { mass_properties_cache: Default::default(), id: id(), vertices, edges, shells, genus, kind: Default::default(), cells: Vec::new() };
let (_, su, pv) = orient_by.ok_or("no whole face of the sheet Σ + r·N to orient by")?;
let (um, vm) = (0.5 * (su[0] + su[1]), 0.5 * (pv[0] + pv[1]));
let surface = &fits[&(row_of(su[0] + 1e-12), column_of(vm))];
let normal = surface.normal(um, vm)?;
let outward = tube.frame(tube.from + (tube.to - tube.from) * um, vm).ok_or("the core circle's sweep is singular")?.normal;
let along = normal.dot(outward);
if along < 0.0 {
crate::orientation::flip_all_faces(&mut solid).map_err(|e| e.message)?;
} else if !(along > 0.0) {
return Err("the tube's normal is undecided".into());
}
Ok(solid)
}