use super::{
ArcFrame, BlendEdge, BlendError, BlendSpec, End, Frame, Mesh, Path, Prof, Profile,
face_surface, side_face,
};
use crate::math::*;
use crate::model::Surface;
const REGULAR: f64 = 32.0;
const SAME: f64 = 1e-9;
pub(super) type Sect = (f64, f64);
pub(super) type ArcEnds = (Vec<Sect>, [Vec<V>; 2], [Surface; 2]);
pub(super) fn arc_ends(
e: &BlendEdge,
i: usize,
fr: &Frame,
a: &ArcFrame,
prof: &Prof,
) -> Result<ArcEnds, BlendError> {
let given: Vec<Sect> = match &e.path {
Path::Arc { sections, .. } => sections
.iter()
.filter(|x| x[0].is_finite() && x[1].is_finite())
.map(|x| (x[0], x[1]))
.collect(),
Path::Line | Path::Curve { .. } => Vec::new(),
};
let order = |t: &mut Vec<Sect>| {
t.sort_by(|x, y| x.0.total_cmp(&y.0));
t.dedup_by(|x, y| (x.0 - y.0).abs() <= SAME);
};
let sweep = a.sweep;
let full = sweep >= TAU * (1.0 - 1e-12);
if full {
let mut t: Vec<Sect> = given.iter().map(|x| (x.0.rem_euclid(TAU), x.1)).collect();
order(&mut t);
if t.len() > 1 && t[t.len() - 1].0 - t[0].0 >= TAU - SAME {
t.pop();
}
if t.len() < 3 {
let n = REGULAR as usize;
t = (0..n).map(|j| (TAU * j as f64 / n as f64, 0.0)).collect();
}
let none = || Surface::Faceted;
return Ok((t, [Vec::new(), Vec::new()], [none(), none()]));
}
let shift_at = |t: f64| {
given
.iter()
.find(|x| (x.0 - t).abs() <= SAME)
.map_or(0.0, |x| x.1)
};
let mut inner: Vec<Sect> = if given.is_empty() {
let n = ((REGULAR * sweep / TAU).ceil() as usize).max(1);
(1..n).map(|j| (sweep * j as f64 / n as f64, 0.0)).collect()
} else {
given
.iter()
.copied()
.filter(|x| x.0 > SAME && x.0 < sweep - SAME)
.collect()
};
order(&mut inner);
let delta = (PI / 8.0).min((TAU - sweep) / 4.0);
let mut t = Vec::with_capacity(inner.len() + 4);
let open = [0, 1].map(|k| matches!(e.ends[k], End::Open { .. }));
let (s0, s1) = (shift_at(0.0), shift_at(sweep));
if open[0] {
t.push((-delta, s0));
}
t.push((0.0, s0));
t.extend(inner);
t.push((sweep, s1));
if open[1] {
t.push((sweep + delta, s1));
}
let ring = prof.ring();
let mer: Vec<(f64, f64)> = ring.iter().map(|q| a.meridian(prof.base + *q)).collect();
let mut rings: [Vec<V>; 2] = [Vec::new(), Vec::new()];
let mut caps = [Surface::Faceted, Surface::Faceted];
for end in 0..2 {
let (at, dr) = if end == 0 { t[0] } else { t[t.len() - 1] };
rings[end] = mer.iter().map(|&(r, z)| a.at(r + dr, z, at)).collect();
let tangent = a.a.cross(a.radial(at));
let out = if end == 0 { tangent * -1.0 } else { tangent };
caps[end] = match &e.ends[end] {
End::Plane { origin, normal } => {
let (o, n) = (V::from(*origin), V::from(*normal));
if n.dot(a.a).abs() > 1e-6 || (a.c - o).dot(n).abs() > 1e-6 * (a.rho + fr.len) {
return Err(BlendError::Invalid(format!(
"edge {i}: an arc's tool ends only on a plane through its axis"
)));
}
let dn = tangent.dot(n);
if dn.abs() > 1e-6 {
for x in &mut rings[end] {
*x = *x + tangent * ((o - *x).dot(n) / dn);
}
}
Surface::Plane {
origin: *origin,
normal: *normal,
}
}
End::Chain { .. } | End::Open { .. } => Surface::Plane {
origin: a.c.arr(),
normal: out.arr(),
},
End::Corner(_) | End::Mitre { .. } => {
return Err(BlendError::Invalid(format!(
"edge {i}: an arc's tool has no corner or mitre ends"
)));
}
};
}
Ok((t, rings, caps))
}
fn revolved(a: &ArcFrame, p: (f64, f64), q: (f64, f64)) -> Surface {
let ((r1, z1), (r2, z2)) = (p, q);
let scale = r1.abs().max(r2.abs()).max(z1.abs()).max(z2.abs());
let eps = 1e-12 * scale.max(1e-300);
if (z1 - z2).abs() <= eps {
return Surface::Plane {
origin: (a.c + a.a * (0.5 * (z1 + z2))).arr(),
normal: a.a.arr(),
};
}
if (r1 - r2).abs() <= eps {
return Surface::Cylinder {
origin: a.c.arr(),
axis: a.a.arr(),
radius: 0.5 * (r1 + r2),
};
}
let z_apex = z1 + (z2 - z1) * (r1 / (r1 - r2));
let up = 0.5 * (z1 + z2) > z_apex;
Surface::Cone {
apex: (a.c + a.a * z_apex).arr(),
axis: (if up { a.a } else { a.a * -1.0 }).arr(),
slope: ((r2 - r1) / (z2 - z1)).abs(),
}
}
#[allow(clippy::too_many_arguments)]
pub(super) fn arc_into(
m: &mut Mesh,
spec: &BlendSpec,
e: &BlendEdge,
fr: &Frame,
a: &ArcFrame,
prof: &Prof,
angles: &[Sect],
rings: &[Vec<V>; 2],
caps: &[Surface; 2],
skip: [bool; 2],
) -> Result<u32, BlendError> {
let ring = prof.ring();
let k = ring.len();
let n_arc = prof.arc.len();
let mer: Vec<(f64, f64)> = ring.iter().map(|q| a.meridian(prof.base + *q)).collect();
let blend = m.surf(match spec.profile {
Profile::Fillet => {
let (rc, zc) = a.meridian(prof.base);
Surface::Torus {
center: (a.c + a.a * zc).arr(),
axis: a.a.arr(),
major_radius: rc,
minor_radius: spec.size,
}
}
Profile::Chamfer => revolved(a, mer[0], mer[1]),
});
let full = rings[0].is_empty();
let last = angles.len() - 1;
let secs: Vec<Vec<V>> = angles
.iter()
.enumerate()
.map(|(s, &(t, dr))| {
if !full && s == 0 {
rings[0].clone()
} else if !full && s == last {
rings[1].clone()
} else {
mer.iter().map(|&(r, z)| a.at(r + dr, z, t)).collect()
}
})
.collect();
let wind: f64 = (0..k)
.map(|j| ring[j].cross(ring[(j + 1) % k]).dot(fr.d))
.sum();
let ccw = wind > 0.0;
let surf: Vec<u32> = (0..k)
.map(|j| {
let j1 = (j + 1) % k;
if j + 1 < n_arc {
blend
} else if let Some(f) = side_face(spec, e, fr, prof, ring[j], ring[j1]) {
m.surf(face_surface(&e.faces[f]))
} else {
m.surf(revolved(a, mer[j], mer[j1]))
}
})
.collect();
let spans = if full { secs.len() } else { secs.len() - 1 };
for s in 0..spans {
let (r0, r1) = (&secs[s], &secs[(s + 1) % secs.len()]);
for j in 0..k {
let j1 = (j + 1) % k;
let (a0, b0) = (m.vert(r0[j]), m.vert(r0[j1]));
let (a1, b1) = (m.vert(r1[j]), m.vert(r1[j1]));
if ccw {
m.tri([a0, b0, b1], surf[j]);
m.tri([a0, b1, a1], surf[j]);
} else {
m.tri([a0, b1, b0], surf[j]);
m.tri([a0, a1, b1], surf[j]);
}
}
}
if !full {
for end in 0..2 {
if skip[end] {
continue;
}
let at = if end == 0 {
angles[0].0
} else {
angles[last].0
};
let tangent = a.a.cross(a.radial(at));
let out = if end == 0 { tangent * -1.0 } else { tangent };
let pts = &rings[end];
let mut nrm = V::default();
for j in 0..k {
nrm = nrm + pts[j].cross(pts[(j + 1) % k]);
}
let nrm = if nrm.dot(out) < 0.0 { nrm * -1.0 } else { nrm };
let s = m.surf(caps[end].clone());
m.polygon(pts, nrm.norm(), s)?;
}
}
Ok(blend)
}