use super::{
Error, HobbyOptions, MAX_SAMPLES, Result, Sample, StrokeSection, StrokeStyle, Vec2, arc,
bezier, hobby_controls, robust_stroke, stroke, tolerance_ok,
};
use crate::{Element, Layer, Layout};
pub fn parametric(
f: impl Fn(f64) -> Result<Vec2>,
tolerance: f64,
initial_intervals: usize,
max_evals: usize,
) -> Result<Vec<Sample>> {
tolerance_ok(tolerance)?;
if initial_intervals == 0 || max_evals > 4 * MAX_SAMPLES || initial_intervals > max_evals / 4 {
return Err(Error::invalid("invalid parametric sampling budget"));
}
let mut remaining = max_evals;
let mut eval = |t: f64| {
if remaining == 0 {
return Err(Error::invalid("parametric sampling budget exceeded"));
}
remaining -= 1;
let p = f(t)?;
if !p.finite() {
return Err(Error::invalid("nonfinite parametric sample"));
}
Ok(p)
};
let mut result = vec![(0., eval(0.)?)];
for i in 0..initial_intervals {
let a = i as f64 / initial_intervals as f64;
let b = (i + 1) as f64 / initial_intervals as f64;
let mut stack = vec![(a, result.last().unwrap().1, b, eval(b)?, 0)];
while let Some((l, p, r, q, depth)) = stack.pop() {
let mid = (l + r) * 0.5;
let m = eval(mid)?;
let mut error = (m - (p * 0.5 + q * 0.5)).norm();
for t in [0.25, 0.75] {
let actual = eval(l + (r - l) * t)?;
error = error.max((actual - (p * (1. - t) + q * t)).norm());
}
if error <= tolerance {
result.push((r, q));
} else if depth >= 40 {
return Err(Error::invalid(
"parametric tolerance exceeds numeric resolution",
));
} else {
stack.push((mid, m, r, q, depth + 1));
stack.push((l, p, mid, m, depth + 1));
}
}
}
Ok(result)
}
pub struct Curve {
vertices: Vec<Vec2>,
tolerance: f64,
heading: f64,
control: Option<Vec2>,
}
impl Curve {
pub fn new(start: Vec2, tolerance: f64) -> Result<Self> {
tolerance_ok(tolerance)?;
start.grid()?;
Ok(Self {
vertices: vec![start],
tolerance,
heading: 0.,
control: None,
})
}
pub fn points(&self) -> &[Vec2] {
&self.vertices
}
pub fn endpoint(&self) -> Vec2 {
*self.vertices.last().unwrap()
}
pub fn heading(&self) -> f64 {
self.heading
}
fn append(
&mut self,
samples: &[Sample],
control: Option<Vec2>,
heading: Option<f64>,
) -> Result<&mut Self> {
if samples.first().map(|p| p.1) != Some(self.endpoint())
|| samples.len() > MAX_SAMPLES.saturating_sub(self.vertices.len())
|| !samples.iter().all(|s| s.1.finite())
{
return Err(Error::invalid(
"nonfinite, disconnected or over-budget curve section",
));
}
for (_, p) in &samples[1..] {
if self.vertices.last() != Some(p) {
self.vertices.push(*p);
}
}
self.control = control;
if let Some(h) = heading {
self.heading = h;
} else if self.vertices.len() > 1 {
self.heading = (self.endpoint() - self.vertices[self.vertices.len() - 2]).angle();
}
Ok(self)
}
pub fn line_to(&mut self, point: Vec2) -> Result<&mut Self> {
self.append(&[(0., self.endpoint()), (1., point)], None, None)
}
pub fn bezier_to(&mut self, controls: &[Vec2]) -> Result<&mut Self> {
let start = self.endpoint();
let hull: Vec<_> = std::iter::once(start)
.chain(controls.iter().copied())
.collect();
let samples = bezier(&hull, self.tolerance)?;
let end = hull[hull.len() - 1];
let tangent = hull[..hull.len() - 1]
.iter()
.rev()
.find(|&&p| p != end)
.map(|&p| (end - p).angle());
self.append(&samples, Some(hull[hull.len() - 2]), tangent)
}
pub fn smooth_cubic_to(&mut self, second: Vec2, end: Vec2) -> Result<&mut Self> {
let start = self.endpoint();
self.bezier_to(&[start * 2. - self.control.unwrap_or(start), second, end])
}
pub fn smooth_quadratic_to(&mut self, end: Vec2) -> Result<&mut Self> {
let start = self.endpoint();
self.bezier_to(&[start * 2. - self.control.unwrap_or(start), end])
}
pub fn arc(
&mut self,
radii: Vec2,
initial: f64,
final_angle: f64,
rotation: f64,
) -> Result<&mut Self> {
let s = arc(
self.endpoint(),
radii,
initial,
final_angle,
rotation,
self.tolerance,
)?;
let angle = final_angle - rotation;
let t = (radii.x * angle.sin()).atan2(radii.y * angle.cos());
let h = rotation
+ (radii.y * t.cos()).atan2(-radii.x * t.sin())
+ if final_angle < initial {
std::f64::consts::PI
} else {
0.
};
self.append(&s, None, Some(h))
}
pub fn turn(&mut self, radius: f64, angle: f64) -> Result<&mut Self> {
let start = self.heading - angle.signum() * std::f64::consts::FRAC_PI_2;
self.arc(Vec2::new(radius, radius), start, start + angle, 0.)
}
pub fn interpolate(&mut self, knots: &[Vec2], options: &HobbyOptions<'_>) -> Result<&mut Self> {
let pts: Vec<_> = std::iter::once(self.endpoint())
.chain(knots.iter().copied())
.collect();
let controls = hobby_controls(&pts, options)?;
let mut samples = vec![(0., self.endpoint())];
let mut last = None;
for (i, [a, b]) in controls.iter().copied().enumerate() {
let end = pts[(i + 1) % pts.len()];
last = Some((b, end));
let s = bezier(&[pts[i], a, b, end], self.tolerance)?;
samples.extend(
s.into_iter()
.skip(1)
.map(|(t, p)| ((i as f64 + t) / controls.len() as f64, p)),
);
if samples.len() >= MAX_SAMPLES {
return Err(Error::invalid("Hobby vertex budget exceeded"));
}
}
let (b, end) = last.unwrap();
self.append(&samples, Some(b), Some((end - b).angle()))
}
pub fn parametric(
&mut self,
f: impl Fn(f64) -> Result<Vec2>,
initial_intervals: usize,
max_evals: usize,
) -> Result<&mut Self> {
let s = parametric(f, self.tolerance, initial_intervals, max_evals)?;
self.append(&s, None, None)
}
}
#[derive(Clone, Copy)]
pub struct Track {
pub layer: Layer,
pub width: f64,
pub offset: f64,
pub style: StrokeStyle,
}
struct TrackData {
track: Track,
widths: Vec<f64>,
offsets: Vec<f64>,
sections: Vec<StrokeSection>,
}
pub struct PathBuilder {
points: Vec<Vec2>,
tracks: Vec<TrackData>,
}
impl PathBuilder {
pub fn new(start: Vec2, tracks: &[Track]) -> Result<Self> {
start.grid()?;
if tracks.is_empty()
|| tracks
.iter()
.any(|tr| tr.width < 0. || !tr.width.is_finite() || !tr.offset.is_finite())
{
return Err(Error::invalid("invalid path tracks"));
}
Ok(Self {
points: vec![start],
tracks: tracks
.iter()
.map(|&track| TrackData {
track,
widths: vec![track.width],
offsets: vec![track.offset],
sections: Vec::new(),
})
.collect(),
})
}
pub fn append(
&mut self,
samples: &[Sample],
profiles: &[Vec<(f64, f64)>],
) -> Result<&mut Self> {
if samples.len() < 2
|| samples.len() > MAX_SAMPLES.saturating_sub(self.points.len())
|| samples.first().map(|s| &s.1) != self.points.last()
|| !samples.iter().all(|(_, p)| p.finite())
|| samples.windows(2).any(|w| w[0].1 == w[1].1)
|| profiles.len() != self.tracks.len()
|| profiles.iter().any(|p| {
p.len() != samples.len()
|| p.iter()
.any(|&(w, o)| w < 0. || !w.is_finite() || !o.is_finite())
})
{
return Err(Error::invalid("invalid multitrack path section"));
}
let points: Vec<_> = samples.iter().map(|s| s.1).collect();
for (data, profile) in self.tracks.iter_mut().zip(profiles) {
if data.sections.is_empty() {
data.widths.clear();
data.offsets.clear();
}
for pair in profile.windows(2) {
data.widths.extend([pair[0].0, pair[1].0]);
data.offsets.extend([pair[0].1, pair[1].1]);
}
data.sections.push(StrokeSection {
points: points.clone(),
widths: profile.iter().map(|v| v.0).collect(),
offsets: profile.iter().map(|v| v.1).collect(),
});
}
self.points.extend_from_slice(&points[1..]);
Ok(self)
}
pub fn taper(&mut self, samples: &[Sample], ends: &[(f64, f64)]) -> Result<&mut Self> {
if ends.len() != self.tracks.len() {
return Err(Error::invalid("supply an endpoint profile per track"));
}
let profiles: Vec<_> = self
.tracks
.iter()
.zip(ends)
.map(|(d, &(w, o))| {
let a = *d.widths.last().unwrap();
let b = *d.offsets.last().unwrap();
samples
.iter()
.map(|&(t, _)| (a + (w - a) * t, b + (o - b) * t))
.collect()
})
.collect();
self.append(samples, &profiles)
}
pub fn polygons(&self, robust: bool) -> Result<Vec<Element>> {
let mut elements = Vec::new();
for d in &self.tracks {
let ring = if robust {
robust_stroke(&d.sections, d.track.style, &mut |_| {
Err(Error::invalid("use robust_stroke for custom callbacks"))
})?
} else {
stroke(&self.points, &d.widths, &d.offsets, d.track.style)?
};
for points in crate::geometry::fracture(&[ring], usize::MAX)? {
elements.push(Element::Polygon {
layer: d.track.layer,
points,
});
}
}
Ok(elements)
}
pub fn add_to(&self, layout: &mut Layout, cell: &str, robust: bool) -> Result<()> {
let elements = self.polygons(robust)?;
for el in elements {
layout.add_element(cell, el)?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::paths::{Cap, Join};
#[test]
fn rust_builders_preserve_units_and_layer_tags() {
let start = Vec2::new(0., 0.);
let mut c = Curve::new(start, 0.1).unwrap();
c.line_to(Vec2::new(100., 0.))
.unwrap()
.turn(50., std::f64::consts::FRAC_PI_2)
.unwrap();
assert!((c.endpoint() - Vec2::new(150., 50.)).norm() < 1e-10);
let tag = Layer {
number: 3,
datatype: 1,
};
let track = Track {
layer: tag,
width: 12.,
offset: 4.,
style: StrokeStyle {
join: Join::Miter,
cap: Cap::Flush,
tolerance: 0.1,
miter_limit: 2.,
},
};
let mut builder = PathBuilder::new(start, &[track]).unwrap();
let section = parametric(|t| Ok(Vec2::new(100. * t, 0.)), 0.1, 2, 64).unwrap();
builder.taper(§ion, &[(20., 4.)]).unwrap();
for robust in [false, true] {
let elements = builder.polygons(robust).unwrap();
let [Element::Polygon { layer, points }] = elements.as_slice() else {
panic!("expected one polygon")
};
assert_eq!(*layer, tag);
let twice: i64 = points
.iter()
.zip(points.iter().cycle().skip(1))
.map(|(a, b)| a.x * b.y - a.y * b.x)
.sum();
assert_eq!(twice.abs(), 3200);
}
}
}