VectorCraft: An open-source, vector art tool written by scratch in pure Rust
Affinity: pressure curves keep dips between samples and stay within a document-wide limit
dotCooCooe441d3ba1879
diff --git a/crates/affinity/README.md b/crates/affinity/README.mdindex 90c078023..fd2d6dc71 100644--- a/crates/affinity/README.md+++ b/crates/affinity/README.md@@ -34,7 +34,7 @@ Affinity files.| Opacity, visibility, lock, names, the blend modes VectorCraft has | the same |Everything else is reported in the import warnings, one line per kind with a count, never-dropped silently: bevel, blur and other layer effects, adjustment layers and live filters, brush strokes, pressure curves that can't be read,+dropped silently: bevel, blur and other layer effects, adjustment layers and live filters, brush strokes, pressure curves that can't be read or that go past the million points one document may hold,transparency gradients, fill opacity, bitmap fills, master pages based on other master pages, conical gradients (as radial),special shapes (cloud, heart, cog, callouts, arrows…, imported as their bounding ellipse), cornertypes other than round or straight, stars with rounded points, several fills or strokes on one object (thediff --git a/crates/affinity/src/geometry.rs b/crates/affinity/src/geometry.rsindex 83ea85428..945c3040f 100644--- a/crates/affinity/src/geometry.rs+++ b/crates/affinity/src/geometry.rs@@ -172,16 +172,19 @@ fn curves(r: &mut Reader, crvs: ObjId, budget: &mut OutlineBudget) -> Option<Pat/// Most segments a stroke's pressure curve may have; the curves in real documents have a handful.const MAX_PRESSURE_SEGMENTS: usize = 256;-/// Most points a pressure curve is sampled at: each segment gets an equal share, at least 2 (its-/// middle and its end) and 8 at most.+/// Most regular samples of a pressure curve: each segment gets an equal share, at least 2 (its+/// middle and its end) and 8 at most. The points where a segment's width stops rising or falling+/// come on top (at most two per segment), so a curve has at most 1 + 4 × [`MAX_PRESSURE_SEGMENTS`]+/// points; the document's limit counts all of them.const PRESSURE_POINTS: usize = 512;/// A stroke's pressure curve (`LDsc.LDeP`, a `CrvD` whose positional `Data` holds an array of/// 18-byte records as in [`curves`]): x is the position along the path (0 to 1) and y the width as/// a fraction of the stroke's weight. Each segment is sampled at 2 to 8 points, at most-/// [`PRESSURE_POINTS`] in all → (position, width) in order along the path, positions clamped into-/// 0..1 and never going back, widths clamped into 0..1. `None` when the curve can't be read or has-/// more than [`MAX_PRESSURE_SEGMENTS`] segments.+/// [`PRESSURE_POINTS`] in all, and also where its width stops rising or falling (at most two more+/// points), so a dip between samples is kept → (position, width) in order along the path,+/// positions clamped into 0..1 and never going back, widths clamped into 0..1. `None` when the+/// curve can't be read or has more than [`MAX_PRESSURE_SEGMENTS`] segments.pub(crate) fn pressure(r: &Reader, crvd: ObjId) -> Option<Vec<(f64, f64)>> {let s = r.s;let data = s.obj(crvd, b"Data")?;@@ -198,8 +201,11 @@ pub(crate) fn pressure(r: &Reader, crvd: ObjId) -> Option<Vec<(f64, f64)>> {let mut samples = vec![(curve.start.x, curve.start.y)];let mut from = curve.start;for [c1, c2, to] in &curve.segments {- for i in 1..=steps {- let t = f64::from(i) / f64::from(steps);+ let mut ts: Vec<f64> = (1..=steps).map(|i| f64::from(i) / f64::from(steps)).collect();+ ts.extend(turning_points(from.y, c1.y, c2.y, to.y).into_iter().flatten());+ ts.sort_by(f64::total_cmp);+ ts.dedup_by(|a, b| (*a - *b).abs() < 1e-9);+ for t in ts {let u = 1.0 - t;let at = |a: f64, b: f64, c: f64, d: f64| u * u * u * a + 3.0 * u * u * t * b + 3.0 * u * t * t * c + t * t * t * d;samples.push((at(from.x, c1.x, c2.x, to.x), at(from.y, c1.y, c2.y, to.y)));@@ -218,6 +224,29 @@ pub(crate) fn pressure(r: &Reader, crvd: ObjId) -> Option<Vec<(f64, f64)>> {)}+/// The parameters strictly between 0 and 1 where the cubic Bézier with control values `a`, `b`,+/// `c` and `d` stops rising or falling (where its derivative is 0). The values are scaled into+/// -1..1 first, so huge ones can't overflow the discriminant.+fn turning_points(a: f64, b: f64, c: f64, d: f64) -> [Option<f64>; 2] {+ let scale = a.abs().max(b.abs()).max(c.abs()).max(d.abs());+ if !(scale.is_finite() && scale > 0.0) {+ return [None, None];+ }+ let (a, b, c, d) = (a / scale, b / scale, c / scale, d / scale);+ let (d0, d1, d2) = (b - a, c - b, d - c);+ let (qa, qb, qc) = (d0 - 2.0 * d1 + d2, 2.0 * (d1 - d0), d0);+ let inside = |t: f64| (t.is_finite() && t > 0.0 && t < 1.0).then_some(t);+ if qa.abs() < 1e-12 {+ return [if qb.abs() < 1e-12 { None } else { inside(-qc / qb) }, None];+ }+ let disc = qb * qb - 4.0 * qa * qc;+ if disc < 0.0 {+ return [None, None];+ }+ let root = disc.sqrt();+ [inside((-qb - root) / (2.0 * qa)), inside((-qb + root) / (2.0 * qa))]+}+struct Anchor {p: Point,inh: Option<Point>,@@ -309,3 +338,19 @@ fn corner_radii(fields: Vec<&Value>) -> Option<Vec<(usize, f64)>> {.collect(),)}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn turning_points_of_huge_control_values_are_found() {+ let small = turning_points(1.0, -3.0, 3.0, 1.0);+ let huge = turning_points(1e200, -3e200, 3e200, 1e200);+ assert!(small.iter().all(Option::is_some), "{small:?}");+ for (s, h) in small.iter().zip(&huge) {+ let (Some(s), Some(h)) = (s, h) else { panic!("{huge:?}") };+ assert!((s - h).abs() < 1e-12, "{small:?} {huge:?}");+ }+ }+}diff --git a/crates/affinity/src/model/read.rs b/crates/affinity/src/model/read.rsindex f94de75b9..00910baab 100644--- a/crates/affinity/src/model/read.rs+++ b/crates/affinity/src/model/read.rs@@ -26,6 +26,9 @@ const MAX_DOCUMENT_CHARS: usize = 16 << 20;/// Table cells of all tables together (each becomes a text object with its edge lines).const MAX_DOCUMENT_CELLS: usize = 1 << 18;+/// Points of all strokes' pressure curves together (a stroke style may be shared by many layers).+const MAX_DOCUMENT_PRESSURE_POINTS: usize = 1 << 20;+/// What a whole read may still use. Shared objects can be linked from many layers, and embedded/// documents are read with what their embedding document left, so linking or embedding the/// same content many times can't multiply the work.@@ -39,10 +42,18 @@ pub(crate) struct Budget {pub(crate) chars: usize,/// Table cells ([`MAX_DOCUMENT_CELLS`] in all).pub(crate) cells: usize,+ /// Points of pressure curves ([`MAX_DOCUMENT_PRESSURE_POINTS`] in all).+ pub(crate) pressure: usize,}impl Budget {- pub(crate) const FULL: Budget = Budget { nodes: MAX_NODES, pixels: MAX_LAYER_PIXELS, chars: MAX_DOCUMENT_CHARS, cells: MAX_DOCUMENT_CELLS };+ pub(crate) const FULL: Budget = Budget {+ nodes: MAX_NODES,+ pixels: MAX_LAYER_PIXELS,+ chars: MAX_DOCUMENT_CHARS,+ cells: MAX_DOCUMENT_CELLS,+ pressure: MAX_DOCUMENT_PRESSURE_POINTS,+ };}/// Read a document: archive, `doc.dat` and the model.diff --git a/crates/affinity/src/paint.rs b/crates/affinity/src/paint.rsindex 144357ab7..cfc95b8dd 100644--- a/crates/affinity/src/paint.rs+++ b/crates/affinity/src/paint.rs@@ -357,9 +357,25 @@ pub(crate) fn stroke(r: &mut Reader, pen: ObjId, ldsc: ObjId, local: Affine, behr.warn("brush strokes (imported as plain strokes)");}// The pressure curve sets the width along the path; one at full width all along is a plain- // stroke.- let profile = match s.obj(ldsc, b"LDeP").map(|p| crate::geometry::pressure(r, p)) {- Some(Some(points)) => (!points.iter().all(|(_, w)| (w - 1.0).abs() < 1e-3)).then_some(points),+ // stroke. Every curve read, full width or not, counts against the document's points, and once+ // they are used up the rest are not read.+ const BEYOND: &str = "pressure strokes beyond the pressure points one document may hold (imported as plain strokes)";+ let ldep = s.obj(ldsc, b"LDeP");+ if ldep.is_some() && r.budget.pressure == 0 {+ r.warn(BEYOND);+ }+ let profile = match ldep.filter(|_| r.budget.pressure > 0).map(|p| crate::geometry::pressure(r, p)) {+ Some(Some(points)) => match r.budget.pressure.checked_sub(points.len()) {+ Some(left) => {+ r.budget.pressure = left;+ (!points.iter().all(|(_, w)| (w - 1.0).abs() < 1e-9)).then_some(points)+ }+ None => {+ r.budget.pressure = 0;+ r.warn(BEYOND);+ None+ }+ },Some(None) => {r.warn("pressure strokes whose pressure curve can't be read (imported as plain strokes)");Nonediff --git a/crates/affinity/tests/support/affinity3-signatures.txt b/crates/affinity/tests/support/affinity3-signatures.txtindex 462d32172..13e8f0c53 100644--- a/crates/affinity/tests/support/affinity3-signatures.txt+++ b/crates/affinity/tests/support/affinity3-signatures.txt@@ -1,6 +1,6 @@-affinity3-mexican-guy.af dpi=300;spreads=1;model_crc32=ce96643c;counts={"depth": 8, "fills": 169, "gradients": 0, "groups": 23, "nodes": 283, "opacity": 1, "segments": 1491, "shapes": 260, "strokes": 114, "subpaths": 264};boards=[];fonts={};warnings=["blur effects (left out) (156×)"]-affinity3-mexican-man.af dpi=300;spreads=1;model_crc32=08a70ca5;counts={"depth": 7, "fills": 277, "gradients": 2, "groups": 29, "nodes": 903, "segments": 3225, "shapes": 874, "strokes": 540, "subpaths": 881};boards=[];fonts={};warnings=["blur effects (left out) (244×)"]-affinity3-mexican-woman.af dpi=300;spreads=1;model_crc32=557d4a95;counts={"depth": 9, "fills": 527, "gradients": 0, "groups": 28, "nodes": 595, "segments": 3562, "shapes": 567, "strokes": 60, "subpaths": 570};boards=[];fonts={};warnings=["blur effects (left out) (278×)"]+affinity3-mexican-guy.af dpi=300;spreads=1;model_crc32=32b7cf3f;counts={"depth": 8, "fills": 169, "gradients": 0, "groups": 23, "nodes": 283, "opacity": 1, "segments": 1491, "shapes": 260, "strokes": 114, "subpaths": 264};boards=[];fonts={};warnings=["blur effects (left out) (156×)"]+affinity3-mexican-man.af dpi=300;spreads=1;model_crc32=c10daaea;counts={"depth": 7, "fills": 277, "gradients": 2, "groups": 29, "nodes": 903, "segments": 3225, "shapes": 874, "strokes": 540, "subpaths": 881};boards=[];fonts={};warnings=["blur effects (left out) (244×)"]+affinity3-mexican-woman.af dpi=300;spreads=1;model_crc32=3bc13374;counts={"depth": 9, "fills": 527, "gradients": 0, "groups": 28, "nodes": 595, "segments": 3562, "shapes": 567, "strokes": 60, "subpaths": 570};boards=[];fonts={};warnings=["blur effects (left out) (278×)"]affinity3-playing-cards.af dpi=300;spreads=1;model_crc32=bc0c838d;counts={"depth": 5, "fills": 363, "gradients": 0, "groups": 758, "nodes": 1350, "segments": 4864, "shapes": 592, "strokes": 17, "subpaths": 656};boards=[];fonts={};warnings=["blur effects (left out) (309×)", "brush strokes (imported as plain strokes)"]patchy-adjust-curves.af dpi=72;spreads=1;model_crc32=36ab962f;counts={"depth": 1, "images": 1, "nodes": 2, "unsupported": 1};boards=[];fonts={};warnings=["adjustment layers"]patchy-adjust-hsl.af dpi=72;spreads=1;model_crc32=e2eac05e;counts={"depth": 1, "images": 1, "nodes": 2, "unsupported": 1};boards=[];fonts={};warnings=["adjustment layers"]diff --git a/crates/engine/src/cmd/fileio/tests_affinity.rs b/crates/engine/src/cmd/fileio/tests_affinity.rsindex a288c5ec1..a57da79fc 100644--- a/crates/engine/src/cmd/fileio/tests_affinity.rs+++ b/crates/engine/src/cmd/fileio/tests_affinity.rs@@ -303,40 +303,52 @@ mod native {/// A version-12 document holding an open curve with an 8 px stroke whose pressure curve (`LDeP`)/// is made of `records`.fn pressure_document(records: Vec<Vec<u8>>) -> Vec<u8> {- let line = F::Def(- 20,- vec![tag(b"PCrv"), tag(b"VNod"), tag(b"Node")],- vec![- (- tag(b"Crvs"),- F::Obj(- tag(b"PCvD"),- vec![(- tag(b"Data"),- F::Pos(vec![F::U8(0), F::U32(1), F::Bool(false), F::Records(18, vec![node(0.0, 0.0, 1, 0), node(100.0, 0.0, 1, 0)])]),- )],- ),- ),- (tag(b"LIFl"), F::Shared(vec![solid(24, rgba(0.0, 0.0, 0.0, 1.0))])),- (- tag(b"LILn"),- F::Shared(vec![F::Def(- 27,- vec![tag(b"LDsc")],- vec![- (tag(b"LDeL"), F::Def(28, vec![tag(b"LSty")], vec![(tag(b"Wght"), F::F64(8.0))])),- (tag(b"LDSc"), F::Bool(false)),- (- tag(b"LDeP"),- F::Obj(tag(b"CrvD"), vec![(tag(b"Data"), F::Pos(vec![F::U32(0), F::Bool(false), F::Records(18, records)]))]),+ pressure_documents(records, 1)+ }++ /// [`pressure_document`] with `copies` curves, all linking the first one's fill and stroke.+ fn pressure_documents(records: Vec<Vec<u8>>, copies: u32) -> Vec<u8> {+ let mut style = Some((+ solid(24, rgba(0.0, 0.0, 0.0, 1.0)),+ F::Def(+ 27,+ vec![tag(b"LDsc")],+ vec![+ (tag(b"LDeL"), F::Def(28, vec![tag(b"LSty")], vec![(tag(b"Wght"), F::F64(8.0))])),+ (tag(b"LDSc"), F::Bool(false)),+ (tag(b"LDeP"), F::Obj(tag(b"CrvD"), vec![(tag(b"Data"), F::Pos(vec![F::U32(0), F::Bool(false), F::Records(18, records)]))])),+ ],+ ),+ ));+ let lines = (0..copies)+ .map(|i| {+ let (fill, line) = style.take().unwrap_or((F::Ref(24), F::Ref(27)));+ F::Def(+ if i == 0 { 20 } else { 1000 + i },+ vec![tag(b"PCrv"), tag(b"VNod"), tag(b"Node")],+ vec![+ (+ tag(b"Crvs"),+ F::Obj(+ tag(b"PCvD"),+ vec![(+ tag(b"Data"),+ F::Pos(vec![+ F::U8(0),+ F::U32(1),+ F::Bool(false),+ F::Records(18, vec![node(0.0, 0.0, 1, 0), node(100.0, 0.0, 1, 0)]),+ ]),+ )],),- ],- )]),- ),- ],- );- let spread =- F::Def(2, vec![tag(b"Sprd")], vec![(tag(b"SprB"), F::F64s(vec![0.0, 0.0, 200.0, 100.0])), (tag(b"Chld"), F::Shared(vec![line]))]);+ ),+ (tag(b"LIFl"), F::Shared(vec![fill])),+ (tag(b"LILn"), F::Shared(vec![line])),+ ],+ )+ })+ .collect();+ let spread = F::Def(2, vec![tag(b"Sprd")], vec![(tag(b"SprB"), F::F64s(vec![0.0, 0.0, 200.0, 100.0])), (tag(b"Chld"), F::Shared(lines))]);let doc = synth::stream(&[(tag(b"UVCn"), F::Obj(tag(b"UVCn"), vec![(tag(b"UPPI"), F::F64(72.0))])),(tag(b"DocR"), F::Def(1, vec![tag(b"DocN")], vec![(tag(b"Chld"), F::Shared(vec![spread]))])),@@ -402,6 +414,56 @@ mod native {assert!(r.warnings.iter().all(|w| !w.contains("pressure")), "{:?}", r.warnings);}+ #[test]+ fn a_dip_between_the_samples_of_a_long_pressure_curve_is_kept() {+ // 256 segments at full width, except one whose handles sit at widths 0 and 2: its width is+ // 1 at its middle and end but 0.71875 a quarter of the way along.+ let mut curve = vec![node(0.0, 1.0, 4, 0)];+ for i in 1..=256 {+ let (a, b) = (f64::from(i - 1) / 256.0, f64::from(i) / 256.0);+ let (h1, h2) = if i == 100 { (0.0, 2.0) } else { (1.0, 1.0) };+ curve.extend([node(a + (b - a) / 3.0, h1, 0, 1), node(b - (b - a) / 3.0, h2, 0, 2), node(b, 1.0, 4, 0)]);+ }+ let profile = stroke_of(&load("dip.af", &pressure_document(curve)).unwrap().doc).profile.unwrap_or_else(|| panic!("the dip is kept"));+ let narrowest = profile.points.iter().map(|p| p.1).fold(1.0, f64::min);+ assert!((narrowest - 0.71).abs() < 0.02, "{narrowest}");+ }++ #[test]+ fn a_pressure_curve_just_under_full_width_is_kept() {+ let curve = vec![node(0.0, 0.9995, 4, 0), node(1.0, 0.9995, 4, 0)];+ let profile = stroke_of(&load("near.af", &pressure_document(curve)).unwrap().doc).profile.unwrap_or_else(|| panic!("the curve is kept"));+ assert_eq!(profile.at(0.5), (0.9995, 0.9995));+ }++ #[test]+ fn pressure_curves_stay_within_the_points_of_one_document() {+ // One 256-segment curve linked from 2100 strokes: more than a million points in all.+ let mut curve = vec![node(0.0, 1.0, 4, 0)];+ for i in 1..=256 {+ let (a, b) = (f64::from(i - 1) / 256.0, f64::from(i) / 256.0);+ curve.extend([node(a + (b - a) / 3.0, 0.0, 0, 1), node(b - (b - a) / 3.0, 0.0, 0, 2), node(b, 1.0, 4, 0)]);+ }+ let r = load("many.af", &pressure_documents(curve, 2100)).unwrap();+ let mut profiles = Vec::new();+ r.doc.walk(|n| {+ if let Some(AppearanceItem::Stroke(k)) = n.appearance.items.iter().find(|i| matches!(i, AppearanceItem::Stroke(_))) {+ profiles.push(k.profile.as_ref().map_or(0, |p| p.points.len()));+ }+ });+ assert_eq!(profiles.len(), 2100);+ assert!(profiles.iter().sum::<usize>() <= 1 << 20, "{}", profiles.iter().sum::<usize>());+ assert!(profiles.iter().filter(|n| **n > 0).count() > 1000);+ assert!(profiles.contains(&0));+ assert!(r.warnings.iter().any(|w| w.contains("pressure points one document may hold")), "{:?}", r.warnings);++ // Curves at full width count too, so linking one from many strokes can't repeat its work+ // without bound.+ let flat: Vec<Vec<u8>> = (0..=768).map(|i| node(f64::from(i) / 768.0, 1.0, if i % 3 == 0 { 4 } else { 0 }, (i % 3) as u8)).collect();+ let r = load("flat-many.af", &pressure_documents(flat, 2100)).unwrap();+ assert!(r.warnings.iter().any(|w| w.contains("pressure points one document may hold")), "{:?}", r.warnings);+ }+#[test]fn native_documents_save_reopen_export_place_and_template() {let bytes = document(Method::Zstd);