From 946bed1328d1deb21ca1c2ebfa7b7d951e6daaaf Mon Sep 17 00:00:00 2001 From: Livio Sidler <94077193+LS254@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:51:07 +0100 Subject: [PATCH] M4, #2731: lines that are not the outline are stroked together and trimmed by their own stroke; the fill is asked by rows From the second review of #2732: - How far beside a segment the fill is looked for goes by the segment's length: by the network's size it stepped over a small shape far from another. - The fill's winding number comes from the segments of the point's row (Rows): asking the path went through all of it for every segment, 2 s for 2,500 squares and 34 ms now. - The lines in the fill and the ones outside it are stroked as one network, so a join between two of them stays a join. - What an inside stroke takes off past the outline is what the lines ending there paint, not what another line paints beside them. --- crates/pathops/src/loose.rs | 165 +++++++++++++++++++++--------- crates/pathops/src/loose_tests.rs | 72 +++++++++++++ 2 files changed, 190 insertions(+), 47 deletions(-) diff --git a/crates/pathops/src/loose.rs b/crates/pathops/src/loose.rs index bd94239fb..92fd90967 100644 --- a/crates/pathops/src/loose.rs +++ b/crates/pathops/src/loose.rs @@ -33,14 +33,17 @@ pub(crate) fn outline(net: &VectorNetwork, props: &StrokeProps, align: StrokeAli let rounded = net.rounded(); let net = rounded.as_ref().unwrap_or(net); let fill = net.fill_path(); + let rows = Rows::new(&fill); let filled = |p: Point| { - let w = fill.winding(p); + let w = rows.winding(p); if even_odd { w % 2 != 0 } else { w != 0 } }; // A segment is placed by what is filled beside its middle, a little way off to either side: // the loops alone don't say (a loop inside another of the same direction bounds nothing). + // How far off goes by the segment's own length, so that the step stays inside what it bounds + // however far apart the network's shapes lie. let bounds = fill.bounding_box(); - let off = (bounds.width().max(bounds.height()) * 1e-5).max(1e-9); + let far = bounds.width().max(bounds.height()) * 1e-5; let places: Vec = (0..net.segments.len()) .map(|i| { let Some(c) = net.cubic(i) else { return Place::Beyond }; @@ -48,6 +51,8 @@ pub(crate) fn outline(net: &VectorNetwork, props: &StrokeProps, align: StrokeAli if along.hypot2() == 0.0 { along = c.p3 - c.p0; } + let length = (c.p1 - c.p0).hypot() + (c.p2 - c.p1).hypot() + (c.p3 - c.p2).hypot(); + let off = (length * 1e-3).min(far).max(1e-9); let side = Vec2::new(-along.y, along.x).normalize() * off; if !side.is_finite() { return if filled(at) { Place::Within } else { Place::Beyond }; @@ -80,51 +85,9 @@ pub(crate) fn outline(net: &VectorNetwork, props: &StrokeProps, align: StrokeAli }; let op = if align == StrokeAlign::Inside { linesweeper::BinaryOp::Intersection } else { linesweeper::BinaryOp::Difference }; let edge = crate::clip(centred(&part(&|p| p == Place::Edge), w * 2.0), &fill, even_odd, op); - let lines = if align == StrokeAlign::Inside { - let within = centred(&part(&|p| p == Place::Within), w); - // Where a line in the fill ends on the outline, an inside stroke must not show past it. - // Only there: a line may leave the fill further on, or run close to its edge. - let mut on_edge = vec![false; net.vertices.len()]; - for (s, _) in net.segments.iter().zip(&places).filter(|(_, p)| **p == Place::Edge) { - for v in [s.a, s.b] { - if let Some(e) = on_edge.get_mut(v) { - *e = true; - } - } - } - // As far as a cap or a mitre reaches from the point. - let reach = w * props.miter_limit.clamp(2.0, 16.0) / 2.0; - let mut ends = BezPath::new(); - for (s, _) in net.segments.iter().zip(&places).filter(|(_, p)| **p == Place::Within) { - for v in [s.a, s.b] { - if on_edge.get(v) == Some(&true) - && let Some(p) = net.vertices.get(v) - { - ends.extend(Circle::new((p.x, p.y), reach).to_path(0.01)); - if let Some(e) = on_edge.get_mut(v) { - *e = false; - } - } - } - } - let trimmed = if ends.elements().is_empty() { - Ok(within.clone()) - } else { - let past = if even_odd { - crate::simplify(&within).and_then(|s| crate::binary_by(&s, &fill, linesweeper::FillRule::EvenOdd, linesweeper::BinaryOp::Difference)) - } else { - crate::binary(&within, &fill, linesweeper::BinaryOp::Difference) - }; - past.and_then(|past| crate::binary(&past, &ends, linesweeper::BinaryOp::Intersection)) - .and_then(|past| crate::binary(&within, &past, linesweeper::BinaryOp::Difference)) - }; - // Should that fail: all of it cut by the fill, as the outline's stroke is. - let mut lines = trimmed.unwrap_or_else(|_| crate::clip(within, &fill, even_odd, linesweeper::BinaryOp::Intersection)); - lines.extend(centred(&part(&|p| p == Place::Beyond), w).elements().iter().copied()); - lines - } else { - centred(&part(&|p| p != Place::Edge), w) - }; + // The other segments are stroked together, so a join between two of them stays a join. + let others = centred(&part(&|p| p != Place::Edge), w); + let lines = if align == StrokeAlign::Inside { trimmed(net, &places, &others, &fill, even_odd, ¢red, props) } else { others }; // One area without overlaps, as the even-odd rule the aligned strokes are filled by needs. let joined = crate::simplify(&lines).and_then(|lines| crate::binary_by(&edge, &lines, linesweeper::FillRule::EvenOdd, linesweeper::BinaryOp::Union)); @@ -135,6 +98,114 @@ pub(crate) fn outline(net: &VectorNetwork, props: &StrokeProps, align: StrokeAli })) } +/// `others` (the stroke of the segments that are not the outline) for an inside stroke: without +/// what shows past the outline where a line in the fill ends on it. Only that: a line may leave +/// the fill further on or run close to its edge, and another line's stroke there stays whole. +fn trimmed( + net: &VectorNetwork, + places: &[Place], + others: &BezPath, + fill: &BezPath, + even_odd: bool, + centred: &dyn Fn(&VectorNetwork, f64) -> BezPath, + props: &StrokeProps, +) -> BezPath { + let w = props.weight; + let mut on_edge = vec![false; net.vertices.len()]; + for (s, _) in net.segments.iter().zip(places).filter(|(_, p)| **p == Place::Edge) { + for v in [s.a, s.b] { + if let Some(e) = on_edge.get_mut(v) { + *e = true; + } + } + } + // The lines in the fill that end on the outline, and the points where they do. + let ends_on = |s: &figcraft_doc::Segment| [s.a, s.b].into_iter().filter(|v| on_edge.get(*v) == Some(&true)); + let touches: Vec = net.segments.iter().zip(places).map(|(s, p)| *p == Place::Within && ends_on(s).next().is_some()).collect(); + if !touches.contains(&true) { + return others.clone(); + } + // As far as a cap or a mitre reaches from the point. + let reach = w * props.miter_limit.clamp(2.0, 16.0) / 2.0; + let mut around = BezPath::new(); + let mut seen = vec![false; net.vertices.len()]; + for (s, _) in net.segments.iter().zip(&touches).filter(|(_, t)| **t) { + for v in ends_on(s) { + if let (Some(p), Some(seen)) = (net.vertices.get(v), seen.get_mut(v)) + && !std::mem::replace(seen, true) + { + around.extend(Circle::new((p.x, p.y), reach).to_path(0.01)); + } + } + } + let part = |keep: &dyn Fn(usize) -> bool| -> VectorNetwork { + let mut vertices = net.vertices.clone(); + for v in &mut vertices { + v.radius = 0.0; + } + let segments = net.segments.iter().enumerate().filter(|(i, _)| keep(*i)).map(|(_, s)| *s).collect(); + VectorNetwork { vertices, segments, regions: Vec::new() } + }; + let touching = centred(&part(&|i| touches.get(i) == Some(&true)), w); + let rest = centred(&part(&|i| touches.get(i) == Some(&false) && places.get(i) != Some(&Place::Edge)), w); + use linesweeper::BinaryOp::{Difference, Intersection}; + let past = if even_odd { + crate::simplify(&touching).and_then(|s| crate::binary_by(&s, fill, linesweeper::FillRule::EvenOdd, Difference)) + } else { + crate::binary(&touching, fill, Difference) + }; + past.and_then(|past| crate::binary(&past, &around, Intersection)) + .and_then(|past| crate::binary(&past, &rest, Difference)) + .and_then(|past| crate::binary(others, &past, Difference)) + // Should that fail: the lines in the fill cut by it as the outline's stroke is, the others whole. + .unwrap_or_else(|_| { + let within = centred(&part(&|i| places.get(i) == Some(&Place::Within)), w); + let mut lines = crate::clip(within, fill, even_odd, Intersection); + lines.extend(centred(&part(&|i| places.get(i) == Some(&Place::Beyond)), w).elements().iter().copied()); + lines + }) +} + +/// A fill's segments by the rows they cross, for the winding number at many points: a point +/// looks at the segments of its row only. (Asking the path itself goes through all of it for +/// every point: a network of many shapes times its own size.) +pub(crate) struct Rows { + top: f64, + height: f64, + rows: Vec, +} + +impl Rows { + pub(crate) fn new(fill: &BezPath) -> Self { + let bounds = fill.bounding_box(); + let count = (fill.elements().len() as f64).sqrt().ceil().clamp(1.0, 4096.0) as usize; + let height = bounds.height() / count as f64; + let mut this = Self { top: bounds.y0, height, rows: vec![BezPath::new(); count] }; + for seg in fill.segments() { + let b = seg.bounding_box(); + for row in this.row(b.y0)..=this.row(b.y1) { + if let Some(r) = this.rows.get_mut(row) { + r.move_to(seg.start()); + r.push(seg.as_path_el()); + } + } + } + this + } + + fn row(&self, y: f64) -> usize { + if !(self.height > 0.0 && y.is_finite()) { + return 0; + } + (((y - self.top) / self.height).floor().max(0.0) as usize).min(self.rows.len().saturating_sub(1)) + } + + /// The winding number of the fill at `p`: the sum over the segments level with it. + pub(crate) fn winding(&self, p: Point) -> i32 { + self.rows.get(self.row(p.y)).map_or(0, |r| r.winding(p)) + } +} + /// How often each segment is in the loops of the regions. fn loop_uses(net: &VectorNetwork) -> Vec { let mut uses = vec![0usize; net.segments.len()]; diff --git a/crates/pathops/src/loose_tests.rs b/crates/pathops/src/loose_tests.rs index 7e9ef809f..bb2c52ba7 100644 --- a/crates/pathops/src/loose_tests.rs +++ b/crates/pathops/src/loose_tests.rs @@ -124,3 +124,75 @@ fn a_loop_the_fill_rule_does_not_cut_out_is_a_line_in_the_fill() { } } } + +/// The square of 100 and more points and lines: `extra` points after the square's four, and +/// `lines` between points by number. +fn square_with(extra: &[(f64, f64)], lines: &[(usize, usize)]) -> VectorNetwork { + let mut vertices: Vec = [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)].iter().map(|(x, y)| Vertex::new(*x, *y)).collect(); + vertices.extend(extra.iter().map(|(x, y)| Vertex::new(*x, *y))); + let mut segments = vec![Segment::line(0, 1), Segment::line(1, 2), Segment::line(2, 3), Segment::line(3, 0)]; + segments.extend(lines.iter().map(|(a, b)| Segment::line(*a, *b))); + VectorNetwork { vertices, segments, regions: vec![Region { loops: vec![vec![0, 1, 2, 3]], ..Default::default() }] } +} + +#[test] +fn shapes_far_apart_keep_their_aligned_strokes() { + // Two squares of 10, two million units apart: what lies beside an edge is looked for a + // little way off by the edge's own length, not by the size of the whole network. + let far = 2_000_000.0; + let at = [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0), (far, 0.0), (far + 10.0, 0.0), (far + 10.0, 10.0), (far, 10.0)]; + let vertices: Vec = at.iter().map(|(x, y)| Vertex::new(*x, *y)).collect(); + let segments: Vec = + [(0, 1), (1, 2), (2, 3), (3, 0), (4, 5), (5, 6), (6, 7), (7, 4)].iter().map(|(a, b)| Segment::line(*a, *b)).collect(); + let net = VectorNetwork { vertices, segments, regions: vec![Region { loops: vec![vec![0, 1, 2, 3], vec![4, 5, 6, 7]], ..Default::default() }] }; + for align in [StrokeAlign::Inside, StrokeAlign::Outside] { + let area = stroke(&net, align); + for x in [5.0, far + 5.0] { + assert_eq!( + (painted(&area, x, 1.0), painted(&area, x, -1.0)), + (align == StrokeAlign::Inside, align == StrokeAlign::Outside), + "{align:?} at {x}" + ); + } + } +} + +#[test] +fn lines_that_are_not_the_outline_keep_the_join_between_them() { + // From the middle out through the right edge and up: the corner at (105, 50) lies outside + // the fill, between a line that starts in it and one that doesn't. + let net = square_with(&[(50.0, 50.0), (105.0, 50.0), (105.0, -50.0)], &[(4, 5), (5, 6)]); + let props = StrokeProps { weight: 4.0, align: StrokeAlign::Inside, join: figcraft_doc::StrokeJoin::Round, ..Default::default() }; + let area = crate::stroke_outline_of(&net.stroke_path(), &props, true, Some(&net)); + assert!(painted(&area, 106.0, 51.0), "the round join"); + assert!(!painted(&area, 107.5, 52.5), "and no more than it"); +} + +#[test] +fn a_line_ending_on_the_outline_leaves_another_lines_stroke_whole() { + // A branch from a point on the left edge, and a short line just inside that edge beside it, + // a unit of whose stroke lies outside the square. + let mut net = square_with(&[(0.0, 50.0), (40.0, 50.0), (1.0, 45.0), (1.0, 55.0)], &[(4, 5), (6, 7)]); + // The point (0, 50) is on the outline: the left edge goes through it. + net.segments[3] = Segment::line(3, 4); + net.segments.push(Segment::line(4, 0)); + net.regions[0].loops = vec![vec![0, 1, 2, 3, 6]]; + let with_branch = stroke(&net, StrokeAlign::Inside); + assert!(painted(&with_branch, -0.5, 50.0), "the short line's stroke beside the branch's end"); + assert!(painted(&with_branch, 20.0, 51.4) && !painted(&with_branch, 20.0, 53.2), "the branch"); +} + +#[test] +fn the_rows_give_the_fills_own_winding_numbers() { + // A ring and a curved blob beside it, asked at a grid of points. + let mut fill = figcraft_geom::kurbo::Circle::new((40.0, 40.0), 35.0).to_path(0.1); + fill.extend(figcraft_geom::kurbo::Circle::new((40.0, 40.0), 12.0).to_path(0.1).reverse_subpaths()); + fill.extend(figcraft_geom::kurbo::Ellipse::new((130.0, 20.0), (30.0, 55.0), 0.4).to_path(0.1)); + let rows = crate::loose::Rows::new(&fill); + for i in 0..60 { + for j in 0..50 { + let p = Point::new(-10.0 + f64::from(i) * 3.37, -45.0 + f64::from(j) * 2.91); + assert_eq!(rows.winding(p), fill.winding(p), "at {p:?}"); + } + } +}