M13.5: stroke taper/wave/multi-dashes, radial gradient highlight, variable-width mask feather, adaptive motion-blur samples
Shapes (SHP-2): Stroke Taper (pixels/percent start/end length, width, ease) and Wave (amount, pixels/cycles, wavelength, phase) rendered as a variable-width outline; Dash 2/Gap 2/Dash 3/Gap 3 (shape.dashes.add/remove, timeline +/- buttons); radial gradient Highlight Length/Angle as a focal gradient. Masks (MSK-1): mask feather points on the Mask Path (mask.featherPoint.*, Mask Feather tool add/drag), per-point signed radius and tension, rendered from the signed distance to the path; carried through vertex edits. Motion blur (LYR-10): Adaptive Sample Limit comp setting; 2D layers take one sample per pixel of shutter travel between Samples Per Frame and the limit. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
c406b71cba
commit
bbaee1fa0f
@@ -0,0 +1,268 @@
|
||||
//! Variable-width mask feather (After Effects' Mask Feather tool).
|
||||
//!
|
||||
//! Feather points sit on the mask path with a signed radius (outer > 0, inner < 0) and a
|
||||
//! tension. Between points the outer and inner radii are interpolated along the path's arc
|
||||
//! length (smoothly at tension 0, linearly at tension 1; closed paths wrap around). Every pixel
|
||||
//! near the path takes the feather width at its nearest path position: outside the path the
|
||||
//! opacity falls from 1 at the edge to 0 at the outer radius, inside it rises from 0 at the
|
||||
//! edge to 1 at the inner radius. Where no radius applies the edge stays hard (anti-aliased).
|
||||
|
||||
use effectcraft_geom::{Mat3, vec2};
|
||||
use effectcraft_keyframe::{FeatherPoint, ShapePath};
|
||||
use effectcraft_raster::Mask;
|
||||
|
||||
use crate::{FillRule, fill_coverage, to_kurbo};
|
||||
|
||||
/// A flattened path in buffer space: points, their arc lengths, and per segment the
|
||||
/// `(parameter, arc length)` table used to place feather points.
|
||||
struct Flat {
|
||||
pts: Vec<[f64; 2]>,
|
||||
s: Vec<f64>,
|
||||
seg_tables: Vec<Vec<(f64, f64)>>,
|
||||
len: f64,
|
||||
}
|
||||
|
||||
fn cubic(p0: [f64; 2], p1: [f64; 2], p2: [f64; 2], p3: [f64; 2], t: f64) -> [f64; 2] {
|
||||
let u = 1.0 - t;
|
||||
let (a, b, c, d) = (u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t);
|
||||
[a * p0[0] + b * p1[0] + c * p2[0] + d * p3[0], a * p0[1] + b * p1[1] + c * p2[1] + d * p3[1]]
|
||||
}
|
||||
|
||||
fn flatten(sp: &ShapePath, m: &Mat3) -> Flat {
|
||||
let n = sp.vertices.len();
|
||||
let tr = |p: [f64; 2]| {
|
||||
let r = m.apply(vec2(p[0], p[1]));
|
||||
[r.x, r.y]
|
||||
};
|
||||
let mut pts: Vec<[f64; 2]> = Vec::new();
|
||||
let mut s: Vec<f64> = Vec::new();
|
||||
let mut seg_tables = Vec::new();
|
||||
let segs = sp.segment_count();
|
||||
let mut acc = 0.0;
|
||||
for i in 0..segs {
|
||||
let j = (i + 1) % n;
|
||||
let v0 = sp.vertices[i];
|
||||
let v1 = sp.vertices[j];
|
||||
let o = sp.out_tangents.get(i).copied().unwrap_or([0.0; 2]);
|
||||
let it = sp.in_tangents.get(j).copied().unwrap_or([0.0; 2]);
|
||||
let (p0, p1, p2, p3) = (tr(v0), tr([v0[0] + o[0], v0[1] + o[1]]), tr([v1[0] + it[0], v1[1] + it[1]]), tr(v1));
|
||||
let est = ((p1[0] - p0[0]).hypot(p1[1] - p0[1]) + (p2[0] - p1[0]).hypot(p2[1] - p1[1]) + (p3[0] - p2[0]).hypot(p3[1] - p2[1])).max(1.0);
|
||||
let k = ((est / 1.5).ceil() as usize).clamp(4, 1024);
|
||||
let mut table = Vec::with_capacity(k + 1);
|
||||
if pts.is_empty() {
|
||||
pts.push(p0);
|
||||
s.push(0.0);
|
||||
}
|
||||
table.push((0.0, acc));
|
||||
let mut prev = p0;
|
||||
for q in 1..=k {
|
||||
let t = q as f64 / k as f64;
|
||||
let p = cubic(p0, p1, p2, p3, t);
|
||||
acc += (p[0] - prev[0]).hypot(p[1] - prev[1]);
|
||||
pts.push(p);
|
||||
s.push(acc);
|
||||
table.push((t, acc));
|
||||
prev = p;
|
||||
}
|
||||
seg_tables.push(table);
|
||||
}
|
||||
Flat { pts, s, seg_tables, len: acc }
|
||||
}
|
||||
|
||||
impl Flat {
|
||||
/// Arc length of a feather point.
|
||||
fn arc_of(&self, f: &FeatherPoint) -> Option<f64> {
|
||||
let table = self.seg_tables.get(f.segment)?;
|
||||
let t = f.t.clamp(0.0, 1.0);
|
||||
let i = table.partition_point(|e| e.0 <= t).clamp(1, table.len() - 1);
|
||||
let (a, b) = (table[i - 1], table[i]);
|
||||
let u = if b.0 > a.0 { (t - a.0) / (b.0 - a.0) } else { 0.0 };
|
||||
Some(a.1 + (b.1 - a.1) * u)
|
||||
}
|
||||
}
|
||||
|
||||
/// Outer / inner feather radius (buffer pixels) along the path, from the feather points.
|
||||
struct Profile {
|
||||
/// (arc length, outer radius, inner radius, tension), sorted by arc length.
|
||||
pts: Vec<(f64, f64, f64, f64)>,
|
||||
len: f64,
|
||||
closed: bool,
|
||||
}
|
||||
|
||||
impl Profile {
|
||||
fn at(&self, u: f64) -> (f64, f64) {
|
||||
let p = &self.pts;
|
||||
if p.is_empty() {
|
||||
return (0.0, 0.0);
|
||||
}
|
||||
if p.len() == 1 {
|
||||
return (p[0].1, p[0].2);
|
||||
}
|
||||
let blend = |a: &(f64, f64, f64, f64), b: &(f64, f64, f64, f64), x: f64| {
|
||||
let x = x.clamp(0.0, 1.0);
|
||||
let smooth = x * x * (3.0 - 2.0 * x);
|
||||
let tension = ((a.3 + b.3) * 0.5).clamp(0.0, 1.0);
|
||||
let w = smooth + (x - smooth) * tension;
|
||||
(a.1 + (b.1 - a.1) * w, a.2 + (b.2 - a.2) * w)
|
||||
};
|
||||
let first = p[0];
|
||||
let last = p[p.len() - 1];
|
||||
if u < first.0 || u >= last.0 {
|
||||
if !self.closed {
|
||||
return if u < first.0 { (first.1, first.2) } else { (last.1, last.2) };
|
||||
}
|
||||
// Wrap from the last point to the first through the path's start.
|
||||
let span = (self.len - last.0) + first.0;
|
||||
let x = if u >= last.0 { u - last.0 } else { u + self.len - last.0 };
|
||||
return blend(&last, &first, if span > 1e-9 { x / span } else { 0.0 });
|
||||
}
|
||||
let i = p.partition_point(|e| e.0 <= u).clamp(1, p.len() - 1);
|
||||
let (a, b) = (&p[i - 1], &p[i]);
|
||||
let span = b.0 - a.0;
|
||||
blend(a, b, if span > 1e-9 { (u - a.0) / span } else { 0.0 })
|
||||
}
|
||||
}
|
||||
|
||||
/// Coverage of a mask path with feather points, transformed by `m` (translate + uniform scale)
|
||||
/// into a `w × h` mask. `expansion` (layer pixels) grows (>0) or shrinks the mask first;
|
||||
/// `linear` selects the Linear feather falloff instead of Smooth.
|
||||
pub fn variable_feather_coverage(sp: &ShapePath, m: &Mat3, w: u32, h: u32, expansion: f64, linear: bool) -> Mask {
|
||||
let scale = m.mean_scale();
|
||||
let path = to_kurbo(sp);
|
||||
let hard = fill_coverage(std::slice::from_ref(&path), m, w, h, FillRule::NonZero);
|
||||
let flat = flatten(sp, m);
|
||||
if flat.pts.len() < 2 {
|
||||
return hard;
|
||||
}
|
||||
let mut pts: Vec<(f64, f64, f64, f64)> = sp
|
||||
.feather
|
||||
.iter()
|
||||
.filter_map(|f| {
|
||||
let u = flat.arc_of(f)?;
|
||||
let r = f.radius * scale;
|
||||
Some((u, r.max(0.0), (-r).max(0.0), f.tension))
|
||||
})
|
||||
.collect();
|
||||
pts.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
let prof = Profile { pts, len: flat.len, closed: sp.closed };
|
||||
let rmax = prof.pts.iter().map(|p| p.1.max(p.2)).fold(0.0, f64::max);
|
||||
let exp = expansion * scale;
|
||||
let reach = rmax + exp.abs() + 2.0;
|
||||
let (wu, hu) = (w as usize, h as usize);
|
||||
let mut dist = vec![f32::INFINITY; wu * hu];
|
||||
let mut arc = vec![0.0f32; wu * hu];
|
||||
for k in 0..flat.pts.len() - 1 {
|
||||
let (a, b) = (flat.pts[k], flat.pts[k + 1]);
|
||||
let (sa, sb) = (flat.s[k], flat.s[k + 1]);
|
||||
let (dx, dy) = (b[0] - a[0], b[1] - a[1]);
|
||||
let l2 = dx * dx + dy * dy;
|
||||
let x0 = ((a[0].min(b[0]) - reach).floor().max(0.0)) as usize;
|
||||
let x1 = ((a[0].max(b[0]) + reach).ceil().min(w as f64 - 1.0)).max(-1.0) as isize;
|
||||
let y0 = ((a[1].min(b[1]) - reach).floor().max(0.0)) as usize;
|
||||
let y1 = ((a[1].max(b[1]) + reach).ceil().min(h as f64 - 1.0)).max(-1.0) as isize;
|
||||
if x1 < 0 || y1 < 0 {
|
||||
continue;
|
||||
}
|
||||
for y in y0..=y1 as usize {
|
||||
for x in x0..=x1 as usize {
|
||||
let (px, py) = (x as f64 + 0.5, y as f64 + 0.5);
|
||||
let t = if l2 > 0.0 { (((px - a[0]) * dx + (py - a[1]) * dy) / l2).clamp(0.0, 1.0) } else { 0.0 };
|
||||
let (qx, qy) = (a[0] + dx * t - px, a[1] + dy * t - py);
|
||||
let d = (qx * qx + qy * qy).sqrt() as f32;
|
||||
let i = y * wu + x;
|
||||
if d < dist[i] {
|
||||
dist[i] = d;
|
||||
arc[i] = (sa + (sb - sa) * t) as f32;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let ramp = |x: f64| {
|
||||
let x = x.clamp(0.0, 1.0);
|
||||
if linear { x } else { x * x * (3.0 - 2.0 * x) }
|
||||
};
|
||||
let mut out = Mask::new(w, h, 0.0);
|
||||
for (i, o) in out.data.iter_mut().enumerate() {
|
||||
let inside = hard.data[i] >= 0.5;
|
||||
let d = dist[i] as f64;
|
||||
if !d.is_finite() || d > reach {
|
||||
// Farther from the path than any feather or expansion reaches.
|
||||
*o = if inside { 1.0 } else { 0.0 };
|
||||
continue;
|
||||
}
|
||||
// Signed distance to the expanded edge (negative inside).
|
||||
let sd = if inside { -d } else { d } - exp;
|
||||
let (ro, ri) = prof.at(arc[i] as f64);
|
||||
let a = if sd > 0.0 {
|
||||
if ro > 0.5 { ramp(1.0 - sd / ro) } else { (0.5 - sd).clamp(0.0, 1.0) }
|
||||
} else if ri > 0.5 {
|
||||
ramp(-sd / ri)
|
||||
} else {
|
||||
(0.5 - sd).clamp(0.0, 1.0)
|
||||
};
|
||||
*o = a as f32;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn square() -> ShapePath {
|
||||
// 100×100 square from (50,50) to (150,150), clockwise: top, right, bottom, left segments.
|
||||
ShapePath::rect([100.0, 100.0], 100.0, 100.0)
|
||||
}
|
||||
|
||||
fn at(m: &Mask, x: u32, y: u32) -> f32 {
|
||||
m.data[(y * m.width + x) as usize]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_points_is_the_hard_mask() {
|
||||
let m = variable_feather_coverage(&square(), &Mat3::IDENTITY, 200, 200, 0.0, false);
|
||||
assert!(at(&m, 100, 100) > 0.99 && at(&m, 40, 100) < 0.01);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_outer_point_feathers_all_around() {
|
||||
let mut sp = square();
|
||||
sp.feather = vec![FeatherPoint { segment: 0, t: 0.5, radius: 20.0, tension: 0.0 }];
|
||||
let m = variable_feather_coverage(&sp, &Mat3::IDENTITY, 200, 200, 0.0, true);
|
||||
// Above the top edge: 1 at the edge falling linearly to 0 at 20 px.
|
||||
assert!((at(&m, 100, 39) - 0.475).abs() < 0.06, "{}", at(&m, 100, 39));
|
||||
assert!(at(&m, 100, 28) < 0.01);
|
||||
assert!(at(&m, 100, 60) > 0.99, "inside stays opaque");
|
||||
// One point applies to the whole closed path.
|
||||
assert!((at(&m, 161, 100) - 0.475).abs() < 0.06, "{}", at(&m, 161, 100));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outer_and_inner_points_vary_along_the_path() {
|
||||
let mut sp = square();
|
||||
// Outer 20 px in the middle of the top edge, inner 20 px in the middle of the bottom edge.
|
||||
sp.feather = vec![FeatherPoint { segment: 0, t: 0.5, radius: 20.0, tension: 1.0 }, FeatherPoint { segment: 2, t: 0.5, radius: -20.0, tension: 1.0 }];
|
||||
let m = variable_feather_coverage(&sp, &Mat3::IDENTITY, 200, 200, 0.0, true);
|
||||
// Top: soft outside, hard inside.
|
||||
assert!(at(&m, 100, 45) > 0.6 && at(&m, 100, 45) < 0.8, "{}", at(&m, 100, 45));
|
||||
assert!(at(&m, 100, 52) > 0.99);
|
||||
// Bottom: hard outside, soft inside (0 at the edge, 1 at 20 px in).
|
||||
assert!(at(&m, 100, 152) < 0.01);
|
||||
assert!((at(&m, 100, 140) - 0.475).abs() < 0.06, "{}", at(&m, 100, 140));
|
||||
// Half way round (middle of the right edge): both radii are half way, 10 px.
|
||||
assert!((at(&m, 154, 100) - 0.55).abs() < 0.05, "{}", at(&m, 154, 100));
|
||||
assert!((at(&m, 145, 100) - 0.45).abs() < 0.05, "{}", at(&m, 145, 100));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scale_and_expansion() {
|
||||
let mut sp = square();
|
||||
sp.feather = vec![FeatherPoint { segment: 0, t: 0.5, radius: 10.0, tension: 0.0 }];
|
||||
// Half resolution: the 10 px feather is 5 buffer pixels.
|
||||
let m = variable_feather_coverage(&sp, &Mat3::scale(vec2(0.5, 0.5)), 100, 100, 0.0, true);
|
||||
assert!(at(&m, 50, 22) > 0.4 && at(&m, 50, 22) < 0.6, "{}", at(&m, 50, 22));
|
||||
let e = variable_feather_coverage(&sp, &Mat3::IDENTITY, 200, 200, 10.0, true);
|
||||
assert!(at(&e, 100, 41) > 0.99, "expanded by 10 px: {}", at(&e, 100, 41));
|
||||
assert!((at(&e, 100, 34) - 0.45).abs() < 0.05, "{}", at(&e, 100, 34));
|
||||
}
|
||||
}
|
||||
@@ -191,7 +191,7 @@ fn from_cubics(cs: &[[P; 4]], closed: bool) -> ShapePath {
|
||||
v[j] = c[3];
|
||||
}
|
||||
}
|
||||
ShapePath { vertices: v, in_tangents: ins, out_tangents: outs, closed }
|
||||
ShapePath { vertices: v, in_tangents: ins, out_tangents: outs, closed, feather: Vec::new() }
|
||||
}
|
||||
|
||||
/// Exactly the same outline with `total` vertices (≥ the current count), the extra vertices
|
||||
@@ -272,7 +272,13 @@ fn rotate(p: &ShapePath, k: usize) -> ShapePath {
|
||||
return p.clone();
|
||||
}
|
||||
let r = |v: &Vec<P>| (0..n).map(|i| v[(i + k) % n]).collect();
|
||||
ShapePath { vertices: r(&p.vertices), in_tangents: r(&p.in_tangents), out_tangents: r(&p.out_tangents), closed: p.closed }
|
||||
ShapePath {
|
||||
vertices: r(&p.vertices),
|
||||
in_tangents: r(&p.in_tangents),
|
||||
out_tangents: r(&p.out_tangents),
|
||||
closed: p.closed,
|
||||
feather: p.feather.iter().map(|f| effectcraft_keyframe::FeatherPoint { segment: (f.segment + n - k % n) % n, ..*f }).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The same path traversed the other way (closed paths keep vertex 0 first).
|
||||
@@ -287,6 +293,8 @@ pub fn reversed(p: &ShapePath) -> ShapePath {
|
||||
in_tangents: idx.iter().map(|i| p.out_tangents[*i]).collect(),
|
||||
out_tangents: idx.iter().map(|i| p.in_tangents[*i]).collect(),
|
||||
closed: p.closed,
|
||||
// Feather points sit on segments that reversal renumbers: they are not carried.
|
||||
feather: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -447,6 +455,7 @@ pub fn interpolate(a: &ShapePath, b: &ShapePath, u: f64, o: &InterpOpts) -> Shap
|
||||
in_tangents: lin(&a.in_tangents, &b.in_tangents),
|
||||
out_tangents: lin(&a.out_tangents, &b.out_tangents),
|
||||
closed: a.closed,
|
||||
feather: a.feather.clone(),
|
||||
};
|
||||
}
|
||||
// Procrustes: b ≈ s R (a − ca) + cb.
|
||||
@@ -468,7 +477,7 @@ pub fn interpolate(a: &ShapePath, b: &ShapePath, u: f64, o: &InterpOpts) -> Shap
|
||||
let (th_u, s_u) = (theta * u, s.max(1e-9).powf(u));
|
||||
let c_u = lerp(ca, cb, u);
|
||||
let w = (o.bending_resistance / 100.0).clamp(0.0, 1.0);
|
||||
let mut out = ShapePath { vertices: vec![], in_tangents: vec![], out_tangents: vec![], closed: a.closed };
|
||||
let mut out = ShapePath { vertices: vec![], in_tangents: vec![], out_tangents: vec![], closed: a.closed, feather: a.feather.clone() };
|
||||
for i in 0..n {
|
||||
// Rigid path: a's vertex carried by the interpolated similarity, plus the residual
|
||||
// (b − fully transformed a) blended in linearly.
|
||||
|
||||
+24
-2
@@ -6,10 +6,12 @@
|
||||
//! (for Merge Paths) in [`boolean`] and curve offsetting in [`offset`].
|
||||
|
||||
pub mod boolean;
|
||||
pub mod feather;
|
||||
mod fit;
|
||||
pub mod interp;
|
||||
pub mod offset;
|
||||
pub mod ops;
|
||||
pub mod varstroke;
|
||||
|
||||
use effectcraft_geom::Mat3;
|
||||
use effectcraft_keyframe::ShapePath;
|
||||
@@ -73,7 +75,13 @@ pub fn from_kurbo(path: &BezPath) -> Vec<ShapePath> {
|
||||
match *el {
|
||||
PathEl::MoveTo(p) => {
|
||||
flush(&mut cur, &mut out);
|
||||
cur = Some(ShapePath { vertices: vec![[p.x, p.y]], in_tangents: vec![[0.0; 2]], out_tangents: vec![[0.0; 2]], closed: false });
|
||||
cur = Some(ShapePath {
|
||||
vertices: vec![[p.x, p.y]],
|
||||
in_tangents: vec![[0.0; 2]],
|
||||
out_tangents: vec![[0.0; 2]],
|
||||
closed: false,
|
||||
feather: Vec::new(),
|
||||
});
|
||||
last = p;
|
||||
}
|
||||
PathEl::LineTo(p) => {
|
||||
@@ -251,11 +259,22 @@ pub struct StrokeStyle {
|
||||
pub miter: f64,
|
||||
/// Dash pattern (dash, gap, …) and offset.
|
||||
pub dash: Option<(Vec<f64>, f64)>,
|
||||
/// Stroke Taper (variable width at the ends).
|
||||
pub taper: Option<varstroke::Taper>,
|
||||
/// Stroke Wave (periodic width).
|
||||
pub wave: Option<varstroke::Wave>,
|
||||
}
|
||||
|
||||
impl StrokeStyle {
|
||||
/// Whether the width varies along the path (Taper or Wave active).
|
||||
pub fn is_variable(&self) -> bool {
|
||||
self.taper.as_ref().is_some_and(|t| t.is_active()) || self.wave.as_ref().is_some_and(|w| w.is_active())
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for StrokeStyle {
|
||||
fn default() -> Self {
|
||||
StrokeStyle { width: 1.0, cap: Cap::Butt, join: Join::Miter, miter: 4.0, dash: None }
|
||||
StrokeStyle { width: 1.0, cap: Cap::Butt, join: Join::Miter, miter: 4.0, dash: None, taper: None, wave: None }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -264,6 +283,9 @@ pub fn stroke_outline(paths: &[BezPath], style: &StrokeStyle, res_scale: f64) ->
|
||||
if style.width <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
if style.is_variable() {
|
||||
return varstroke::outline(paths, style, res_scale);
|
||||
}
|
||||
let mut all = BezPath::new();
|
||||
for p in paths {
|
||||
all.extend(p.elements().iter().copied());
|
||||
|
||||
@@ -0,0 +1,399 @@
|
||||
//! Variable-width strokes: the shape Stroke's **Taper** (start/end length, width and ease) and
|
||||
//! **Wave** (amount, wavelength or cycles, phase), with dashes cut along the same arc length.
|
||||
//!
|
||||
//! The stroke is built as a union of positively-wound primitives: one trapezoid per flattened
|
||||
//! segment (its two ends at the local widths), a disc at every bend (round joins) and the caps.
|
||||
//! Filled with the non-zero rule the union is exact, whatever the width profile does.
|
||||
|
||||
use kurbo::{BezPath, PathEl, Point, Shape, Vec2};
|
||||
|
||||
use crate::{Cap, StrokeStyle};
|
||||
|
||||
/// Stroke Taper. Lengths are pixels, or fractions of each path's length when `percent`; widths and
|
||||
/// eases are fractions (0–1). A width of 0 tapers to a point.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Taper {
|
||||
pub percent: bool,
|
||||
pub start_len: f64,
|
||||
pub end_len: f64,
|
||||
pub start_width: f64,
|
||||
pub end_width: f64,
|
||||
pub start_ease: f64,
|
||||
pub end_ease: f64,
|
||||
}
|
||||
|
||||
impl Taper {
|
||||
pub fn is_active(&self) -> bool {
|
||||
(self.start_len > 0.0 && self.start_width < 1.0) || (self.end_len > 0.0 && self.end_width < 1.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Stroke Wave: the width oscillates between `1 - amount` and 1 of the stroke width.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Wave {
|
||||
/// 0–1.
|
||||
pub amount: f64,
|
||||
/// Units: `Some(cycles)` = cycles along each path, else `wavelength` in pixels.
|
||||
pub cycles: Option<f64>,
|
||||
pub wavelength: f64,
|
||||
/// Degrees.
|
||||
pub phase: f64,
|
||||
}
|
||||
|
||||
impl Wave {
|
||||
pub fn is_active(&self) -> bool {
|
||||
self.amount > 0.0 && self.cycles.map_or(self.wavelength > 0.0, |c| c > 0.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Ease profile from the tip (`u = 0`) to full width (`u = 1`): linear at ease 0, a quarter
|
||||
/// circle (bulging outwards) at ease 1.
|
||||
fn ease(u: f64, e: f64) -> f64 {
|
||||
let u = u.clamp(0.0, 1.0);
|
||||
let round = (1.0 - (1.0 - u) * (1.0 - u)).max(0.0).sqrt();
|
||||
u + (round - u) * e.clamp(0.0, 1.0)
|
||||
}
|
||||
|
||||
/// Width factor (0–1) at arc length `s` of a path `len` long.
|
||||
pub fn width_factor(taper: Option<&Taper>, wave: Option<&Wave>, s: f64, len: f64) -> f64 {
|
||||
let mut k = 1.0;
|
||||
if let Some(t) = taper.filter(|t| t.is_active()) {
|
||||
let (mut ls, mut le) = if t.percent { (t.start_len * len, t.end_len * len) } else { (t.start_len, t.end_len) };
|
||||
ls = ls.max(0.0);
|
||||
le = le.max(0.0);
|
||||
// Overlapping tapers share the path in proportion.
|
||||
if ls + le > len && ls + le > 0.0 {
|
||||
let f = len / (ls + le);
|
||||
ls *= f;
|
||||
le *= f;
|
||||
}
|
||||
let sw = t.start_width.clamp(0.0, 1.0);
|
||||
let ew = t.end_width.clamp(0.0, 1.0);
|
||||
if ls > 0.0 && s < ls {
|
||||
k = f64::min(k, sw + (1.0 - sw) * ease(s / ls, t.start_ease));
|
||||
}
|
||||
if le > 0.0 && s > len - le {
|
||||
k = f64::min(k, ew + (1.0 - ew) * ease((len - s) / le, t.end_ease));
|
||||
}
|
||||
}
|
||||
if let Some(w) = wave.filter(|w| w.is_active()) {
|
||||
let lambda = match w.cycles {
|
||||
Some(c) => len / c,
|
||||
None => w.wavelength,
|
||||
};
|
||||
if lambda > 0.0 {
|
||||
let ph = std::f64::consts::TAU * s / lambda + w.phase.to_radians();
|
||||
k *= 1.0 - w.amount.clamp(0.0, 1.0) * (0.5 - 0.5 * ph.cos());
|
||||
}
|
||||
}
|
||||
k
|
||||
}
|
||||
|
||||
/// A flattened subpath: points and their cumulative arc lengths.
|
||||
struct Poly {
|
||||
pts: Vec<Point>,
|
||||
s: Vec<f64>,
|
||||
closed: bool,
|
||||
}
|
||||
|
||||
impl Poly {
|
||||
fn len(&self) -> f64 {
|
||||
self.s.last().copied().unwrap_or(0.0)
|
||||
}
|
||||
/// Point at arc length `t` (clamped), and the index of the segment it lies on.
|
||||
fn at(&self, t: f64) -> (Point, usize) {
|
||||
let i = self.s.partition_point(|&x| x <= t).clamp(1, self.pts.len() - 1);
|
||||
let (a, b) = (self.s[i - 1], self.s[i]);
|
||||
let u = if b > a { ((t - a) / (b - a)).clamp(0.0, 1.0) } else { 0.0 };
|
||||
(self.pts[i - 1].lerp(self.pts[i], u), i)
|
||||
}
|
||||
}
|
||||
|
||||
/// Flatten each subpath, then subdivide so no segment is longer than `step`.
|
||||
fn flatten(path: &BezPath, tol: f64, step: f64) -> Vec<Poly> {
|
||||
let mut out: Vec<Poly> = Vec::new();
|
||||
let mut cur: Vec<Point> = Vec::new();
|
||||
let mut closed = false;
|
||||
let flush = |cur: &mut Vec<Point>, closed: bool, out: &mut Vec<Poly>| {
|
||||
let mut pts: Vec<Point> = Vec::with_capacity(cur.len());
|
||||
for &p in cur.iter() {
|
||||
if pts.last().is_none_or(|q: &Point| q.distance(p) > 1e-9) {
|
||||
pts.push(p);
|
||||
}
|
||||
}
|
||||
if closed && pts.len() > 2 && pts[0].distance(pts[pts.len() - 1]) > 1e-9 {
|
||||
pts.push(pts[0]);
|
||||
}
|
||||
cur.clear();
|
||||
if pts.len() < 2 {
|
||||
return;
|
||||
}
|
||||
// Subdivide.
|
||||
let mut fine = vec![pts[0]];
|
||||
for w in pts.windows(2) {
|
||||
let d = w[0].distance(w[1]);
|
||||
let n = (d / step).ceil().max(1.0) as usize;
|
||||
for k in 1..=n {
|
||||
fine.push(w[0].lerp(w[1], k as f64 / n as f64));
|
||||
}
|
||||
}
|
||||
let mut s = Vec::with_capacity(fine.len());
|
||||
let mut acc = 0.0;
|
||||
s.push(0.0);
|
||||
for w in fine.windows(2) {
|
||||
acc += w[0].distance(w[1]);
|
||||
s.push(acc);
|
||||
}
|
||||
out.push(Poly { pts: fine, s, closed });
|
||||
};
|
||||
kurbo::flatten(path.elements().iter().copied(), tol, |el| match el {
|
||||
PathEl::MoveTo(p) => {
|
||||
flush(&mut cur, closed, &mut out);
|
||||
closed = false;
|
||||
cur.push(p);
|
||||
}
|
||||
PathEl::LineTo(p) => cur.push(p),
|
||||
PathEl::ClosePath => {
|
||||
closed = true;
|
||||
flush(&mut cur, closed, &mut out);
|
||||
closed = false;
|
||||
}
|
||||
_ => {}
|
||||
});
|
||||
flush(&mut cur, closed, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// Arc-length intervals that are "on" for a dash pattern on a path `len` long.
|
||||
pub fn dash_intervals(pattern: &[f64], offset: f64, len: f64) -> Vec<(f64, f64)> {
|
||||
let pat: Vec<f64> = pattern.iter().map(|v| v.max(0.0)).collect();
|
||||
let pat = if pat.len() % 2 == 1 { [pat.clone(), pat].concat() } else { pat };
|
||||
let period: f64 = pat.iter().sum();
|
||||
if pat.len() < 2 || period <= 1e-9 || len <= 0.0 {
|
||||
return vec![(0.0, len)];
|
||||
}
|
||||
// Pattern position at s = 0.
|
||||
let mut pos = offset.rem_euclid(period);
|
||||
let mut idx = 0;
|
||||
while pos >= pat[idx] {
|
||||
pos -= pat[idx];
|
||||
idx = (idx + 1) % pat.len();
|
||||
}
|
||||
let mut s = 0.0;
|
||||
let mut out = Vec::new();
|
||||
let mut guard = 0usize;
|
||||
while s < len && guard < 1_000_000 {
|
||||
guard += 1;
|
||||
let seg = pat[idx] - pos;
|
||||
let e = (s + seg).min(len);
|
||||
if idx % 2 == 0 && e >= s {
|
||||
out.push((s, e));
|
||||
}
|
||||
s += seg;
|
||||
pos = 0.0;
|
||||
idx = (idx + 1) % pat.len();
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Append `p` to `out`, wound positively.
|
||||
fn push_pos(out: &mut BezPath, p: BezPath) {
|
||||
let p = if p.area() < 0.0 { p.reverse_subpaths() } else { p };
|
||||
out.extend(p.elements().iter().copied());
|
||||
}
|
||||
|
||||
fn quad(out: &mut BezPath, pts: [Point; 4]) {
|
||||
let mut p = BezPath::new();
|
||||
p.move_to(pts[0]);
|
||||
p.line_to(pts[1]);
|
||||
p.line_to(pts[2]);
|
||||
p.line_to(pts[3]);
|
||||
p.close_path();
|
||||
if p.area().abs() > 1e-12 {
|
||||
push_pos(out, p);
|
||||
}
|
||||
}
|
||||
|
||||
fn disc(out: &mut BezPath, c: Point, r: f64) {
|
||||
if r > 1e-6 {
|
||||
push_pos(out, kurbo::Circle::new(c, r).to_path(0.05));
|
||||
}
|
||||
}
|
||||
|
||||
/// Outline of a tapered / waved stroke (local space; `res_scale` = device/local scale).
|
||||
pub fn outline(paths: &[BezPath], style: &StrokeStyle, res_scale: f64) -> Option<BezPath> {
|
||||
if style.width <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
let rs = res_scale.max(0.01);
|
||||
let mut out = BezPath::new();
|
||||
let half = style.width / 2.0;
|
||||
for path in paths {
|
||||
// Fine enough for the width profile: ½ device pixel, at most ~20 000 samples per path.
|
||||
let rough = flatten(path, 0.1 / rs, f64::INFINITY);
|
||||
for poly0 in rough {
|
||||
let len0 = poly0.len();
|
||||
if len0 <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
let step = (0.5 / rs).max(len0 / 20_000.0);
|
||||
let mut bp = BezPath::new();
|
||||
bp.move_to(poly0.pts[0]);
|
||||
for p in &poly0.pts[1..] {
|
||||
bp.line_to(*p);
|
||||
}
|
||||
let poly = flatten(&bp, 0.1 / rs, step).pop()?;
|
||||
let poly = Poly { closed: poly0.closed, ..poly };
|
||||
let len = poly.len();
|
||||
let wf = |s: f64| half * width_factor(style.taper.as_ref(), style.wave.as_ref(), s, len);
|
||||
let intervals = match &style.dash {
|
||||
Some((d, off)) if d.iter().any(|v| *v > 0.0) => dash_intervals(d, *off, len),
|
||||
_ => vec![(0.0, len)],
|
||||
};
|
||||
let whole = intervals.len() == 1 && intervals[0].0 <= 0.0 && intervals[0].1 >= len;
|
||||
for (a, b) in intervals {
|
||||
// The piece's points: interpolated ends plus every vertex strictly inside.
|
||||
let (pa, ia) = poly.at(a);
|
||||
let (pb, ib) = poly.at(b);
|
||||
let mut pts = vec![(pa, a)];
|
||||
for i in ia..ib {
|
||||
pts.push((poly.pts[i], poly.s[i]));
|
||||
}
|
||||
pts.push((pb, b));
|
||||
pts.dedup_by(|x, y| x.0.distance(y.0) < 1e-9);
|
||||
if pts.len() < 2 {
|
||||
// A zero-length dash: only its caps show.
|
||||
if matches!(style.cap, Cap::Round) {
|
||||
disc(&mut out, pa, wf(a));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let closed = whole && poly.closed;
|
||||
let dir = |i: usize| (pts[i + 1].0 - pts[i].0).normalize();
|
||||
for i in 0..pts.len() - 1 {
|
||||
let d = dir(i);
|
||||
let n = Vec2::new(-d.y, d.x);
|
||||
let (p0, s0) = pts[i];
|
||||
let (p1, s1) = pts[i + 1];
|
||||
let (w0, w1) = (wf(s0), wf(s1));
|
||||
quad(&mut out, [p0 + n * w0, p1 + n * w1, p1 - n * w1, p0 - n * w0]);
|
||||
// Joins: a disc where the direction turns.
|
||||
if i > 0 && dir(i - 1).dot(d) < 0.9999 {
|
||||
disc(&mut out, p0, w0);
|
||||
}
|
||||
}
|
||||
if closed {
|
||||
disc(&mut out, pts[0].0, wf(0.0));
|
||||
continue;
|
||||
}
|
||||
// Caps.
|
||||
let last = pts.len() - 1;
|
||||
let ends = [(pts[0].0, wf(pts[0].1), -dir(0)), (pts[last].0, wf(pts[last].1), dir(last - 1))];
|
||||
for (p, w, outward) in ends {
|
||||
match style.cap {
|
||||
Cap::Butt => {}
|
||||
Cap::Round => disc(&mut out, p, w),
|
||||
Cap::Square => {
|
||||
let n = Vec2::new(-outward.y, outward.x);
|
||||
let q = p + outward * w;
|
||||
quad(&mut out, [p + n * w, q + n * w, q - n * w, p - n * w]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{FillRule, fill_coverage};
|
||||
use effectcraft_geom::Mat3;
|
||||
|
||||
fn line(len: f64) -> BezPath {
|
||||
let mut p = BezPath::new();
|
||||
p.move_to((10.0, 50.0));
|
||||
p.line_to((10.0 + len, 50.0));
|
||||
p
|
||||
}
|
||||
|
||||
fn column(m: &effectcraft_raster::Mask, x: usize) -> f32 {
|
||||
(0..m.height as usize).map(|y| m.data[y * m.width as usize + x]).sum()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn taper_width_profile() {
|
||||
let t = Taper { percent: false, start_len: 50.0, end_len: 0.0, start_width: 0.0, end_width: 1.0, start_ease: 0.0, end_ease: 0.0 };
|
||||
assert!(width_factor(Some(&t), None, 0.0, 200.0).abs() < 1e-9);
|
||||
assert!((width_factor(Some(&t), None, 25.0, 200.0) - 0.5).abs() < 1e-9);
|
||||
assert!((width_factor(Some(&t), None, 100.0, 200.0) - 1.0).abs() < 1e-9);
|
||||
// Ease bulges the profile outwards.
|
||||
let e = Taper { start_ease: 1.0, ..t.clone() };
|
||||
assert!(width_factor(Some(&e), None, 25.0, 200.0) > 0.8);
|
||||
// Percent units and overlapping tapers.
|
||||
let p = Taper { percent: true, start_len: 0.75, end_len: 0.75, start_width: 0.0, end_width: 0.0, ..t };
|
||||
assert!((width_factor(Some(&p), None, 100.0, 200.0) - 1.0).abs() < 1e-9, "meet in the middle at full width");
|
||||
assert!(width_factor(Some(&p), None, 50.0, 200.0) < 0.6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wave_width_profile() {
|
||||
let w = Wave { amount: 1.0, cycles: None, wavelength: 40.0, phase: 0.0 };
|
||||
assert!((width_factor(None, Some(&w), 0.0, 200.0) - 1.0).abs() < 1e-9);
|
||||
assert!(width_factor(None, Some(&w), 20.0, 200.0).abs() < 1e-9);
|
||||
let c = Wave { cycles: Some(5.0), ..w.clone() };
|
||||
assert!(width_factor(None, Some(&c), 20.0, 200.0).abs() < 1e-9, "5 cycles over 200 px = 40 px");
|
||||
let ph = Wave { phase: 180.0, ..w };
|
||||
assert!(width_factor(None, Some(&ph), 0.0, 200.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tapered_line_coverage_grows_along_the_path() {
|
||||
let t = Taper { percent: false, start_len: 100.0, end_len: 0.0, start_width: 0.0, end_width: 1.0, start_ease: 0.0, end_ease: 0.0 };
|
||||
let st = StrokeStyle { width: 20.0, taper: Some(t), ..Default::default() };
|
||||
let o = outline(&[line(150.0)], &st, 1.0).unwrap();
|
||||
let m = fill_coverage(&[o], &Mat3::IDENTITY, 200, 100, FillRule::NonZero);
|
||||
let (c1, c2, c3) = (column(&m, 30), column(&m, 70), column(&m, 140));
|
||||
assert!((c1 - 4.0).abs() < 1.0, "20% along the taper → 4 px: {c1}");
|
||||
assert!((c2 - 12.0).abs() < 1.0, "{c2}");
|
||||
assert!((c3 - 20.0).abs() < 0.6, "{c3}");
|
||||
let area: f32 = m.data.iter().sum();
|
||||
assert!((area - (100.0 * 10.0 + 50.0 * 20.0)).abs() < 40.0, "{area}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dash_intervals_multi_segment() {
|
||||
let iv = dash_intervals(&[10.0, 5.0, 2.0, 3.0], 0.0, 45.0);
|
||||
assert_eq!(iv, vec![(0.0, 10.0), (15.0, 17.0), (20.0, 30.0), (35.0, 37.0), (40.0, 45.0)]);
|
||||
let off = dash_intervals(&[10.0, 10.0], 5.0, 30.0);
|
||||
assert_eq!(off, vec![(0.0, 5.0), (15.0, 25.0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn waved_dashed_stroke_has_gaps() {
|
||||
let st = StrokeStyle {
|
||||
width: 10.0,
|
||||
dash: Some((vec![20.0, 10.0], 0.0)),
|
||||
wave: Some(Wave { amount: 0.5, cycles: None, wavelength: 30.0, phase: 0.0 }),
|
||||
..Default::default()
|
||||
};
|
||||
let o = outline(&[line(150.0)], &st, 1.0).unwrap();
|
||||
let m = fill_coverage(&[o], &Mat3::IDENTITY, 200, 100, FillRule::NonZero);
|
||||
assert!(column(&m, 41) > 9.0, "dash at full width (wave crest): {}", column(&m, 41));
|
||||
assert!(column(&m, 35) < 0.01, "gap");
|
||||
assert!(column(&m, 55) > 4.0 && column(&m, 55) < 6.5, "wave trough ≈ half width: {}", column(&m, 55));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closed_tapered_path_is_continuous() {
|
||||
let r = crate::rect([60.0, 60.0], [50.0, 50.0], 0.0);
|
||||
let st = StrokeStyle { width: 6.0, wave: Some(Wave { amount: 0.2, cycles: Some(4.0), wavelength: 0.0, phase: 0.0 }), ..Default::default() };
|
||||
let o = outline(&[r], &st, 1.0).unwrap();
|
||||
let m = fill_coverage(&[o], &Mat3::IDENTITY, 100, 100, FillRule::NonZero);
|
||||
assert!(m.data.iter().all(|v| *v <= 1.0001));
|
||||
let area: f32 = m.data.iter().sum();
|
||||
assert!(area > 240.0 * 6.0 * 0.8 && area < 240.0 * 6.0 * 1.05, "{area}");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user