Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletions crates/ink/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@

pub mod pick;
pub mod rack;
pub mod ruler;
pub mod shape;
pub mod shapes;
pub mod svg;
Expand Down Expand Up @@ -246,6 +247,37 @@ impl Stroke {
self.dabs.is_empty()
}

/// The stroke with the hand's tremor taken out, for when the pen is lifted (issue #44).
///
/// A pen reports where it is to a fraction of a point, and a hand shakes by about that
/// much. The spline that draws a stroke passes through every reading, so each wobble
/// became a kink, and on a wide highlighter a kink turns the ribbon's edges into a zigzag.
/// Each reading between the ends is drawn towards the average of itself and its
/// neighbours, but never further than a tremor: at most a third of a point, or an eighth of
/// the stroke's width for a wide one. A deliberate corner moves less than that relative to
/// its size, so writing keeps its shape. The first and last readings and every pressure
/// stay exactly as they were.
#[must_use]
pub fn settled(mut self) -> Self {
if self.dabs.len() < 3 {
return self;
}
let limit = (self.width / 8.0).max(0.35);
for _ in 0..2 {
let before = self.dabs.clone();
for (i, dab) in self.dabs.iter_mut().enumerate().skip(1) {
let (Some(prev), Some(next)) = (before.get(i - 1), before.get(i + 1)) else { continue };
let (ax, ay) = ((prev.x + 2.0 * dab.x + next.x) / 4.0, (prev.y + 2.0 * dab.y + next.y) / 4.0);
let (dx, dy) = (ax - dab.x, ay - dab.y);
let len = dx.hypot(dy);
let scale = if len > limit { limit / len } else { 1.0 };
dab.x += dx * scale;
dab.y += dy * scale;
}
}
self
}

/// The box the ink covers, including smoothing and the selected full-width padding.
/// `None` for a stroke with no readings.
pub fn bounds(&self) -> Option<(f32, f32, f32, f32)> {
Expand Down Expand Up @@ -381,6 +413,35 @@ mod tests {
assert_eq!(Tool::Highlighter.floor(), 1.0, "and it is a flat chisel, so pressure does not thin it");
}

#[test]
fn settling_a_stroke_takes_out_tremor_but_keeps_corners_and_ends() {
// Issue #44: a straight line drawn by a shaking hand.
let mut shaky = Stroke::new(Tool::Highlighter, Rgb::BLACK, 12.0);
for i in 0..60 {
let wobble = if i % 2 == 0 { 0.6 } else { -0.6 };
shaky.add(Dab::new(i as f32 * 2.0, 50.0 + wobble, 0.7));
}
let worst = |s: &Stroke| s.dabs.iter().skip(1).take(s.dabs.len() - 2).map(|d| (d.y - 50.0).abs()).fold(0.0_f32, f32::max);
let settled = shaky.clone().settled();
assert!(worst(&settled) < worst(&shaky) / 3.0, "{} then {}", worst(&shaky), worst(&settled));
assert_eq!(settled.dabs.first(), shaky.dabs.first(), "the start stays put");
assert_eq!(settled.dabs.last(), shaky.dabs.last(), "the end stays put");
assert!(settled.dabs.iter().zip(&shaky.dabs).all(|(a, b)| a.pressure == b.pressure), "pressure is untouched");

// A V written with a fine pen: the corner moves no further than a tremor.
let mut vee = Stroke::new(Tool::Pen, Rgb::BLACK, 2.0);
for (x, y) in [(0.0, 0.0), (5.0, 10.0), (10.0, 20.0), (15.0, 10.0), (20.0, 0.0)] {
vee.add(Dab::new(x, y, 0.5));
}
let corner = vee.clone().settled().dabs[2];
assert!((corner.y - 20.0).abs() <= 0.35 * 2.0 + 1e-4, "{corner:?}");
// Too short to have a middle: left alone.
let mut two = Stroke::new(Tool::Pen, Rgb::BLACK, 2.0);
two.add(Dab::new(0.0, 0.0, 0.5));
two.add(Dab::new(9.0, 1.0, 0.5));
assert_eq!(two.clone().settled(), two);
}

#[test]
fn readings_that_say_nothing_new_are_dropped() {
let mut s = Stroke::new(Tool::Pen, Rgb::BLACK, 3.0);
Expand Down
211 changes: 211 additions & 0 deletions crates/ink/src/ruler.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,211 @@
//! Draw > Ruler (issue #293): a straightedge laid on the page.
//!
//! The ruler is something the user holds, not page content: it is never written to a file.
//! A stroke begun just outside one of its long edges is laid along that edge, so a line
//! drawn against it comes out straight, and the ink is ordinary ink after that. All of it is
//! arithmetic in page points, tested here without a window.

/// How long the ruler is, in points (about 20 cm).
pub const LENGTH: f32 = 567.0;
/// How wide it is, in points.
pub const WIDTH: f32 = 46.0;
/// How far outside an edge a pen may land and still be drawn along it, in points.
pub const REACH: f32 = 14.0;
/// The round handle that turns the ruler sits this far in from its right-hand end.
pub const HANDLE_IN: f32 = 18.0;
/// The handle's radius, in points.
pub const HANDLE_R: f32 = 10.0;

/// Which long edge a stroke is drawn along.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Edge {
/// The edge above the middle when the ruler lies flat.
Upper,
/// The edge below it.
Lower,
}

/// Where the ruler lies: its middle, in page points, and how far it is turned, in degrees
/// clockwise on screen (y grows down the page).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Ruler {
pub x: f32,
pub y: f32,
pub angle: f32,
}

