mirror of
https://github.com/storytold/effectcraft.git
synced 2026-11-19 16:45:28 +00:00
Merge current main and retain CSS plus prefix-path shared APIs
This commit is contained in:
commit
f65ad2a42d
6 files changed
+148
-370
No files matched your search
Generated
+13
-12
@@ -1485,9 +1485,9 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-svg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=006ed3d965d5f3b77829b87a43eacd5ca0b4f997#006ed3d965d5f3b77829b87a43eacd5ca0b4f997"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=af9985523a079c9e25c638003dbd9aa09fa4d254#af9985523a079c9e25c638003dbd9aa09fa4d254"
|
||||
dependencies = [
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=006ed3d965d5f3b77829b87a43eacd5ca0b4f997)",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=af9985523a079c9e25c638003dbd9aa09fa4d254)",
|
||||
"flate2",
|
||||
"kurbo",
|
||||
"quick-xml 0.41.0",
|
||||
@@ -1657,16 +1657,6 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=006ed3d965d5f3b77829b87a43eacd5ca0b4f997#006ed3d965d5f3b77829b87a43eacd5ca0b4f997"
|
||||
dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
@@ -1687,6 +1677,16 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=af9985523a079c9e25c638003dbd9aa09fa4d254#af9985523a079c9e25c638003dbd9aa09fa4d254"
|
||||
dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
@@ -2293,6 +2293,7 @@ dependencies = [
|
||||
"effectcraft-raster",
|
||||
"kurbo",
|
||||
"linesweeper",
|
||||
"log",
|
||||
"tiny-skia 0.12.0",
|
||||
]
|
||||
|
||||
|
||||
+1
-1
@@ -22,7 +22,7 @@ craft-ps = { version = "0.1.0", git = "https://github.com/storytold/craft-libs",
|
||||
craft-exr = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
|
||||
craft-gif = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
|
||||
craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "ce2ec507c2e6a6a078a5f450f641487f8931816d" }
|
||||
craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "006ed3d965d5f3b77829b87a43eacd5ca0b4f997" }
|
||||
craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "af9985523a079c9e25c638003dbd9aa09fa4d254" }
|
||||
craft-webp = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
|
||||
craft-lottie = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
|
||||
craft-mesh = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87", default-features = false, features = ["stl", "obj", "gltf", "fbx"] }
|
||||
|
||||
@@ -14,5 +14,6 @@ effectcraft-geom = { workspace = true }
|
||||
effectcraft-keyframe = { workspace = true }
|
||||
effectcraft-raster = { workspace = true }
|
||||
kurbo = { workspace = true }
|
||||
log = { workspace = true }
|
||||
tiny-skia = { workspace = true }
|
||||
linesweeper = "0.5"
|
||||
+49
-5
@@ -351,14 +351,28 @@ fn round_sub(sub: &Sub, r: f64, out: &mut BezPath) {
|
||||
/// join. `copies` copies are made, copy *i* (0-based) offset by `amount · (i + 1 + copy_offset)`,
|
||||
/// all returned in the same compound path.
|
||||
pub fn offset(paths: &[BezPath], amount: f64, join: Join, miter_limit: f64, copies: f64, copy_offset: f64) -> Vec<BezPath> {
|
||||
let n = copies.round().clamp(1.0, 1000.0) as usize;
|
||||
offset_within(paths, amount, join, miter_limit, copies, copy_offset, MAX_OPERATOR_SEGMENTS)
|
||||
}
|
||||
|
||||
/// [`offset`] with each path's result held to `max` elements (its first copy aside).
|
||||
fn offset_within(paths: &[BezPath], amount: f64, join: Join, miter_limit: f64, copies: f64, copy_offset: f64, max: usize) -> Vec<BezPath> {
|
||||
let n = pieces_within_budget(paths, copies.round().clamp(1.0, 1000.0) as usize);
|
||||
paths
|
||||
.iter()
|
||||
.map(|p| {
|
||||
let mut out = BezPath::new();
|
||||
for i in 0..n {
|
||||
let d = amount * (i as f64 + 1.0 + copy_offset);
|
||||
out.extend(crate::offset::offset_path(p, d, join, miter_limit).elements().iter().copied());
|
||||
let copy = crate::offset::offset_path(p, d, join, miter_limit);
|
||||
// The budget is spent on what `offset_path` returns (an open subpath comes back as
|
||||
// a closed outline of many segments; a zero offset as the path itself): the first
|
||||
// copy is always kept, and a copy that would pass the budget is not made, so the
|
||||
// work stays within a small multiple of it.
|
||||
if i > 0 && out.elements().len().saturating_add(copy.elements().len()) > max {
|
||||
log::warn!("path: Offset Paths made {i} of {n} copies; more would pass {max} segments");
|
||||
break;
|
||||
}
|
||||
out.extend(copy.elements().iter().copied());
|
||||
}
|
||||
out
|
||||
})
|
||||
@@ -387,6 +401,14 @@ pub fn twist(paths: &[BezPath], angle_deg: f64, center: [f64; 2]) -> Vec<BezPath
|
||||
return paths.to_vec();
|
||||
}
|
||||
let k = a / rmax;
|
||||
// The pieces a segment asks for; the uniform cap applies only when the requests together
|
||||
// would pass the budget (long segments keep their detail next to many short ones otherwise).
|
||||
let want = |len: f64| ((a.abs() * len / rmax) / 0.15 + len / 50.0).ceil().clamp(1.0, 64.0) as usize;
|
||||
let requested = paths
|
||||
.iter()
|
||||
.flat_map(subs)
|
||||
.fold(0usize, |n, sub| sub.segs.iter().fold(n.saturating_add(overhead_of(&sub)), |n, seg| n.saturating_add(want(seg.arclen(ACC)))));
|
||||
let most = if requested <= MAX_OPERATOR_SEGMENTS { 64 } else { pieces_within_budget(paths, 64) };
|
||||
let rot = |v: Vec2, th: f64| {
|
||||
let (s, co) = th.sin_cos();
|
||||
Vec2::new(v.x * co - v.y * s, v.x * s + v.y * co)
|
||||
@@ -414,7 +436,7 @@ pub fn twist(paths: &[BezPath], angle_deg: f64, center: [f64; 2]) -> Vec<BezPath
|
||||
for seg in &sub.segs {
|
||||
let cb = seg.to_cubic();
|
||||
let len = seg.arclen(ACC);
|
||||
let m = ((a.abs() * len / rmax) / 0.15 + len / 50.0).ceil().clamp(1.0, 64.0) as usize;
|
||||
let m = want(len).min(most);
|
||||
for i in 0..m {
|
||||
let q = cb.subsegment(i as f64 / m as f64..(i + 1) as f64 / m as f64);
|
||||
let (p0, p3) = (map(q.p0), map(q.p3));
|
||||
@@ -442,6 +464,28 @@ struct Sample {
|
||||
len_next: f64,
|
||||
}
|
||||
|
||||
/// Most segments an expanding operator (Zig Zag, Wiggle Paths, Twist, Offset Paths' copies)
|
||||
/// makes from its input. Operators stack, each expanding the previous one's output; capping each
|
||||
/// output keeps a short stack from multiplying a simple path into billions of points.
|
||||
pub const MAX_OPERATOR_SEGMENTS: usize = 1 << 20;
|
||||
|
||||
/// Elements a subpath adds besides its segments: a `MoveTo`, and a `ClosePath` only when closed.
|
||||
fn overhead_of(sub: &Sub) -> usize {
|
||||
if sub.closed { 2 } else { 1 }
|
||||
}
|
||||
|
||||
/// `want` pieces (or copies) per input segment, reduced so the whole output (segments times
|
||||
/// pieces, plus per-subpath overhead) stays within [`MAX_OPERATOR_SEGMENTS`] (never below 1, so the input itself always passes through).
|
||||
fn pieces_within_budget(paths: &[BezPath], want: usize) -> usize {
|
||||
// Count what is subdivided (drawn segments) and keep room for each subpath's own MoveTo/Close.
|
||||
let (mut segs, mut overhead) = (0usize, 0usize);
|
||||
for sub in paths.iter().flat_map(subs) {
|
||||
segs = segs.saturating_add(sub.segs.len());
|
||||
overhead = overhead.saturating_add(overhead_of(&sub));
|
||||
}
|
||||
want.min(MAX_OPERATOR_SEGMENTS.saturating_sub(overhead) / segs.max(1)).max(1)
|
||||
}
|
||||
|
||||
/// Split every segment into `m` pieces of equal arc length. Original vertices get the average of
|
||||
/// their incoming and outgoing tangents (so a corner's normal is its bisector).
|
||||
fn resample(sub: &Sub, m: usize) -> Vec<Sample> {
|
||||
@@ -503,7 +547,7 @@ fn emit(samples: &[Sample], disp: &[Vec2], closed: bool, smooth: bool, handle: f
|
||||
/// `smooth` makes rounded waves instead of sharp zig zags. A closed path with `n` segments ends up
|
||||
/// with `n · (ridges + 1)` vertices (open: one more).
|
||||
pub fn zigzag(paths: &[BezPath], size: f64, ridges: f64, smooth: bool) -> Vec<BezPath> {
|
||||
let m = ridges.round().clamp(0.0, 1000.0) as usize + 1;
|
||||
let m = pieces_within_budget(paths, ridges.round().clamp(0.0, 1000.0) as usize + 1);
|
||||
paths
|
||||
.iter()
|
||||
.map(|p| {
|
||||
@@ -586,7 +630,7 @@ pub fn wiggle(paths: &[BezPath], w: &WiggleParams, time_s: f64) -> Vec<BezPath>
|
||||
if w.size == 0.0 {
|
||||
return paths.to_vec();
|
||||
}
|
||||
let m = w.detail.round().clamp(0.0, 1000.0) as usize + 1;
|
||||
let m = pieces_within_budget(paths, w.detail.round().clamp(0.0, 1000.0) as usize + 1);
|
||||
let seed = w.seed.round() as i64 as u64;
|
||||
let t = time_s * w.speed + w.phase_deg / 360.0;
|
||||
let corr = (w.correlation / 100.0).clamp(0.0, 1.0);
|
||||
|
||||
@@ -182,6 +182,25 @@ fn offset_copies() {
|
||||
assert!(close(o[0].bounding_box().width(), 140.0, 1e-3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offset_copies_are_budgeted_by_the_output_they_return() {
|
||||
// An open one-segment subpath comes back as a closed outline of several elements, so the copies
|
||||
// stop when the returned elements pass the budget, not when the input segments would.
|
||||
let line = || {
|
||||
let mut p = BezPath::new();
|
||||
p.move_to((0.0, 0.0));
|
||||
p.line_to((50.0, 0.0));
|
||||
p
|
||||
};
|
||||
let one = offset_within(&[line()], 5.0, Join::Round, 4.0, 1.0, 0.0, usize::MAX)[0].elements().len();
|
||||
assert!(one > 4, "{one}");
|
||||
let o = offset_within(&[line()], 5.0, Join::Round, 4.0, 50.0, 0.0, one * 3);
|
||||
let moves = o[0].elements().iter().filter(|e| matches!(e, PathEl::MoveTo(_))).count();
|
||||
assert!((1..50).contains(&moves) && o[0].elements().len() <= one * 4, "{moves} contours, {} elements", o[0].elements().len());
|
||||
// The first copy always comes back, however small the budget.
|
||||
assert!(!offset_within(&[line()], 5.0, Join::Round, 4.0, 5.0, 0.0, 0)[0].elements().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offset_open_path_outlines() {
|
||||
let mut l = BezPath::new();
|
||||
@@ -246,6 +265,22 @@ fn twist_of_centred_circle_keeps_it_round() {
|
||||
assert_eq!(id[0], sq(0.0, 0.0, 5.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn twist_keeps_requested_detail_when_the_whole_request_fits_the_budget() {
|
||||
// One long segment asks for 64 pieces; 20,000 tiny ones ask for one each. Together that is
|
||||
// far under the budget, so the long one is not cut to what a uniform 64 per segment would allow.
|
||||
let mut long = BezPath::new();
|
||||
long.move_to((0.0, 0.0));
|
||||
long.line_to((5000.0, 0.0));
|
||||
let mut tiny = BezPath::new();
|
||||
tiny.move_to((0.0, 1.0));
|
||||
for i in 1..=20_000 {
|
||||
tiny.line_to((i as f64 * 1e-3, 1.0));
|
||||
}
|
||||
let t = twist(&[long, tiny], 90.0, [0.0, 0.0]);
|
||||
assert_eq!(t[0].elements().len(), 1 + 64);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- zig zag
|
||||
|
||||
#[test]
|
||||
@@ -417,3 +452,48 @@ fn normalize_and_filled_area() {
|
||||
let n = crate::boolean::normalize(&p, FillRule::EvenOdd);
|
||||
assert!(close(n.area().abs(), 10000.0, 1e-6));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- operator budget
|
||||
|
||||
#[test]
|
||||
fn stacked_expanding_operators_stay_within_the_segment_budget() {
|
||||
// Three Zig Zags at 1000 ridges would turn a square into 4 · 1001³ segments; each output
|
||||
// is held to the budget instead, and the last operators still pass the geometry through.
|
||||
let mut p = vec![sq(0.0, 0.0, 100.0)];
|
||||
for _ in 0..3 {
|
||||
p = zigzag(&p, 1.0, 1000.0, false);
|
||||
let n: usize = p.iter().map(|q| q.elements().len()).sum();
|
||||
assert!(n <= 2 * MAX_OPERATOR_SEGMENTS, "{n}");
|
||||
}
|
||||
let w = wiggle(&p, &WiggleParams { detail: 1000.0, ..Default::default() }, 0.0);
|
||||
let n: usize = w.iter().map(|q| q.elements().len()).sum();
|
||||
assert!(n <= 2 * MAX_OPERATOR_SEGMENTS, "{n}");
|
||||
let o = offset(&[sq(0.0, 0.0, 100.0)], 1.0, Join::Miter, 4.0, 1000.0, 0.0);
|
||||
assert!(!o[0].elements().is_empty());
|
||||
// Within the budget nothing changes: 4 segments × 11 pieces.
|
||||
assert_eq!(vertex_count(&zigzag(&[sq(0.0, 0.0, 100.0)], 1.0, 10.0, false)[0]), 44);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn many_short_open_paths_keep_their_requested_detail_within_the_budget() {
|
||||
// 1000 open lines at 1000 ridges: 1,001,000 segments fit the budget, so nothing is reduced.
|
||||
let lines: Vec<BezPath> = (0..1000)
|
||||
.map(|i| {
|
||||
let mut p = BezPath::new();
|
||||
p.move_to((0.0, i as f64));
|
||||
p.line_to((100.0, i as f64));
|
||||
p
|
||||
})
|
||||
.collect();
|
||||
let z = zigzag(&lines, 1.0, 1000.0, false);
|
||||
assert!(z.iter().all(|q| q.elements().len() == 1 + 1001));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_subpaths_reserve_one_element_of_overhead() {
|
||||
// 349,525 open lines: the move-to is the only extra element, so 2 copies fit the budget
|
||||
// (a closed subpath's extra close-path would leave room for 1).
|
||||
let line = BezPath::from_vec(vec![PathEl::MoveTo((0.0, 0.0).into()), PathEl::LineTo((1.0, 0.0).into())]);
|
||||
let lines = vec![line; 349_525];
|
||||
assert_eq!(pieces_within_budget(&lines, 3), 2);
|
||||
}
|
||||
+4
-352
@@ -1,360 +1,12 @@
|
||||
//! SVG path data (SVG 1.1 §8.3 / SVG 2 §9.3): every command, implicit repeats, relative
|
||||
//! coordinates, smooth curves and elliptical arcs (converted to cubics through kurbo's `SvgArc`).
|
||||
//! Parsing stops at the first error, keeping what was read (as the specification asks).
|
||||
//! Prefix-preserving SVG path and numeric-list parsing is shared with craft-svg.
|
||||
//! App document budgets and geometry policy remain with the importer.
|
||||
|
||||
use kurbo::{BezPath, PathEl, Point, SvgArc, Vec2};
|
||||
|
||||
/// Maximum path elements retained from one SVG path or point list.
|
||||
pub(crate) const MAX_PATH_ELEMENTS: usize = 100_000;
|
||||
|
||||
/// Tokenizer over numbers and command letters.
|
||||
struct Lex<'a> {
|
||||
b: &'a [u8],
|
||||
i: usize,
|
||||
}
|
||||
|
||||
impl Lex<'_> {
|
||||
fn skip_sep(&mut self) {
|
||||
while self.i < self.b.len() && (self.b[self.i].is_ascii_whitespace() || self.b[self.i] == b',') {
|
||||
self.i += 1;
|
||||
}
|
||||
}
|
||||
fn command(&mut self) -> Option<u8> {
|
||||
self.skip_sep();
|
||||
let c = *self.b.get(self.i)?;
|
||||
if c.is_ascii_alphabetic() && c != b'e' && c != b'E' {
|
||||
self.i += 1;
|
||||
Some(c)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
fn at_number(&mut self) -> bool {
|
||||
self.skip_sep();
|
||||
self.b.get(self.i).is_some_and(|c| c.is_ascii_digit() || matches!(c, b'-' | b'+' | b'.'))
|
||||
}
|
||||
fn number(&mut self) -> Option<f64> {
|
||||
self.skip_sep();
|
||||
let start = self.i;
|
||||
let b = self.b;
|
||||
let mut i = self.i;
|
||||
if i < b.len() && matches!(b[i], b'-' | b'+') {
|
||||
i += 1;
|
||||
}
|
||||
let mut digits = false;
|
||||
while i < b.len() && b[i].is_ascii_digit() {
|
||||
i += 1;
|
||||
digits = true;
|
||||
}
|
||||
if i < b.len() && b[i] == b'.' {
|
||||
i += 1;
|
||||
while i < b.len() && b[i].is_ascii_digit() {
|
||||
i += 1;
|
||||
digits = true;
|
||||
}
|
||||
}
|
||||
if !digits {
|
||||
return None;
|
||||
}
|
||||
if i < b.len() && matches!(b[i], b'e' | b'E') {
|
||||
let mut j = i + 1;
|
||||
if j < b.len() && matches!(b[j], b'-' | b'+') {
|
||||
j += 1;
|
||||
}
|
||||
if j < b.len() && b[j].is_ascii_digit() {
|
||||
while j < b.len() && b[j].is_ascii_digit() {
|
||||
j += 1;
|
||||
}
|
||||
i = j;
|
||||
}
|
||||
}
|
||||
self.i = i;
|
||||
let number = std::str::from_utf8(&b[start..i]).ok()?.parse::<f64>().ok()?;
|
||||
number.is_finite().then_some(number)
|
||||
}
|
||||
/// Arc flags may be written without separators ("a1 1 0 00 1 1").
|
||||
fn flag(&mut self) -> Option<bool> {
|
||||
self.skip_sep();
|
||||
let c = *self.b.get(self.i)?;
|
||||
self.i += 1;
|
||||
match c {
|
||||
b'0' => Some(false),
|
||||
b'1' => Some(true),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse no more than `max_values`; the flag reports whether another valid value was present.
|
||||
pub(crate) fn numbers_bounded(s: &str, max_values: usize) -> (Vec<f64>, bool) {
|
||||
let mut l = Lex { b: s.as_bytes(), i: 0 };
|
||||
let mut v = vec![];
|
||||
while l.at_number() {
|
||||
if v.len() >= max_values {
|
||||
return (v, true);
|
||||
}
|
||||
match l.number() {
|
||||
Some(x) => v.push(x),
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
(v, false)
|
||||
}
|
||||
|
||||
/// Parse path data into a kurbo path, retaining at most [`MAX_PATH_ELEMENTS`] elements.
|
||||
/// Malformed or overlong input returns the prefix parsed before the problem.
|
||||
pub fn parse_path_data(d: &str) -> BezPath {
|
||||
parse_path_data_bounded(d, MAX_PATH_ELEMENTS).0
|
||||
}
|
||||
|
||||
/// Pen position and reflection state while parsing path commands.
|
||||
struct PathState {
|
||||
/// Current point.
|
||||
current: Point,
|
||||
/// Start of the current subpath.
|
||||
start: Point,
|
||||
/// Last cubic control point, for smooth curves.
|
||||
last_cubic: Option<Point>,
|
||||
/// Last quadratic control point, for smooth curves.
|
||||
last_quad: Option<Point>,
|
||||
/// Whether a subpath is open.
|
||||
open: bool,
|
||||
}
|
||||
|
||||
/// Cap on path elements and whether it has been hit.
|
||||
struct PathLimit {
|
||||
/// Maximum number of path elements.
|
||||
max_elements: usize,
|
||||
/// Set when the cap or a non-finite coordinate stopped output.
|
||||
exceeded: bool,
|
||||
}
|
||||
|
||||
/// Parse at most `max_elements`, reporting when more path geometry was present.
|
||||
pub(crate) fn parse_path_data_bounded(d: &str, max_elements: usize) -> (BezPath, bool) {
|
||||
let mut l = Lex { b: d.as_bytes(), i: 0 };
|
||||
let mut p = BezPath::new();
|
||||
let mut state = PathState { current: Point::ZERO, start: Point::ZERO, last_cubic: None, last_quad: None, open: false };
|
||||
let mut limit = PathLimit { max_elements, exceeded: false };
|
||||
let mut cmd: Option<u8> = None;
|
||||
loop {
|
||||
if p.elements().len() >= limit.max_elements {
|
||||
l.skip_sep();
|
||||
limit.exceeded = l.i < l.b.len();
|
||||
break;
|
||||
}
|
||||
let c = match l.command() {
|
||||
Some(c) => c,
|
||||
None => match cmd {
|
||||
// Implicit repeat (a moveto repeats as lineto). Z takes no numbers, so a number
|
||||
// after it is an error: repeating Z would loop forever without consuming input.
|
||||
Some(c) if l.at_number() && !c.eq_ignore_ascii_case(&b'z') => match c {
|
||||
b'M' => b'L',
|
||||
b'm' => b'l',
|
||||
other => other,
|
||||
},
|
||||
_ => break,
|
||||
},
|
||||
};
|
||||
let rel = c.is_ascii_lowercase();
|
||||
let base = if rel { state.current.to_vec2() } else { Vec2::ZERO };
|
||||
let pt = |l: &mut Lex| -> Option<Point> { Some(Point::new(l.number()?, l.number()?) + base) };
|
||||
let ok = (|| -> Option<()> {
|
||||
match c.to_ascii_uppercase() {
|
||||
b'M' => {
|
||||
state.current = pt(&mut l)?;
|
||||
if !push_element(&mut p, PathEl::MoveTo(state.current), &mut limit) {
|
||||
return None;
|
||||
}
|
||||
state.start = state.current;
|
||||
state.open = true;
|
||||
state.last_cubic = None;
|
||||
state.last_quad = None;
|
||||
}
|
||||
b'Z' => {
|
||||
if state.open && !push_element(&mut p, PathEl::ClosePath, &mut limit) {
|
||||
return None;
|
||||
}
|
||||
state.current = state.start;
|
||||
state.last_cubic = None;
|
||||
state.last_quad = None;
|
||||
}
|
||||
_ if !state.open => {
|
||||
// A segment without a preceding moveto starts at the current point.
|
||||
if !push_element(&mut p, PathEl::MoveTo(state.current), &mut limit) {
|
||||
return None;
|
||||
}
|
||||
state.open = true;
|
||||
return segment(&mut l, c, base, &mut p, &mut state, &mut limit);
|
||||
}
|
||||
_ => return segment(&mut l, c, base, &mut p, &mut state, &mut limit),
|
||||
}
|
||||
Some(())
|
||||
})();
|
||||
if ok.is_none() {
|
||||
break;
|
||||
}
|
||||
if limit.exceeded {
|
||||
break;
|
||||
}
|
||||
cmd = Some(c);
|
||||
if c.eq_ignore_ascii_case(&b'z') {
|
||||
// After Z a new segment starts from the subpath start (an unused move is dropped
|
||||
// below).
|
||||
if !push_element(&mut p, PathEl::MoveTo(state.start), &mut limit) {
|
||||
break;
|
||||
}
|
||||
state.open = true;
|
||||
}
|
||||
}
|
||||
(strip_trailing_moves(p), limit.exceeded)
|
||||
}
|
||||
|
||||
/// Push an element if finite and under the cap; otherwise mark the limit exceeded and return false.
|
||||
fn push_element(p: &mut BezPath, element: PathEl, limit: &mut PathLimit) -> bool {
|
||||
let finite = match element {
|
||||
PathEl::MoveTo(point) | PathEl::LineTo(point) => point.x.is_finite() && point.y.is_finite(),
|
||||
PathEl::QuadTo(control, point) => [control.x, control.y, point.x, point.y].iter().all(|value| value.is_finite()),
|
||||
PathEl::CurveTo(first, second, point) => [first.x, first.y, second.x, second.y, point.x, point.y].iter().all(|value| value.is_finite()),
|
||||
PathEl::ClosePath => true,
|
||||
};
|
||||
if p.elements().len() >= limit.max_elements || !finite {
|
||||
limit.exceeded = true;
|
||||
return false;
|
||||
}
|
||||
p.push(element);
|
||||
true
|
||||
}
|
||||
|
||||
/// Parse one path command's arguments into `p`, returning `None` on malformed or over-limit input.
|
||||
fn segment(l: &mut Lex, c: u8, base: Vec2, p: &mut BezPath, state: &mut PathState, limit: &mut PathLimit) -> Option<()> {
|
||||
let num = |l: &mut Lex| l.number();
|
||||
let pt = |l: &mut Lex| -> Option<Point> { Some(Point::new(l.number()?, l.number()?) + base) };
|
||||
match c.to_ascii_uppercase() {
|
||||
b'L' => {
|
||||
let current = pt(l)?;
|
||||
if !push_element(p, PathEl::LineTo(current), limit) {
|
||||
return None;
|
||||
}
|
||||
state.current = current;
|
||||
state.last_cubic = None;
|
||||
state.last_quad = None;
|
||||
}
|
||||
b'H' => {
|
||||
let x = num(l)? + base.x;
|
||||
let current = Point::new(x, state.current.y);
|
||||
if !push_element(p, PathEl::LineTo(current), limit) {
|
||||
return None;
|
||||
}
|
||||
state.current = current;
|
||||
state.last_cubic = None;
|
||||
state.last_quad = None;
|
||||
}
|
||||
b'V' => {
|
||||
let y = num(l)? + base.y;
|
||||
let current = Point::new(state.current.x, y);
|
||||
if !push_element(p, PathEl::LineTo(current), limit) {
|
||||
return None;
|
||||
}
|
||||
state.current = current;
|
||||
state.last_cubic = None;
|
||||
state.last_quad = None;
|
||||
}
|
||||
b'C' => {
|
||||
let (c1, c2, e) = (pt(l)?, pt(l)?, pt(l)?);
|
||||
if !push_element(p, PathEl::CurveTo(c1, c2, e), limit) {
|
||||
return None;
|
||||
}
|
||||
state.last_cubic = Some(c2);
|
||||
state.last_quad = None;
|
||||
state.current = e;
|
||||
}
|
||||
b'S' => {
|
||||
let c1 = state.last_cubic.map_or(state.current, |c| state.current + (state.current - c));
|
||||
let (c2, e) = (pt(l)?, pt(l)?);
|
||||
if !push_element(p, PathEl::CurveTo(c1, c2, e), limit) {
|
||||
return None;
|
||||
}
|
||||
state.last_cubic = Some(c2);
|
||||
state.last_quad = None;
|
||||
state.current = e;
|
||||
}
|
||||
b'Q' => {
|
||||
let (q, e) = (pt(l)?, pt(l)?);
|
||||
if !push_element(p, PathEl::QuadTo(q, e), limit) {
|
||||
return None;
|
||||
}
|
||||
state.last_quad = Some(q);
|
||||
state.last_cubic = None;
|
||||
state.current = e;
|
||||
}
|
||||
b'T' => {
|
||||
let q = state.last_quad.map_or(state.current, |c| state.current + (state.current - c));
|
||||
let e = pt(l)?;
|
||||
if !push_element(p, PathEl::QuadTo(q, e), limit) {
|
||||
return None;
|
||||
}
|
||||
state.last_quad = Some(q);
|
||||
state.last_cubic = None;
|
||||
state.current = e;
|
||||
}
|
||||
b'A' => {
|
||||
let rx = num(l)?.abs();
|
||||
let ry = num(l)?.abs();
|
||||
let rot = num(l)?;
|
||||
let large = l.flag()?;
|
||||
let sweep = l.flag()?;
|
||||
let e = pt(l)?;
|
||||
let arc = SvgArc { from: state.current, to: e, radii: Vec2::new(rx, ry), x_rotation: rot.to_radians(), large_arc: large, sweep };
|
||||
let mut last_end = None;
|
||||
if let Some(a) = kurbo::Arc::from_svg_arc(&arc) {
|
||||
// Scale tolerance with the radius so the segment count stays bounded.
|
||||
let tol = 0.1_f64.max(a.radii.x.max(a.radii.y) * 1e-4);
|
||||
a.to_cubic_beziers(tol, |c1, c2, end| {
|
||||
if limit.exceeded {
|
||||
return;
|
||||
}
|
||||
if push_element(p, PathEl::CurveTo(c1, c2, end), limit) {
|
||||
last_end = Some(end);
|
||||
}
|
||||
});
|
||||
}
|
||||
if limit.exceeded {
|
||||
return None;
|
||||
}
|
||||
// Degenerate arcs (e.g. huge radii) may emit nothing or stop short of the end point.
|
||||
if last_end.is_none_or(|q| (q - e).hypot() > 1e-3 * (1.0 + e.to_vec2().hypot())) && !push_element(p, PathEl::LineTo(e), limit) {
|
||||
return None;
|
||||
}
|
||||
state.current = e;
|
||||
state.last_cubic = None;
|
||||
state.last_quad = None;
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// Drop move-tos that start no segment (from closepath bookkeeping).
|
||||
fn strip_trailing_moves(p: BezPath) -> BezPath {
|
||||
use kurbo::PathEl;
|
||||
let els = p.elements();
|
||||
let mut out = BezPath::new();
|
||||
for (i, e) in els.iter().enumerate() {
|
||||
if let PathEl::MoveTo(_) = e {
|
||||
let next_is_seg = els.get(i + 1).is_some_and(|n| !matches!(n, PathEl::MoveTo(_)));
|
||||
if !next_is_seg {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
out.push(*e);
|
||||
}
|
||||
out
|
||||
}
|
||||
pub use craft_svg::prefix_path::{MAX_PATH_ELEMENTS, numbers_bounded, parse_path_data, parse_path_data_bounded};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use kurbo::PathEl;
|
||||
use kurbo::{PathEl, Point};
|
||||
|
||||
#[test]
|
||||
/// Huge arc radii stay bounded.
|
||||
|
||||
Reference in new issue
Block a user