Shape operators: cap each expanding operator's output (#2948)

This commit is contained in:
Dylan M. Taylor
2026-11-16 21:58:09 -05:00
committed by GitHub
parent defa16a26f
commit 41da144555
4 changed files with 131 additions and 5 deletions
Generated
+1
View File
@@ -2293,6 +2293,7 @@ dependencies = [
"effectcraft-raster",
"kurbo",
"linesweeper",
"log",
"tiny-skia 0.12.0",
]
+1
View File
@@ -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
View File
@@ -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);
+80
View File
@@ -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);
}