impl Ruler {
/// A ruler lying flat with its middle at (`x`, `y`).
pub fn at(x: f32, y: f32) -> Self {
Self { x, y, angle: 0.0 }
}

fn axis(&self) -> (f32, f32) {
let a = self.angle.to_radians();
(a.cos(), a.sin())
}

/// A page point in the ruler's own terms: how far along it from the middle, and how
/// far across (negative towards the upper edge).
pub fn to_local(&self, x: f32, y: f32) -> (f32, f32) {
let (c, s) = self.axis();
let (dx, dy) = (x - self.x, y - self.y);
(dx * c + dy * s, -dx * s + dy * c)
}

/// Back from the ruler's terms to the page.
pub fn to_page(&self, along: f32, across: f32) -> (f32, f32) {
let (c, s) = self.axis();
(self.x + along * c - across * s, self.y + along * s + across * c)
}

/// The ruler's four corners on the page, clockwise from the upper left.
pub fn corners(&self) -> [(f32, f32); 4] {
let (h, w) = (LENGTH / 2.0, WIDTH / 2.0);
[self.to_page(-h, -w), self.to_page(h, -w), self.to_page(h, w), self.to_page(-h, w)]
}

/// Whether the point is on the ruler, where a press holds it rather than drawing.
pub fn contains(&self, x: f32, y: f32) -> bool {
let (along, across) = self.to_local(x, y);
along.abs() <= LENGTH / 2.0 && across.abs() <= WIDTH / 2.0
}

/// The middle of the round handle that turns the ruler.
pub fn handle(&self) -> (f32, f32) {
self.to_page(LENGTH / 2.0 - HANDLE_IN, 0.0)
}

/// Whether the point is on the turning handle.
pub fn on_handle(&self, x: f32, y: f32) -> bool {
let (hx, hy) = self.handle();
(x - hx).hypot(y - hy) <= HANDLE_R + 2.0
}

/// The edge a pen landing here draws along, if it landed close enough outside one.
/// `reach` is in page points (smaller when the page is zoomed in, so it stays the same
/// on screen).
pub fn edge_near(&self, x: f32, y: f32, reach: f32) -> Option<Edge> {
let (along, across) = self.to_local(x, y);
if along.abs() > LENGTH / 2.0 {
return None;
}
let w = WIDTH / 2.0;
if (-w - reach..-w).contains(&across) {
Some(Edge::Upper)
} else if across > w && across <= w + reach {
Some(Edge::Lower)
} else {
None
}
}

/// Where a reading is drawn when the pen runs along `edge`: on the line half the pen's
/// `width` outside the edge, so the ink touches the ruler and does not run under it, and
/// no further along than the ruler is long.
pub fn along(&self, edge: Edge, x: f32, y: f32, width: f32) -> (f32, f32) {
let (along, _) = self.to_local(x, y);
let off = WIDTH / 2.0 + width.max(0.0) / 2.0;
let across = match edge {
Edge::Upper => -off,
Edge::Lower => off,
};
self.to_page(along.clamp(-LENGTH / 2.0, LENGTH / 2.0), across)
}

/// Turns the ruler by `degrees` (clockwise on screen), kept within a half turn either way.
pub fn turn(&mut self, degrees: f32) {
self.angle = normal(self.angle + degrees);
}

/// Turns the ruler about its middle so that its handle points at (`x`, `y`).
pub fn point_at(&mut self, x: f32, y: f32) {
let (dx, dy) = (x - self.x, y - self.y);
if dx.hypot(dy) > 1.0 {
self.angle = normal(dy.atan2(dx).to_degrees());
}
}

/// The angle shown to the user: whole degrees from 0 to 179, as a protractor reads a
/// line (a ruler turned half round lies along the same line).
pub fn shown_degrees(&self) -> u16 {
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
let d = (-self.angle).rem_euclid(180.0).round() as u16;
d % 180
}
}

