linesweeper: intersection scans step over ending segments in one pass

When many segments end at one sweep height while others start there, each
new segment's scan walked the whole run of ending segments with one indexed
tree lookup per segment. Both scans now step over such a run with one pass
of a TreeVec iterator; TreeVec::range_rev_to provides the reverse pass for
the left scan. The scans compare the same segments and push the same events.
This commit is contained in:
dotCooCoo committed 2026-11-07 11:06:46 -08:00
1 parent 904f55bb21
commit 64a08eecdb
5 files changed
+277 -23

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`, `src/treevec.rs` | `intersection_scan_right` and `intersection_scan_left` step over each run of sweep-line segments that end at the current height with one pass of a `TreeVec` iterator, instead of one indexed tree lookup per segment. `TreeVec::range_rev_to` iterates the elements before an index from back to front for the left scan. The scans compare the same segments and push the same events, so the output does not change; a polygon with 40,000 segments ending and 40,000 starting at one height sweeps in about 60% of the time. The `scans_step_over_segments_that_end` test checks that a segment ending at the current height does not stop the scan, `runs_of_ending_segments_keep_the_output` checks the area of such a polygon, and the `treevec` test `range_rev_to` checks the iterator. |
`omitted_files` lists the 43 files of the package left out here, with their hashes:
+5 -3
View File
@@ -7,7 +7,9 @@
"upstream_repository": null,
"upstream_revision": "824b0791a750f7b27b8edcbb6c6244d0e629875e",
"upstream_directory": "",
"local_patches": [],
"local_patches": [
"In `src/sweep/sweep_line.rs`, `intersection_scan_right` and `intersection_scan_left` step over each run of segments that end at the current height with one pass of a `TreeVec` iterator instead of one indexed lookup per segment; `src/treevec.rs` adds `TreeVec::range_rev_to` for the left scan. The output does not change."
],
"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,9 +64,9 @@
{ "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": "5dfbff54f25438ddb800f4136af5c7ef1d6d2a3a626ea5311dacefd884c5c9e8" },
{ "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/treevec.rs", "source_sha256": "d88b9fbf02fa9f318560e1d483d465555f2b696ae12c00f8e4f5b71ea6779445", "source_git_blob": null, "sha256": "84b5f7349524bbd44d4cb5f1a8d9aec3f4d182f3ab792e493c112f34e3fcc1ac" },
{ "path": "src/typed_vec.rs", "source_sha256": "3e9a2675b8a40d8fc4df0575bd9d0d16b5604d18e9b78638dd5a612b28fc4c30", "source_git_blob": null, "sha256": "3e9a2675b8a40d8fc4df0575bd9d0d16b5604d18e9b78638dd5a612b28fc4c30" },
{ "path": "tests/fonts.rs", "source_sha256": "081604ebf560a19ff0427efd9a17eaaa0a3b46ad0bf58323fd6e21b6c0764400", "source_git_blob": null, "sha256": "081604ebf560a19ff0427efd9a17eaaa0a3b46ad0bf58323fd6e21b6c0764400" },
{ "path": "tests/paperjs.rs", "source_sha256": "6ff2a3178f13cde3d7304101ae592ae32b4b2734069f5fc56a532a4883d9f782", "source_git_blob": null, "sha256": "6ff2a3178f13cde3d7304101ae592ae32b4b2734069f5fc56a532a4883d9f782" },
+117 -10
View File
@@ -488,12 +488,30 @@ impl<'segs> Sweeper<'segs> {
}
let mut height_bound = seg.end().y;
for j in (start_idx + 1)..self.line.segs.len() {
let other_idx = self.line.seg(j);
let other = &self.segments[other_idx];
if other.end().y == y {
continue;
// Craft patch (scan runs): when the next segment ends at `y`, the run
// of segments that end at `y` is stepped over with one pass of the
// tree iterator, instead of one indexed lookup per segment. Such a segment is not a barrier for the
// far-apart `break` below, because it leaves the line at `y`.
let len = self.line.segs.len();
let segments = self.segments;
let mut next = start_idx + 1;
while next < len {
let mut other_idx = self.line.seg(next);
if segments[other_idx].end().y == y {
next += self
.line
.segs
.range(next..)
.take_while(|entry| segments[entry.seg].end().y == y)
.count();
if next >= len {
break;
}
other_idx = self.line.seg(next);
}
let j = next;
next += 1;
let other = &self.segments[other_idx];
// Our basic comparisons use eps tolerance and eps/2 accuracy, so if
// our max_x is 1.5 eps less than their min_x then we're guaranteed
@@ -552,12 +570,26 @@ impl<'segs> Sweeper<'segs> {
}
let mut height_bound = seg.end().y;
for j in (0..start_idx).rev() {
let other_idx = self.line.seg(j);
let other = &self.segments[other_idx];
if other.end().y == y {
continue;
// Craft patch (scan runs): see `intersection_scan_right`.
let segments = self.segments;
let mut next = start_idx;
while next > 0 {
let mut other_idx = self.line.seg(next - 1);
if segments[other_idx].end().y == y {
next -= self
.line
.segs
.range_rev_to(next)
.take_while(|entry| segments[entry.seg].end().y == y)
.count();
if next == 0 {
break;
}
other_idx = self.line.seg(next - 1);
}
next -= 1;
let j = next;
let other = &self.segments[other_idx];
if seg.min_x() - 2.0 * self.eps > other.max_x() {
break;
@@ -2005,6 +2037,81 @@ mod tests {
insta::assert_ron_snapshot!(snapshot_outputs(segs, 0.01));
}
// Craft patch (scan runs).
fn closed_polygon(path: &mut BezPath, points: &[(f64, f64)]) {
path.move_to(points[0]);
for &q in &points[1..] {
path.line_to(q);
}
path.close_path();
}
fn total_area(contours: &crate::topology::Contours) -> f64 {
use kurbo::Shape;
contours
.contours()
.map(|c| c.path.area())
.sum::<f64>()
.abs()
}
// Craft patch (scan runs): a triangle ends at y = 1 between a vertical
// edge that starts there and an edge that crosses that vertical lower down.
// The right scan from the vertical steps over the ending edges and still
// finds the crossing.
#[test]
fn scans_step_over_segments_that_end() {
let mut a = BezPath::new();
closed_polygon(&mut a, &[(9.0, 0.0), (11.0, 0.0), (10.0, 1.0)]);
closed_polygon(&mut a, &[(0.0, 1.0), (0.0, 3.0), (-1.0, 3.0)]);
let mut b = BezPath::new();
closed_polygon(&mut b, &[(11.0, 0.9), (12.0, 3.0), (-5.0, 3.0)]);
let out = crate::binary_op(
&a,
&b,
crate::FillRule::NonZero,
crate::BinaryOp::Intersection,
)
.unwrap();
assert_eq!(out.contours().count(), 1);
let area = total_area(&out);
assert!((area - 0.51688).abs() < 1e-4, "area {area}");
}
// Craft patch (scan runs): 400 edges end and 400 start at y = 1.
#[test]
fn runs_of_ending_segments_keep_the_output() {
let n = 200;
let mut points = Vec::new();
for i in 0..=2 * n {
points.push((i as f64, if i % 2 == 0 { 0.0 } else { 1.0 }));
}
for i in (0..=2 * n).rev() {
points.push((i as f64 + 0.5, if i % 2 == 0 { 2.0 } else { 1.0 }));
}
let mut wave = BezPath::new();
closed_polygon(&mut wave, &points);
let expected = {
use kurbo::Shape;
wave.area().abs()
};
let out = crate::binary_op(
&wave,
&BezPath::new(),
crate::FillRule::NonZero,
crate::BinaryOp::Union,
)
.unwrap();
assert_eq!(out.contours().count(), 1);
let area = total_area(&out);
assert!(
(area - expected).abs() < 1e-6,
"area {area}, expected {expected}"
);
}
#[test]
fn square_and_diamond() {
let square = [p(0.0, 0.0), p(1.0, 0.0), p(1.0, 1.0), p(0.0, 1.0)];
+139
View File
@@ -645,6 +645,28 @@ impl<T, const B: usize> TreeVec<T, B> {
};
IterMut { inner }
}
// Craft patch (scan runs): reverse iteration for `intersection_scan_left`.
/// Returns an iterator over the elements before index `end`, from the
/// last one to the first. An `end` past the length means the length.
pub(crate) fn range_rev_to(&self, end: usize) -> RevIter<'_, T, B> {
let end = end.min(self.len());
let inner = match &*self.root {
Node::Leaf { data } => RevIterInner::Simple(data[..end].iter()),
Node::Internal { .. } => {
let mut ret = RevTreeIter {
stack: Vec::new(),
leaf: [].iter(),
remaining: end,
};
if end > 0 {
ret.descend_to(&*self.root, end);
}
RevIterInner::Tree(ret)
}
};
RevIter { inner }
}
}
impl<T, const B: usize> FromIterator<T> for TreeVec<T, B> {
@@ -781,6 +803,107 @@ impl<'a, T, const B: usize> Iterator for Iter<'a, T, B> {
}
}
// Craft patch (scan runs): reverse iteration for `intersection_scan_left`.
/// An iterator over elements of a [`TreeVec`], from back to front.
pub(crate) struct RevIter<'a, T, const B: usize> {
inner: RevIterInner<'a, T, B>,
}
enum RevIterInner<'a, T, const B: usize> {
Simple(std::slice::Iter<'a, T>),
Tree(RevTreeIter<'a, T, B>),
}
// The mirror image of `TreeIter`: the stack holds the children still to visit
// on the left, and elements come off the back of each slice.
struct RevTreeIter<'a, T, const B: usize> {
stack: Vec<std::slice::Iter<'a, Box<Node<T, B>>>>,
leaf: std::slice::Iter<'a, T>,
remaining: usize,
}
impl<'a, T, const B: usize> RevTreeIter<'a, T, B> {
// Fill out the rest of the stack and the leaf, by descending
// to the last descendent of `node`.
fn descend(&mut self, mut node: &'a Node<T, B>) {
loop {
match node {
Node::Leaf { data } => {
self.leaf = data.iter();
return;
}
Node::Internal { children, .. } => {
let mut children = children.iter();
// unwrap: internal nodes are always non-empty
node = children.next_back().unwrap();
self.stack.push(children);
}
}
}
}
// Fill out the rest of the stack and the leaf, so that the next element is
// the one at offset `end - 1` in the subtree rooted at `node`. `end` must
// be positive.
fn descend_to(&mut self, mut node: &'a Node<T, B>, mut end: usize) {
loop {
match node {
Node::Leaf { data } => {
self.leaf = data[..end].iter();
return;
}
Node::Internal { children, size } => {
let Some((idx, child_offset)) = child_idx(size, end - 1) else {
return;
};
end = child_offset + 1;
let mut children = children[..=idx].iter();
// unwrap: child_idx always returns a valid index into children
node = children.next_back().unwrap();
self.stack.push(children);
}
}
}
}
fn next(&mut self) -> Option<&'a T> {
if self.remaining == 0 {
None
} else {
self.remaining -= 1;
if let Some(ret) = self.leaf.next_back() {
Some(ret)
} else {
// The current leaf is exhausted. Unwind the stack until we find
// a non-exhausted internal node, then descend again.
loop {
let stack_top = self.stack.last_mut()?;
let Some(next_node) = stack_top.next_back() else {
self.stack.pop();
continue;
};
self.descend(next_node);
return self.leaf.next_back();
}
}
}
}
}
impl<'a, T, const B: usize> Iterator for RevIter<'a, T, B> {
type Item = &'a T;
#[inline(always)]
fn next(&mut self) -> Option<Self::Item> {
match &mut self.inner {
RevIterInner::Simple(it) => it.next_back(),
RevIterInner::Tree(it) => it.next(),
}
}
}
/// An iterator over mutable references elements of a [`TreeVec`].
pub struct IterMut<'a, T, const B: usize> {
inner: IterMutInner<'a, T, B>,
@@ -934,6 +1057,22 @@ mod tests {
assert_eq!(*vec.get(5).unwrap(), 1);
}
// Craft patch (scan runs).
#[test]
fn range_rev_to() {
for len in [0, 1, 4, 5, 17, 70] {
let vec: TreeVec<usize, 4> = (0..len).collect();
for end in 0..=len + 2 {
let got: Vec<usize> = vec.range_rev_to(end).copied().collect();
let expected: Vec<usize> = (0..end.min(len)).rev().collect();
assert_eq!(got, expected, "len {len}, end {end}");
}
let take: Vec<usize> = vec.range_rev_to(len).take(3).copied().collect();
let expected: Vec<usize> = (0..len).rev().take(3).collect();
assert_eq!(take, expected, "len {len}");
}
}
#[test]
fn iter() {
let mut vec = TreeVec::<i32, 4>::default();