use anyhow::{Error, bail};
use etagere::euclid::{Point2D, Vector2D};
use lyon_path::geom::{Angle, CubicBezierSegment, QuadraticBezierSegment};
use lyon_path::math::{Vector, vector};
use lyon_path::traits::SvgPathBuilder;
use lyon_path::{ArcFlags, Event, Polygon};
pub use lyon_path::math::Transform;
pub use lyon_path::{FillRule, LineCap, LineJoin};
use crate::{PathCurve, PathTiles, Pixels, Point, point, px};
use std::sync::Arc;
pub enum PathStyle {
Stroke(StrokeOptions),
Fill(FillOptions),
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct StrokeOptions {
pub line_width: f32,
pub line_cap: LineCap,
pub line_join: LineJoin,
pub miter_limit: f32,
}
impl Default for StrokeOptions {
fn default() -> Self {
Self {
line_width: 1.0,
line_cap: LineCap::Butt,
line_join: LineJoin::Miter,
miter_limit: 4.0,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct FillOptions {
pub fill_rule: FillRule,
}
impl Default for FillOptions {
fn default() -> Self {
Self {
fill_rule: FillRule::EvenOdd,
}
}
}
pub struct PathBuilder {
raw: lyon_path::builder::WithSvg<lyon_path::BuilderImpl>,
transform: Option<lyon_path::math::Transform>,
pub style: PathStyle,
dash_array: Option<Vec<Pixels>>,
}
impl From<lyon_path::Builder> for PathBuilder {
fn from(builder: lyon_path::Builder) -> Self {
Self {
raw: builder.with_svg(),
..Default::default()
}
}
}
impl From<lyon_path::builder::WithSvg<lyon_path::BuilderImpl>> for PathBuilder {
fn from(raw: lyon_path::builder::WithSvg<lyon_path::BuilderImpl>) -> Self {
Self {
raw,
..Default::default()
}
}
}
impl From<lyon_path::math::Point> for Point<Pixels> {
fn from(p: lyon_path::math::Point) -> Self {
point(px(p.x), px(p.y))
}
}
impl From<Point<Pixels>> for lyon_path::math::Point {
fn from(p: Point<Pixels>) -> Self {
lyon_path::math::point(p.x.0, p.y.0)
}
}
impl From<Point<Pixels>> for Vector {
fn from(p: Point<Pixels>) -> Self {
vector(p.x.0, p.y.0)
}
}
impl From<Point<Pixels>> for Point2D<f32, Pixels> {
fn from(p: Point<Pixels>) -> Self {
Point2D::new(p.x.0, p.y.0)
}
}
impl Default for PathBuilder {
fn default() -> Self {
Self {
raw: lyon_path::Path::builder().with_svg(),
style: PathStyle::Fill(FillOptions::default()),
transform: None,
dash_array: None,
}
}
}
impl PathBuilder {
pub fn stroke(width: Pixels) -> Self {
Self {
style: PathStyle::Stroke(StrokeOptions {
line_width: width.0,
..Default::default()
}),
..Self::default()
}
}
pub fn fill() -> Self {
Self::default()
}
pub fn with_style(self, style: PathStyle) -> Self {
Self { style, ..self }
}
pub fn dash_array(mut self, dash_array: &[Pixels]) -> Self {
let array = if dash_array.len() % 2 == 1 {
let mut new_dash_array = dash_array.to_vec();
new_dash_array.extend_from_slice(dash_array);
new_dash_array
} else {
dash_array.to_vec()
};
self.dash_array = Some(array);
self
}
#[inline]
pub fn move_to(&mut self, to: Point<Pixels>) {
self.raw.move_to(to.into());
}
#[inline]
pub fn line_to(&mut self, to: Point<Pixels>) {
self.raw.line_to(to.into());
}
#[inline]
pub fn curve_to(&mut self, to: Point<Pixels>, ctrl: Point<Pixels>) {
self.raw.quadratic_bezier_to(ctrl.into(), to.into());
}
#[inline]
pub fn cubic_bezier_to(
&mut self,
to: Point<Pixels>,
control_a: Point<Pixels>,
control_b: Point<Pixels>,
) {
self.raw
.cubic_bezier_to(control_a.into(), control_b.into(), to.into());
}
pub fn arc_to(
&mut self,
radii: Point<Pixels>,
x_rotation: Pixels,
large_arc: bool,
sweep: bool,
to: Point<Pixels>,
) {
self.raw.arc_to(
radii.into(),
Angle::degrees(x_rotation.into()),
ArcFlags { large_arc, sweep },
to.into(),
);
}
pub fn relative_arc_to(
&mut self,
radii: Point<Pixels>,
x_rotation: Pixels,
large_arc: bool,
sweep: bool,
to: Point<Pixels>,
) {
self.raw.relative_arc_to(
radii.into(),
Angle::degrees(x_rotation.into()),
ArcFlags { large_arc, sweep },
to.into(),
);
}
pub fn add_polygon(&mut self, points: &[Point<Pixels>], closed: bool) {
let points = points.iter().copied().map(|p| p.into()).collect::<Vec<_>>();
self.raw.add_polygon(Polygon {
points: points.as_ref(),
closed,
});
}
#[inline]
pub fn close(&mut self) {
self.raw.close();
}
#[inline]
pub fn transform(&mut self, transform: Transform) {
self.transform = Some(transform);
}
#[inline]
pub fn translate(&mut self, to: Point<Pixels>) {
if let Some(transform) = self.transform {
self.transform = Some(transform.then_translate(Vector2D::new(to.x.0, to.y.0)));
} else {
self.transform = Some(Transform::translation(to.x.0, to.y.0))
}
}
#[inline]
pub fn scale(&mut self, scale: f32) {
if let Some(transform) = self.transform {
self.transform = Some(transform.then_scale(scale, scale));
} else {
self.transform = Some(Transform::scale(scale, scale));
}
}
#[inline]
pub fn rotate(&mut self, angle: f32) {
let radians = angle.to_radians();
if let Some(transform) = self.transform {
self.transform = Some(transform.then_rotate(Angle::radians(radians)));
} else {
self.transform = Some(Transform::rotation(Angle::radians(radians)));
}
}
pub fn build(self) -> Result<Path, Error> {
let (curves, fill_rule) = self.outline()?;
Ok(Path::from_curves(curves, fill_rule))
}
pub(crate) fn outline(self) -> Result<(Vec<PathCurve>, FillRule), Error> {
let path = if let Some(transform) = self.transform {
self.raw.build().transformed(&transform)
} else {
self.raw.build()
};
Ok(match self.style {
PathStyle::Stroke(options) => (
Self::stroke_outline(&path, &options, self.dash_array.as_deref())?,
FillRule::NonZero,
),
PathStyle::Fill(options) => (Self::fill_outline(&path)?, options.fill_rule),
})
}
fn stroke_outline(
path: &lyon_path::Path,
options: &StrokeOptions,
dash_array: Option<&[Pixels]>,
) -> Result<Vec<PathCurve>, Error> {
let outline = skia_path(path)
.map(|skia_path| match dash_array {
Some(dash_array) => {
let array = dash_array.iter().map(|length| length.0).collect();
match tiny_skia_path::StrokeDash::new(array, 0.0) {
Some(dash) => skia_path
.dash(&dash, STROKE_RESOLUTION_SCALE)
.unwrap_or(skia_path),
None => skia_path,
}
}
None => skia_path,
})
.and_then(|skia_path| {
skia_path.stroke(
&tiny_skia_path::Stroke {
width: options.line_width,
miter_limit: options.miter_limit,
line_cap: match options.line_cap {
LineCap::Butt => tiny_skia_path::LineCap::Butt,
LineCap::Square => tiny_skia_path::LineCap::Square,
LineCap::Round => tiny_skia_path::LineCap::Round,
},
line_join: match options.line_join {
LineJoin::Miter => tiny_skia_path::LineJoin::Miter,
LineJoin::MiterClip => tiny_skia_path::LineJoin::MiterClip,
LineJoin::Round => tiny_skia_path::LineJoin::Round,
LineJoin::Bevel => tiny_skia_path::LineJoin::Bevel,
},
dash: None,
},
STROKE_RESOLUTION_SCALE,
)
});
let Some(outline) = outline else {
return Ok(Vec::new());
};
let mut output = Outline::default();
let at = |p: tiny_skia_path::Point| point(p.x, p.y);
for segment in outline.segments() {
match segment {
tiny_skia_path::PathSegment::MoveTo(p) => output.move_to(at(p)),
tiny_skia_path::PathSegment::LineTo(p) => output.line_to(at(p)),
tiny_skia_path::PathSegment::QuadTo(ctrl, p) => output.curve_to(at(p), at(ctrl)),
tiny_skia_path::PathSegment::CubicTo(ctrl1, ctrl2, p) => {
output.cubic_to(at(p), at(ctrl1), at(ctrl2))
}
tiny_skia_path::PathSegment::Close => output.close(),
}
}
output.into_curves()
}
fn fill_outline(path: &lyon_path::Path) -> Result<Vec<PathCurve>, Error> {
let mut output = Outline::default();
let at = |p: lyon_path::math::Point| point(p.x, p.y);
for event in path.iter() {
match event {
Event::Begin { at: p } => output.move_to(at(p)),
Event::Line { to, .. } => output.line_to(at(to)),
Event::Quadratic { ctrl, to, .. } => output.curve_to(at(to), at(ctrl)),
Event::Cubic {
ctrl1, ctrl2, to, ..
} => output.cubic_to(at(to), at(ctrl1), at(ctrl2)),
Event::End { .. } => output.close(),
}
}
output.into_curves()
}
}
#[derive(Clone, Debug)]
pub struct Path {
curves: Arc<[PathCurve]>,
even_odd: bool,
}
impl Path {
pub(crate) fn from_curves(curves: Vec<PathCurve>, fill_rule: FillRule) -> Self {
Self {
curves: curves.into(),
even_odd: matches!(fill_rule, FillRule::EvenOdd),
}
}
pub(crate) fn even_odd(&self) -> bool {
self.even_odd
}
pub(crate) fn bin(&self, scale: f32) -> PathTiles {
crate::path_winding::bin(&self.curves, self.even_odd, scale)
}
pub(crate) fn transformed(&self, matrix: crate::TransformationMatrix, scale: f32) -> Self {
let map = |p: Point<f32>| {
let moved = matrix.apply(point(Pixels(p.x * scale), Pixels(p.y * scale)));
point(moved.x.0 / scale, moved.y.0 / scale)
};
let mut curves = Vec::with_capacity(self.curves.len());
for curve in self.curves.iter() {
let (from, to) = if curve.sign < 0.0 {
(curve.p1, curve.p0)
} else {
(curve.p0, curve.p1)
};
if curve.a == point(0.0, 0.0) {
let (from, to) = (map(from), map(to));
if from != to {
curves.push(PathCurve::line(from, to));
}
} else {
let ctrl = point(curve.p0.x + curve.b.x / 2.0, curve.p0.y + curve.b.y / 2.0);
PathCurve::push_monotone(&mut curves, map(from), map(ctrl), map(to));
}
}
Self {
curves: curves.into(),
even_odd: self.even_odd,
}
}
}
#[derive(Default)]
pub(crate) struct Outline {
curves: Vec<PathCurve>,
start: Point<f32>,
current: Point<f32>,
non_finite: bool,
}
impl Outline {
fn accepts(&mut self, points: &[Point<f32>]) -> bool {
self.non_finite |= !points
.iter()
.all(|point| point.x.is_finite() && point.y.is_finite());
!self.non_finite
}
pub(crate) fn move_to(&mut self, to: Point<f32>) {
if !self.accepts(&[to]) {
return;
}
self.close();
self.start = to;
self.current = to;
}
pub(crate) fn line_to(&mut self, to: Point<f32>) {
if self.accepts(&[to]) && to != self.current {
self.curves.push(PathCurve::line(self.current, to));
self.current = to;
}
}
pub(crate) fn curve_to(&mut self, to: Point<f32>, ctrl: Point<f32>) {
if !self.accepts(&[to, ctrl]) || (to == self.current && ctrl == self.current) {
return;
}
PathCurve::push_monotone(&mut self.curves, self.current, ctrl, to);
self.current = to;
}
pub(crate) fn cubic_to(&mut self, to: Point<f32>, ctrl1: Point<f32>, ctrl2: Point<f32>) {
const TOLERANCE: f32 = 0.25;
if !self.accepts(&[to, ctrl1, ctrl2]) {
return;
}
let lyon_point = |p: Point<f32>| lyon_path::math::point(p.x, p.y);
let cubic = CubicBezierSegment {
from: lyon_point(self.current),
ctrl1: lyon_point(ctrl1),
ctrl2: lyon_point(ctrl2),
to: lyon_point(to),
};
cubic.for_each_quadratic_bezier(TOLERANCE, &mut |quadratic| {
self.curve_to(
point(quadratic.to.x, quadratic.to.y),
point(quadratic.ctrl.x, quadratic.ctrl.y),
);
});
}
pub(crate) fn close(&mut self) {
let start = self.start;
self.line_to(start);
}
pub(crate) fn into_curves(mut self) -> Result<Vec<PathCurve>, Error> {
if self.non_finite {
bail!("path has a non-finite point");
}
self.close();
Ok(self.curves)
}
}
impl PathCurve {
fn new(p0: Point<f32>, ctrl: Point<f32>, p1: Point<f32>, sign: f32) -> Self {
Self {
p0,
p1,
a: point(p0.x - 2.0 * ctrl.x + p1.x, p0.y - 2.0 * ctrl.y + p1.y),
b: point(2.0 * (ctrl.x - p0.x), 2.0 * (ctrl.y - p0.y)),
sign,
pad: 0,
}
}
fn line(from: Point<f32>, to: Point<f32>) -> Self {
let (p0, p1, sign) = downward(from, to);
Self {
p0,
p1,
a: point(0.0, 0.0),
b: point(p1.x - p0.x, p1.y - p0.y),
sign,
pad: 0,
}
}
fn push_monotone(curves: &mut Vec<Self>, p0: Point<f32>, ctrl: Point<f32>, p1: Point<f32>) {
let curve = QuadraticBezierSegment {
from: lyon_path::math::point(p0.x, p0.y),
ctrl: lyon_path::math::point(ctrl.x, ctrl.y),
to: lyon_path::math::point(p1.x, p1.y),
};
curve.for_each_monotonic(&mut |monotone| {
let from = point(monotone.from.x, monotone.from.y);
let to = point(monotone.to.x, monotone.to.y);
if from == to {
return;
}
let (p0, p1, sign) = downward(from, to);
let ctrl = point(
monotone.ctrl.x.clamp(p0.x.min(p1.x), p0.x.max(p1.x)),
monotone.ctrl.y.clamp(p0.y, p1.y),
);
curves.push(Self::new(p0, ctrl, p1, sign));
});
}
}
fn downward(from: Point<f32>, to: Point<f32>) -> (Point<f32>, Point<f32>, f32) {
if from.y > to.y {
(to, from, -1.0)
} else {
(from, to, 1.0)
}
}
const STROKE_RESOLUTION_SCALE: f32 = 2.0;
fn skia_path(path: &lyon_path::Path) -> Option<tiny_skia_path::Path> {
let mut builder = tiny_skia_path::PathBuilder::new();
for event in path.iter() {
match event {
Event::Begin { at } => builder.move_to(at.x, at.y),
Event::Line { to, .. } => builder.line_to(to.x, to.y),
Event::Quadratic { ctrl, to, .. } => builder.quad_to(ctrl.x, ctrl.y, to.x, to.y),
Event::Cubic {
ctrl1, ctrl2, to, ..
} => builder.cubic_to(ctrl1.x, ctrl1.y, ctrl2.x, ctrl2.y, to.x, to.y),
Event::End { close, .. } => {
if close {
builder.close();
}
}
}
}
builder.finish()
}