fn normal(degrees: f32) -> f32 {
let d = degrees.rem_euclid(360.0);
if d > 180.0 { d - 360.0 } else { d }
}

#[cfg(test)]
mod tests {
use super::*;

fn close(a: (f32, f32), b: (f32, f32)) -> bool {
(a.0 - b.0).abs() < 1e-3 && (a.1 - b.1).abs() < 1e-3
}

#[test]
fn page_and_ruler_terms_agree_at_any_angle() {
for angle in [0.0, 30.0, -45.0, 90.0, 179.0] {
let r = Ruler { x: 200.0, y: 300.0, angle };
for (x, y) in [(200.0, 300.0), (10.0, 20.0), (450.0, 280.0)] {
let (a, c) = r.to_local(x, y);
assert!(close(r.to_page(a, c), (x, y)), "angle {angle}");
}
}
}

#[test]
fn a_press_on_the_ruler_holds_it_and_one_just_outside_an_edge_draws_along_it() {
let r = Ruler::at(300.0, 200.0);
assert!(r.contains(300.0, 200.0));
assert!(r.contains(300.0 - LENGTH / 2.0 + 1.0, 200.0 + WIDTH / 2.0 - 1.0));
assert!(!r.contains(300.0, 200.0 - WIDTH / 2.0 - 1.0));
assert_eq!(r.edge_near(300.0, 200.0 - WIDTH / 2.0 - 4.0, REACH), Some(Edge::Upper));
assert_eq!(r.edge_near(300.0, 200.0 + WIDTH / 2.0 + 4.0, REACH), Some(Edge::Lower));
assert_eq!(r.edge_near(300.0, 200.0 - WIDTH / 2.0 - REACH - 1.0, REACH), None, "too far off to mean the ruler");
assert_eq!(r.edge_near(300.0, 200.0, REACH), None, "on the ruler is holding it, not drawing");
assert_eq!(r.edge_near(300.0 + LENGTH, 200.0 - WIDTH / 2.0 - 4.0, REACH), None, "past its end");
assert!(r.on_handle(r.handle().0, r.handle().1));
}

#[test]
fn a_shaky_hand_along_a_turned_ruler_draws_a_straight_line() {
let r = Ruler { x: 100.0, y: 100.0, angle: 30.0 };
let width = 4.0;
let wobbly: Vec<(f32, f32)> =
(0..20).map(|i| r.to_page(-100.0 + i as f32 * 10.0, -WIDTH / 2.0 - 3.0 + if i % 2 == 0 { 2.0 } else { -1.5 })).collect();
let drawn: Vec<(f32, f32)> = wobbly.iter().map(|&(x, y)| r.along(Edge::Upper, x, y, width)).collect();
for &(x, y) in &drawn {
let (_, across) = r.to_local(x, y);
assert!((across + WIDTH / 2.0 + width / 2.0).abs() < 1e-3, "every point is on the one line beside the edge");
}
// And it follows the pen along the ruler.
let first = r.to_local(drawn[0].0, drawn[0].1).0;
let last = r.to_local(drawn[19].0, drawn[19].1).0;
assert!((first + 100.0).abs() < 1e-3 && (last - 90.0).abs() < 1e-3);
// No further than the ruler is long.
let past = r.along(Edge::Lower, r.to_page(LENGTH, 0.0).0, r.to_page(LENGTH, 0.0).1, width);
assert!((r.to_local(past.0, past.1).0 - LENGTH / 2.0).abs() < 1e-3);
}

#[test]
fn turning_shows_the_angle_a_protractor_would() {
let mut r = Ruler::at(0.0, 0.0);
assert_eq!(r.shown_degrees(), 0);
r.turn(-30.0);
assert_eq!(r.shown_degrees(), 30, "turned anticlockwise on screen reads 30");
r.turn(-180.0);
assert_eq!(r.shown_degrees(), 30, "half round lies on the same line");
r.turn(400.0);
assert!(r.angle > -180.0 && r.angle <= 180.0);
r.point_at(0.0, -50.0);
assert_eq!(r.shown_degrees(), 90);
r.point_at(50.0, 0.0);
assert_eq!(r.shown_degrees(), 0);
}
}
42 changes: 37 additions & 5 deletions crates/ink/src/shape.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,18 +78,29 @@ pub fn width_at(stroke: &Stroke, pressure: f32) -> f32 {
(stroke.width * share).max(crate::MIN_WIDTH)
}

