Skip to content

ProCraft for Android: An Android native painting app written in Rust

Rust

feat(brush): pressure curves and dynamics as the reference draws them

Josh191b1c93379e
diff --git a/apps/procraft-android/src/brush_files.rs b/apps/procraft-android/src/brush_files.rs
index f593f20..5ce9c09 100644
--- a/apps/procraft-android/src/brush_files.rs
+++ b/apps/procraft-android/src/brush_files.rs
@@ -146,7 +146,8 @@ fn folder_id(seed: u64, i: usize) -> String {
/// A brush from a brush file: the studio's controls on a fresh brush, its images found or stood in
/// for.
fn brush_from(file: &BrushFile) -> Brush {
- let mut b = Brush { name: file.name.clone(), ..Brush::round_pen() };
+ // only the curves the file has (a control without one doesn't follow the pressure)
+ let mut b = Brush { name: file.name.clone(), pressure_curves: Default::default(), ..Brush::round_pen() };
let (image, source, hardness) = shape_for(&file.shape);
b.shape.image = image;
b.shape.source = source;
@@ -166,6 +167,9 @@ fn brush_from(file: &BrushFile) -> Brush {
if let Some(points) = &file.pressure_curve {
b.pressure_curve = Curve::new(points);
}
+ for (kind, points) in &file.pressure_curves {
+ b.pressure_curves.set(*kind, Some(Curve::new(points)));
+ }
b.notches = file.notches.clone();
let (image, source) = grain_for(&file.grain, file.thumbnail.as_deref());
b.grain.image = image;
diff --git a/apps/procraft-android/src/brush_library.rs b/apps/procraft-android/src/brush_library.rs
index 4142ce0..46475ea 100644
--- a/apps/procraft-android/src/brush_library.rs
+++ b/apps/procraft-android/src/brush_library.rs
@@ -3,8 +3,8 @@
use std::collections::BTreeMap;
-use procraft_engine::brush::{Author, Brush, Notches, ResetPoint, Source, StockImage, StockImages};
-use procraft_engine::brushfile::Texture;
+use procraft_engine::brush::{Author, Brush, Notches, PressureCurves, ResetPoint, Source, StockImage, StockImages};
+use procraft_engine::brushfile::{self, Texture};
use procraft_engine::curve::Curve;
use procraft_engine::geom::Vec2;
use procraft_engine::library::{BrushSet, SHELF};
@@ -115,6 +115,9 @@ struct SavedBrush {
size_curve: Vec<[f32; 2]>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
opacity_curve: Vec<[f32; 2]>,
+ /// Its own pressure curves for other controls, by their keys in brush files, if they differ.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pressure_curves: Option<BTreeMap<String, Vec<[f32; 2]>>>,
/// The brush's own shape and grain images, as text.
#[serde(default, skip_serializing_if = "Option::is_none")]
shape_source: Option<String>,
@@ -271,6 +274,14 @@ impl State {
curve: kept(&brush.pressure_curve, &base.pressure_curve),
size_curve: kept(&brush.size_curve, &base.size_curve),
opacity_curve: kept(&brush.opacity_curve, &base.opacity_curve),
+ pressure_curves: (brush.pressure_curves != base.pressure_curves).then(|| {
+ let points = |c: &Curve| c.points().iter().map(|p| [p.x, p.y]).collect();
+ brush
+ .pressure_curves
+ .iter()
+ .map(|(k, c)| (brushfile::pressure_curve_key(k).to_owned(), points(c)))
+ .collect()
+ }),
shape_source: brush.shape.source.as_ref().map(Source::to_text),
grain_source: brush.grain.source.as_ref().map(Source::to_text),
shape_image: image(brush.shape.image, base.shape.image),
@@ -335,6 +346,17 @@ impl State {
*curve = Curve::new(&pts);
}
}
+ if let Some(curves) = &b.pressure_curves {
+ brush.pressure_curves = PressureCurves::default();
+ for (key, points) in curves {
+ if let Some(kind) = brushfile::pressure_curve_of(key)
+ && points.len() >= 2
+ {
+ let pts: Vec<Vec2> = points.iter().map(|&[x, y]| Vec2::new(x, y)).collect();
+ brush.pressure_curves.set(kind, Some(Curve::new(&pts)));
+ }
+ }
+ }
brush.notches = b.notches.notches();
brush.author = b.author.as_ref().map(|a| Author {
name: a.name.clone(),
diff --git a/apps/procraft-android/src/lib.rs b/apps/procraft-android/src/lib.rs
index 5e8948e..b1eac8a 100644
--- a/apps/procraft-android/src/lib.rs
+++ b/apps/procraft-android/src/lib.rs
@@ -543,6 +543,26 @@ impl State {
}
}
+/// Draws `samples` into the canvas's open stroke: their stamps as they come or, for a stroke shown
+/// with its tip, those the end taper no longer reaches for good and the rest as the tip. Whether
+/// anything was drawn.
+fn draw_samples(
+ canvas: &mut Canvas,
+ builder: &mut StrokeBuilder,
+ samples: &[Sample],
+ guide: &procraft_engine::guide::Guide,
+) -> bool {
+ if canvas.shows_tip() && builder.shows_tip() {
+ let (kept, tip) = builder.add_tipped(samples);
+ canvas.add_stamps(&guide::mirrored(guide, &kept));
+ canvas.set_tip(&guide::mirrored(guide, &tip));
+ return !kept.is_empty() || !tip.is_empty();
+ }
+ let stamps = guide::mirrored(guide, &builder.add(samples));
+ canvas.add_stamps(&stamps);
+ !stamps.is_empty()
+}
+
/// Ends the canvas's open stroke with `builder`'s final stamps: a painted or erased stroke is
/// redrawn once in its final form (end taper); a smudge, which has already changed the layer, and
/// an adjustment painted on, which adds to its mask, only get the stamps not drawn yet.
@@ -835,7 +855,6 @@ impl CanvasSession {
st.drawn.clear();
st.drawn_pressure = 0.0;
st.remember_input(&canvas_samples);
- let stamps = guide::mirrored(&st.doc.guide, &builder.add(&canvas_samples));
// painted and erased strokes can be made shapes once they end
st.last_stroke = None;
st.began =
@@ -851,7 +870,7 @@ impl CanvasSession {
});
let Some(canvas) = st.canvas.as_mut() else { return };
canvas.begin_stroke(current, style);
- canvas.add_stamps(&stamps);
+ draw_samples(canvas, &mut builder, &canvas_samples, &st.doc.guide);
st.stroke = Some(builder);
self.shared.frame(st);
}
@@ -873,9 +892,7 @@ impl CanvasSession {
}
st.remember_input(&canvas_samples);
let (Some(builder), Some(canvas)) = (st.stroke.as_mut(), st.canvas.as_mut()) else { return };
- let stamps = guide::mirrored(&st.doc.guide, &builder.add(&canvas_samples));
- if !stamps.is_empty() {
- canvas.add_stamps(&stamps);
+ if draw_samples(canvas, builder, &canvas_samples, &st.doc.guide) {
st.redraw_painted_on();
self.shared.frame(st);
}
@@ -891,7 +908,12 @@ impl CanvasSession {
}
let canvas_samples = st.to_canvas(&samples);
let (Some(builder), Some(canvas)) = (st.stroke.as_ref(), st.canvas.as_mut()) else { return };
- canvas.set_prediction(&builder.preview(&canvas_samples));
+ // a stroke shown with its tip ends it where the input is predicted to go
+ if canvas.shows_tip() && builder.shows_tip() {
+ canvas.set_tip(&guide::mirrored(&st.doc.guide, &builder.preview_tip(&canvas_samples)));
+ } else {
+ canvas.set_prediction(&builder.preview(&canvas_samples));
+ }
self.shared.frame(st);
}
diff --git a/apps/procraft-android/src/tests.rs b/apps/procraft-android/src/tests.rs
index 24b9715..bed8b37 100644
--- a/apps/procraft-android/src/tests.rs
+++ b/apps/procraft-android/src/tests.rs
@@ -1337,9 +1337,9 @@ fn curve_samples_follow_the_curve() {
for (i, v) in straight.iter().enumerate() {
assert!((v - i as f32 / 4.0).abs() < 1e-5);
}
- // through a raised middle point, never above the top
+ // through a raised middle point (as its table reads it), never above the top
let bent = crate::studio::curve_samples(vec![0.0, 0.0, 0.5, 0.8, 1.0, 1.0], 101);
- assert!((bent[50] - 0.8).abs() < 1e-4);
+ assert!((bent[50] - 0.8).abs() < 1e-3);
assert!(bent.iter().all(|v| (0.0..=1.0).contains(v)));
}
@@ -1931,6 +1931,25 @@ fn slider_notches_are_kept_with_the_library() {
assert!(!t.remove_slider_notch(true, 0.3));
}
+#[test]
+fn a_brushs_own_pressure_curves_are_kept_with_the_library() {
+ use procraft_engine::brush::PressureCurve;
+ use procraft_engine::curve::Curve;
+ use procraft_engine::geom::Vec2;
+ let bend = Curve::new(&[Vec2::new(0.0, 0.2), Vec2::new(1.0, 0.6)]);
+ let s = CanvasSession::new(64, 64);
+ {
+ let mut st = s.shared.lock();
+ let (set, index) = st.brush_ref(st.tool);
+ let brush = st.library.get_mut(set).and_then(|l| l.brushes.get_mut(index)).unwrap();
+ brush.pressure_curves.set(PressureCurve::GrainDepth, Some(bend.clone()));
+ }
+ let t = CanvasSession::new(64, 64);
+ assert!(t.load_brush_library(s.saved_brush_library()));
+ let st = t.shared.lock();
+ assert_eq!(st.brush(st.tool).pressure_curves.get(PressureCurve::GrainDepth), Some(&bend));
+}
+
#[test]
fn a_pad_keeps_its_strokes_and_its_sample_gives_way() {
let pad = CanvasSession::new(200, 120);
diff --git a/crates/engine/src/brush.rs b/crates/engine/src/brush.rs
index ae04c18..94c5077 100644
--- a/crates/engine/src/brush.rs
+++ b/crates/engine/src/brush.rs
@@ -49,9 +49,10 @@ impl Source {
/// Size and opacity at the ends of a stroke.
#[derive(Clone, Debug, PartialEq)]
pub struct Taper {
- /// Length of the start taper, 0..1 of [`TAPER_SPAN`] stamp diameters.
+ /// Length of the start taper, 0..1: of [`TAPER_TIME_MS`] for the newer taper, of
+ /// [`CLASSIC_TAPER_SPAN`] canvas pixels for the classic one.
pub start: f32,
- /// Length of the end taper, 0..1 of [`TAPER_SPAN`] stamp diameters.
+ /// Length of the end taper, likewise.
pub end: f32,
/// How thin the tips get: 0 = no change, 1 = down to nothing.
pub size: f32,
@@ -59,107 +60,38 @@ pub struct Taper {
pub opacity: f32,
}
-/// A taper length of 1 spans this many stamp diameters.
-pub const TAPER_SPAN: f32 = 24.0;
-
-/// A classic taper of length 1 spans this many canvas pixels, whatever the brush's size (as
-/// measured: the width grows evenly to full over it).
-pub const CLASSIC_TAPER_SPAN: f32 = 520.0;
-/// A classic end taper comes to its tip over at most the last this many milliseconds of the
-/// stroke, however long it is set (as measured, at any speed: a quarter of the width 11 ms before
-/// the pen lifts, half 24 ms, nine tenths 51 ms).
-pub const CLASSIC_END_MS: f32 = 58.0;
-/// The newer taper's ends on touch run over at most the first and the last this many milliseconds
-/// of the stroke, whatever the brush's size or the stroke's length (as measured: a quarter of the
-/// width 16 ms before the finger lifts, half 37 ms, nine tenths 73 ms).
-pub const TIMED_START_MS: f32 = 6.0;
-pub const TIMED_END_MS: f32 = 82.5;
-/// A newer taper of length 1 on touch lasts this long, up to those (as measured: a length of
-/// 0.0225 ends in a short tip, 0.0625 already in the whole, 0 in none).
-pub const TIMED_TAPER_SPAN_MS: f32 = 1300.0;
-/// How the width comes to an end taper's tip: the share of the end still to go, to this power.
-const CLASSIC_END_EASE: f32 = 0.83;
-const TIMED_END_EASE: f32 = 0.855;
-
-/// How far a taper of `len` canvas pixels has grown `d` pixels in, eased by `power`.
-fn grown(len: f32, d: f32, power: f32) -> f32 {
- if len <= 0.0 { 1.0 } else { (d / len).clamp(0.0, 1.0).powf(power) }
-}
+/// A newer taper of length 1 lasts this many milliseconds of the stroke, from when it starts or
+/// back from when it ends.
+pub const TAPER_TIME_MS: f64 = 83.34;
+
+/// A classic taper of length 1 spans this many canvas pixels, whatever the brush's size.
+pub const CLASSIC_TAPER_SPAN: f32 = 512.0;
impl Taper {
pub const NONE: Taper = Taper { start: 0.0, end: 0.0, size: 0.0, opacity: 0.0 };
- /// The multipliers (size, opacity) at `distance` px from the start of a stroke of `length` px
- /// drawn with a `diameter` px brush; `length` is `None` while the stroke is still being drawn.
- pub fn factors(&self, distance: f32, length: Option<f32>, diameter: f32) -> (f32, f32) {
- let span = TAPER_SPAN * diameter.max(0.5);
- let (mut start, mut end) = (self.start.max(0.0) * span, self.end.max(0.0) * span);
- if let Some(total) = length {
- // a stroke shorter than its tapers tapers in proportion; a tap not at all
- let sum = start + end;
- if sum > total.max(0.0) && sum > 0.0 {
- let k = total.max(0.0) / sum;
- start *= k;
- end *= k;
- }
- }
- let ramp = |len: f32, d: f32| -> f32 {
- if len <= 0.0 {
- return 1.0;
- }
- let u = (d / len).clamp(0.0, 1.0);
- 1.0 - (1.0 - u) * (1.0 - u)
- };
- let mut t = ramp(start, distance);
- if let Some(total) = length {
- t = t.min(ramp(end, (total - distance).max(0.0)));
- }
- (1.0 - self.size.clamp(0.0, 1.0) * (1.0 - t), 1.0 - self.opacity.clamp(0.0, 1.0) * (1.0 - t))
- }
-
- /// As [`Taper::factors`] for a classic taper, as measured: the start grows evenly over its
- /// length in canvas pixels whatever the brush's size; the end comes to its tip over its length
- /// or over the last [`CLASSIC_END_MS`] of the stroke, whichever is shorter (`pace`: how fast
- /// the stroke ended, canvas pixels a millisecond); a stroke shorter than its tapers just
- /// doesn't reach full.
- pub fn classic_factors(&self, distance: f32, length: Option<f32>, pace: f32) -> (f32, f32) {
- // a tap keeps its full size
- if length.is_some_and(|l| l <= 0.0) {
- return (1.0, 1.0);
- }
- let start = self.start.max(0.0) * CLASSIC_TAPER_SPAN;
- let end = (self.end.max(0.0) * CLASSIC_TAPER_SPAN).min(CLASSIC_END_MS * pace.max(0.0));
- let mut t = grown(start, distance, 1.0);
- if let Some(total) = length {
- t = t.min(grown(end, (total - distance).max(0.0), CLASSIC_END_EASE));
- }
- self.applied(t)
+ /// The multipliers (size, opacity) where the start taper has grown `start` and the end taper
+ /// `end` of the way to full (0..1 each), with a tip of sharpness `tip` (0 comes to a point,
+ /// 1 stays almost whole until the very end).
+ pub fn applied(&self, start: f32, end: f32, tip: f32) -> (f32, f32) {
+ let power = Taper::tip_power(tip);
+ let left = |grown: f32| 1.0 - grown.clamp(0.0, 1.0).powf(power);
+ let (size, opacity) = (self.size.clamp(0.0, 1.0), self.opacity.clamp(0.0, 1.0));
+ let (s, e) = (left(start), left(end));
+ let thinned = (1.0 - size * s) * (1.0 - size * e);
+ let faded = (1.0 - (opacity * s).powf(2.5)) * (1.0 - (opacity * e).powf(2.5));
+ (thinned, faded)
}
- /// As [`Taper::factors`] for the newer taper on touch, as measured: each end lasts its length
- /// in time ([`TIMED_TAPER_SPAN_MS`] for 1) up to [`TIMED_START_MS`] and [`TIMED_END_MS`],
- /// over as much of the stroke as the finger covered in that time (`paces`: how fast the
- /// stroke started and ended, canvas pixels a millisecond).
- pub fn timed_factors(&self, distance: f32, length: Option<f32>, paces: (f32, f32)) -> (f32, f32) {
- if length.is_some_and(|l| l <= 0.0) {
- return (1.0, 1.0);
- }
- let lasts = |share: f32, most: f32| (share.max(0.0) * TIMED_TAPER_SPAN_MS).min(most);
- let start = lasts(self.start, TIMED_START_MS) * paces.0.max(0.0);
- let end = lasts(self.end, TIMED_END_MS) * paces.1.max(0.0);
- let mut t = grown(start, distance, 1.0);
- if let Some(total) = length {
- t = t.min(grown(end, (total - distance).max(0.0), TIMED_END_EASE));
- }
- self.applied(t)
- }
-
- /// The multipliers (size, opacity) where the taper has grown `t` of the way to full.
- fn applied(&self, t: f32) -> (f32, f32) {
- (1.0 - self.size.clamp(0.0, 1.0) * (1.0 - t), 1.0 - self.opacity.clamp(0.0, 1.0) * (1.0 - t))
+ /// The power a taper's growth is taken to for a tip of sharpness `tip` (1 for a sharp one).
+ pub fn tip_power(tip: f32) -> f32 {
+ 1.0 - TIP_BLUNTING * tip.clamp(0.0, 1.0)
}
}
+/// How far a blunt tip (1) bends the taper's growth: it grows to the power 1 less this.
+const TIP_BLUNTING: f32 = 0.984375;
+
/// How a stroke's stamps build up within the stroke (the studio's rendering modes: Light Glaze
/// keeps the strongest; Uniformed Glaze, Intense Glaze and Intense Blending build up; Heavy Glaze
/// and Uniform Blending build up gradually).
@@ -186,6 +118,78 @@ pub enum PressureUse {
Roundness = 3,
}
+/// What else a brush may give a pressure curve of its own: the control is then scaled by the
+/// curve at the stamp's pressure (a finger's is full), and without one it doesn't follow the
+/// pressure at all.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
+pub enum PressureCurve {
+ LateralJitter,
+ LinearJitter,
+ Count,
+ CountJitter,
+ SizeJitter,
+ OpacityJitter,
+ Scatter,
+ /// The roundness jitter's two ways: along the stamp's height and its width.
+ RoundnessJitterY,
+ RoundnessJitterX,
+ GrainMovement,
+ GrainScale,
+ GrainZoom,
+ GrainDepth,
+ GrainDepthJitter,
+ WetGrade,
+ WetBlur,
+ WetBlurJitter,
+ WetnessJitter,
+ /// The colour's own response to pressure: hue, saturation, brightness and the secondary
+ /// colour's share.
+ Hue,
+ Saturation,
+ Brightness,
+ Secondary,
+ /// The stamp colour jitters.
+ HueJitter,
+ SaturationJitter,
+ LightnessJitter,
+ DarknessJitter,
+ SecondaryJitter,
+}
+
+/// A brush's own [`PressureCurve`]s, those it has.
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct PressureCurves(BTreeMap<PressureCurve, Curve>);
+
+impl PressureCurves {
+ pub fn get(&self, kind: PressureCurve) -> Option<&Curve> {
+ self.0.get(&kind)
+ }
+
+ /// Gives `kind` a curve, or takes its curve away.
+ pub fn set(&mut self, kind: PressureCurve, curve: Option<Curve>) {
+ match curve {
+ Some(c) => self.0.insert(kind, c),
+ None => self.0.remove(&kind),
+ };
+ }
+
+ /// The curves a new brush has: the colour's following the pressure, straight.
+ pub fn new_brush() -> PressureCurves {
+ let colour =
+ [PressureCurve::Hue, PressureCurve::Saturation, PressureCurve::Brightness, PressureCurve::Secondary];
+ PressureCurves(colour.into_iter().map(|k| (k, Curve::linear())).collect())
+ }
+
+ /// What `kind` is scaled by at `pressure`: 1 without a curve.
+ pub fn at(&self, kind: PressureCurve, pressure: f32) -> f32 {
+ self.0.get(&kind).map_or(1.0, |c| c.eval(pressure))
+ }
+
+ pub fn iter(&self) -> impl Iterator<Item = (PressureCurve, &Curve)> {
+ self.0.iter().map(|(k, c)| (*k, c))
+ }
+}
+
/// The size slider's curve: the size it sets is its place to this power.
pub const SIZE_CURVE: f32 = 2.2;
@@ -260,7 +264,7 @@ pub struct Shape {
pub follow: f32,
/// Turn with the direction the pen leans.
pub follow_azimuth: bool,
- /// A random rotation per stamp.
+ /// A random rotation, the same for every stamp of a stroke.
pub randomise: bool,
/// 1 = as drawn; lower squashes the stamp across its rotation.
pub roundness: f32,
@@ -377,6 +381,8 @@ pub struct Brush {
/// opacity.
pub size_curve: Curve,
pub opacity_curve: Curve,
+ /// Its own pressure curves for its other controls.
+ pub pressure_curves: PressureCurves,
/// Taper for pens and for fingers.
pub pen_taper: Taper,
pub touch_taper: Taper,
@@ -524,6 +530,7 @@ impl Brush {
pressure_curve: Curve::linear(),
size_curve: Curve::linear(),
opacity_curve: Curve::linear(),
+ pressure_curves: PressureCurves::new_brush(),
pen_taper: Taper { start: 0.15, end: 0.2, size: 0.8, opacity: 0.0 },
touch_taper: Taper { start: 0.1, end: 0.1, size: 0.6, opacity: 0.0 },
shape: Shape::default(),
@@ -595,69 +602,19 @@ mod tests {
use super::*;
#[test]
- fn taper_ramps_in_and_out() {
+ fn a_taper_thins_and_fades_its_tips_as_far_as_it_has_grown() {
let t = Taper { start: 0.5, end: 0.5, size: 1.0, opacity: 0.5 };
- let d = 10.0;
- let span = 0.5 * TAPER_SPAN * d;
- assert_eq!(t.factors(0.0, None, d), (0.0, 0.5));
- assert_eq!(t.factors(span, None, d), (1.0, 1.0));
- let (mid, _) = t.factors(span * 4.0, Some(span * 8.0), d);
- assert_eq!(mid, 1.0);
- let (end, _) = t.factors(span * 8.0, Some(span * 8.0), d);
- assert_eq!(end, 0.0);
- assert_eq!(Taper::NONE.factors(0.0, Some(0.0), d), (1.0, 1.0));
- // a tap keeps its full size; a short stroke still thins at both ends
- assert_eq!(t.factors(0.0, Some(0.0), d), (1.0, 1.0));
- let (short_tip, _) = t.factors(0.0, Some(span), d);
- let (short_mid, _) = t.factors(span / 2.0, Some(span), d);
- assert!(short_tip < 0.1 && short_mid > 0.99);
- }
-
- #[test]
- fn a_classic_taper_spans_canvas_pixels_whatever_the_size() {
- let t = Taper { start: 0.5, end: 1.0, size: 1.0, opacity: 0.0 };
- // the start grows evenly over half of the span
- let half = 0.5 * CLASSIC_TAPER_SPAN;
- assert_eq!(t.classic_factors(0.0, None, 1.0).0, 0.0);
- assert!((t.classic_factors(half / 2.0, None, 1.0).0 - 0.5).abs() < 1e-5);
- assert_eq!(t.classic_factors(half, None, 1.0).0, 1.0);
- // the end is a short tip however long it is set, as long as the pen takes to lift: the
- // faster the stroke ends, the longer the tip
- let total = 2000.0;
- for pace in [0.5, 1.0, 3.0] {
- let tip = CLASSIC_END_MS * pace;
- assert_eq!(t.classic_factors(total - tip, Some(total), pace).0, 1.0);
- let half_way = t.classic_factors(total - tip / 2.0, Some(total), pace).0;
- assert!((half_way - 0.5f32.powf(CLASSIC_END_EASE)).abs() < 1e-5);
- }
- // set short, the end is shorter still
- let short = Taper { end: 0.02, ..t };
- assert_eq!(short.classic_factors(total - 0.02 * CLASSIC_TAPER_SPAN, Some(total), 1.0).0, 1.0);
- // a short stroke doesn't reach full; a tap keeps its size
- assert!(t.classic_factors(100.0, Some(150.0), 1.0).0 < 0.5);
- assert_eq!(t.classic_factors(0.0, Some(0.0), 1.0), (1.0, 1.0));
- }
-
- #[test]
- fn the_newer_taper_on_touch_lasts_a_time() {
- let t = Taper { start: 0.5, end: 0.5, size: 1.0, opacity: 0.0 };
- let total = 2000.0;
- // its ends cover what the finger moves over in their time, however long they are set
- for pace in [0.5, 1.0, 3.0] {
- let (start, end) = (TIMED_START_MS * pace, TIMED_END_MS * pace);
- let at = |d: f32, t: &Taper| t.timed_factors(d, Some(total), (pace, pace)).0;
- assert_eq!(at(0.0, &t), 0.0);
- assert!((at(start / 2.0, &t) - 0.5).abs() < 1e-5);
- assert_eq!(at(start, &t), 1.0);
- assert_eq!(at(total - end, &t), 1.0);
- assert!(at(total - end / 2.0, &t) < 0.6);
- assert_eq!(at(total - end, &Taper { end: 1.0, ..t }), 1.0);
- }
- // set very short, an end is shorter; set to none, there is none
- let short = Taper { end: 0.02, ..t };
- assert_eq!(short.timed_factors(total - 0.02 * TIMED_TAPER_SPAN_MS, Some(total), (1.0, 1.0)).0, 1.0);
- assert_eq!(Taper { end: 0.0, ..t }.timed_factors(total, Some(total), (1.0, 1.0)).0, 1.0);
- assert_eq!(t.timed_factors(0.0, Some(0.0), (1.0, 1.0)), (1.0, 1.0));
+ // grown fully at both ends: whole; at a tip: thinned to nothing, faded by its opacity
+ assert_eq!(t.applied(1.0, 1.0, 0.0), (1.0, 1.0));
+ let (size, opacity) = t.applied(0.0, 1.0, 0.0);
+ assert_eq!(size, 0.0);
+ assert!((opacity - (1.0 - 0.5f32.powf(2.5))).abs() < 1e-6);
+ // a sharp tip grows evenly; a blunt one is almost whole a little way in
+ assert!((t.applied(0.25, 1.0, 0.0).0 - 0.25).abs() < 1e-6);
+ assert!(t.applied(0.05, 1.0, 1.0).0 > 0.95);
+ // both ends at once take away what each other leaves
+ assert!((t.applied(0.5, 0.5, 0.0).0 - 0.25).abs() < 1e-6);
+ assert_eq!(Taper::NONE.applied(0.0, 0.0, 0.0), (1.0, 1.0));
}
#[test]
diff --git a/crates/engine/src/brushfile.rs b/crates/engine/src/brushfile.rs
index 8951e59..e6ab84d 100644
--- a/crates/engine/src/brushfile.rs
+++ b/crates/engine/src/brushfile.rs
@@ -5,7 +5,7 @@
//! file's own numbers. A set file is a zip of brushes, each in a folder of its own, with
//! `brushset.plist` giving the set's name and the folders in order.
-use crate::brush::{BRUSH_BEHIND, Brush, GRAIN_HEIGHT, GRAIN_LINEAR_HEIGHT, Notches, SIZE_CURVE};
+use crate::brush::{BRUSH_BEHIND, Brush, GRAIN_HEIGHT, GRAIN_LINEAR_HEIGHT, Notches, PressureCurve, SIZE_CURVE};
use crate::document::BlendMode;
use crate::geom::Vec2;
use crate::keyed::{Archive, Builder, Object};
@@ -30,6 +30,9 @@ pub struct BrushFile {
/// The pressure's own curves for the size and the opacity, if not straight.
pub size_curve: Option<Vec<Vec2>>,
pub opacity_curve: Option<Vec<Vec2>>,
+ /// Its own pressure curves for other controls, those it has (straight ones too: a control
+ /// without one doesn't follow the pressure).
+ pub pressure_curves: Vec<(PressureCurve, Vec<Vec2>)>,
pub shape: Texture,
pub grain: Texture,
/// Where the size and opacity sliders start when it is picked, 0..1.
@@ -395,6 +398,47 @@ fn escape(s: &str) -> String {
s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;")
}
+/// Where brush files keep each [`PressureCurve`].
+pub const PRESSURE_CURVES: [(PressureCurve, &str); 27] = [
+ (PressureCurve::LateralJitter, "dynamicsPressurePlotJitterCurve"),
+ (PressureCurve::LinearJitter, "dynamicsPressurePlotJitterLongitudinalCurve"),
+ (PressureCurve::Count, "dynamicsPressureStampCountCurve"),
+ (PressureCurve::CountJitter, "dynamicsPressureStampCountJitterCurve"),
+ (PressureCurve::SizeJitter, "dynamicsPressureSizeJitterCurve"),
+ (PressureCurve::OpacityJitter, "dynamicsPressureOpacityJitterCurve"),
+ (PressureCurve::Scatter, "dynamicsPressureShapeScatterCurve"),
+ (PressureCurve::RoundnessJitterY, "dynamicsPressureShapeRoundessVerticalJitterCurve"),
+ (PressureCurve::RoundnessJitterX, "dynamicsPressureShapeRoundessHorizontalJitterCurve"),
+ (PressureCurve::GrainMovement, "dynamicsPressureGrainMovementCurve"),
+ (PressureCurve::GrainScale, "dynamicsPressureGrainScaleCurve"),
+ (PressureCurve::GrainZoom, "dynamicsPressureGrainZoomCurve"),
+ (PressureCurve::GrainDepth, "dynamicsPressureGrainDepthCurve"),
+ (PressureCurve::GrainDepthJitter, "dynamicsPressureGrainDepthJitterCurve"),
+ (PressureCurve::WetGrade, "dynamicsPressureGradeCurve"),
+ (PressureCurve::WetBlur, "dynamicsPressureBlurCurve"),
+ (PressureCurve::WetBlurJitter, "dynamicsPressureBlurJitterCurve"),
+ (PressureCurve::WetnessJitter, "dynamicsPressureWetnessCurve"),
+ (PressureCurve::Hue, "dynamicsPressureHueCurve"),
+ (PressureCurve::Saturation, "dynamicsPressureSaturationCurve"),
+ (PressureCurve::Brightness, "dynamicsPressureBrightnessCurve"),
+ (PressureCurve::Secondary, "dynamicsPressureSecondaryColorCurve"),
+ (PressureCurve::HueJitter, "dynamicsPressureHueJitterCurve"),
+ (PressureCurve::SaturationJitter, "dynamicsPressureSaturationJitterCurve"),
+ (PressureCurve::LightnessJitter, "dynamicsPressureLightnessJitterCurve"),
+ (PressureCurve::DarknessJitter, "dynamicsPressureDarknessJitterCurve"),
+ (PressureCurve::SecondaryJitter, "dynamicsPressureSecondaryColorJitterCurve"),
+];
+
+/// The key brush files keep `kind` under.
+pub fn pressure_curve_key(kind: PressureCurve) -> &'static str {
+ PRESSURE_CURVES.iter().find(|(k, _)| *k == kind).map_or("", |(_, key)| key)
+}
+
+/// The curve kept under `key`, if it is one.
+pub fn pressure_curve_of(key: &str) -> Option<PressureCurve> {
+ PRESSURE_CURVES.iter().find(|(_, k)| *k == key).map(|(kind, _)| *kind)
+}
+
/// Reads the brush whose files are under `prefix` in `zip`.
fn read_in(zip: &ZipReader<'_>, prefix: &str) -> Option<BrushFile> {
let archive = Archive::read(&zip.read(&format!("{prefix}Brush.archive"))?)?;
@@ -411,6 +455,20 @@ fn read_in(zip: &ZipReader<'_>, prefix: &str) -> Option<BrushFile> {
set(control, to_control(kept, v));
}
}
+ // a file without the pen's own taper keys tapers a pen as it does touch
+ for (pen, touch, control) in [
+ ("pencilTaperStartLength", "taperStartLength", "pen_taper_start"),
+ ("pencilTaperEndLength", "taperEndLength", "pen_taper_end"),
+ ("pencilTaperSize", "taperSize", "pen_taper_size"),
+ ("pencilTaperOpacity", "taperOpacity", "pen_taper_opacity"),
+ ("pencilTaperShape", "taperShape", "pen_taper_tip"),
+ ] {
+ if f.num(pen).is_none()
+ && let Some(v) = f.num(touch)
+ {
+ set(control, v as f32);
+ }
+ }
if let Some(v) = f.num("shapeCount") {
let count = stamp_count(v);
set("count", (count - 1.0) / (crate::studio::MAX_COUNT as f32 - 1.0));
@@ -497,6 +555,15 @@ fn read_in(zip: &ZipReader<'_>, prefix: &str) -> Option<BrushFile> {
sizes: ["savedPaintSizes", "savedSmudgeSizes", "savedEraseSizes"].map(|k| place(f.reals(k))),
opacities: ["savedPaintOpacities", "savedSmudgeOpacities", "savedEraseOpacities"].map(|k| f.reals(k)),
};
+ let mut pressure_curves: Vec<(PressureCurve, Vec<Vec2>)> =
+ PRESSURE_CURVES.iter().filter_map(|&(kind, key)| Some((kind, f.curve(key)?))).collect();
+ // a file from before the linear jitter had its own keys: it follows the lateral one's curve
+ if f.num("plotJitterLongitudinal").is_none()
+ && !pressure_curves.iter().any(|(k, _)| *k == PressureCurve::LinearJitter)
+ && let Some((_, c)) = pressure_curves.iter().find(|(k, _)| *k == PressureCurve::LateralJitter)
+ {
+ pressure_curves.push((PressureCurve::LinearJitter, c.clone()));
+ }
Some(BrushFile {
name: f.text("name").unwrap_or_else(|| "Imported Brush".to_owned()),
author: f.text("authorName").unwrap_or_default(),
@@ -507,6 +574,7 @@ fn read_in(zip: &ZipReader<'_>, prefix: &str) -> Option<BrushFile> {
pressure_curve: f.curve("dynamicsPressureOverall").filter(|c| !is_straight(c)),
size_curve: f.curve("dynamicsPressureSizeCurve").filter(|c| !is_straight(c)),
opacity_curve: f.curve("dynamicsPressureOpacityCurve").filter(|c| !is_straight(c)),
+ pressure_curves,
shape: texture("bundledShapePath", "Shape.png", "shapeInverted"),
grain: texture("bundledGrainPath", "Grain.png", "textureInverted"),
paint_size: f.num("paintSize").unwrap_or(0.5) as f32,
@@ -642,12 +710,17 @@ fn add_brush(zip: &mut ZipWriter, prefix: &str, brush: &Brush, author: &str, pic
}
}
}
- // the pressure response, and its own curves for the size and the opacity
+ // the pressure response, its own curves for the size and the opacity, and those the brush has
+ // for its other controls
+ let others = brush.pressure_curves.iter().map(|(kind, c)| (pressure_curve_key(kind), c));
for (key, c) in [
("dynamicsPressureOverall", &brush.pressure_curve),
("dynamicsPressureSizeCurve", &brush.size_curve),
("dynamicsPressureOpacityCurve", &brush.opacity_curve),
- ] {
+ ]
+ .into_iter()
+ .chain(others)
+ {
let points: Vec<Value> = c.points().iter().map(|p| b.string(&format!("{{{:.6}, {:.6}}}", p.x, p.y))).collect();
let list = b.array(points, true);
let curve = b.object(&["ValkyrieMagnitudinalCurve", "NSObject"], vec![("points", list)]);
@@ -839,6 +912,65 @@ mod tests {
assert!(read_set(&write(brushes.first().unwrap(), "", &pictures())).is_none());
}
+ #[test]
+ fn pressure_curves_survive_a_round_trip_straight_ones_too() {
+ use crate::brush::PressureCurve;
+ use crate::curve::Curve;
+ let mut brush = Brush { pressure_curves: Default::default(), ..Brush::round_pen() };
+ let bend = Curve::new(&[Vec2::new(0.0, 0.0), Vec2::new(0.5, 0.8), Vec2::new(1.0, 1.0)]);
+ brush.pressure_curves.set(PressureCurve::Count, Some(bend));
+ brush.pressure_curves.set(PressureCurve::HueJitter, Some(Curve::linear()));
+ let pictures =
+ Pictures { shape_png: b"s", grain_png: None, thumbnail_png: b"t", author_png: None, signature_png: None };
+ let back = read(&write(&brush, "", &pictures)).unwrap();
+ let kinds: Vec<PressureCurve> = back.pressure_curves.iter().map(|(k, _)| *k).collect();
+ assert_eq!(kinds, [PressureCurve::Count, PressureCurve::HueJitter]);
+ let count = &back.pressure_curves[0].1;
+ assert!((count[1] - Vec2::new(0.5, 0.8)).length() < 1e-5);
+ }
+
+ #[test]
+ fn a_file_without_linear_jitter_keys_gives_it_the_laterals_curve() {
+ use crate::brush::PressureCurve;
+ let mut b = Builder::new();
+ let root = b.reserve();
+ let name = b.string("Old");
+ let points = vec![b.string("{0, 0}"), b.string("{0.5, 0.9}"), b.string("{1, 1}")];
+ let list = b.array(points, true);
+ let curve = b.object(&["ValkyrieMagnitudinalCurve", "NSObject"], vec![("points", list)]);
+ b.fill(
+ &root,
+ &["SilicaBrush", "ValkyrieBrush", "NSObject"],
+ vec![("name", name), ("plotJitter", Value::Real(0.5)), ("dynamicsPressurePlotJitterCurve", curve)],
+ );
+ let mut zip = ZipWriter::new();
+ zip.add("Brush.archive", &b.finish(root));
+ let back = read(&zip.finish()).unwrap();
+ let curve = |kind| back.pressure_curves.iter().find(|(k, _)| *k == kind).map(|(_, c)| c.clone());
+ assert!(curve(PressureCurve::LateralJitter).is_some());
+ assert_eq!(curve(PressureCurve::LinearJitter), curve(PressureCurve::LateralJitter));
+ }
+
+ #[test]
+ fn a_file_without_pen_taper_keys_tapers_a_pen_as_touch() {
+ let mut b = Builder::new();
+ let root = b.reserve();
+ let name = b.string("Old");
+ b.fill(
+ &root,
+ &["SilicaBrush", "ValkyrieBrush", "NSObject"],
+ vec![("name", name), ("taperStartLength", Value::Real(0.4)), ("pencilTaperEndLength", Value::Real(0.2))],
+ );
+ let mut zip = ZipWriter::new();
+ zip.add("Brush.archive", &b.finish(root));
+ let back = read(&zip.finish()).unwrap();
+ let get = |k: &str| back.settings.iter().rev().find(|(key, _)| key == k).map(|(_, v)| *v);
+ assert_eq!(get("pen_taper_start"), Some(0.4));
+ assert_eq!(get("touch_taper_start"), Some(0.4));
+ // its own key wins
+ assert_eq!(get("pen_taper_end"), Some(0.2));
+ }
+
#[test]
fn other_files_are_not_brushes() {
assert!(read(b"nothing").is_none());
diff --git a/crates/engine/src/curve.rs b/crates/engine/src/curve.rs
index b865b36..11ca07d 100644
--- a/crates/engine/src/curve.rs
+++ b/crates/engine/src/curve.rs
@@ -1,13 +1,31 @@
//! Response curves (pressure, tilt...): a smooth curve through control points on the unit square.
+use std::sync::{Arc, OnceLock};
+
use crate::geom::Vec2;
-/// A curve `[0, 1] → [0, 1]` through control points: monotone cubic Hermite interpolation, so it
-/// passes through every point and never overshoots between monotone points.
-#[derive(Clone, Debug, PartialEq)]
+/// How many places a curve is sampled at.
+const STEPS: usize = 1024;
+
+/// A curve `[0, 1] → [0, 1]` through control points, bent as brush files' curves are: a natural
+/// cubic spline through the points (it may swing past them), held level beyond the first and the
+/// last, sampled at [`STEPS`] places and read in a straight line between them.
+#[derive(Clone)]
pub struct Curve {
points: Vec<Vec2>,
- tangents: Vec<f32>,
+ table: Arc<[f32]>,
+}
+
+impl PartialEq for Curve {
+ fn eq(&self, other: &Curve) -> bool {
+ self.points == other.points
+ }
+}
+
+impl std::fmt::Debug for Curve {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_tuple("Curve").field(&self.points).finish()
+ }
}
impl Default for Curve {
@@ -18,7 +36,10 @@ impl Default for Curve {
impl Curve {
pub fn linear() -> Curve {
- Curve::new(&[Vec2::new(0.0, 0.0), Vec2::new(1.0, 1.0)])
+ static TABLE: OnceLock<Arc<[f32]>> = OnceLock::new();
+ let points = vec![Vec2::new(0.0, 0.0), Vec2::new(1.0, 1.0)];
+ let table = TABLE.get_or_init(|| sampled(&points)).clone();
+ Curve { points, table }
}
/// Points are clamped to the unit square and sorted by x; of points sharing an x the first
@@ -32,10 +53,10 @@ impl Curve {
pts.sort_by(|a, b| a.x.total_cmp(&b.x));
pts.dedup_by(|later, earlier| (later.x - earlier.x).abs() < 1e-6);
if pts.len() < 2 {
- pts = vec![Vec2::new(0.0, 0.0), Vec2::new(1.0, 1.0)];
+ return Curve::linear();
}
- let tangents = monotone_tangents(&pts);
- Curve { points: pts, tangents }
+ let table = sampled(&pts);
+ Curve { points: pts, table }
}
pub fn points(&self) -> &[Vec2] {
@@ -43,83 +64,83 @@ impl Curve {
}
pub fn eval(&self, x: f32) -> f32 {
- let x = if x.is_finite() { x } else { 0.0 };
- let (Some(first), Some(last)) = (self.points.first(), self.points.last()) else { return x };
- if x <= first.x {
- return first.y;
- }
- if x >= last.x {
- return last.y;
- }
- // the segment [i, i + 1] holding x
- let i = self.points.partition_point(|p| p.x <= x).saturating_sub(1);
- let (Some(p0), Some(p1), Some(m0), Some(m1)) =
- (self.points.get(i), self.points.get(i + 1), self.tangents.get(i), self.tangents.get(i + 1))
- else {
- return x;
- };
- let h = p1.x - p0.x;
- if h <= 0.0 {
- return p0.y;
- }
- let t = (x - p0.x) / h;
- let (t2, t3) = (t * t, t * t * t);
- let y = (2.0 * t3 - 3.0 * t2 + 1.0) * p0.y
- + (t3 - 2.0 * t2 + t) * h * m0
- + (-2.0 * t3 + 3.0 * t2) * p1.y
- + (t3 - t2) * h * m1;
- y.clamp(0.0, 1.0)
+ let x = if x.is_finite() { x.clamp(0.0, 1.0) } else { 0.0 };
+ let f = x * (STEPS - 1) as f32;
+ let i = f.floor() as usize;
+ let at = |k: usize| self.table.get(k.min(STEPS - 1)).copied().unwrap_or(x);
+ let (a, b) = (at(i), at(i + 1));
+ a + (b - a) * (f - i as f32)
}
}
-/// Fritsch–Carlson tangents for points sorted by strictly increasing x.
-fn monotone_tangents(pts: &[Vec2]) -> Vec<f32> {
- let secants: Vec<f32> = pts
- .windows(2)
- .map(|w| match w {
- [p0, p1] => (p1.y - p0.y) / (p1.x - p0.x),
- _ => 0.0,
- })
- .collect();
- let n = pts.len();
+/// The curve through `pts` (sorted, at least two) sampled at [`STEPS`] places: the points scaled
+/// up by the steps, the spline read at each whole step, and that taken over one step less (so a
+/// curve ending below the top comes out a little higher), held to 0..1.
+fn sampled(pts: &[Vec2]) -> Arc<[f32]> {
+ let n = STEPS as f32;
+ let knots: Vec<Vec2> = pts.iter().map(|p| *p * n).collect();
+ let bends = second_derivatives(&knots);
+ (0..STEPS).map(|i| (spline(&knots, &bends, i as f32) / (n - 1.0)).clamp(0.0, 1.0)).collect::<Vec<f32>>().into()
+}
+
+/// A natural cubic spline's second derivatives at `knots` (none at either end).
+fn second_derivatives(knots: &[Vec2]) -> Vec<f32> {
+ let n = knots.len();
let mut m = vec![0.0f32; n];
- for (i, slot) in m.iter_mut().enumerate() {
- let before = i.checked_sub(1).and_then(|j| secants.get(j)).copied();
- let after = secants.get(i).copied();
- *slot = match (before, after) {
- (Some(a), Some(b)) if a * b > 0.0 => (a + b) / 2.0,
- (Some(_), Some(_)) => 0.0,
- (Some(a), None) => a,
- (None, Some(b)) => b,
- (None, None) => 0.0,
- };
- }
- for (i, &d) in secants.iter().enumerate() {
- if d == 0.0 {
- if let Some(v) = m.get_mut(i) {
- *v = 0.0;
- }
- if let Some(v) = m.get_mut(i + 1) {
- *v = 0.0;
- }
- continue;
+ if n < 3 {
+ return m;
+ }
+ // the tridiagonal system for the inner knots, solved forward then back
+ let mut diag = vec![0.0f32; n];
+ let mut rhs = vec![0.0f32; n];
+ for i in 1..n - 1 {
+ let (Some(p0), Some(p1), Some(p2)) = (knots.get(i - 1), knots.get(i), knots.get(i + 1)) else { continue };
+ let (h0, h1) = (p1.x - p0.x, p2.x - p1.x);
+ let mut d = 2.0 * (h0 + h1);
+ let mut r = 6.0 * ((p2.y - p1.y) / h1 - (p1.y - p0.y) / h0);
+ if i > 1 {
+ let w = h0 / diag.get(i - 1).copied().unwrap_or(1.0);
+ d -= w * h0;
+ r -= w * rhs.get(i - 1).copied().unwrap_or(0.0);
}
- let (Some(&mi), Some(&mj)) = (m.get(i), m.get(i + 1)) else { continue };
- let (a, b) = (mi / d, mj / d);
- let s = a * a + b * b;
- if s > 9.0 {
- let tau = 3.0 / s.sqrt();
- if let Some(v) = m.get_mut(i) {
- *v = tau * a * d;
- }
- if let Some(v) = m.get_mut(i + 1) {
- *v = tau * b * d;
- }
+ if let (Some(dv), Some(rv)) = (diag.get_mut(i), rhs.get_mut(i)) {
+ *dv = d;
+ *rv = r;
+ }
+ }
+ for i in (1..n - 1).rev() {
+ let (Some(p1), Some(p2)) = (knots.get(i), knots.get(i + 1)) else { continue };
+ let h1 = p2.x - p1.x;
+ let next = if i + 1 < n - 1 { m.get(i + 1).copied().unwrap_or(0.0) } else { 0.0 };
+ let d = diag.get(i).copied().unwrap_or(1.0);
+ if let Some(v) = m.get_mut(i) {
+ *v = (rhs.get(i).copied().unwrap_or(0.0) - h1 * next) / d;
}
}
m
}
+/// The spline through `knots` with second derivatives `bends` at `x`, level beyond its ends.
+fn spline(knots: &[Vec2], bends: &[f32], x: f32) -> f32 {
+ let (Some(first), Some(last)) = (knots.first(), knots.last()) else { return x };
+ if x <= first.x {
+ return first.y;
+ }
+ if x >= last.x {
+ return last.y;
+ }
+ let i = knots.partition_point(|p| p.x <= x).saturating_sub(1);
+ let (Some(p0), Some(p1)) = (knots.get(i), knots.get(i + 1)) else { return x };
+ let (m0, m1) = (bends.get(i).copied().unwrap_or(0.0), bends.get(i + 1).copied().unwrap_or(0.0));
+ let h = p1.x - p0.x;
+ if h <= 0.0 {
+ return p0.y;
+ }
+ let a = (p1.x - x) / h;
+ let b = 1.0 - a;
+ a * p0.y + b * p1.y + ((a * a * a - a) * m0 + (b * b * b - b) * m1) * h * h / 6.0
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -127,23 +148,33 @@ mod tests {
#[test]
fn linear_is_identity() {
let c = Curve::linear();
- for i in 0..=10 {
- let x = i as f32 / 10.0;
+ for i in 0..=100 {
+ let x = i as f32 / 100.0;
assert!((c.eval(x) - x).abs() < 1e-5);
}
+ assert_eq!(Curve::new(&[Vec2::new(0.0, 0.0), Vec2::new(1.0, 1.0)]), c);
}
#[test]
- fn passes_through_points_and_stays_monotone() {
+ fn passes_near_its_points_as_a_natural_spline() {
let c = Curve::new(&[Vec2::new(0.0, 0.0), Vec2::new(0.3, 0.6), Vec2::new(0.7, 0.7), Vec2::new(1.0, 1.0)]);
- assert!((c.eval(0.3) - 0.6).abs() < 1e-5);
- assert!((c.eval(0.7) - 0.7).abs() < 1e-5);
- let mut prev = 0.0;
- for i in 0..=100 {
- let y = c.eval(i as f32 / 100.0);
- assert!(y + 1e-6 >= prev, "not monotone at {i}");
- prev = y;
- }
+ assert!((c.eval(0.3) - 0.6).abs() < 2e-3, "{}", c.eval(0.3));
+ assert!((c.eval(0.7) - 0.7).abs() < 2e-3, "{}", c.eval(0.7));
+ // a natural spline: straight at its ends, so its middle swings above the points' line
+ let mid = c.eval(0.5);
+ assert!(mid > 0.65 + 1e-3, "{mid}");
+ // the spline read by hand at x = 0.5 (second derivatives of the system above)
+ let knots: Vec<Vec2> = c.points().iter().map(|p| *p * 1024.0).collect();
+ let by_hand = spline(&knots, &second_derivatives(&knots), 0.5 * 1023.0) / 1023.0;
+ assert!((mid - by_hand).abs() < 1e-4);
+ }
+
+ #[test]
+ fn a_curve_ending_below_the_top_is_held_level_and_a_little_raised() {
+ let c = Curve::new(&[Vec2::new(0.0, 0.2), Vec2::new(0.6, 0.8)]);
+ // past its last point it stays at that point's height, over one step less
+ assert!((c.eval(0.9) - 0.8 * 1024.0 / 1023.0).abs() < 1e-5);
+ assert!((c.eval(0.0) - 0.2 * 1024.0 / 1023.0).abs() < 1e-5);
}
#[test]
diff --git a/crates/engine/src/stroke.rs b/crates/engine/src/stroke.rs
index d5abfb8..eb80dd4 100644
--- a/crates/engine/src/stroke.rs
+++ b/crates/engine/src/stroke.rs
@@ -2,7 +2,7 @@
//! response, spacing, the shape's placement (rotation, scatter, count, jitter, roundness) and
//! taper.
-use crate::brush::{Brush, FLOW_POWER, Rendering, Taper, Tilt};
+use crate::brush::{Brush, CLASSIC_TAPER_SPAN, FLOW_POWER, PressureCurve, Rendering, TAPER_TIME_MS, Taper, Tilt};
use crate::curve::Curve;
use crate::geom::{IRect, Vec2};
use crate::input::{Pointer, Sample};
@@ -32,8 +32,8 @@ pub struct Stamp {
pub grain_bleed: f32,
/// The shape mirrored across its own vertical and horizontal axes.
pub flip: [bool; 2],
- /// The colour shifted: hue (turns), saturation and lightness (each −1..1).
- pub shift: [f32; 3],
+ /// How its colour moves from the brush's.
+ pub tint: Tint,
/// How much of the secondary colour it paints with, 0..1.
pub secondary: f32,
/// A moving grain's depth and tile size here, as multiples of the brush's.
@@ -50,6 +50,9 @@ pub struct Stamp {
/// How much of the brush's wet-mix attack this stamp has: the pressure (as opacity follows
/// it), as far as the attack's tilt switch lets it, 0..1.
pub attack: f32,
+ /// The wet mix's grade, blur, blur jitter and wetness jitter as this stamp's pressure scales
+ /// them (the brush's own pressure curves; 1 each without them).
+ pub wet: [f32; 4],
}
impl Stamp {
@@ -65,7 +68,7 @@ impl Stamp {
grain_press: 1.0,
grain_bleed: 0.0,
flip: [false; 2],
- shift: [0.0; 3],
+ tint: Tint::NONE,
secondary: 0.0,
grain_depth: 1.0,
grain_size: 1.0,
@@ -73,12 +76,43 @@ impl Stamp {
taper: 1.0,
transfer: 1.0,
attack: 1.0,
+ wet: [1.0; 4],
}
}
/// Pixels the stamp can touch: its square shape at any rotation.
pub fn bounds(&self) -> IRect {
- IRect::around(self.center, self.radius * std::f32::consts::SQRT_2)
+ IRect::around(self.center, self.radius * self.roundness.clamp(1.0, MOST_ROUNDNESS) * std::f32::consts::SQRT_2)
+ }
+}
+
+/// How a stamp's colour moves from the brush's, in hue, saturation and brightness: the hue
+/// turned by `hue` (turns), the saturation and the brightness each taken to `x keep + add`
+/// (`[keep, add]`), then held to 0..1.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct Tint {
+ pub hue: f32,
+ pub saturation: [f32; 2],
+ pub brightness: [f32; 2],
+}
+
+impl Tint {
+ pub const NONE: Tint = Tint { hue: 0.0, saturation: [1.0, 0.0], brightness: [1.0, 0.0] };
+
+ /// This and `other` together: what each moves the colour by, added.
+ pub fn plus(self, other: Tint) -> Tint {
+ let [sk, sa] = self.saturation;
+ let [ok, oa] = other.saturation;
+ let [bk, ba] = self.brightness;
+ let [pk, pa] = other.brightness;
+ Tint { hue: self.hue + other.hue, saturation: [sk + ok - 1.0, sa + oa], brightness: [bk + pk - 1.0, ba + pa] }
+ }
+
+ /// The hue, saturation and brightness moved on by as much again, whatever the colour.
+ fn shifted(self, [hue, saturation, brightness]: [f32; 3]) -> Tint {
+ let [sk, sa] = self.saturation;
+ let [bk, ba] = self.brightness;
+ Tint { hue: self.hue + hue, saturation: [sk, sa + saturation], brightness: [bk, ba + brightness] }
}
}
@@ -92,14 +126,22 @@ struct Placed {
angle: f32,
roundness: f32,
flip: [bool; 2],
- shift: [f32; 3],
+ tint: Tint,
secondary: f32,
grain_depth: f32,
grain_size: f32,
grain_press: f32,
+ /// How far its moving grain rolls along with the stroke (see [`Extras::grain_movement`]).
+ grain_movement: f32,
gradation: f32,
transfer: f32,
attack: f32,
+ wet: [f32; 4],
+ /// The pressure as the size, opacity, bleed and roundness took it.
+ pressed: [f32; 4],
+ /// How much of the stamp's roundness is the drawn shape's, which the pressure squeezes (the
+ /// rest is what leaning adds).
+ drawn_share: f32,
}
#[derive(Clone, Copy, Debug)]
@@ -145,8 +187,13 @@ const MOST_AVERAGED: usize = 32;
/// expression, how much of the way back to the pen it comes.
const MOTION_FILTER_MOST: f32 = 0.9;
const EXPRESSION_MOST: f32 = 0.5;
-/// A lateral or linear jitter of 1 moves a stamp up to this many diameters.
-const JITTER_REACH: f32 = 2.0;
+/// The most a stamp's height may be of its width (a roundness jitter can make it taller than
+/// wide).
+pub const MOST_ROUNDNESS: f32 = 20.0;
+
+/// The lateral and linear jitter as brush files keep them: the control to the power 2.2, times
+/// this; each moves a stamp up to that many times half its diagonal (plus a pixel).
+const JITTER_FILE_SCALE: f32 = 3.0;
/// A fall off of 1 fades a stroke out over this many diameters.
const FALLOFF_SPAN: f32 = 30.0;
@@ -160,7 +207,8 @@ struct Extras {
count_jitter: f32,
pressure_roundness: f32,
tilt_roundness: f32,
- roundness_jitter: f32,
+ /// The roundness jitter along the stamp's height and across its width.
+ roundness_jitter: [f32; 2],
speed_size: f32,
speed_opacity: f32,
speed_spacing: f32,
@@ -192,6 +240,10 @@ struct Extras {
/// How blunt the pen's and the finger's taper ends are, 0 (sharp) to 1.
pen_taper_tip: f32,
touch_taper_tip: f32,
+ /// How far a pen's pressure fades into its tapers, 0..1.
+ taper_pressure: f32,
+ /// A pen's stroke shows its end tapered as it is drawn.
+ tip_animation: bool,
/// The secondary colour mixed in per stamp and per stroke (jitter, 0..1), and by light
/// pressure and by leaning (−1..1).
stamp_secondary: f32,
@@ -258,7 +310,7 @@ impl Extras {
count_jitter: unit("count_jitter"),
pressure_roundness: both("pressure_roundness"),
tilt_roundness: both("tilt_roundness"),
- roundness_jitter: unit("roundness_jitter_y").max(unit("roundness_jitter_x")),
+ roundness_jitter: [unit("roundness_jitter_y"), unit("roundness_jitter_x")],
speed_size: both("speed_size"),
speed_opacity: both("speed_opacity"),
speed_spacing: unit("speed_spacing"),
@@ -287,6 +339,8 @@ impl Extras {
grain_zoom: unit("grain_zoom"),
pen_taper_tip: unit("pen_taper_tip"),
touch_taper_tip: unit("touch_taper_tip"),
+ taper_pressure: unit("pen_taper_pressure"),
+ tip_animation: b.setting("pen_tip_animation") >= 0.5,
stamp_secondary: unit("stamp_secondary"),
stroke_secondary: unit("stroke_secondary"),
pressure_secondary: both("pressure_secondary"),
@@ -327,10 +381,13 @@ impl Extras {
/// Streamline is tuned for input at this interval; other rates are scaled to match.
const REFERENCE_INTERVAL_MS: f64 = 1000.0 / 120.0;
-/// How fast a stroke starts is read over its first this many milliseconds, and how fast it ends
-/// over its last (for the tapers that last a time).
-const PACE_WINDOW_MS: f64 = 20.0;
-const END_PACE_WINDOW_MS: f64 = 60.0;
+/// When a classic taper ends, the stroke runs on past the last point by this many steps (touch,
+/// pen), each this much of the one before and turning this much more than it, and the end taper
+/// comes to its tip over them.
+const RUN_ON_TOUCH: usize = 4;
+const RUN_ON_PEN: usize = 1;
+const RUN_ON_SHRINK: f32 = 0.66;
+const RUN_ON_TURN: f32 = 1.125;
/// How far (canvas pixels) offset jitter may move a stroke's start in a moving grain.
const GRAIN_JITTER_SPAN: f32 = 1024.0;
/// Stamps a stroke may hold (a guard against runaway input, far above any real stroke).
@@ -392,9 +449,11 @@ pub struct StrokeBuilder {
pad: Option<bool>,
gap_jitter: f32,
/// The whole stroke's colour shift, drawn once.
- stroke_shift: [f32; 3],
+ stroke_shift: Tint,
/// The stroke's share of the secondary colour, picked as it starts.
stroke_secondary: f32,
+ /// The random turn every stamp of the stroke takes (a randomised shape), picked as it starts.
+ stroke_turn: f32,
/// How far the canvas is turned on screen, for a brush whose shapes keep to the screen.
screen_turn: f32,
/// Screen points a canvas pixel spans, for the speed dynamics.
@@ -404,12 +463,16 @@ pub struct StrokeBuilder {
filtered: Option<Vec2>,
/// Where in a moving grain the stroke starts.
grain_start: Vec2,
- /// How far the input has gone (canvas pixels, as it came) and when: its latest stretch, the
- /// time it started and how fast it went at first (for the tapers that last a time).
- trail: std::collections::VecDeque<(f64, f32)>,
+ /// When each sample came (milliseconds, always later than the one before) and how far the
+ /// input had gone by then (canvas pixels, as it came), for the tapers that last a time.
+ history: Vec<(f64, f32)>,
input_length: f32,
- started_ms: Option<f64>,
- start_pace: Option<f32>,
+ /// The two input points before the last, for running a classic taper's end on past it.
+ before_last: [Option<Vec2>; 2],
+ /// How far a finished stroke ran on past its last point (see [`StrokeBuilder::run_on`]).
+ ran_on: Option<f32>,
+ /// How many stamps have been drawn for good, for a stroke shown with its tip.
+ kept: usize,
}
/// Smoothing and pressure set for every stroke, whatever the brush, on top of the brush's own.
@@ -538,17 +601,19 @@ impl StrokeBuilder {
exact: false,
pad: None,
gap_jitter: 1.0,
- stroke_shift: [0.0; 3],
+ stroke_shift: Tint::NONE,
stroke_secondary: 0.0,
+ stroke_turn: 0.0,
screen_turn: 0.0,
points_per_pixel: 1.0,
input: InputSettings::default(),
filtered: None,
grain_start: Vec2::ZERO,
- trail: std::collections::VecDeque::new(),
+ history: Vec::new(),
input_length: 0.0,
- started_ms: None,
- start_pace: None,
+ before_last: [None; 2],
+ ran_on: None,
+ kept: 0,
}
.reading_extras()
}
@@ -563,19 +628,23 @@ impl StrokeBuilder {
if self.extras.grain_offset_jitter {
self.grain_start = Vec2::new(self.random.next(), self.random.next()) * GRAIN_JITTER_SPAN;
}
+ if self.brush.shape.randomise {
+ self.stroke_turn = self.random.next() * std::f32::consts::TAU;
+ }
self
}
- /// A random colour shift by `jitter` (hue, saturation, lightness, darkness).
- fn color_jitter(&mut self, [hue, saturation, lightness, darkness]: [f32; 4]) -> [f32; 3] {
+ /// A random colour change by `jitter` (hue, saturation, lightness, darkness): the hue turned
+ /// either way, the saturation drawn toward a random one, the colour lightened by a share of
+ /// what is left to white and darkened by a share of what is left to black.
+ fn color_jitter(&mut self, [hue, saturation, lightness, darkness]: [f32; 4]) -> Tint {
if hue == 0.0 && saturation == 0.0 && lightness == 0.0 && darkness == 0.0 {
- return [0.0; 3];
+ return Tint::NONE;
}
- [
- (self.random.next() * 2.0 - 1.0) * hue * 0.5,
- -self.random.next() * saturation,
- self.random.next() * lightness - self.random.next() * darkness,
- ]
+ let turn = (self.random.next() - 0.5) * hue;
+ let toward = self.random.next() * saturation;
+ let (lighter, darker) = (self.random.next() * lightness, self.random.next() * darkness);
+ Tint { hue: turn, saturation: [1.0 - saturation, toward], brightness: [1.0 - lighter - darker, lighter] }
}
pub fn pointer(&self) -> Pointer {
@@ -619,14 +688,51 @@ impl StrokeBuilder {
self.clone().add(samples)
}
+ /// Whether the stroke shows its end tapered as it is drawn: a pen's, with a taper that lasts a
+ /// time and the tip animation on.
+ pub fn shows_tip(&self) -> bool {
+ self.pointer.has_pressure() && self.extras.tip_animation && !self.classic() && self.taper().end > 0.0
+ }
+
+ /// Adds samples to a stroke shown with its tip (see [`StrokeBuilder::shows_tip`]): returns
+ /// the stamps to draw for good now, those the end taper no longer reaches, and the tip, the
+ /// stamps after them as they would be drawn were the stroke to end here.
+ pub fn add_tipped(&mut self, samples: &[Sample]) -> (Vec<Stamp>, Vec<Stamp>) {
+ self.add(samples);
+ let start = self.start_span();
+ let reach = self.length - self.end_span(0.0);
+ let to = self.placed.iter().position(|p| p.distance >= reach).unwrap_or(self.placed.len()).max(self.kept);
+ let kept = self.placed.get(self.kept..to).unwrap_or_default();
+ let kept = kept.iter().map(|p| self.finish_stamp(p, start, None)).collect();
+ self.kept = to;
+ (kept, self.tip_from(to))
+ }
+
+ /// The tip as it would be with `samples` added (for drawing predicted input), the stroke
+ /// left as it is.
+ pub fn preview_tip(&self, samples: &[Sample]) -> Vec<Stamp> {
+ let mut ahead = self.clone();
+ ahead.add(samples);
+ ahead.tip_from(self.kept)
+ }
+
+ /// The stamps from `from` on as they would be drawn were the stroke to end here.
+ fn tip_from(&self, from: usize) -> Vec<Stamp> {
+ let (start, end, length) = (self.start_span(), self.end_span(0.0), self.length);
+ let tip = self.placed.get(from..).unwrap_or_default();
+ tip.iter().map(|p| self.finish_stamp(p, start, Some((length, end)))).collect()
+ }
+
/// Every stamp so far as currently drawn (no end taper yet).
pub fn stamps(&self) -> Vec<Stamp> {
- self.placed.iter().map(|p| self.finish_stamp(p, None)).collect()
+ let start = self.start_span();
+ self.placed.iter().map(|p| self.finish_stamp(p, start, None)).collect()
}
/// Ends the stroke: walks on to where the pen lifted and applies the end taper. Returns all of
/// the stroke's stamps, as they should finally be drawn.
pub fn finish(&mut self) -> Vec<Stamp> {
+ let mut run_on = 0.0;
if let (Some(last), Some(head)) = (self.last_sample, self.head) {
let to = PathPoint {
pos: last.pos,
@@ -638,9 +744,15 @@ impl StrokeBuilder {
};
let mut ignored = Vec::new();
self.walk_to(to, &mut ignored);
+ run_on = match self.ran_on {
+ Some(r) => r,
+ None => self.run_on(to, &mut ignored),
+ };
}
+ self.ran_on = Some(run_on);
let length = self.length;
- let stamps: Vec<Stamp> = self.placed.iter().map(|p| self.finish_stamp(p, Some(length))).collect();
+ let (start, end) = (self.start_span(), self.end_span(run_on));
+ let stamps: Vec<Stamp> = self.placed.iter().map(|p| self.finish_stamp(p, start, Some((length, end)))).collect();
self.bounds = stamps.iter().fold(IRect::EMPTY, |b, s| b.union(s.bounds()));
stamps
}
@@ -709,43 +821,97 @@ impl StrokeBuilder {
_ => target,
};
self.smoothed = Some(smoothed);
- self.keep_pace(s);
+ self.keep_time(s);
+ if let Some(last) = self.last_sample {
+ self.before_last = [self.before_last[1], Some(last.pos)];
+ }
self.last_sample = Some(s);
self.walk_to(smoothed, out);
}
- /// Notes how far and how fast the input has come with `s`.
- fn keep_pace(&mut self, s: Sample) {
+ /// Notes how far the input has come with `s`, and when (samples without times of their own
+ /// count as coming at the usual rate).
+ fn keep_time(&mut self, s: Sample) {
self.input_length += self.last_sample.map_or(0.0, |l| s.pos.distance(l.pos));
- let started = *self.started_ms.get_or_insert(s.time_ms);
- self.trail.push_back((s.time_ms, self.input_length));
- while self.trail.len() > 2 && self.trail.get(1).is_some_and(|&(t, _)| s.time_ms - t >= END_PACE_WINDOW_MS) {
- self.trail.pop_front();
- }
- if self.start_pace.is_none() && s.time_ms - started >= PACE_WINDOW_MS {
- self.start_pace = Some(self.input_length / (s.time_ms - started) as f32);
- }
+ let at = match self.history.last() {
+ Some(&(before, _)) if s.time_ms <= before => before + REFERENCE_INTERVAL_MS,
+ _ => s.time_ms,
+ };
+ self.history.push((at, self.input_length));
}
- /// How fast the stroke started and how fast it is going now (lately), canvas pixels a
- /// millisecond; samples without times count as coming at the usual rate.
- fn paces(&self) -> (f32, f32) {
- let pace = |gone: f32, ms: f64, samples: usize| {
- let ms = if ms >= 1.0 { ms } else { samples.saturating_sub(1) as f64 * REFERENCE_INTERVAL_MS };
- if ms > 0.0 { gone / ms as f32 } else { 0.0 }
- };
- let now = match (self.trail.front(), self.trail.back()) {
- (Some(&(t0, l0)), Some(&(t1, l1))) => pace(l1 - l0, t1 - t0, self.trail.len()),
- _ => 0.0,
- };
- let started = self.start_pace.unwrap_or_else(|| {
- let ms = match (self.started_ms, self.last_sample) {
- (Some(t0), Some(last)) => last.time_ms - t0,
- _ => 0.0,
- };
- pace(self.input_length, ms, self.segments as usize)
+ /// The input's length (as it came) put on the path the stamps follow, which smoothing
+ /// shortens.
+ fn on_path(&self, input: f32) -> f32 {
+ if self.input_length > 0.0 { input * (self.length / self.input_length).min(1.0) } else { input }
+ }
+
+ fn classic(&self) -> bool {
+ self.brush.extra.get("classic_taper").is_some_and(|&v| v >= 0.5)
+ }
+
+ /// How far along the path the start taper grows to full (0: none): the classic one over its
+ /// length in canvas pixels; the newer one over the input up to the first point past its time.
+ fn start_span(&self) -> f32 {
+ let taper = self.taper();
+ if taper.start <= 0.0 {
+ return 0.0;
+ }
+ if self.classic() {
+ return taper.start * CLASSIC_TAPER_SPAN;
+ }
+ let Some(&(t0, _)) = self.history.first() else { return 0.0 };
+ let time = f64::from(taper.start) * TAPER_TIME_MS;
+ let input = self.history.iter().find(|(t, _)| t - t0 > time).map_or(self.input_length, |&(_, l)| l);
+ self.on_path(input)
+ }
+
+ /// How far back from the end the end taper starts (0: none): the classic one over the run-on
+ /// (`run_on` canvas pixels) up to its length; the newer one over the input since the last
+ /// point before its time.
+ fn end_span(&self, run_on: f32) -> f32 {
+ let taper = self.taper();
+ if taper.end <= 0.0 {
+ return 0.0;
+ }
+ if self.classic() {
+ return run_on.min(taper.end * CLASSIC_TAPER_SPAN);
+ }
+ let Some(&(last, total)) = self.history.last() else { return 0.0 };
+ let time = f64::from(taper.end) * TAPER_TIME_MS;
+ let first = self.history.iter().position(|(t, _)| *t >= last - time).unwrap_or(0);
+ let before = first.checked_sub(1).and_then(|i| self.history.get(i)).map_or(0.0, |&(_, l)| l);
+ self.on_path(total - before)
+ }
+
+ /// A classic taper's end runs the stroke on past `last` (where the input ended) as it was
+ /// going, a few shrinking steps that turn on as it turned; how far it went (canvas pixels).
+ fn run_on(&mut self, last: PathPoint, out: &mut Vec<Stamp>) -> f32 {
+ let (Some(before), Some(last_input)) = (self.before_last[1], self.last_sample) else { return 0.0 };
+ if !self.classic() || self.taper().end <= 0.0 {
+ return 0.0;
+ }
+ let step = last_input.pos - before;
+ let mut reach = step.length();
+ if reach.is_nan() || reach <= 1e-3 {
+ return 0.0;
+ }
+ let mut heading = step.y.atan2(step.x);
+ let mut turn = self.before_last[0].map_or(0.0, |b| {
+ let earlier = before - b;
+ let d = heading - earlier.y.atan2(earlier.x);
+ (d + std::f32::consts::PI).rem_euclid(std::f32::consts::TAU) - std::f32::consts::PI
});
- (started, now)
+ let steps = if self.pointer.has_pressure() { RUN_ON_PEN } else { RUN_ON_TOUCH };
+ let (start, mut at) = (self.length, last);
+ for _ in 0..steps {
+ reach *= RUN_ON_SHRINK;
+ turn *= RUN_ON_TURN;
+ heading += turn;
+ at = PathPoint { pos: at.pos + Vec2::new(heading.cos(), heading.sin()) * reach, ..at };
+ self.walk_to(at, out);
+ }
+ self.length - start
}
/// Walks the path from its head to `to`, placing stamps at the brush's spacing.
@@ -897,6 +1063,7 @@ impl StrokeBuilder {
fn place(&mut self, p: PathPoint, distance: f32, out: &mut Vec<Stamp>) {
let x = self.extras;
+ let start_span = self.start_span();
let sw = x.tilt_switches;
if x.spacing_jitter > 0.0 {
self.gap_jitter = (1.0 + x.spacing_jitter * (self.random.next() * 2.0 - 1.0)).max(0.05);
@@ -923,15 +1090,46 @@ impl StrokeBuilder {
if self.brush.rendering == Rendering::Gradual && !self.brush.mixes_wet() {
alpha = StrokeBuilder::gradual(alpha, diameter / self.step(p));
}
+ use PressureCurve as PC;
let shape = self.brush.shape.clone();
- let count = shape.count.clamp(1, 16);
- // the count tilt: as many beyond the first as the lean lets through
- let count = if sw.count.is_some() {
- 1 + ((count - 1) as f32 * self.switched(p, sw.count)).floor() as u32
- } else {
- count
- };
- let dropped = (self.random.next() * x.count_jitter * count as f32) as u32;
+ // the brush's own pressure curves for its other controls, at the stamp's pressure (a
+ // finger's is full): each control scaled by its curve, or left as it is without one
+ let pressure = p.soft[2].clamp(0.0, 1.0);
+ let curves = &self.brush.pressure_curves;
+ let by = |k: PressureCurve| curves.at(k, pressure);
+ let [count_by, count_jitter_by, lateral_by, linear_by, size_jitter_by, opacity_jitter_by, scatter_by] = [
+ PC::Count,
+ PC::CountJitter,
+ PC::LateralJitter,
+ PC::LinearJitter,
+ PC::SizeJitter,
+ PC::OpacityJitter,
+ PC::Scatter,
+ ]
+ .map(by);
+ let [roundness_y_by, roundness_x_by, movement_by, grain_scale_by, zoom_by, depth_by, depth_jitter_by] = [
+ PC::RoundnessJitterY,
+ PC::RoundnessJitterX,
+ PC::GrainMovement,
+ PC::GrainScale,
+ PC::GrainZoom,
+ PC::GrainDepth,
+ PC::GrainDepthJitter,
+ ]
+ .map(by);
+ let wet = [PC::WetGrade, PC::WetBlur, PC::WetBlurJitter, PC::WetnessJitter].map(by);
+ let color_jitter_by =
+ [PC::HueJitter, PC::SaturationJitter, PC::LightnessJitter, PC::DarknessJitter, PC::SecondaryJitter];
+ let color_has_curve = color_jitter_by.map(|k| curves.get(k).is_some());
+ let color_jitter_by = color_jitter_by.map(by);
+ // the colour moves with the pressure as its curves say (without one, as far as at full)
+ let color_by = [PC::Hue, PC::Saturation, PC::Brightness, PC::Secondary].map(by);
+ // as many beyond the first as the count tilt, the count's own curve and its jitter let
+ // through, rounded down once
+ let leaning = if sw.count.is_some() { self.switched(p, sw.count) } else { 1.0 };
+ let beyond = (shape.count.clamp(1, 16) - 1) as f32 * leaning * count_by;
+ let beyond = beyond * (1.0 - self.random.next() * x.count_jitter * count_jitter_by);
+ let count = 1 + beyond.clamp(0.0, 15.0).floor() as u32;
let (along, across) = (
Vec2::new(self.direction.cos(), self.direction.sin()),
Vec2::new(-self.direction.sin(), self.direction.cos()),
@@ -940,16 +1138,31 @@ impl StrokeBuilder {
// takes it from its upright roundness towards its leaning one
let grown = self.tilt_growth(p);
let drawn = (diameter - grown).max(1e-3);
- let shaped =
- shape.roundness.clamp(0.05, 1.0) * (1.0 - x.pressure_roundness * (1.0 - p.soft[3].clamp(0.0, 1.0)));
+ let drawn_share = drawn / (drawn + grown);
let leant = self.leaning(p, x.tilt_angles.roundness);
let tilted = x.tilt_roundness_max * (1.0 - leant) + (1.0 - x.tilt_roundness) * leant;
- let base_roundness = (drawn * shaped + grown) / (drawn + grown) * tilted;
+ let base_roundness = self.pressed_roundness(drawn_share, p.soft[3]) * tilted;
+ // the jitter reaches half the stamp's diagonal (its square as round as it is here), and a
+ // pixel more
+ let half = self.square_at(p) * 0.5;
+ let jitter_reach = half * (1.0 + base_roundness * base_roundness).sqrt() + 1.0;
// leaning moves the stamps toward the pen's cap, by up to their radius
let cap = self.toward_cap(p) * (diameter * 0.5);
- let jitter_lateral = x.jitter_lateral * self.switched(p, sw.jitter_lateral);
- let jitter_linear = x.jitter_linear * self.switched(p, sw.jitter_linear);
+ let file = |c: f32| JITTER_FILE_SCALE * c.powf(2.2);
+ let jitter_lateral = file(x.jitter_lateral) * self.switched(p, sw.jitter_lateral) * lateral_by;
+ let jitter_linear = file(x.jitter_linear) * self.switched(p, sw.jitter_linear) * linear_by;
+ // a colour jitter's tilt switch drives it by the lean in place of the pressure, and with a
+ // curve of its own the pressure's share comes on top
let color_tilt = sw.color.map(|theta| self.switched(p, theta));
+ let (mut color_first, mut color_more) = (color_jitter_by, [0.0f32; 5]);
+ for ((((first, more), tilt), on), has_curve) in
+ color_first.iter_mut().zip(color_more.iter_mut()).zip(color_tilt).zip(sw.color).zip(color_has_curve)
+ {
+ if on.is_some() {
+ *more = if has_curve { *first } else { 0.0 };
+ *first = tilt;
+ }
+ }
// the wet attack follows the pressure, and the lean when its switch is on (a finger as a
// pen lying flat)
let attack_tilt = match sw.attack {
@@ -958,17 +1171,20 @@ impl StrokeBuilder {
Some(theta) => Tilt::reach(std::f32::consts::FRAC_PI_2, theta),
};
let attack = (p.soft[1].clamp(0.0, 1.0) * attack_tilt).clamp(0.0, 1.0);
- let [hue_tilt, saturation_tilt, lightness_tilt, darkness_tilt, secondary_tilt] = color_tilt;
- for _ in 0..(count - dropped.min(count - 1)) {
- let size = 1.0 - shape.size_jitter.clamp(0.0, 1.0) * self.random.next();
- let fade = 1.0 - shape.opacity_jitter.clamp(0.0, 1.0) * self.random.next();
+ let [hue_by, saturation_by, lightness_by, darkness_by, secondary_by] = color_first;
+ let [hue_more, saturation_more, lightness_more, darkness_more, secondary_more] = color_more;
+ for _ in 0..count {
+ let size = 1.0 - shape.size_jitter.clamp(0.0, 1.0) * size_jitter_by * self.random.next();
+ let fade = 1.0 - shape.opacity_jitter.clamp(0.0, 1.0) * opacity_jitter_by * self.random.next();
let mut center = p.pos + cap;
- if x.jitter_lateral > 0.0 {
- center =
- center + across * ((self.random.next() * 2.0 - 1.0) * jitter_lateral * JITTER_REACH * diameter);
- }
- if x.jitter_linear > 0.0 {
- center = center + along * ((self.random.next() * 2.0 - 1.0) * jitter_linear * JITTER_REACH * diameter);
+ // one random point a stamp: as far as a share of the reach, in a random direction, the
+ // reach across and along the stroke each its own
+ if x.jitter_lateral > 0.0 || x.jitter_linear > 0.0 {
+ let far = self.random.next();
+ let towards = (self.random.next() * 2.0 - 1.0) * std::f32::consts::PI;
+ center = center
+ + across * (far * towards.sin() * jitter_lateral * jitter_reach)
+ + along * (far * towards.cos() * jitter_linear * jitter_reach);
}
if shape.throw > 0.0 {
let a = self.random.next() * std::f32::consts::TAU;
@@ -979,38 +1195,55 @@ impl StrokeBuilder {
if shape.follow_azimuth {
angle += p.azimuth;
}
- if shape.randomise {
- angle += self.random.next() * std::f32::consts::TAU;
- }
+ angle += self.stroke_turn;
if shape.scatter > 0.0 {
- angle += (self.random.next() * 2.0 - 1.0) * shape.scatter * std::f32::consts::PI;
+ angle += (self.random.next() * 2.0 - 1.0) * shape.scatter * scatter_by * std::f32::consts::PI;
}
- let roundness = (base_roundness * (1.0 - x.roundness_jitter * self.random.next())).clamp(0.05, 1.0);
+ // the roundness jitter squeezes the width and the height apart, and the stamp is scaled
+ // back so the larger of them stays whole
+ let [jitter_y, jitter_x] = x.roundness_jitter;
+ let squeezed = |jitter: f32, rng: &mut Random| if jitter > 0.0 { 1.0 - jitter * rng.next() } else { 1.0 };
+ let wide = squeezed(jitter_x * roundness_x_by, &mut self.random);
+ let tall = squeezed(jitter_y * roundness_y_by, &mut self.random);
+ let most = wide.max(tall).max(1e-3);
+ let (wide, tall) = ((wide / most).max(0.05), tall / most);
+ let roundness = (base_roundness * tall / wide).clamp(0.05, MOST_ROUNDNESS);
let flip = [x.flip_x && self.random.next() < 0.5, x.flip_y && self.random.next() < 0.5];
let [h, s, l, d] = x.stamp_color;
- let stamp_shift =
- self.color_jitter([h * hue_tilt, s * saturation_tilt, l * lightness_tilt, d * darkness_tilt]);
- // light pressure and leaning shift the colour as far as their controls say
+ let mut stamp_tint = self.color_jitter([h * hue_by, s * saturation_by, l * lightness_by, d * darkness_by]);
+ let more = [h * hue_more, s * saturation_more, l * lightness_more, d * darkness_more];
+ if more.iter().any(|&m| m > 0.0) {
+ stamp_tint = stamp_tint.plus(self.color_jitter(more));
+ }
+ // pressure and leaning move the colour on as far as their controls say
let lean = x.tilt_angles.color.map(|theta| self.leaning(p, theta));
- let shift = [0, 1, 2].map(|k| {
+ let moved = [0, 1, 2].map(|k| {
let by = |a: &[f32; 3]| a.get(k).copied().unwrap_or(0.0);
- let scale = if k == 0 { 0.5 } else { 1.0 };
- by(&stamp_shift)
- + by(&self.stroke_shift)
- + scale * (by(&x.pressure_color) * light + by(&x.tilt_color) * by(&lean))
+ by(&x.pressure_color) * color_by.get(k).copied().unwrap_or(1.0) + by(&x.tilt_color) * by(&lean)
});
+ let tint = self.stroke_shift.plus(stamp_tint).shifted(moved);
// random numbers only for the controls in use, so strokes without them replay as before
- let secondary =
- (if x.stamp_secondary > 0.0 { x.stamp_secondary * secondary_tilt * self.random.next() } else { 0.0 }
- + self.stroke_secondary
- + x.pressure_secondary * light
- + x.tilt_secondary * self.leaning(p, x.tilt_angles.secondary))
- .clamp(0.0, 1.0);
+ let mut stamp_secondary = 0.0;
+ if x.stamp_secondary > 0.0 {
+ stamp_secondary = x.stamp_secondary * secondary_by * self.random.next();
+ if secondary_more > 0.0 {
+ stamp_secondary += x.stamp_secondary * secondary_more * self.random.next();
+ }
+ }
+ let secondary = (stamp_secondary
+ + self.stroke_secondary
+ + x.pressure_secondary * color_by[3]
+ + x.tilt_secondary * self.leaning(p, x.tilt_angles.secondary))
+ .clamp(0.0, 1.0);
// a moving grain: deeper (or shallower) from stamp to stamp, never under its least;
// leaning lets more of it through
let base = self.brush.grain.depth.max(1e-3);
- let jitter = if x.grain_depth_jitter > 0.0 { x.grain_depth_jitter * self.random.next() } else { 0.0 };
- let mut depth = base * (1.0 - jitter);
+ let jitter = if x.grain_depth_jitter > 0.0 {
+ x.grain_depth_jitter * depth_jitter_by * self.random.next()
+ } else {
+ 0.0
+ };
+ let mut depth = base * (1.0 - jitter) * depth_by;
depth += (1.0 - depth) * (x.tilt_bleed * self.leaning(p, x.tilt_angles.bleed)).clamp(0.0, 1.0);
let grain_press = (1.0 - light).clamp(0.0, 1.0);
let mut depth = depth.max(x.grain_depth_min).clamp(0.0, 1.0);
@@ -1020,26 +1253,31 @@ impl StrokeBuilder {
depth = least + (depth - least) * (1.0 - self.switched(p, sw.grain_depth));
}
// sized with the stamp, against the stroke's size, unless cropped
- let grain_size = 1.0 + (diameter * size / self.diameter.max(1e-3) - 1.0) * (1.0 - x.grain_zoom);
+ let grain_size = (1.0 + (diameter * size / self.diameter.max(1e-3) - 1.0) * (1.0 - x.grain_zoom * zoom_by))
+ * grain_scale_by;
let placed = Placed {
center,
distance,
- diameter: diameter * size,
+ diameter: diameter * size * wide,
alpha: alpha * fade,
angle,
roundness,
flip,
- shift,
+ tint,
secondary,
grain_depth: depth / base,
grain_size: grain_size.max(0.05),
grain_press,
+ grain_movement: x.grain_movement * movement_by,
gradation: (x.tilt_gradation * self.leaning(p, x.tilt_angles.gradation)).max(0.0).sqrt().min(1.0),
transfer,
attack,
+ wet,
+ pressed: p.soft,
+ drawn_share,
};
self.placed.push(placed);
- let stamp = self.finish_stamp(&placed, None);
+ let stamp = self.finish_stamp(&placed, start_span, None);
self.bounds = self.bounds.union(stamp.bounds());
out.push(stamp);
}
@@ -1048,38 +1286,66 @@ impl StrokeBuilder {
/// Where a stamp's moving grain is read from (see [`Stamp::grain_offset`]): in place on the
/// canvas as far as the grain rolls, from wherever the stroke starts in it.
fn grain_offset(&self, p: &Placed) -> Vec2 {
- self.grain_start + p.center * self.extras.grain_movement
+ self.grain_start + p.center * p.grain_movement
+ }
+
+ /// The stamp's roundness before leaning and jitter: the shape's, squeezed as light pressure
+ /// `pressure` says, on the `drawn_share` of the stamp that isn't grown by leaning.
+ fn pressed_roundness(&self, drawn_share: f32, pressure: f32) -> f32 {
+ let squeezed = 1.0 - self.extras.pressure_roundness * (1.0 - pressure.clamp(0.0, 1.0));
+ drawn_share * self.brush.shape.roundness.clamp(0.05, 1.0) * squeezed + (1.0 - drawn_share)
}
fn taper(&self) -> &Taper {
if self.pointer.has_pressure() { &self.brush.pen_taper } else { &self.brush.touch_taper }
}
- fn finish_stamp(&self, p: &Placed, length: Option<f32>) -> Stamp {
- // a brush file's classic taper as measured; the newer kind on touch lasts a time as
- // measured, on a pen it goes by stamp diameters
- let classic = self.brush.extra.get("classic_taper").is_some_and(|&v| v >= 0.5);
- let (size, alpha) = if classic {
- self.taper().classic_factors(p.distance, length, self.paces().1)
- } else if !self.pointer.has_pressure() {
- self.taper().timed_factors(p.distance, length, self.paces())
- } else {
- self.taper().factors(p.distance, length, self.diameter)
+ /// The stamp `p` as drawn, its start taper growing over `start_span` canvas pixels of the
+ /// path and, once the stroke has ended, its end taper over the last `end` of its length:
+ /// `(length, end)`.
+ fn finish_stamp(&self, p: &Placed, start_span: f32, end: Option<(f32, f32)>) -> Stamp {
+ let grown = |gone: f32, span: f32| if span > 0.0 { (gone / span).clamp(0.0, 1.0) } else { 1.0 };
+ let (start, finish) = match end {
+ // a tap keeps its whole size
+ Some((length, _)) if length <= 0.0 => (1.0, 1.0),
+ Some((length, span)) => (grown(p.distance, start_span), grown(length - p.distance, span)),
+ None => (grown(p.distance, start_span), 1.0),
};
- // a blunt tip keeps part of the width where a sharp one comes to a point
let tip = if self.pointer.has_pressure() { self.extras.pen_taper_tip } else { self.extras.touch_taper_tip };
- let size = size + (1.0 - size) * tip * 0.5;
+ let (mut size, mut alpha) = self.taper().applied(start, finish, tip);
+ // a pen's pressure fades into the tapers as far as the brush says: the size, opacity,
+ // bleed and roundness it gave scaled to what the faded pressure gives
+ let fade = self.extras.taper_pressure;
+ let (mut grain_press, mut roundness) = (p.grain_press, p.roundness);
+ if self.pointer.has_pressure() && fade > 0.0 {
+ let kept = (1.0 - fade) + fade * (start * finish).powf(Taper::tip_power(tip));
+ let [s, o, b, r] = p.pressed;
+ let (s0, o0) = self.brush.factors(s, o);
+ let (s1, o1) = self.brush.factors(s * kept, o * kept);
+ if s0 > 0.0 {
+ size *= s1 / s0;
+ }
+ if o0 > 0.0 {
+ alpha *= (o1 / o0).powf(FLOW_POWER);
+ }
+ grain_press = (b * kept).clamp(0.0, 1.0);
+ let r0 = self.pressed_roundness(p.drawn_share, r);
+ if r0 > 0.0 {
+ let r1 = self.pressed_roundness(p.drawn_share, r * kept);
+ roundness = (roundness * r1 / r0).clamp(0.05, MOST_ROUNDNESS);
+ }
+ }
Stamp {
center: p.center,
radius: (p.diameter * size * 0.5).max(0.25),
alpha: (p.alpha * alpha).clamp(0.0, 1.0),
angle: p.angle,
- roundness: p.roundness,
+ roundness,
grain_offset: self.grain_offset(p),
- grain_press: p.grain_press,
+ grain_press,
grain_bleed: self.extras.pressure_bleed.clamp(0.0, 1.0),
flip: p.flip,
- shift: p.shift,
+ tint: p.tint,
secondary: p.secondary,
grain_depth: p.grain_depth,
grain_size: p.grain_size,
@@ -1087,6 +1353,7 @@ impl StrokeBuilder {
taper: size.clamp(0.0, 1.0),
transfer: p.transfer,
attack: p.attack,
+ wet: p.wet,
}
}
}
@@ -1239,7 +1506,8 @@ mod tests {
#[test]
fn a_touch_stroke_tapers_over_what_it_covers_in_the_taper_s_time() {
let brush = Brush { touch_taper: Taper { start: 0.5, end: 0.5, size: 1.0, opacity: 0.0 }, ..plain() };
- // 600 px drawn in samples `ms` apart: the faster, the longer the tapered ends
+ // 600 px drawn in samples `ms` apart: the end taper covers the input since the last
+ // sample before its time (0.5 x 83 ms), so the faster, the longer it is
let near_end = |ms: f64| {
let mut b = StrokeBuilder::new(brush.clone(), 20.0, Pointer::Finger);
let samples: Vec<Sample> =
@@ -1249,7 +1517,7 @@ mod tests {
let at = |x: f32| {
all.iter().min_by(|a, b| (a.center.x - x).abs().total_cmp(&(b.center.x - x).abs())).unwrap().radius
};
- (at(600.0 - 50.0), at(300.0))
+ (at(600.0 - 30.0), at(300.0))
};
let (fast, full) = near_end(8.0);
let (slow, _) = near_end(32.0);
@@ -1257,6 +1525,102 @@ mod tests {
assert!((slow - full).abs() < 1e-3, "{slow} {full}");
}
+ #[test]
+ fn a_classic_end_runs_on_past_the_lift_and_tapers_there() {
+ let mut brush = Brush { touch_taper: Taper { start: 0.0, end: 1.0, size: 1.0, opacity: 0.0 }, ..plain() };
+ brush.pen_taper = brush.touch_taper.clone();
+ brush.set_setting("classic_taper", 1.0);
+ // 300 px in 10 px steps
+ let ran_to = |pointer| {
+ let mut b = StrokeBuilder::new(brush.clone(), 10.0, pointer);
+ b.add(&line(30, 300.0));
+ let all = b.finish();
+ let last = all.last().unwrap();
+ let at_lift = all.iter().min_by(|a, b| (a.center.x - 300.0).abs().total_cmp(&(b.center.x - 300.0).abs()));
+ (last.center.x, last.radius, at_lift.unwrap().radius)
+ };
+ // a finger runs on four shrinking steps (0.66, 0.44, 0.29, 0.19 of the last), a pen one
+ let (touch_end, touch_tip, touch_at_lift) = ran_to(Pointer::Finger);
+ assert!((touch_end - (300.0 + 15.73)).abs() < 1.0, "{touch_end}");
+ assert!(touch_tip < 0.5 && touch_at_lift > 4.9, "{touch_tip} {touch_at_lift}");
+ let (pen_end, pen_tip, _) = ran_to(Pointer::Stylus);
+ assert!((pen_end - 306.6).abs() < 1.0, "{pen_end}");
+ assert!(pen_tip < 1.0, "{pen_tip}");
+ }
+
+ #[test]
+ fn taper_pressure_fades_a_pens_pressure_into_its_tapers() {
+ // a taper that thins nothing by itself, a size that follows the pressure in full
+ let taper = Taper { start: 0.5, end: 0.5, size: 0.0, opacity: 0.0 };
+ let mut brush = Brush { pen_taper: taper.clone(), touch_taper: taper, pressure_size: 1.0, ..plain() };
+ let stamp = |brush: &Brush, pointer, at: usize| {
+ let mut b = StrokeBuilder::new(brush.clone(), 10.0, pointer);
+ let samples: Vec<Sample> =
+ (0..=100).map(|i| Sample::at(Vec2::new(i as f32 * 2.0, 50.0), 1.0, i as f64 * 4.0)).collect();
+ b.add(&samples);
+ b.finish().get(at).cloned().unwrap()
+ };
+ let near_start = |brush: &Brush, pointer| stamp(brush, pointer, 5).radius;
+ assert_eq!(near_start(&brush, Pointer::Stylus), 5.0);
+ brush.set_setting("pen_taper_pressure", 1.0);
+ assert!(near_start(&brush, Pointer::Stylus) < 3.0, "{}", near_start(&brush, Pointer::Stylus));
+ // a finger has no pressure to fade
+ assert_eq!(near_start(&brush, Pointer::Finger), 5.0);
+ // the bleed and the roundness take the faded pressure too, and are whole further in
+ brush.set_setting("pressure_bleed", 1.0);
+ brush.set_setting("pressure_roundness", 1.0);
+ let (tip, inside) = (stamp(&brush, Pointer::Stylus, 5), stamp(&brush, Pointer::Stylus, 40));
+ assert!(tip.grain_press < 0.6 && tip.roundness < 0.6, "{} {}", tip.grain_press, tip.roundness);
+ assert!(inside.grain_press > 0.99 && inside.roundness > 0.99, "{} {}", inside.grain_press, inside.roundness);
+ }
+
+ #[test]
+ fn a_pens_tip_shows_tapered_as_it_is_drawn() {
+ let taper = Taper { start: 0.0, end: 0.5, size: 1.0, opacity: 0.0 };
+ let brush = Brush { pen_taper: taper.clone(), touch_taper: taper, ..plain() };
+ // 2 px every 4 ms: the last 42 ms are the last 20 px or so
+ let samples: Vec<Sample> =
+ (0..=100).map(|i| Sample::at(Vec2::new(i as f32 * 2.0, 50.0), 1.0, i as f64 * 4.0)).collect();
+ let mut b = StrokeBuilder::new(brush.clone(), 10.0, Pointer::Stylus);
+ assert!(b.shows_tip());
+ let (kept, tip) = b.add_tipped(samples.get(..60).unwrap());
+ assert!(kept.iter().all(|s| s.radius == 5.0));
+ assert!(tip.len() < 30 && tip.last().unwrap().radius < 1.0, "{} {}", tip.len(), tip.last().unwrap().radius);
+ assert_eq!(kept.len() + tip.len(), b.stamp_count());
+ // drawn on, the old tip is kept whole and a new one shown
+ let (more, tip) = b.add_tipped(samples.get(60..).unwrap());
+ assert!(more.iter().all(|s| s.radius == 5.0) && more.first().unwrap().center.x < 118.0);
+ assert_eq!(kept.len() + more.len() + tip.len(), b.stamp_count());
+ // a predicted tip runs on to where the input is predicted to go, the stroke left as it is
+ let ahead = b.preview_tip(&[Sample::at(Vec2::new(240.0, 50.0), 1.0, 420.0)]);
+ assert!(ahead.last().unwrap().center.x > 230.0 && ahead.last().unwrap().radius < 1.0);
+ assert_eq!(kept.len() + more.len() + tip.len(), b.stamp_count());
+ // a finger, a classic taper or the animation off show no tip
+ assert!(!StrokeBuilder::new(brush.clone(), 10.0, Pointer::Finger).shows_tip());
+ let mut classic = brush.clone();
+ classic.set_setting("classic_taper", 1.0);
+ assert!(!StrokeBuilder::new(classic, 10.0, Pointer::Stylus).shows_tip());
+ let mut off = brush;
+ off.set_setting("pen_tip_animation", 0.0);
+ assert!(!StrokeBuilder::new(off, 10.0, Pointer::Stylus).shows_tip());
+ }
+
+ #[test]
+ fn a_newer_taper_on_a_pen_lasts_its_time() {
+ let brush = Brush { pen_taper: Taper { start: 0.5, end: 0.0, size: 1.0, opacity: 0.0 }, ..plain() };
+ // 2 px every 4 ms: half of 83 ms is reached by the eleventh sample, 22 px in
+ let mut b = StrokeBuilder::new(brush, 10.0, Pointer::Stylus);
+ let samples: Vec<Sample> =
+ (0..=100).map(|i| Sample::at(Vec2::new(i as f32 * 2.0, 50.0), 1.0, i as f64 * 4.0)).collect();
+ b.add(&samples);
+ let all = b.finish();
+ let at = |x: f32| all.iter().min_by(|a, b| (a.center.x - x).abs().total_cmp(&(b.center.x - x).abs())).unwrap();
+ assert!((at(11.0).radius - 2.5).abs() < 0.3, "{}", at(11.0).radius);
+ assert_eq!(at(30.0).radius, 5.0);
+ // no end taper set: the end stays whole
+ assert_eq!(all.last().unwrap().radius, 5.0);
+ }
+
#[test]
fn bad_samples_are_skipped() {
let mut b = StrokeBuilder::new(plain(), 10.0, Pointer::Stylus);
@@ -1297,6 +1661,115 @@ mod tests {
assert_eq!(again.add(&down), stamps);
}
+ #[test]
+ fn jitter_moves_a_stamp_within_half_its_diagonal_times_the_files_amount() {
+ let jittered = |lateral: f32, linear: f32| {
+ let mut brush = plain();
+ brush.set_setting("jitter_lateral", lateral);
+ brush.set_setting("jitter_linear", linear);
+ // a horizontal line at y = 50, stamps every pixel
+ StrokeBuilder::new(brush, 10.0, Pointer::Stylus).add(&line(20, 200.0))
+ };
+ // a round 10 px tip fills 10 / 0.797 of its square: half its diagonal and a pixel is 9.87;
+ // full lateral jitter is 3 of those across the stroke, none along it
+ let reach = 10.0 / crate::brushfile::ROUND_TIP_SHARE * 0.5 * std::f32::consts::SQRT_2 + 1.0;
+ let across: Vec<f32> = jittered(1.0, 0.0).iter().map(|s| (s.center.y - 50.0).abs()).collect();
+ assert!(across.iter().all(|&d| d <= 3.0 * reach + 1e-3), "{across:?}");
+ assert!(across.iter().any(|&d| d > 1.5 * reach));
+ // both: one random point a stamp, inside the circle of that reach
+ let both = jittered(1.0, 1.0);
+ let straight = jittered(0.0, 0.0);
+ for (j, s) in both.iter().zip(&straight) {
+ assert!(j.center.distance(s.center) <= 3.0 * reach + 1e-3);
+ }
+ }
+
+ #[test]
+ fn roundness_jitter_squeezes_width_and_height_apart() {
+ let stamps = |key: &str| {
+ let mut brush = plain();
+ brush.set_setting(key, 0.8);
+ StrokeBuilder::new(brush, 10.0, Pointer::Stylus).add(&line(20, 200.0))
+ };
+ // the width squeezed: narrower and taller than wide, the height whole
+ let narrow = stamps("roundness_jitter_x");
+ assert!(narrow.iter().any(|s| s.roundness > 1.5));
+ assert!(narrow.iter().all(|s| (s.radius * s.roundness - 5.0).abs() < 1e-3 && s.radius <= 5.0));
+ // the height squeezed: flatter, the width whole
+ let flat = stamps("roundness_jitter_y");
+ assert!(flat.iter().any(|s| s.roundness < 0.6));
+ assert!(flat.iter().all(|s| s.radius == 5.0 && s.roundness <= 1.0));
+ // a stamp taller than wide is held in its bounds
+ let tall = narrow.iter().max_by(|a, b| a.roundness.total_cmp(&b.roundness)).unwrap();
+ assert!(tall.bounds().height() as f32 >= 2.0 * tall.radius * tall.roundness);
+ }
+
+ #[test]
+ fn a_randomised_shape_turns_the_whole_stroke_one_way() {
+ let shape = Shape { randomise: true, follow: 0.0, ..Shape::default() };
+ let angles = |seed: u32| -> Vec<f32> {
+ let mut b =
+ StrokeBuilder::with_seed(Brush { shape: shape.clone(), ..plain() }, 10.0, Pointer::Stylus, seed);
+ b.add(&line(20, 200.0)).iter().map(|s| s.angle).collect()
+ };
+ let one = angles(1);
+ assert!(one.iter().all(|&a| a == one[0]), "{one:?}");
+ assert_ne!(angles(2)[0], one[0]);
+ }
+
+ #[test]
+ fn count_jitter_takes_a_share_off_the_stamps_beyond_the_first() {
+ let shape = Shape { count: 16, ..Shape::default() };
+ let mut brush = Brush { shape, ..plain() };
+ brush.set_setting("count_jitter", 0.5);
+ let stamps = StrokeBuilder::new(brush, 10.0, Pointer::Stylus).add(&line(40, 400.0));
+ // stamps of one place share its centre
+ let mut counts: Vec<usize> = Vec::new();
+ for (i, s) in stamps.iter().enumerate() {
+ if i == 0 || stamps[i - 1].center != s.center {
+ counts.push(0);
+ }
+ *counts.last_mut().unwrap() += 1;
+ }
+ // 15 beyond the first, less up to half of them: 8 to 16, and not always all
+ assert!(counts.iter().all(|&n| (8..=16).contains(&n)), "{counts:?}");
+ assert!(counts.iter().any(|&n| n < 16) && counts.iter().any(|&n| n > 12), "{counts:?}");
+ }
+
+ #[test]
+ fn a_brushs_own_pressure_curves_scale_its_count_and_jitters() {
+ use crate::brush::PressureCurve;
+ use crate::curve::Curve;
+ let shape = Shape { count: 5, size_jitter: 0.8, ..Shape::default() };
+ let mut brush = Brush { shape, pressure_size: 0.0, ..plain() };
+ brush.pressure_curves.set(PressureCurve::Count, Some(Curve::linear()));
+ brush.pressure_curves.set(PressureCurve::SizeJitter, Some(Curve::linear()));
+ brush.pressure_curves.set(PressureCurve::WetBlur, Some(Curve::linear()));
+ let stroke = |brush: &Brush, pointer, pressure: f32| {
+ let samples: Vec<Sample> =
+ (0..=10).map(|i| Sample::at(Vec2::new(i as f32 * 10.0, 50.0), pressure, i as f64 * 4.0)).collect();
+ StrokeBuilder::new(brush.clone(), 10.0, pointer).add(&samples)
+ };
+ let spread = |stamps: &[Stamp]| {
+ let (least, most) = stamps.iter().fold((f32::MAX, 0.0f32), |(l, m), s| (l.min(s.radius), m.max(s.radius)));
+ most / least
+ };
+ // pressing lightly: one stamp a place, hardly jittered
+ let light = stroke(&brush, Pointer::Stylus, 0.05);
+ assert!(spread(&light) < 1.05, "{}", spread(&light));
+ // the wet blur scaled the same way, the rest of the wet mix untouched
+ assert!(light.iter().all(|s| s.wet[1] < 0.1 && s.wet[0] == 1.0), "{:?}", light[0].wet);
+ // pressing fully, or a finger: five a place, jittered as far as the brush says
+ for full in [stroke(&brush, Pointer::Stylus, 1.0), stroke(&brush, Pointer::Finger, 0.0)] {
+ assert_eq!(full.len(), 5 * light.len());
+ assert!(spread(&full) > 2.0, "{}", spread(&full));
+ }
+ // without the curves, light pressure jitters and counts in full
+ brush.pressure_curves = Default::default();
+ let plain_light = stroke(&brush, Pointer::Stylus, 0.05);
+ assert_eq!(plain_light.len(), 5 * light.len());
+ }
+
#[test]
fn tilt_widens_the_pen_but_not_fingers() {
let angle = 0.1 * std::f32::consts::FRAC_PI_2;
@@ -1518,14 +1991,14 @@ mod tests {
let plain_light = mid(&stroke(&[], 0.3, Taper::NONE));
let flow_light = mid(&stroke(&[("pressure_flow", 1.0)], 0.3, Taper::NONE));
assert!(flow_light.alpha < plain_light.alpha * 0.5, "{} {}", flow_light.alpha, plain_light.alpha);
- // a blunt tip keeps width at the stroke's ends
+ // a blunt tip keeps width at the stroke's ends (all but the very first stamp)
let taper = Taper { start: 0.3, end: 0.3, size: 1.0, opacity: 0.0 };
- let sharp = stroke(&[], 1.0, taper.clone())[0].radius;
- let blunt = stroke(&[("pen_taper_tip", 1.0)], 1.0, taper)[0].radius;
+ let sharp = stroke(&[], 1.0, taper.clone())[2].radius;
+ let blunt = stroke(&[("pen_taper_tip", 1.0)], 1.0, taper)[2].radius;
assert!(blunt > sharp + 1.0, "{blunt} {sharp}");
- // the secondary colour: by light pressure, and jittered per stamp
+ // the secondary colour: by pressure, as its curve says, and jittered per stamp
assert_eq!(mid(&stroke(&[], 0.3, Taper::NONE)).secondary, 0.0);
- assert!((mid(&stroke(&[("pressure_secondary", 1.0)], 0.3, Taper::NONE)).secondary - 0.7).abs() < 0.05);
+ assert!((mid(&stroke(&[("pressure_secondary", 1.0)], 0.3, Taper::NONE)).secondary - 0.3).abs() < 0.05);
let jittered = stroke(&[("stamp_secondary", 1.0)], 1.0, Taper::NONE);
assert!(jittered.iter().any(|s| s.secondary > 0.5) && jittered.iter().any(|s| s.secondary < 0.5));
// a moving grain: filled in by pressing harder, never under its least, jittered
diff --git a/crates/engine/src/textures.rs b/crates/engine/src/textures.rs
index bfa0302..94820fd 100644
--- a/crates/engine/src/textures.rs
+++ b/crates/engine/src/textures.rs
@@ -108,16 +108,24 @@ pub mod grain {
const COARSE_LIGHT: f32 = 0.6;
const COARSE_DEPTH: f32 = 1.25;
+static SHAPES: std::sync::OnceLock<Vec<GrayImage>> = std::sync::OnceLock::new();
+static GRAINS: std::sync::OnceLock<Vec<GrayImage>> = std::sync::OnceLock::new();
+
/// The shapes, made once.
pub fn shapes() -> Vec<GrayImage> {
- static MADE: std::sync::OnceLock<Vec<GrayImage>> = std::sync::OnceLock::new();
- MADE.get_or_init(make_shapes).clone()
+ SHAPES.get_or_init(make_shapes).clone()
}
/// The grains, made once.
pub fn grains() -> Vec<GrayImage> {
- static MADE: std::sync::OnceLock<Vec<GrayImage>> = std::sync::OnceLock::new();
- MADE.get_or_init(make_grains).clone()
+ GRAINS.get_or_init(make_grains).clone()
+}
+
+/// Makes the shapes and grains now, so the first canvas doesn't wait for them (slow: off the main
+/// thread).
+pub fn prepare() {
+ SHAPES.get_or_init(make_shapes);
+ GRAINS.get_or_init(make_grains);
}
fn make_shapes() -> Vec<GrayImage> {
diff --git a/crates/gpu/src/canvas.rs b/crates/gpu/src/canvas.rs
index 1e1dbb4..da58cc8 100644
--- a/crates/gpu/src/canvas.rs
+++ b/crates/gpu/src/canvas.rs
@@ -12,7 +12,7 @@ use procraft_engine::animation::{self, FrameLook};
use procraft_engine::brush::{BRUSH_BEHIND, Brush, GRAIN_LINEAR_HEIGHT, GrainMode, Rendering, Source};
use procraft_engine::document::{BlendMode, Document, Layer, LayerId, LayerKind};
use procraft_engine::geom::{Affine, IRect};
-use procraft_engine::stroke::Stamp;
+use procraft_engine::stroke::{MOST_ROUNDNESS, Stamp};
use procraft_engine::textures::{self, GrayImage, TEXTURE_SIZE};
use crate::{Gpu, GpuError};
@@ -38,9 +38,9 @@ const _: () = assert!(
const MESH_ATTRIBUTES: [wgpu::VertexAttribute; 2] = wgpu::vertex_attr_array![0 => Float32x2, 1 => Float32x2];
/// The vertex layout of a stamp instance (stroke stamps and the predicted tail).
-const STAMP_ATTRIBUTES: [wgpu::VertexAttribute; 10] = wgpu::vertex_attr_array![
+const STAMP_ATTRIBUTES: [wgpu::VertexAttribute; 11] = wgpu::vertex_attr_array![
0 => Float32x2, 1 => Float32, 2 => Float32, 3 => Float32, 4 => Float32, 5 => Float32x2, 6 => Float32x2, 7 => Float32x4,
- 8 => Float32x4, 9 => Float32x4
+ 8 => Float32x4, 9 => Float32x4, 10 => Float32
];
#[repr(C)]
@@ -399,14 +399,17 @@ struct StampInstance {
grain_offset: [f32; 2],
/// −1 where the shape is mirrored on that axis, else 1.
flip: [f32; 2],
- /// Hue (turns), saturation and lightness shifts, and room for more.
- shift: [f32; 4],
+ /// The tint (see [`stamp_extras`]): the hue's turn, the saturation's keep and add, the
+ /// brightness's keep.
+ tint: [f32; 4],
/// A moving grain's depth and tile size as multiples of the brush's, the share of the
/// secondary colour, and how far it fades across its width (tilt gradation).
look: [f32; 4],
/// How hard the paint is pressed into a moving grain and how much that counts, and room for
/// more.
more: [f32; 4],
+ /// The tint's brightness add.
+ brightness_add: f32,
}
/// A stamp's (alpha, transfer) as its instance takes them: a capped stroke keeps its transfer
@@ -444,10 +447,15 @@ fn drawn_radius(style: &StrokeStyle, radius: f32, taper: f32) -> f32 {
}
/// A stamp's mirroring and colour shift for the GPU, kept finite.
-fn stamp_extras(s: &Stamp) -> ([f32; 2], [f32; 4]) {
+/// A stamp's flips (each 1 or -1), and its tint as the shader takes it: the hue's turn, the
+/// saturation's keep and add, the brightness's keep, then apart its add.
+fn stamp_extras(s: &Stamp) -> ([f32; 2], [f32; 4], f32) {
let flip = s.flip.map(|f| if f { -1.0 } else { 1.0 });
- let [h, sat, l] = s.shift.map(|v| if v.is_finite() { v.clamp(-1.0, 1.0) } else { 0.0 });
- (flip, [h, sat, l, 0.0])
+ let t = s.tint;
+ let ok = |v: f32, none: f32| if v.is_finite() { v.clamp(-4.0, 4.0) } else { none };
+ let [sk, sa] = t.saturation;
+ let [bk, ba] = t.brightness;
+ (flip, [ok(t.hue, 0.0), ok(sk, 1.0), ok(sa, 0.0), ok(bk, 1.0)], ok(ba, 0.0))
}
#[repr(C)]
@@ -766,6 +774,8 @@ enum Op {
/// Stamps added to the stroke (`clear`: the stroke is redrawn from scratch).
Stamps {
instances: Vec<StampInstance>,
+ /// Each stamp's wet-mix scaling (see [`Stamp::wet`]), for the wet paint drawn in place.
+ wet: Vec<[f32; 4]>,
style: StrokeStyle,
clear: bool,
layer: LayerId,
@@ -774,6 +784,10 @@ enum Op {
},
Commit(ActiveStroke),
Cancel,
+ /// What the stroke has under this rectangle is put aside, for a tip drawn over it.
+ SaveTip(IRect),
+ /// What was put aside under this rectangle comes back (the tip drawn over it goes).
+ Untip(IRect),
Undo,
Redo,
Clear(LayerId),
@@ -1106,7 +1120,11 @@ pub struct Canvas {
pipelines: std::sync::Arc<Pipelines>,
screen: ScreenPipelines,
layers: HashMap<LayerId, LayerGpu>,
+ stroke: wgpu::Texture,
stroke_view: wgpu::TextureView,
+ /// Where the open stroke's tip is drawn (see [`Canvas::set_tip`]), and what it covered.
+ tip: Option<IRect>,
+ tip_backup: Option<wgpu::Texture>,
/// Ping-pong pair; the finished composite is always left in the first.
composite: [wgpu::Texture; 2],
composite_views: [wgpu::TextureView; 2],
@@ -1319,7 +1337,10 @@ impl Canvas {
pipelines,
screen: ScreenPipelines::default(),
layers: HashMap::new(),
+ stroke: stroke_texture,
stroke_view,
+ tip: None,
+ tip_backup: None,
composite,
composite_views,
groups: Vec::new(),
@@ -1507,26 +1528,63 @@ impl Canvas {
/// Draws more of the open stroke.
pub fn add_stamps(&mut self, stamps: &[Stamp]) {
+ self.untip();
self.push_stamps(stamps, false);
}
/// Redraws the open stroke from scratch with `stamps` (its final form, e.g. with the end taper).
pub fn replace_stamps(&mut self, stamps: &[Stamp]) {
+ self.tip = None;
self.push_stamps(stamps, true);
}
- fn push_stamps(&mut self, stamps: &[Stamp], clear: bool) {
+ /// Whether the open stroke can show a tip (see [`Canvas::set_tip`]): one built up in the
+ /// stroke texture, not painted in place or onto an adjustment.
+ pub fn shows_tip(&self) -> bool {
+ self.active.is_some_and(|a| !a.pencil && !a.style.in_place())
+ }
+
+ /// The open stroke's tip, drawn over it until the next stamps or tip: its last stamps as
+ /// they'd be drawn were it to end now.
+ pub fn set_tip(&mut self, stamps: &[Stamp]) {
+ self.untip();
+ if !self.shows_tip() || stamps.is_empty() {
+ return;
+ }
+ let at = self.ops.len();
+ let bounds = self.push_stamps(stamps, false);
+ if bounds.is_empty() {
+ return;
+ }
+ self.ops.insert(at, Op::SaveTip(bounds));
+ self.tip = Some(bounds);
+ }
+
+ /// Takes the tip off the open stroke.
+ fn untip(&mut self) {
+ if let Some(rect) = self.tip.take() {
+ self.dirty = self.dirty.union(rect);
+ self.ops.push(Op::Untip(rect));
+ }
+ }
+
+ /// Queues `stamps` into the open stroke (`clear`: from scratch); where they reach.
+ fn push_stamps(&mut self, stamps: &[Stamp], clear: bool) -> IRect {
let full = self.full();
- let Some(active) = self.active.as_mut() else { return };
+ let Some(active) = self.active.as_mut() else { return IRect::EMPTY };
let mut bounds = IRect::EMPTY;
let style = active.style;
let capped = self.pipelines.stamp_capped.is_some();
- let instances: Vec<StampInstance> = stamps
+ let drawn: Vec<&Stamp> =
+ stamps.iter().filter(|s| s.center.is_finite() && s.radius.is_finite() && s.alpha.is_finite()).collect();
+ let wet: Vec<[f32; 4]> =
+ drawn.iter().map(|s| s.wet.map(|v| if v.is_finite() { v.clamp(0.0, 1.0) } else { 1.0 })).collect();
+ let instances: Vec<StampInstance> = drawn
.iter()
- .filter(|s| s.center.is_finite() && s.radius.is_finite() && s.alpha.is_finite())
.map(|s| {
let radius = drawn_radius(&style, s.radius, s.taper);
- bounds = bounds.union(IRect::around(s.center, radius * std::f32::consts::SQRT_2));
+ let tall = if s.roundness.is_finite() { s.roundness.clamp(1.0, MOST_ROUNDNESS) } else { 1.0 };
+ bounds = bounds.union(IRect::around(s.center, radius * tall * std::f32::consts::SQRT_2));
// without the capped pipeline, the transfer goes into the stamp
let (alpha, transfer) = capped_alpha(&style, capped, s);
StampInstance {
@@ -1534,14 +1592,15 @@ impl Canvas {
radius,
alpha,
angle: if s.angle.is_finite() { s.angle } else { 0.0 },
- roundness: if s.roundness.is_finite() { s.roundness.clamp(0.05, 1.0) } else { 1.0 },
+ roundness: if s.roundness.is_finite() { s.roundness.clamp(0.05, MOST_ROUNDNESS) } else { 1.0 },
grain_offset: if s.grain_offset.is_finite() {
[s.grain_offset.x, s.grain_offset.y]
} else {
[0.0; 2]
},
flip: stamp_extras(s).0,
- shift: stamp_extras(s).1,
+ tint: stamp_extras(s).1,
+ brightness_add: stamp_extras(s).2,
look: [s.grain_depth, s.grain_size, s.secondary, s.gradation]
.map(|v| if v.is_finite() { v.clamp(0.0, 64.0) } else { 0.0 }),
more: [s.grain_press, s.grain_bleed, transfer, s.attack]
@@ -1561,12 +1620,14 @@ impl Canvas {
let pencil = active.pencil;
self.ops.push(Op::Stamps {
instances,
+ wet,
style: active.style,
clear: clear && !pencil,
layer: active.layer,
pencil,
});
}
+ bounds
}
/// Puts the open stroke into its layer (undoably).
@@ -1584,10 +1645,11 @@ impl Canvas {
radius: drawn_radius(&style, s.radius, s.taper),
alpha,
angle: if s.angle.is_finite() { s.angle } else { 0.0 },
- roundness: if s.roundness.is_finite() { s.roundness.clamp(0.05, 1.0) } else { 1.0 },
+ roundness: if s.roundness.is_finite() { s.roundness.clamp(0.05, MOST_ROUNDNESS) } else { 1.0 },
grain_offset: [0.0; 2],
flip: stamp_extras(s).0,
- shift: stamp_extras(s).1,
+ tint: stamp_extras(s).1,
+ brightness_add: stamp_extras(s).2,
look: [s.grain_depth, s.grain_size, s.secondary, s.gradation]
.map(|v| if v.is_finite() { v.clamp(0.0, 64.0) } else { 0.0 }),
more: [s.grain_press, s.grain_bleed, transfer, s.attack]
@@ -1599,6 +1661,7 @@ impl Canvas {
pub fn end_stroke(&mut self) {
self.prediction.clear();
+ self.untip();
if let Some(active) = self.active.take() {
self.ops.push(Op::Commit(active));
}
@@ -1607,6 +1670,7 @@ impl Canvas {
/// Drops the open stroke.
pub fn cancel_stroke(&mut self) {
self.prediction.clear();
+ self.tip = None;
if let Some(active) = self.active.take() {
self.dirty = self.dirty.union(active.bounds);
self.ops.push(Op::Cancel);
@@ -2124,9 +2188,10 @@ impl Canvas {
let mut history_changed = false;
for op in ops {
match op {
- Op::Stamps { instances, style, layer, clear, .. } if style.in_place() => {
+ Op::Stamps { instances, wet, style, layer, clear, .. } if style.in_place() => {
next_instance = next_instance.saturating_add(u32::try_from(instances.len()).unwrap_or(u32::MAX));
- self.smudge_stamps(device, &mut encoder, &mut smudge_uniforms, &instances, &style, layer, clear);
+ let stamps = (instances.as_slice(), wet.as_slice());
+ self.smudge_stamps(device, &mut encoder, &mut smudge_uniforms, stamps, &style, layer, clear);
}
Op::Stamps { instances, style, clear, pencil, .. } => {
let count = u32::try_from(instances.len()).unwrap_or(u32::MAX);
@@ -2196,6 +2261,33 @@ impl Canvas {
wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
));
}
+ Op::SaveTip(rect) => {
+ let (width, height) = (rect.width(), rect.height());
+ let roomy = self.tip_backup.as_ref().is_some_and(|b| b.width() >= width && b.height() >= height);
+ if !roomy {
+ // grown in steps, so a tip that grows doesn't make one every frame
+ let room = |n: u32, most: u32| n.max(1).next_multiple_of(256).min(most);
+ let (w, h) = self.tip_backup.as_ref().map_or((0, 0), |b| (b.width(), b.height()));
+ let size = (room(width.max(w), self.width), room(height.max(h), self.height));
+ self.tip_backup = Some(texture(device, "tip backup", size.0, size.1, STROKE_FORMAT));
+ }
+ if let Some(backup) = &self.tip_backup {
+ encoder.copy_texture_to_texture(
+ copy_at(&self.stroke, rect.x0, rect.y0),
+ copy_at(backup, 0, 0),
+ extent(width, height),
+ );
+ }
+ }
+ Op::Untip(rect) => {
+ if let Some(backup) = &self.tip_backup {
+ encoder.copy_texture_to_texture(
+ copy_at(backup, 0, 0),
+ copy_at(&self.stroke, rect.x0, rect.y0),
+ extent(rect.width(), rect.height()),
+ );
+ }
+ }
Op::Undo => {
if let Some(step) = self.undo.pop() {
let inverse = self.apply_step(gpu, &mut encoder, doc, step);
@@ -2647,7 +2739,7 @@ impl Canvas {
device: &wgpu::Device,
encoder: &mut wgpu::CommandEncoder,
params: &mut UniformData,
- instances: &[StampInstance],
+ (instances, wet): (&[StampInstance], &[[f32; 4]]),
style: &StrokeStyle,
target: LayerId,
restart: bool,
@@ -2797,24 +2889,28 @@ impl Canvas {
let mut pass =
encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("smudge"), timestamp_writes: None });
pass.set_bind_group(1, &self.brush_bind, &[]);
- for s in instances {
+ for (k, s) in instances.iter().enumerate() {
let center = procraft_engine::geom::Vec2::new(s.center[0], s.center[1]);
- let bbox = IRect::around(center, s.radius * std::f32::consts::SQRT_2).intersect(full);
+ let bbox =
+ IRect::around(center, s.radius * s.roundness.max(1.0) * std::f32::consts::SQRT_2).intersect(full);
if bbox.is_empty() || s.radius <= 0.0 {
continue;
}
changed = changed.union(bbox);
- let wet = style.wet_pull.is_some() && style.tool == StrokeTool::Paint;
+ let wet_paint = style.wet_pull.is_some() && style.tool == StrokeTool::Paint;
// the paint runs out with the length the stroke has gone
if let Some([x, y]) = smudge.last {
smudge.length += (s.center[0] - x).hypot(s.center[1] - y);
}
smudge.last = Some(s.center);
+ // the grade, blur and jitters as far as this stamp's pressure takes them
+ let [grade_by, blur_by, blur_jitter_by, wet_jitter_by] = wet.get(k).copied().unwrap_or([1.0; 4]);
+ let stamp_style = StrokeStyle { grade: style.grade * grade_by, ..*style };
// the mixture varies from stamp to stamp by the wetness jitter
- let jitter = 1.0 - style.wet_jitter * unit_hash(smudge.stamps);
+ let jitter = 1.0 - style.wet_jitter * wet_jitter_by * unit_hash(smudge.stamps);
smudge.stamps = smudge.stamps.saturating_add(1);
- let (mixture, final_mixture, wet_pull) = if wet {
- wet_mixture(style, smudge.length, jitter, s.more[3])
+ let (mixture, final_mixture, wet_pull) = if wet_paint {
+ wet_mixture(&stamp_style, smudge.length, jitter, s.more[3])
} else {
(0.0, 1.0, style.pull.clamp(0.0, 1.0))
};
@@ -2836,11 +2932,13 @@ impl Canvas {
grid: SMUDGE_GRID,
uniform_glaze: u32::from(style.rendering == Rendering::Strongest),
paint: [style.color[0], style.color[1], style.color[2], 1.0],
- mode: u32::from(wet),
+ mode: u32::from(wet_paint),
mixture,
final_mixture,
- grade: style.grade,
- blur: style.blur * (1.0 - style.blur_jitter * unit_hash(smudge.stamps.wrapping_add(7919))),
+ grade: stamp_style.grade,
+ blur: style.blur
+ * blur_by
+ * (1.0 - style.blur_jitter * blur_jitter_by * unit_hash(smudge.stamps.wrapping_add(7919))),
grain: style.grain.map_or(-1, |g| g as i32),
// a moving grain sized and as deep as this stamp says
grain_scale: if moving { -style.grain_scale * s.look[1].max(0.05) } else { style.grain_scale },
diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs
index 1e2136b..b3526cf 100644
--- a/crates/gpu/src/lib.rs
+++ b/crates/gpu/src/lib.rs
@@ -97,10 +97,11 @@ impl Gpu {
Ok(Gpu { instance, adapter, device, queue, errors, canvas_pipelines: Arc::default() })
}
- /// Makes the pipelines canvases draw with now, so the first canvas on this device is made at
- /// once (slow: off the main thread).
+ /// Makes the pipelines canvases draw with, and the brush images they hold, now, so the first
+ /// canvas on this device is made at once (slow: off the main thread).
pub fn prepare_canvases(&self) {
let _ = self.canvas_pipelines();
+ procraft_engine::textures::prepare();
}
/// The pipelines canvases draw with, made by the first canvas on this device.
diff --git a/crates/gpu/src/shaders/stamp.wgsl b/crates/gpu/src/shaders/stamp.wgsl
index 5a1c3dd..6d9f61b 100644
--- a/crates/gpu/src/shaders/stamp.wgsl
+++ b/crates/gpu/src/shaders/stamp.wgsl
@@ -43,11 +43,14 @@ struct StampIn {
@location(4) roundness: f32,
@location(5) grain_offset: vec2<f32>,
@location(6) flip: vec2<f32>,
- @location(7) shift: vec4<f32>,
+ // the tint: the hue's turn, the saturation's keep and add, the brightness's keep
+ @location(7) tint: vec4<f32>,
// a moving grain's depth and tile size as multiples of the brush's; the secondary colour's share
@location(8) look: vec4<f32>,
// how far the paint fills a moving grain in, and room for more
@location(9) more: vec4<f32>,
+ // the tint's brightness add
+ @location(10) brightness_add: f32,
}
struct StampOut {
@@ -60,7 +63,8 @@ struct StampOut {
// there on the canvas (the grain never turns or squashes with the stamp)
@location(3) grain_at: vec2<f32>,
@location(4) flip: vec2<f32>,
- @location(5) shift: vec3<f32>,
+ // the stamp's colour: the brush's tinted, mixed with the secondary
+ @location(5) color: vec3<f32>,
// how hard the paint is pressed into a moving grain, and how much that counts
@location(8) grain_press: f32,
@location(10) grain_bleed: f32,
@@ -90,7 +94,7 @@ fn vs_stamp(@builtin(vertex_index) vi: u32, inst: StampIn) -> StampOut {
o.alpha = inst.alpha;
o.grain_at = inst.grain_offset + (p - inst.center);
o.flip = inst.flip;
- o.shift = inst.shift.xyz;
+ o.color = mix(tinted(su.color.rgb, inst.tint, inst.brightness_add), su.secondary.rgb, inst.look.z);
o.look = inst.look;
o.grain_press = inst.more.x;
o.grain_bleed = inst.more.y;
@@ -98,16 +102,14 @@ fn vs_stamp(@builtin(vertex_index) vi: u32, inst: StampIn) -> StampOut {
return o;
}
-// hue (0..1), saturation and lightness of a colour, and back
-fn to_hsl(c: vec3<f32>) -> vec3<f32> {
+// hue (0..1), saturation and brightness of a colour, and back
+fn to_hsb(c: vec3<f32>) -> vec3<f32> {
let hi = max(c.r, max(c.g, c.b));
let lo = min(c.r, min(c.g, c.b));
- let l = (hi + lo) * 0.5;
let d = hi - lo;
if (d <= 1e-5) {
- return vec3<f32>(0.0, 0.0, l);
+ return vec3<f32>(0.0, 0.0, hi);
}
- let s = d / (1.0 - abs(2.0 * l - 1.0) + 1e-5);
var h = 0.0;
if (hi == c.r) {
h = (c.g - c.b) / d;
@@ -116,15 +118,23 @@ fn to_hsl(c: vec3<f32>) -> vec3<f32> {
} else {
h = (c.r - c.g) / d + 4.0;
}
- return vec3<f32>(fract(h / 6.0), clamp(s, 0.0, 1.0), l);
+ return vec3<f32>(fract(h / 6.0), d / hi, hi);
}
-fn from_hsl(c: vec3<f32>) -> vec3<f32> {
- let k = vec3<f32>(0.0, 2.0 / 3.0, 1.0 / 3.0);
- let p = abs(fract(vec3<f32>(c.x) + k) * 6.0 - 3.0);
- let rgb = clamp(p - 1.0, vec3<f32>(0.0), vec3<f32>(1.0));
- let chroma = (1.0 - abs(2.0 * c.z - 1.0)) * c.y;
- return c.z + chroma * (rgb - 0.5);
+fn from_hsb(c: vec3<f32>) -> vec3<f32> {
+ let k = fract(vec3<f32>(c.x) + vec3<f32>(5.0, 3.0, 1.0) / 6.0) * 6.0;
+ return c.z - c.z * c.y * clamp(min(k, 4.0 - k), vec3<f32>(0.0), vec3<f32>(1.0));
+}
+
+// `c` tinted: its hue turned, its saturation and brightness each kept by so much and added to
+fn tinted(c: vec3<f32>, t: vec4<f32>, brightness_add: f32) -> vec3<f32> {
+ if (all(t == vec4<f32>(0.0, 1.0, 0.0, 1.0)) && brightness_add == 0.0) {
+ return c;
+ }
+ let hsb = to_hsb(c);
+ let s = clamp(hsb.y * t.y + t.z, 0.0, 1.0);
+ let b = clamp(hsb.z * t.w + brightness_add, 0.0, 1.0);
+ return from_hsb(vec3<f32>(fract(hsb.x + t.x), s, b));
}
// the shape image's texel under `uv`, unfiltered
@@ -189,10 +199,5 @@ fn stamp_paint(i: StampOut) -> vec4<f32> {
// paint keeps inside the selection
let inside_selection = textureSampleLevel(selected, shape_smp, i.pos.xy / su.canvas_size, 0.0).r;
a = a * small * small * i.alpha * inside_selection;
- var color = mix(su.color.rgb, su.secondary.rgb, i.look.z);
- if (any(i.shift != vec3<f32>(0.0))) {
- let hsl = to_hsl(color);
- color = from_hsl(vec3<f32>(fract(hsl.x + i.shift.x + 1.0), clamp(hsl.y + i.shift.y, 0.0, 1.0), clamp(hsl.z + i.shift.z, 0.0, 1.0)));
- }
- return vec4<f32>(color * a, a);
+ return vec4<f32>(i.color * a, a);
}
diff --git a/crates/gpu/tests/canvas.rs b/crates/gpu/tests/canvas.rs
index 086ad54..c1b4b7c 100644
--- a/crates/gpu/tests/canvas.rs
+++ b/crates/gpu/tests/canvas.rs
@@ -6,7 +6,7 @@ use procraft_engine::document::Document;
use procraft_engine::geom::{Homography, Vec2};
use procraft_engine::input::{Pointer, Sample};
use procraft_engine::profile::Profile;
-use procraft_engine::stroke::{Stamp, StrokeBuilder};
+use procraft_engine::stroke::{Stamp, StrokeBuilder, Tint};
use procraft_engine::view::View;
use procraft_gpu::{Backdrop, Canvas, Gpu, Resample, StrokeStyle, StrokeTool, SurroundGrid, Target, wgpu};
@@ -467,6 +467,38 @@ fn the_predicted_tail_shows_but_never_paints() {
assert_eq!(pixel(&px, 100, 20, 50), [0, 0, 0, 255]);
}
+#[test]
+fn a_stroke_tip_shows_until_the_next_one_replaces_it() {
+ let Some(gpu) = gpu() else { return };
+ let _check = NoErrors(&gpu);
+ let mut doc = Document::new(100, 100);
+ let mut canvas = Canvas::new(&gpu, &doc).unwrap();
+ let at = |canvas: &mut Canvas, doc: &mut Document, x: u32| {
+ canvas.render(&gpu, doc, None);
+ pixel(&canvas.read_composite(&gpu).unwrap(), 100, x, 50)
+ };
+ let (black, white) = ([0, 0, 0, 255], [255, 255, 255, 255]);
+ canvas.begin_stroke(doc.current(), style(StrokeTool::Paint, 1.0));
+ assert!(canvas.shows_tip());
+ canvas.add_stamps(&[dot(Vec2::new(20.0, 50.0), 5.0)]);
+ canvas.set_tip(&[dot(Vec2::new(40.0, 50.0), 5.0)]);
+ assert_eq!(at(&mut canvas, &mut doc, 40), black, "the tip");
+ // the next tip takes the last one's place; stamps kept stay
+ canvas.set_tip(&[dot(Vec2::new(60.0, 50.0), 5.0)]);
+ assert_eq!(at(&mut canvas, &mut doc, 40), white, "the old tip gone");
+ assert_eq!(at(&mut canvas, &mut doc, 60), black);
+ canvas.add_stamps(&[dot(Vec2::new(80.0, 50.0), 5.0)]);
+ assert_eq!(at(&mut canvas, &mut doc, 60), white, "stamps drawn for good take the tip off");
+ assert_eq!(at(&mut canvas, &mut doc, 80), black);
+ // a tip still showing as the stroke ends is not kept
+ canvas.set_tip(&[dot(Vec2::new(60.0, 50.0), 5.0)]);
+ canvas.end_stroke();
+ assert_eq!(at(&mut canvas, &mut doc, 60), white);
+ assert_eq!(at(&mut canvas, &mut doc, 20), black);
+ canvas.undo();
+ assert_eq!(at(&mut canvas, &mut doc, 20), white);
+}
+
#[test]
fn a_transform_moves_the_layer_and_undoes_as_one_step() {
let Some(gpu) = gpu() else { return };
@@ -858,14 +890,14 @@ fn a_stamps_colour_shift_turns_its_hue() {
let mut canvas = Canvas::new(&gpu, &doc).unwrap();
canvas.begin_stroke(doc.current(), StrokeStyle::new(StrokeTool::Paint, [1.0, 0.0, 0.0], 1.0));
let mut turned = dot(Vec2::new(20.0, 32.0), 6.0);
- turned.shift = [0.5, 0.0, 0.0];
- let mut lighter = dot(Vec2::new(44.0, 32.0), 6.0);
- lighter.shift = [0.0, 0.0, 0.5];
- canvas.add_stamps(&[turned, lighter]);
+ turned.tint = Tint { hue: 0.5, ..Tint::NONE };
+ let mut drained = dot(Vec2::new(44.0, 32.0), 6.0);
+ drained.tint = Tint { saturation: [0.0, 0.0], ..Tint::NONE };
+ canvas.add_stamps(&[turned, drained]);
canvas.end_stroke();
canvas.render(&gpu, &mut doc, None);
let px = canvas.read_composite(&gpu).unwrap();
- // half a turn from red is cyan; half lighter is white
+ // half a turn from red is cyan; drained of its colour, white
assert_eq!(pixel(&px, 64, 20, 32), [0, 255, 255, 255]);
assert_eq!(pixel(&px, 64, 44, 32), [255, 255, 255, 255]);
}
@@ -1234,3 +1266,20 @@ fn a_tapered_round_tip_thins_its_rim_too() {
let (whole, tapered) = (width(1.0), width(0.2));
assert!(tapered < whole, "{tapered} {whole}");
}
+
+#[test]
+fn a_stamp_taller_than_wide_draws_in_full() {
+ let Some(gpu) = gpu() else { return };
+ let _check = NoErrors(&gpu);
+ let mut doc = Document::new(64, 64);
+ let mut canvas = Canvas::new(&gpu, &doc).unwrap();
+ canvas.begin_stroke(doc.current(), style(StrokeTool::Paint, 1.0));
+ // 8 px wide, 24 px tall
+ canvas.add_stamps(&[Stamp { roundness: 3.0, ..dot(Vec2::new(32.0, 32.0), 4.0) }]);
+ canvas.end_stroke();
+ canvas.render(&gpu, &mut doc, None);
+ let px = canvas.read_composite(&gpu).unwrap();
+ let painted = |x: u32, y: u32| pixel(&px, 64, x, y)[0] < 128;
+ assert!(painted(32, 32 + 9) && painted(32, 32 - 9), "its height");
+ assert!(!painted(32 + 7, 32), "its width");
+}