use crate::{PathCommand, Point};
use f_office_units::Length;
use f_office_units::scale::DRAWING_WHOLE;
pub const CURVE_PIECES: i64 = 16;
pub const KAPPA: i64 = 55_228;
#[must_use]
pub fn kappa(radius: Length) -> Length {
(radius * KAPPA).div_toward_zero(DRAWING_WHOLE)
}
#[must_use]
pub fn cubic_points(controls: [Point; 4]) -> Vec<Point> {
let n = i128::from(CURVE_PIECES).pow(3);
let at = |k: i64| {
let (t, s) = (i128::from(k), i128::from(CURVE_PIECES - k));
let mix = |a: Length, b: Length, c: Length, d: Length| {
let sum = s * s * s * i128::from(a.units())
+ 3 * s * s * t * i128::from(b.units())
+ 3 * s * t * t * i128::from(c.units())
+ t * t * t * i128::from(d.units());
Length::from_units(i64::try_from(sum / n).unwrap_or(0))
};
let [p0, p1, p2, p3] = controls;
Point {
x: mix(p0.x, p1.x, p2.x, p3.x),
y: mix(p0.y, p1.y, p2.y, p3.y),
}
};
(1..=CURVE_PIECES).map(at).collect()
}
#[must_use]
pub fn quad_as_cubic(start: Point, control: Point, end: Point) -> [Point; 4] {
let third = |from: Point| Point {
x: from.x + ((control.x - from.x) * 2).div_round(3),
y: from.y + ((control.y - from.y) * 2).div_round(3),
};
[start, third(start), third(end), end]
}
#[must_use]
pub fn line_pieces(points: &[Point], half: Length) -> Vec<PathCommand> {
points
.windows(2)
.filter_map(|pair| match pair {
[a, b] => piece(*a, *b, half),
_ => None,
})
.flatten()
.collect()
}
#[must_use]
pub fn round_line(points: &[Point], half: Length) -> Vec<PathCommand> {
let pieces = points.windows(2).filter_map(|pair| match pair {
[a, b] => band(*a, *b, half),
_ => None,
});
let mut commands: Vec<PathCommand> = pieces.flatten().collect();
for point in points {
commands.extend(disc(*point, half));
}
commands
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum StrokeCap {
#[default]
Flat,
Round,
Square,
}
#[must_use]
pub fn round_dashes(
points: &[Point],
half: Length,
pattern: &[Length],
limit: usize,
) -> Option<Vec<PathCommand>> {
dashes(points, half, pattern, StrokeCap::Round, limit)
}
#[must_use]
pub fn dashes(
points: &[Point],
half: Length,
pattern: &[Length],
cap: StrokeCap,
limit: usize,
) -> Option<Vec<PathCommand>> {
let period: i64 = pattern.iter().map(|length| length.units()).sum();
if period <= 0 || pattern.iter().any(|length| length.units() < 0) {
return None;
}
let mut walk = DashWalk {
commands: Vec::new(),
dash: points.first().copied().into_iter().collect(),
on: true,
index: 0,
left: *pattern.first()?,
dashes: 0,
cap,
last_dir: None,
};
for pair in points.windows(2) {
if let [a, b] = pair {
walk.segment(*a, *b, (half, pattern, limit))?;
}
}
if walk.on {
walk.flush(half);
}
Some(walk.commands)
}
struct DashWalk {
commands: Vec<PathCommand>,
dash: Vec<Point>,
on: bool,
index: usize,
left: Length,
dashes: usize,
cap: StrokeCap,
last_dir: Option<(Length, Length)>,
}
impl DashWalk {
fn flush(&mut self, half: Length) {
match self.cap {
StrokeCap::Round => self.commands.extend(round_line(&self.dash, half)),
StrokeCap::Flat => emit_flat_dash(&self.dash, half, &mut self.commands),
StrokeCap::Square => {
emit_square_dash(&self.dash, half, self.last_dir, &mut self.commands);
}
}
}
fn segment(
&mut self,
a: Point,
b: Point,
(half, pattern, limit): (Length, &[Length], usize),
) -> Option<()> {
if let Some(dir) = along(a, b, half) {
self.last_dir = Some(dir);
}
let (dx, dy) = (
i128::from((b.x - a.x).units()),
i128::from((b.y - a.y).units()),
);
let length = (dx * dx + dy * dy).isqrt();
let mut done = 0_i128;
while i128::from(self.left.units()) <= length - done {
if !self.on && i128::from(self.left.units()) == length - done {
self.left = Length::ZERO;
return Some(());
}
done += i128::from(self.left.units());
let share =
|d: i128| Length::from_units(i64::try_from(d * done / length.max(1)).unwrap_or(0));
let at = Point {
x: a.x + share(dx),
y: a.y + share(dy),
};
if self.on {
self.dash.push(at);
self.flush(half);
self.dashes += 1;
if self.dashes > limit {
return None;
}
}
self.dash.clear();
self.dash.push(at);
self.on = !self.on;
self.index = (self.index + 1) % pattern.len();
self.left = *pattern.get(self.index)?;
}
let rest = i64::try_from(length - done).ok()?;
self.left -= Length::from_units(rest);
if self.on {
self.dash.push(b);
}
Some(())
}
}
fn emit_flat_dash(points: &[Point], half: Length, out: &mut Vec<PathCommand>) {
let mut non_empty = 0_usize;
let mut last_end = None;
for pair in points.windows(2) {
if let [a, b] = pair
&& let Some(quad) = band(*a, *b, half)
{
if non_empty > 0
&& let Some(joint) = last_end
{
out.extend(disc(joint, half));
}
out.extend(quad);
last_end = Some(*b);
non_empty += 1;
}
}
}
fn emit_square_dash(
points: &[Point],
half: Length,
fallback_dir: Option<(Length, Length)>,
out: &mut Vec<PathCommand>,
) {
let segments: Vec<(Point, Point, (Length, Length))> = points
.windows(2)
.filter_map(|pair| match pair {
[a, b] => along(*a, *b, half).map(|dir| (*a, *b, dir)),
_ => None,
})
.collect();
if segments.is_empty() {
if let (Some(¢er), Some((ux, uy))) = (points.first(), fallback_dir) {
let start = Point {
x: center.x - ux,
y: center.y - uy,
};
let end = Point {
x: center.x + ux,
y: center.y + uy,
};
out.extend(quadrilateral(start, end, (ux, uy)));
}
return;
}
let last_index = segments.len() - 1;
for (idx, &(a, b, (ux, uy))) in segments.iter().enumerate() {
let start = if idx == 0 {
Point {
x: a.x - ux,
y: a.y - uy,
}
} else {
out.extend(disc(a, half));
a
};
let end = if idx == last_index {
Point {
x: b.x + ux,
y: b.y + uy,
}
} else {
b
};
out.extend(quadrilateral(start, end, (ux, uy)));
}
}
#[must_use]
pub fn round_outline(corners: &[Point], half: Length) -> Vec<PathCommand> {
let mut points = corners.to_vec();
points.extend(corners.first().copied());
round_line(&points, half)
}
#[must_use]
pub fn disc(center: Point, radius: Length) -> [PathCommand; 6] {
let k = kappa(radius);
let (x, y) = (center.x, center.y);
[
PathCommand::MoveTo(at(x, y - radius)),
PathCommand::CubicTo(
at(x - k, y - radius),
at(x - radius, y - k),
at(x - radius, y),
),
PathCommand::CubicTo(
at(x - radius, y + k),
at(x - k, y + radius),
at(x, y + radius),
),
PathCommand::CubicTo(
at(x + k, y + radius),
at(x + radius, y + k),
at(x + radius, y),
),
PathCommand::CubicTo(
at(x + radius, y - k),
at(x + k, y - radius),
at(x, y - radius),
),
PathCommand::Close,
]
}
#[must_use]
pub fn band(a: Point, b: Point, half: Length) -> Option<[PathCommand; 5]> {
let (ux, uy) = along(a, b, half)?;
Some(quadrilateral(a, b, (ux, uy)))
}
#[must_use]
pub fn piece(a: Point, b: Point, half: Length) -> Option<[PathCommand; 5]> {
let (ux, uy) = along(a, b, half)?;
let start = Point {
x: a.x - ux,
y: a.y - uy,
};
let end = Point {
x: b.x + ux,
y: b.y + uy,
};
Some(quadrilateral(start, end, (ux, uy)))
}
fn along(a: Point, b: Point, half: Length) -> Option<(Length, Length)> {
let (dx, dy) = (
i128::from((b.x - a.x).units()),
i128::from((b.y - a.y).units()),
);
let length = (dx * dx + dy * dy).isqrt();
if length == 0 {
return None;
}
let scale = |d: i128| {
Length::from_units(i64::try_from(d * i128::from(half.units()) / length).unwrap_or(0))
};
Some((scale(dx), scale(dy)))
}
const fn at(x: Length, y: Length) -> Point {
Point { x, y }
}
fn quadrilateral(start: Point, end: Point, (ux, uy): (Length, Length)) -> [PathCommand; 5] {
let (nx, ny) = (-uy, ux);
[
PathCommand::MoveTo(at(start.x + nx, start.y + ny)),
PathCommand::LineTo(at(end.x + nx, end.y + ny)),
PathCommand::LineTo(at(end.x - nx, end.y - ny)),
PathCommand::LineTo(at(start.x - nx, start.y - ny)),
PathCommand::Close,
]
}
#[cfg(test)]
mod tests {
use super::{
CURVE_PIECES, cubic_points, kappa, line_pieces, piece, quad_as_cubic, round_dashes,
round_line,
};
use crate::{PathCommand, Point};
use f_office_units::Length;
fn at(x: i64, y: i64) -> Point {
Point {
x: Length::from_units(x),
y: Length::from_units(y),
}
}
fn turn(commands: &[PathCommand]) -> i128 {
let corners: Vec<Point> = commands
.iter()
.filter_map(|c| match c {
PathCommand::MoveTo(p) | PathCommand::LineTo(p) | PathCommand::CubicTo(_, _, p) => {
Some(*p)
}
_ => None,
})
.collect();
corners
.iter()
.zip(corners.iter().cycle().skip(1))
.map(|(a, b)| {
i128::from(a.x.units()) * i128::from(b.y.units())
- i128::from(b.x.units()) * i128::from(a.y.units())
})
.sum()
}
#[test]
fn a_round_line_is_its_pieces_without_ends_and_a_disc_at_each_point() {
let commands = round_line(
&[at(0, 0), at(1000, 0), at(1000, 600)],
Length::from_units(50),
);
assert_eq!(commands.len(), 2 * 5 + 3 * 6);
assert_eq!(
commands[..5],
[
PathCommand::MoveTo(at(0, 50)),
PathCommand::LineTo(at(1000, 50)),
PathCommand::LineTo(at(1000, -50)),
PathCommand::LineTo(at(0, -50)),
PathCommand::Close,
]
);
assert_eq!(commands[10], PathCommand::MoveTo(at(0, -50)));
let piece_turn = turn(&commands[..5]);
let disc_turn = turn(&commands[10..16]);
assert!(piece_turn != 0 && piece_turn.signum() == disc_turn.signum());
}
#[test]
fn a_curve_ends_at_its_end_in_the_pieces_of_one_count() {
let points = cubic_points([at(0, 0), at(0, 100), at(100, 100), at(100, 0)]);
assert_eq!(points.len(), usize::try_from(CURVE_PIECES).unwrap());
assert_eq!(points.last(), Some(&at(100, 0)));
assert_eq!(points[points.len() / 2 - 1], at(50, 75));
}
#[test]
fn a_straight_curve_stays_on_its_line() {
let points = cubic_points([at(0, 0), at(30, 0), at(60, 0), at(90, 0)]);
assert!(points.iter().all(|p| p.y == Length::ZERO));
assert!(points.windows(2).all(|pair| pair[0].x < pair[1].x));
}
#[test]
fn a_quadratic_curve_takes_controls_two_thirds_of_the_way() {
assert_eq!(
quad_as_cubic(at(0, 0), at(30, 60), at(90, 0)),
[at(0, 0), at(20, 40), at(50, 40), at(90, 0)]
);
}
#[test]
fn a_quadratic_curve_takes_its_controls_to_the_nearest_half_emu_as_its_fill_does() {
let curve = quad_as_cubic(at(0, 0), at(1, 2), at(3, 0));
assert_eq!(curve, [at(0, 0), at(1, 1), at(2, 1), at(3, 0)]);
let [_, first, second, end] = curve;
assert_eq!(
crate::fill_commands(&[
PathCommand::MoveTo(at(0, 0)),
PathCommand::QuadTo(at(1, 2), end)
]),
[
PathCommand::MoveTo(at(0, 0)),
PathCommand::CubicTo(first, second, end)
]
);
}
#[test]
fn the_control_of_a_quarter_circle_lies_at_its_share_of_the_radius() {
assert_eq!(
kappa(Length::from_units(100_000)),
Length::from_units(55_228)
);
}
#[test]
fn a_piece_grows_by_half_at_each_end_and_on_each_side() {
let quad = piece(at(0, 0), at(100, 0), Length::from_units(10)).unwrap();
assert_eq!(
quad,
[
PathCommand::MoveTo(at(-10, 10)),
PathCommand::LineTo(at(110, 10)),
PathCommand::LineTo(at(110, -10)),
PathCommand::LineTo(at(-10, -10)),
PathCommand::Close,
]
);
assert_eq!(piece(at(5, 5), at(5, 5), Length::from_units(10)), None);
}
#[test]
fn a_line_has_one_quadrilateral_for_each_piece_with_length() {
let commands = line_pieces(
&[at(0, 0), at(10, 0), at(10, 0), at(10, 10)],
Length::from_units(1),
);
assert_eq!(commands.len(), 10);
}
fn outlines(commands: &[PathCommand]) -> usize {
commands
.iter()
.filter(|command| matches!(command, PathCommand::MoveTo(_)))
.count()
}
fn lengths(units: &[i64]) -> Vec<Length> {
units.iter().copied().map(Length::from_units).collect()
}
#[test]
fn a_dashed_line_draws_each_whole_dash_as_a_round_line() {
let half = Length::from_units(1);
let dashes = round_dashes(&[at(0, 0), at(100, 0)], half, &lengths(&[2, 6]), 100).unwrap();
assert_eq!(outlines(&dashes), 13 * 3);
assert_eq!(
dashes[..5],
round_line(&[at(0, 0), at(2, 0)], half)[..5],
"the first dash's piece"
);
}
#[test]
fn a_dash_goes_round_a_corner_with_a_round_join() {
let half = Length::from_units(1);
let dashes = round_dashes(
&[at(0, 0), at(10, 0), at(10, 10)],
half,
&lengths(&[15, 100]),
100,
)
.unwrap();
assert_eq!(dashes, round_line(&[at(0, 0), at(10, 0), at(10, 5)], half));
}
#[test]
fn a_dash_of_length_zero_is_a_disc() {
let half = Length::from_units(1);
let dots = round_dashes(&[at(0, 0), at(25, 0)], half, &lengths(&[0, 10]), 100).unwrap();
assert_eq!(outlines(&dots), 3 * 2);
}
#[test]
fn a_pattern_without_length_or_with_too_many_dashes_gives_no_line() {
let half = Length::from_units(1);
let line = [at(0, 0), at(1_000, 0)];
assert_eq!(round_dashes(&line, half, &lengths(&[0, 0]), 100), None);
assert_eq!(round_dashes(&line, half, &lengths(&[]), 100), None);
assert_eq!(round_dashes(&line, half, &lengths(&[4, -1]), 100), None);
assert_eq!(round_dashes(&line, half, &lengths(&[0, 1]), 100), None);
assert!(round_dashes(&line, half, &lengths(&[0, 10]), 101).is_some());
}
#[test]
fn flat_and_square_caps_shape_dashes_and_square_dots() {
use super::{StrokeCap, band, dashes};
let half = Length::from_units(2);
let flat = dashes(
&[at(0, 0), at(25, 0)],
half,
&lengths(&[10, 10]),
StrokeCap::Flat,
100,
)
.unwrap();
assert_eq!(outlines(&flat), 2);
assert_eq!(flat[..5], band(at(0, 0), at(10, 0), half).unwrap());
let sq_dots = dashes(
&[at(0, 0), at(25, 0)],
half,
&lengths(&[0, 10]),
StrokeCap::Square,
100,
)
.unwrap();
assert_eq!(outlines(&sq_dots), 3);
assert_eq!(sq_dots[..5], band(at(-2, 0), at(2, 0), half).unwrap());
let exact = dashes(
&[at(0, 0), at(20, 0)],
half,
&lengths(&[0, 10]),
StrokeCap::Square,
100,
)
.unwrap();
assert_eq!(outlines(&exact), 2);
}
}