/// How many points of the smoothed middle apart the direction of a stroke is read from:
/// one for a fine pen, more for a wide one, so that it covers about a quarter of the width.
pub fn heading_reach(stroke: &Stroke) -> usize {
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
let reach = (stroke.width / 4.0 / STEP).round() as usize;
reach.clamp(1, 12)
}

/// The two edges of the ribbon, left and right of the smoothed middle, point for point
/// with it. A painter that fills triangles wants these; SVG wants them joined up, which is
/// what [`outline`] does. Both come from here, so the file and the screen agree.
pub fn sides(stroke: &Stroke) -> (Vec<(f32, f32)>, Vec<(f32, f32)>) {
let line = centre(stroke);
let mut left: Vec<(f32, f32)> = Vec::with_capacity(line.len());
let mut right: Vec<(f32, f32)> = Vec::with_capacity(line.len());
let reach = heading_reach(stroke);
for (i, d) in line.iter().enumerate() {
// The direction here is the way the line is going, taken from the points either
// side so a corner leans the right way.
let before = line.get(i.saturating_sub(1)).copied().unwrap_or(*d);
let after = line.get(i + 1).copied().unwrap_or(*d);
// side so a corner leans the right way. For a wide nib the points are taken a little
// further off, about a quarter of its width: the edges are that far from the middle,
// so a wobble the eye cannot see in the middle would swing them into a zigzag (#44).
let before = line.get(i.saturating_sub(reach)).copied().unwrap_or(*d);
let after = line.get((i + reach).min(line.len().saturating_sub(1))).copied().unwrap_or(*d);
let (dx, dy) = (after.x - before.x, after.y - before.y);
let len = (dx * dx + dy * dy).sqrt();
// Two readings in the same place say nothing about direction; the ends are round
Expand All @@ -115,14 +126,16 @@ pub fn outline(stroke: &Stroke) -> Vec<(f32, f32)> {
let mut out = left;
// Where the readings give no direction, `sides` assumed the pen was going across the
// page, left to right; each end assumes the same, so a tap still closes into a dot.
// The ends face the way the ribbon's edges arrive there, read over the same reach.
let reach = heading_reach(stroke).min(line.len() - 1);
out.extend(half_circle(
last,
width_at(stroke, last.pressure) / 2.0,
line.get(line.len().saturating_sub(2)).copied().unwrap_or(first),
line.get(line.len().saturating_sub(1 + reach)).copied().unwrap_or(first),
(1.0, 0.0),
));
out.extend(right.into_iter().rev());
out.extend(half_circle(first, width_at(stroke, first.pressure) / 2.0, line.get(1).copied().unwrap_or(last), (-1.0, 0.0)));
out.extend(half_circle(first, width_at(stroke, first.pressure) / 2.0, line.get(reach).copied().unwrap_or(last), (-1.0, 0.0)));
out
}

Expand Down Expand Up @@ -239,6 +252,25 @@ mod tests {
s
}

#[test]
fn a_wide_highlighter_edge_does_not_fold_back_on_a_shaky_line() {
// Issue #44: a highlighter drawn left to right by a hand that shakes a little. Each
// edge must keep going the same way; an edge that steps backwards is a fold, which a
// see-through highlighter paints twice, and that is the zigzag users saw.
let mut s = Stroke::new(Tool::Highlighter, Rgb::BLACK, 14.0);
for i in 0..40 {
let wobble = [0.0, 0.5, -0.3, 0.4, -0.5][i % 5];
s.dabs.push(Dab::new(i as f32 * 1.5, 40.0 + wobble, 1.0));
}
let folds = |s: &Stroke| {
let (left, right) = sides(s);
[left, right].iter().map(|edge| edge.windows(2).filter(|w| w[1].0 < w[0].0 - 0.05).count()).sum::<usize>()
};
assert!(folds(&s) > 0, "the shaky readings as they came do fold");
// As the pen lays it down: settled when lifted, then given its width.
assert_eq!(folds(&s.clone().settled()), 0, "a settled stroke's edges do not fold");
}

#[test]
fn a_smoothed_line_passes_through_every_reading() {
let s = drawn(Tool::Pen, &[(0.0, 0.0, 1.0), (20.0, 14.0, 1.0), (40.0, 0.0, 1.0), (60.0, 14.0, 1.0)]);
Expand Down
Loading
Loading