linesweeper: exact copies of a shape no longer rescan the bundle for every touch

Exact copies of a shape queue a touch event for every pair of coincident
segments, and the touch branch of Sweeper::handle_intersection scanned
the whole bundle in both directions for each one. Sweeping n copies took
time growing faster than n^3: 200 copies of a 4-point polygon took 3.9 s
and 400 copies took 98 s in a release build.

The touch branch now runs its scan right or left from a segment at most
once per sweep line until the sweep-line order changes. A repeated scan
reads the same order, y and segments and would only push events already
queued, so the output does not change. README.craft.md, SOURCE.json and
NOTICE record the change as a local patch.
This commit is contained in:
dotCooCoo committed 2026-11-07 10:13:46 -08:00
1 parent 904f55bb21
commit dec46890b7
4 files changed
+182 -15

No files matched your search

+3 -3
View File
@@ -218,10 +218,10 @@ applications retain their own document-font selection and licensing policy.
linesweeper
linesweeper 0.5.0 (https://crates.io/crates/linesweeper/0.5.0), MIT OR Apache-2.0, is stored in
vendor/linesweeper with its upstream license files and no file changed. Its manifest names Joe Neeman
vendor/linesweeper with its upstream license files and one local patch. Its manifest names Joe Neeman
as author, and its LICENSE-MIT reads "Copyright (c) 2018 Raph Levien". See
vendor/linesweeper/README.craft.md and vendor/linesweeper/SOURCE.json for provenance and the files
left out.
vendor/linesweeper/README.craft.md and vendor/linesweeper/SOURCE.json for provenance, the local
change and the files left out.
Platform lifecycle source provenance
+13 -7
View File
@@ -1,15 +1,21 @@
# Local linesweeper 0.5.0 copy
This is the crates.io linesweeper 0.5.0 package (MIT OR Apache-2.0) with some files left out and no
file changed. `.cargo_vcs_info.json` names the commit it was packaged from,
This is the crates.io linesweeper 0.5.0 package (MIT OR Apache-2.0) with some files left out and the
local patches listed below. `.cargo_vcs_info.json` names the commit it was packaged from,
`824b0791a750f7b27b8edcbb6c6244d0e629875e`. That commit is not in the GitHub repository the manifest
names, which is archived; its README says development moved off GitHub.
Every file here except this one and `SOURCE.json` is byte for byte the file in the `.crate` archive.
`SOURCE.json` records the hash of the `.crate` download (`source_archive_sha256`) and, for every file
kept, the hash in the package (`source_sha256`) and the hash here (`sha256`). `upstream_repository` is
null because no public repository this copy can name holds `upstream_revision`. `local_patches` is
empty.
Every file here except this one, `SOURCE.json` and the patched files below is byte for byte the file
in the `.crate` archive. `SOURCE.json` records the hash of the `.crate` download
(`source_archive_sha256`) and, for every file kept, the hash in the package (`source_sha256`) and the
hash here (`sha256`). `upstream_repository` is null because no public repository this copy can name
holds `upstream_revision`. `local_patches` describes each local patch.
## Local patches
| File | Change |
|---|---|
| `src/sweep/sweep_line.rs` | The touch branch of `Sweeper::handle_intersection` runs its scan right from a segment, or left from a segment, at most once per sweep line until the sweep-line order changes. Exact copies of a shape queue a touch event for every pair of coincident segments, and each event used to scan the whole bundle in both directions, so sweeping `n` copies took time growing faster than `n^3`. The skipped scans would only push events already queued, so the output does not change. The `coincident_copies_scan_once_per_order` test counts the scans for 60 copies of two shapes, and `coincident_copies_keep_the_fill` compares the output fill with the input's nonzero fill for 200 inputs with exact, reversed and split copies. |
`omitted_files` lists the 43 files of the package left out here, with their hashes:
+4 -2
View File
@@ -7,7 +7,9 @@
"upstream_repository": null,
"upstream_revision": "824b0791a750f7b27b8edcbb6c6244d0e629875e",
"upstream_directory": "",
"local_patches": [],
"local_patches": [
"In `src/sweep/sweep_line.rs`, the touch branch of `Sweeper::handle_intersection` runs each scan from a segment in a direction at most once per sweep line until the sweep-line order changes, so exact copies of a shape no longer rescan the whole coincident bundle for every touch event."
],
"files": [
{ "path": ".cargo_vcs_info.json", "source_sha256": "47fba6a9dbdf445a5c97f783c9be62093035f9d5e5cdc2cf3216ad8259bcd8fc", "source_git_blob": null, "sha256": "47fba6a9dbdf445a5c97f783c9be62093035f9d5e5cdc2cf3216ad8259bcd8fc" },
{ "path": ".gitignore", "source_sha256": "88b59092499ae05234330eb7d0b01e953e969caf05261530e3765eef02536cf0", "source_git_blob": null, "sha256": "88b59092499ae05234330eb7d0b01e953e969caf05261530e3765eef02536cf0" },
@@ -62,7 +64,7 @@
{ "path": "src/sweep/snapshots/linesweeper__sweep__sweep_line__tests__square.snap", "source_sha256": "b35c3e6a38d5ecdd8acf315ba0b0bd6485cd8b40193fdd76bd446bdfdb6eda77", "source_git_blob": null, "sha256": "b35c3e6a38d5ecdd8acf315ba0b0bd6485cd8b40193fdd76bd446bdfdb6eda77" },
{ "path": "src/sweep/snapshots/linesweeper__sweep__sweep_line__tests__square_and_diamond.snap", "source_sha256": "3f01a76fb7ff4aef0fd55fd869602d4a2b69fff1bd65632f406b275b5d6af600", "source_git_blob": null, "sha256": "3f01a76fb7ff4aef0fd55fd869602d4a2b69fff1bd65632f406b275b5d6af600" },
{ "path": "src/sweep/snapshots/linesweeper__sweep__sweep_line__tests__two_squares.snap", "source_sha256": "79e3c95e563a66c0ce244125470a106a18dfe29f276b732defd305406c873c7e", "source_git_blob": null, "sha256": "79e3c95e563a66c0ce244125470a106a18dfe29f276b732defd305406c873c7e" },
{ "path": "src/sweep/sweep_line.rs", "source_sha256": "822b261f682911ea0c0370eaf17d9201a1e639b315359dcb6a3b877a229816e3", "source_git_blob": null, "sha256": "822b261f682911ea0c0370eaf17d9201a1e639b315359dcb6a3b877a229816e3" },
{ "path": "src/sweep/sweep_line.rs", "source_sha256": "822b261f682911ea0c0370eaf17d9201a1e639b315359dcb6a3b877a229816e3", "source_git_blob": null, "sha256": "8e2997347238f11d645647a69a30c4e00d997f63dac163e73f242aa0918d4917" },
{ "path": "src/topology.rs", "source_sha256": "9c9b48bc3853884425127e2d64e8ed957ba0d27e1696e2c457e95282e52d6a5b", "source_git_blob": null, "sha256": "9c9b48bc3853884425127e2d64e8ed957ba0d27e1696e2c457e95282e52d6a5b" },
{ "path": "src/treevec.rs", "source_sha256": "d88b9fbf02fa9f318560e1d483d465555f2b696ae12c00f8e4f5b71ea6779445", "source_git_blob": null, "sha256": "d88b9fbf02fa9f318560e1d483d465555f2b696ae12c00f8e4f5b71ea6779445" },
{ "path": "src/typed_vec.rs", "source_sha256": "3e9a2675b8a40d8fc4df0575bd9d0d16b5604d18e9b78638dd5a612b28fc4c30", "source_git_blob": null, "sha256": "3e9a2675b8a40d8fc4df0575bd9d0d16b5604d18e9b78638dd5a612b28fc4c30" },
+162 -3
View File
@@ -350,6 +350,17 @@ pub struct Sweeper<'a> {
comparisons: RefCell<ComparisonCache>,
conservative_comparisons: RefCell<ComparisonCache>,
// Craft patch (coincident touch rescan): the (segment, scans right) pairs
// whose touch-event scan in `handle_intersection` already ran at the
// current `y` with the current sweep-line order. A scan reads only the
// order, `y` and the segments, so running it again before the order
// changes pushes only events it already pushed. Exact copies of a shape
// queue a touch event for every pair of coincident segments, and each one
// used to scan the whole bundle in both directions.
touch_scans: rustc_hash::FxHashSet<(SegIdx, bool)>,
#[cfg(test)]
touch_scan_count: usize,
}
impl<'segs> Sweeper<'segs> {
@@ -377,6 +388,9 @@ impl<'segs> Sweeper<'segs> {
horizontals: Vec::new(),
comparisons: RefCell::new(ComparisonCache::new(eps, eps / 2.0)),
conservative_comparisons: RefCell::new(ComparisonCache::new(4.0 * eps, eps / 2.0)),
touch_scans: rustc_hash::FxHashSet::default(),
#[cfg(test)]
touch_scan_count: 0,
}
}
@@ -469,6 +483,7 @@ impl<'segs> Sweeper<'segs> {
self.y = y;
self.segs_needing_positions.clear();
self.horizontals.clear();
self.touch_scans.clear();
}
fn intersection_scan_right(&mut self, start_idx: usize, which: WhichTouch) {
@@ -785,6 +800,9 @@ impl<'segs> Sweeper<'segs> {
}
}
// The order changes below, so earlier touch scans no longer stand.
self.touch_scans.clear();
// Remove them in reverse to make indexing easier.
let mut removed = Vec::with_capacity(to_move.len());
for &j in to_move.iter().rev() {
@@ -830,9 +848,21 @@ impl<'segs> Sweeper<'segs> {
// We haven't changed the order of any segments, but the "touch" event
// we just processed might have been a witness for the crossing invariant.
// So we need to scan.
self.intersection_scan_right(right_idx, WhichTouch::Mid);
self.intersection_scan_left(left_idx, WhichTouch::Mid);
// So we need to scan, unless the same scan already ran with this order.
if self.touch_scans.insert((right, true)) {
#[cfg(test)]
{
self.touch_scan_count += 1;
}
self.intersection_scan_right(right_idx, WhichTouch::Mid);
}
if self.touch_scans.insert((left, false)) {
#[cfg(test)]
{
self.touch_scan_count += 1;
}
self.intersection_scan_left(left_idx, WhichTouch::Mid);
}
}
}
@@ -2084,6 +2114,135 @@ mod tests {
insta::assert_ron_snapshot!(snapshot_outputs(segs, 0.25));
}
fn closed_polyline(points: &[(f64, f64)]) -> BezPath {
let mut path = BezPath::new();
path.move_to(points[0]);
for &p in &points[1..] {
path.line_to(p);
}
path.close_path();
path
}
fn copies(shape: &BezPath, n: usize) -> BezPath {
(0..n).flat_map(|_| shape.iter()).collect()
}
// Exact copies of a shape queue a touch event for every pair of coincident
// segments. Each touch-event scan runs at most once per segment and
// direction for each sweep-line order, so the number of scans stays
// linear in the number of segments, and the output is the output for one
// copy.
#[test]
fn coincident_copies_scan_once_per_order() {
use crate::topology::Topology;
let quad = closed_polyline(&[(0.0, 0.0), (100.0, 37.0), (60.0, 90.0), (10.0, 70.0)]);
let rect = closed_polyline(&[(0.0, 0.0), (100.0, 0.0), (100.0, 50.0), (0.0, 50.0)]);
for shape in [quad, rect] {
let path = copies(&shape, 60);
let mut segs = Segments::default();
segs.add_bez_path(&path).unwrap();
let mut sweep = Sweeper::new(&segs, 1e-6);
let mut bufs = SweepLineBuffers::default();
let mut lines = 0;
while sweep.next_line(&mut bufs).is_some() {
lines += 1;
}
assert!(
sweep.touch_scan_count <= 2 * segs.len() * lines,
"{} touch scans for {} segments on {lines} sweep lines",
sweep.touch_scan_count,
segs.len()
);
let contour_paths = |path: &BezPath| -> Vec<BezPath> {
Topology::from_path(path, 1e-6)
.unwrap()
.contours(|w| *w != 0)
.contours()
.map(|c| c.path.clone())
.collect()
};
assert_eq!(contour_paths(&path), contour_paths(&shape));
}
}
// Small polygons on an integer grid, with exact, reversed and
// midpoint-split copies of some of them. The nonzero fill of the output
// contours matches the nonzero fill of the input.
#[test]
fn coincident_copies_keep_the_fill() {
use crate::topology::Topology;
use kurbo::{ParamCurve, ParamCurveNearest, Shape};
let mut state = 0x9e37_79b9_7f4a_7c15_u64;
let mut next = |n: u64| {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
state % n
};
for case in 0..200 {
let mut polygons: Vec<Vec<(f64, f64)>> = Vec::new();
for _ in 0..1 + next(3) {
let len = 3 + next(3);
let polygon = (0..len).map(|_| (next(9) as f64, next(9) as f64)).collect();
polygons.push(polygon);
}
for _ in 0..1 + next(3) {
let source = polygons[next(polygons.len() as u64) as usize].clone();
let copy = match next(3) {
0 => source,
1 => source.into_iter().rev().collect(),
_ => {
let mut split = Vec::new();
for (i, &(x0, y0)) in source.iter().enumerate() {
let (x1, y1) = source[(i + 1) % source.len()];
split.push((x0, y0));
split.push(((x0 + x1) / 2.0, (y0 + y1) / 2.0));
}
split
}
};
polygons.push(copy);
}
let input: BezPath = polygons
.iter()
.flat_map(|p| closed_polyline(p).into_iter())
.collect();
let top = Topology::from_path(&input, 1e-6).unwrap();
let contours = top.contours(|w| *w != 0);
for i in 0..64 {
for j in 0..64 {
let p = kurbo::Point::new(i as f64 / 8.0 + 0.0137, j as f64 / 8.0 + 0.0291);
// Skip points too close to an input edge to say which
// side they are on.
let near_edge = input.segments().any(|seg| {
let line = kurbo::Line::new(seg.start(), seg.end());
let t = line.nearest(p, 0.0).t;
line.eval(t).distance(p) < 1e-3
});
if near_edge {
continue;
}
let expected = input.winding(p) != 0;
let enclosing = contours
.contours()
.filter(|c| c.path.winding(p) != 0)
.count();
assert_eq!(
enclosing % 2 == 1,
expected,
"case {case} at {p:?}: {}",
input.to_svg()
);
}
}
}
}
#[test]
fn empty_sweep_line() {
let segs = Segments::default();