use super::{Error, Result, Vec2, arc, on_grid, tolerance_ok};
use crate::Point;
use std::f64::consts::{PI, TAU};
#[derive(Clone, Copy)]
pub enum Join {
Callback,
Miter,
Natural,
Bevel,
Round,
Smooth,
}
#[derive(Clone, Copy)]
pub enum Cap {
Callback,
Flush,
Extended,
Round,
Smooth,
Custom(f64, f64),
}
#[derive(Clone, Copy)]
pub struct StrokeStyle {
pub join: Join,
pub cap: Cap,
pub tolerance: f64,
pub miter_limit: f64,
}
pub struct Junction {
pub a: Vec2,
pub u: Vec2,
pub b: Vec2,
pub v: Vec2,
pub center: Vec2,
pub width: f64,
pub is_cap: bool,
}
type BoundaryFn<'a> = dyn FnMut(Junction) -> Result<Vec<Vec2>> + 'a;
fn no_callback(_: Junction) -> Result<Vec<Vec2>> {
Err(Error::invalid("path boundary callback required"))
}
fn custom_points(result: &mut Vec<Vec2>, j: Junction, callback: &mut BoundaryFn<'_>) -> Result<()> {
let points = callback(j)?;
if points.len() > super::MAX_SAMPLES - result.len().min(super::MAX_SAMPLES)
|| !points.iter().all(|v| v.finite())
{
return Err(Error::invalid(
"invalid callback boundary or path vertex budget exceeded",
));
}
result.extend(points);
Ok(())
}
fn intersect(p: Vec2, v: Vec2, q: Vec2, w: Vec2) -> Option<Vec2> {
let cross = v.cross(w);
if cross.abs() < 1e-12 * v.norm() * w.norm() || cross == 0. {
None
} else {
Some(p + v * ((q - p).cross(w) / cross))
}
}
fn directions(points: &[Vec2]) -> Result<Vec<Vec2>> {
points
.windows(2)
.map(|p| {
let d = p[1] - p[0];
let n = d.norm();
if n == 0. || !n.is_finite() {
Err(Error::invalid("zero-length or nonfinite stroke segment"))
} else {
Ok(d / n)
}
})
.collect()
}
fn profile(values: &[f64], n: usize, i: usize, segment: usize) -> f64 {
if values.len() == n {
values[i]
} else {
values[segment + i]
}
}
pub fn offset_spine(points: &[Vec2], offsets: &[f64]) -> Result<Vec<Vec2>> {
if points.len() < 2
|| ![points.len(), 2 * (points.len() - 1)].contains(&offsets.len())
|| !offsets.iter().all(|v| v.is_finite())
{
return Err(Error::invalid("invalid track offsets"));
}
let dirs = directions(points)?;
let shifted =
|i: usize, j: usize| points[i] + dirs[j].normal() * profile(offsets, points.len(), i, j);
let end = points.len() - 1;
let mut spine = vec![shifted(0, 0)];
for i in 1..end {
let a = shifted(i, i - 1);
let b = shifted(i, i);
if dirs[i - 1].dot(dirs[i]) < -1. + 1e-12 {
return Err(Error::invalid("180 degree cusp in stroke; split the path"));
}
spine.push(
intersect(a, a - shifted(i - 1, i - 1), b, shifted(i + 1, i) - b)
.unwrap_or((a + b) * 0.5),
);
}
spine.push(shifted(end, end - 1));
Ok(spine)
}
fn round_join(
result: &mut Vec<Vec2>,
center: Vec2,
a: Vec2,
b: Vec2,
positive: bool,
tol: f64,
) -> Result<()> {
let radius = (a - center).norm();
if radius == 0. {
result.push(b);
return Ok(());
}
let first = (a - center).angle();
let last = (b - center).angle();
let sweep = if positive {
(last - first).rem_euclid(TAU)
} else {
-((first - last).rem_euclid(TAU))
};
let mut pts = arc(a, Vec2::new(radius, radius), first, first + sweep, 0., tol)?;
pts.last_mut().unwrap().1 = b;
result.extend(pts.into_iter().map(|(_, p)| p));
Ok(())
}
fn smooth_join(
result: &mut Vec<Vec2>,
a: Vec2,
t0: Vec2,
b: Vec2,
t1: Vec2,
tol: f64,
) -> Result<()> {
if (a - b).norm() < f64::EPSILON {
result.push(b);
return Ok(());
}
let controls = super::hobby_controls(
&[a, b],
&super::HobbyOptions {
angles: &[Some(t0.angle()), Some(t1.angle())],
tension_in: &[1.; 2],
tension_out: &[1.; 2],
initial_curl: 1.,
final_curl: 1.,
cycle: false,
},
)?;
result.extend(
super::bezier(&[a, controls[0][0], controls[0][1], b], tol)?
.into_iter()
.map(|(_, p)| p),
);
Ok(())
}
fn side(
spine: &[Vec2],
dirs: &[Vec2],
width: &[f64],
sign: f64,
style: StrokeStyle,
callback: &mut BoundaryFn<'_>,
) -> Result<Vec<Vec2>> {
let point = |i: usize, j: usize| {
spine[i] + dirs[j].normal() * (sign * profile(width, spine.len(), i, j) * 0.5)
};
let n = spine.len() - 1;
let mut result = vec![point(0, 0)];
for i in 1..n {
let a = point(i, i - 1);
let b = point(i, i);
let u = a - point(i - 1, i - 1);
let v = point(i + 1, i) - b;
let hit = intersect(a, u, b, v).unwrap_or((a + b) * 0.5);
let outside = dirs[i - 1].cross(dirs[i]) * sign < -1e-12;
let local_width = profile(width, spine.len(), i, i - 1);
if !outside || local_width == 0. {
result.push(hit);
} else {
match style.join {
Join::Callback => custom_points(
&mut result,
Junction {
a,
u: u / u.norm(),
b,
v: v / v.norm(),
center: spine[i],
width: local_width,
is_cap: false,
},
callback,
)?,
Join::Miter => result.push(hit),
Join::Natural => {
let limit = local_width * 0.5 * style.miter_limit;
let incoming = u / u.norm();
let outgoing = v / v.norm();
let first = (hit - a).dot(incoming);
let second = (b - hit).dot(outgoing);
if first <= limit && second <= limit {
result.push(hit);
} else {
result.extend([
a + incoming * first.min(limit),
b - outgoing * second.min(limit),
]);
}
}
Join::Bevel => result.extend([a, b]),
Join::Round => round_join(&mut result, spine[i], a, b, sign < 0., style.tolerance)?,
Join::Smooth => smooth_join(&mut result, a, u, b, v, style.tolerance)?,
}
}
if result.len() > super::MAX_SAMPLES {
return Err(Error::invalid("stroke vertex budget exceeded"));
}
}
result.push(point(n, n - 1));
Ok(result)
}
fn cap(
out: &mut Vec<Vec2>,
center: Vec2,
a: Vec2,
b: Vec2,
direction: Vec2,
style: StrokeStyle,
callback: &mut BoundaryFn<'_>,
) -> Result<()> {
match style.cap {
Cap::Callback => custom_points(
out,
Junction {
a,
u: direction,
b,
v: direction * -1.,
center,
width: (a - b).norm(),
is_cap: true,
},
callback,
),
Cap::Round => round_join(out, center, a, b, false, style.tolerance),
Cap::Smooth => smooth_join(out, a, direction, b, direction * -1., style.tolerance),
_ => {
out.push(b);
Ok(())
}
}
}
pub fn stroke(
points: &[Vec2],
widths: &[f64],
offsets: &[f64],
style: StrokeStyle,
) -> Result<Vec<Point>> {
stroke_with(points, widths, offsets, style, &mut no_callback)
}
pub fn stroke_with(
points: &[Vec2],
widths: &[f64],
offsets: &[f64],
style: StrokeStyle,
callback: &mut BoundaryFn<'_>,
) -> Result<Vec<Point>> {
grid_outline(&stroke_outline(points, widths, offsets, style, callback)?)
}
pub fn stroke_outline(
points: &[Vec2],
widths: &[f64],
offsets: &[f64],
style: StrokeStyle,
callback: &mut BoundaryFn<'_>,
) -> Result<Vec<Vec2>> {
tolerance_ok(style.tolerance)?;
if points.len() < 2
|| points.len() > super::MAX_SAMPLES
|| ![points.len(), 2 * (points.len() - 1)].contains(&widths.len())
|| ![points.len(), 2 * (points.len() - 1)].contains(&offsets.len())
|| widths.iter().all(|v| *v == 0.)
|| !widths.iter().all(|v| v.is_finite() && *v >= 0.)
|| !offsets.iter().all(|v| v.is_finite())
|| !points.iter().all(|v| v.finite())
|| !style.miter_limit.is_finite()
|| style.miter_limit < 1.
{
return Err(Error::invalid(
"invalid stroke coordinates, widths, offsets or miter limit",
));
}
let spine = offset_spine(points, offsets)?;
let dirs = directions(&spine)?;
let n = spine.len() - 1;
let left = side(&spine, &dirs, widths, 1., style, callback)?;
let right = side(&spine, &dirs, widths, -1., style, callback)?;
finish(
left,
right,
[spine[0], spine[n]],
[dirs[0] * -1., dirs[n - 1]],
[widths[0], widths[widths.len() - 1]],
style,
callback,
)
}
fn finish(
mut left: Vec<Vec2>,
mut right: Vec<Vec2>,
center: [Vec2; 2],
outward: [Vec2; 2],
width: [f64; 2],
style: StrokeStyle,
callback: &mut BoundaryFn<'_>,
) -> Result<Vec<Vec2>> {
let (a, b) = match style.cap {
Cap::Custom(a, b) => (a, b),
Cap::Extended => (width[0] * 0.5, width[1] * 0.5),
_ => (0., 0.),
};
if !a.is_finite() || !b.is_finite() {
return Err(Error::invalid("nonfinite cap extension"));
}
for side in [&mut left, &mut right] {
side[0] = side[0] + outward[0] * a;
let last = side.last_mut().unwrap();
*last = *last + outward[1] * b;
}
let first_l = left[0];
let last_l = *left.last().unwrap();
let first_r = right[0];
let last_r = *right.last().unwrap();
cap(
&mut left, center[1], last_l, last_r, outward[1], style, callback,
)?;
left.extend(right.into_iter().rev());
cap(
&mut left, center[0], first_r, first_l, outward[0], style, callback,
)?;
Ok(left)
}
pub fn grid_outline(outline: &[Vec2]) -> Result<Vec<Point>> {
let mut points = on_grid(outline)?;
if points.len() > 1 && points.first() == points.last() {
points.pop();
}
let has_area = points.first().zip(points.get(1)).is_some_and(|(a, b)| {
points[2..].iter().any(|p| {
let dx = i128::from(b.x) - i128::from(a.x);
let dy = i128::from(b.y) - i128::from(a.y);
dx * (i128::from(p.y) - i128::from(a.y)) != dy * (i128::from(p.x) - i128::from(a.x))
})
});
if !has_area {
return Err(Error::invalid("stroke collapses on the database grid"));
}
Ok(points)
}
pub fn fillet(a: Vec2, b: Vec2, c: Vec2, radius: f64, tolerance: f64) -> Result<Vec<Vec2>> {
let ds = directions(&[a, b, c])?;
let u = ds[0];
let v = ds[1];
let sweep = u.cross(v).atan2(u.dot(v));
if !radius.is_finite() || radius <= 0. {
return Err(Error::invalid("bend radius must be finite and positive"));
}
if sweep.abs() < 1e-12 {
return Ok(vec![b]);
}
let trim = radius * (sweep.abs() * 0.5).tan();
if trim > (b - a).norm() || trim > (c - b).norm() {
return Err(Error::invalid(
"bend radius exceeds adjacent segment length",
));
}
let start = b - u * trim;
let angle = u.angle() - sweep.signum() * PI * 0.5;
Ok(arc(
start,
Vec2::new(radius, radius),
angle,
angle + sweep,
0.,
tolerance,
)?
.into_iter()
.map(|(_, p)| p)
.collect())
}
pub struct StrokeSection {
pub points: Vec<Vec2>,
pub widths: Vec<f64>,
pub offsets: Vec<f64>,
}
struct SegmentBounds {
lo: Vec2,
hi: Vec2,
begin: usize,
end: usize,
children: Option<Box<[SegmentBounds; 2]>>,
}
impl SegmentBounds {
fn build(points: &[Vec2], begin: usize, end: usize) -> Self {
if end - begin <= 12 {
let mut lo = points[begin];
let mut hi = lo;
for p in &points[begin + 1..=end] {
lo.x = lo.x.min(p.x);
lo.y = lo.y.min(p.y);
hi.x = hi.x.max(p.x);
hi.y = hi.y.max(p.y);
}
Self {
lo,
hi,
begin,
end,
children: None,
}
} else {
let mid = begin + (end - begin) / 2;
let a = Self::build(points, begin, mid);
let b = Self::build(points, mid, end);
Self {
lo: Vec2::new(a.lo.x.min(b.lo.x), a.lo.y.min(b.lo.y)),
hi: Vec2::new(a.hi.x.max(b.hi.x), a.hi.y.max(b.hi.y)),
begin,
end,
children: Some(Box::new([a, b])),
}
}
}
fn candidates(&self, p: Vec2, q: Vec2, result: &mut Vec<usize>) {
if self.hi.x < p.x.min(q.x)
|| self.hi.y < p.y.min(q.y)
|| self.lo.x > p.x.max(q.x)
|| self.lo.y > p.y.max(q.y)
{
return;
}
if let Some(children) = &self.children {
for child in children.iter() {
child.candidates(p, q, result);
}
} else {
result.extend(self.begin..self.end);
}
}
}
fn splice(
previous: &mut Vec<Vec2>,
next: &[Vec2],
last_section_start: usize,
budget: &mut usize,
) -> Result<usize> {
let plen = previous.len();
let a = previous[plen - 1];
let b = next[0];
if (a - b).norm() <= 1e-10 {
previous.extend_from_slice(&next[1..]);
return Ok(plen - 1);
}
let tree = SegmentBounds::build(next, 0, next.len() - 1);
let mut arc_lengths = vec![0.];
for pair in next.windows(2) {
arc_lengths.push(arc_lengths.last().unwrap() + (pair[1] - pair[0]).norm());
}
let mut candidates = Vec::new();
let mut best = None;
let mut best_length = f64::INFINITY;
let mut walked_left = 0.;
for i in (last_section_start..plen - 1).rev() {
if walked_left > best_length {
break;
}
let p = previous[i];
let v = previous[i + 1] - p;
let nv = v.norm();
candidates.clear();
tree.candidates(p, previous[i + 1], &mut candidates);
for &j in &candidates {
let walked_right = arc_lengths[j];
if walked_left + walked_right > best_length {
break;
}
if *budget == 0 {
return Err(Error::invalid(
"robust intersection evaluation budget exceeded",
));
}
*budget -= 1;
let q = next[j];
let w = next[j + 1] - q;
let nw = w.norm();
if let Some(hit) = intersect(p, v, q, w) {
let t = (hit - p).dot(v) / (nv * nv);
let s = (hit - q).dot(w) / (nw * nw);
if (-1e-9..=1. + 1e-9).contains(&t) && (-1e-9..=1. + 1e-9).contains(&s) {
let length = walked_left + walked_right + (1. - t) * nv + s * nw;
if length < best_length {
best_length = length;
best = Some((i, j, hit));
}
}
}
}
walked_left += nv;
}
if let Some((i, j, hit)) = best {
previous.truncate(i + 1);
previous.push(hit);
let index = previous.len() - 1;
previous.extend_from_slice(&next[j + 1..]);
Ok(index)
} else {
let v = a - previous[plen - 2];
let w = next[1] - b;
if let Some(hit) = intersect(a, v, b, w)
&& (hit - a).dot(v) >= 0.
&& (b - hit).dot(w) >= 0.
{
previous[plen - 1] = hit;
previous.extend_from_slice(&next[1..]);
Ok(plen - 1)
} else {
previous.extend_from_slice(next);
Ok(plen)
}
}
}
pub fn robust_stroke(
sections: &[StrokeSection],
style: StrokeStyle,
callback: &mut BoundaryFn<'_>,
) -> Result<Vec<Point>> {
robust_stroke_bounded(sections, style, 8_000_000, callback)
}
pub fn robust_stroke_bounded(
sections: &[StrokeSection],
style: StrokeStyle,
max_evals: usize,
callback: &mut BoundaryFn<'_>,
) -> Result<Vec<Point>> {
grid_outline(&robust_outline(sections, style, max_evals, callback)?)
}
pub fn robust_outline(
sections: &[StrokeSection],
style: StrokeStyle,
max_evals: usize,
callback: &mut BoundaryFn<'_>,
) -> Result<Vec<Vec2>> {
tolerance_ok(style.tolerance)?;
if sections.is_empty() {
return Err(Error::invalid("empty robust path"));
}
if sections.iter().all(|s| s.widths.iter().all(|w| *w == 0.)) {
return Err(Error::invalid("robust path has zero width throughout"));
}
let mut rails = [Vec::new(), Vec::new()];
let mut starts = [0, 0];
let mut center = [Vec2::default(); 2];
let mut outward = center;
let mut width = [0.; 2];
for (i, section) in sections.iter().enumerate() {
if section.points.len() < 2
|| section.widths.len() != section.points.len()
|| section.offsets.len() != section.points.len()
|| !section.widths.iter().all(|w| w.is_finite() && *w >= 0.)
{
return Err(Error::invalid("invalid robust section profiles"));
}
let spine = offset_spine(§ion.points, §ion.offsets)?;
let dirs = directions(&spine)?;
let n = spine.len() - 1;
if i == 0 {
center[0] = spine[0];
outward[0] = dirs[0] * -1.;
width[0] = section.widths[0];
}
center[1] = spine[n];
outward[1] = dirs[n - 1];
width[1] = section.widths[n];
for (k, sign) in [1., -1.].into_iter().enumerate() {
let part = side(&spine, &dirs, §ion.widths, sign, style, callback)?;
if i == 0 {
rails[k] = part;
} else {
let mut budget = max_evals;
starts[k] = splice(&mut rails[k], &part, starts[k], &mut budget)?;
}
}
}
let [left, right] = rails;
finish(left, right, center, outward, width, style, callback)
}