From 79e39a5aa43f17a9711da5ce09f07640ba653237 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 7 Nov 2026 09:41:34 -0800 Subject: [PATCH] linesweeper: inconsistent winding numbers are an error, not a panic The contour walk no longer panics when the sweep leaves winding numbers that disagree around a point. contours_for_positions returns Error::InconsistentWindingNumbers instead, in builds with and without debug assertions: for the scan that finds no boundary segment leaving a point, for a walk that re-enters a segment, for the walk's winding checks that were debug_assert!, and for a western boundary segment with no contour. The new Topology::try_contours returns the error, Topology::contours returns no contours in that case, and binary_op returns the error. craft-prepress calls try_contours, so Arrangement::regions still returns GeomError::Degenerate and nonzero still keeps an even-odd path as it is, without catching a panic. --- crates/prepress/src/flatten/geom.rs | 6 +-- crates/prepress/src/flatten/pdf.rs | 11 ++--- vendor/linesweeper/README.craft.md | 3 +- vendor/linesweeper/SOURCE.json | 7 +-- vendor/linesweeper/src/lib.rs | 17 ++++++- vendor/linesweeper/src/topology.rs | 72 ++++++++++++++++------------- 6 files changed, 69 insertions(+), 47 deletions(-) diff --git a/crates/prepress/src/flatten/geom.rs b/crates/prepress/src/flatten/geom.rs index 8f14a1feda..c106bcd2ce 100644 --- a/crates/prepress/src/flatten/geom.rs +++ b/crates/prepress/src/flatten/geom.rs @@ -411,10 +411,10 @@ impl Arrangement { } } -/// The contours of `top`'s faces for which `inside` holds. The contour walk panics when the sweep -/// left winding numbers that disagree around a point; that input is degenerate. +/// The contours of `top`'s faces for which `inside` holds. The contour walk returns an error when the +/// sweep left winding numbers that disagree around a point; that input is degenerate. fn contours(top: &Topology, inside: impl Fn(&Multi) -> bool) -> Result { - std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| top.contours(inside))).map_err(|_| GeomError::Degenerate) + top.try_contours(inside).map_err(|_| GeomError::Degenerate) } /// A point as a map key (the arrangement's vertices are exact). diff --git a/crates/prepress/src/flatten/pdf.rs b/crates/prepress/src/flatten/pdf.rs index 97263858b0..845c114e3f 100644 --- a/crates/prepress/src/flatten/pdf.rs +++ b/crates/prepress/src/flatten/pdf.rs @@ -1272,24 +1272,21 @@ fn dash_pattern(path: &BezPath, dashes: &[f32]) -> Option> { } /// `path` filled by `rule`, as a path filled nonzero. An even-odd path is rebuilt from its -/// boundary; if that fails or panics it is kept as it is. +/// boundary; if that fails it is kept as it is. fn nonzero(path: &BezPath, rule: FillRule) -> BezPath { if rule == FillRule::NonZero { return path.clone(); } let closed = closed(path); - let op = catch_unwind(AssertUnwindSafe(|| { - linesweeper::binary_op(&closed, &BezPath::new(), linesweeper::FillRule::EvenOdd, linesweeper::BinaryOp::Union) - })); - match op { - Ok(Ok(contours)) => { + match linesweeper::binary_op(&closed, &BezPath::new(), linesweeper::FillRule::EvenOdd, linesweeper::BinaryOp::Union) { + Ok(contours) => { let mut out = BezPath::new(); for contour in contours.contours() { out.extend(contour.path.iter()); } out } - Ok(Err(_)) | Err(_) => closed, + Err(_) => closed, } } diff --git a/vendor/linesweeper/README.craft.md b/vendor/linesweeper/README.craft.md index be9d3d7448..be4b80103a 100644 --- a/vendor/linesweeper/README.craft.md +++ b/vendor/linesweeper/README.craft.md @@ -15,7 +15,8 @@ holds `upstream_revision`. `local_patches` describes each local patch. | File | Change | |---|---| -| `src/topology.rs` | `contours_for_positions` panics with "inconsistent winding numbers" when the contour walk finds no boundary segment leaving a point, or re-enters a segment it already walked. Before, a path whose winding numbers came out inconsistent around a point made `contours` loop forever in a build without debug assertions, and in one case allocate a new contour on every lap. The `contours_finish_*` tests cover both loops. | +| `src/topology.rs` | `contours_for_positions` returns `Error::InconsistentWindingNumbers` when the contour walk finds no boundary segment leaving a point, or re-enters a segment it already walked. Its `debug_assert!` checks of the windings along the walk and its panic for a western boundary segment with no contour return the same error. The new `Topology::try_contours` returns that error, and `Topology::contours` returns no contours in that case. Before, a path whose winding numbers came out inconsistent around a point made `contours` loop forever in a build without debug assertions, and in one case allocate a new contour on every lap. The `contours_finish_*` tests cover both loops. | +| `src/lib.rs` | `Error` has the `InconsistentWindingNumbers` variant, and `binary_op_with_eps` returns it from `Topology::try_contours`. The `inconsistent_winding_numbers_are_an_error` test covers it. | `omitted_files` lists the 43 files of the package left out here, with their hashes: diff --git a/vendor/linesweeper/SOURCE.json b/vendor/linesweeper/SOURCE.json index e7be88d55d..804af286b8 100644 --- a/vendor/linesweeper/SOURCE.json +++ b/vendor/linesweeper/SOURCE.json @@ -8,7 +8,8 @@ "upstream_revision": "824b0791a750f7b27b8edcbb6c6244d0e629875e", "upstream_directory": "", "local_patches": [ - "In `src/topology.rs`, `contours_for_positions` panics with \"inconsistent winding numbers\" when the contour walk finds no boundary segment leaving a point or re-enters a segment it already walked, so `contours` no longer loops forever on a path whose winding numbers come out inconsistent around a point." + "In `src/topology.rs`, `contours_for_positions` returns `Error::InconsistentWindingNumbers` when the contour walk finds no boundary segment leaving a point or re-enters a segment it already walked, so `contours` no longer loops forever on a path whose winding numbers come out inconsistent around a point. Its `debug_assert!` checks of the windings along the walk and its panic for a western boundary segment with no contour return the same error. The new `Topology::try_contours` returns that error, and `Topology::contours` returns no contours in that case.", + "In `src/lib.rs`, `Error` has the `InconsistentWindingNumbers` variant, and `binary_op_with_eps` returns it from `Topology::try_contours`." ], "files": [ { "path": ".cargo_vcs_info.json", "source_sha256": "47fba6a9dbdf445a5c97f783c9be62093035f9d5e5cdc2cf3216ad8259bcd8fc", "source_git_blob": null, "sha256": "47fba6a9dbdf445a5c97f783c9be62093035f9d5e5cdc2cf3216ad8259bcd8fc" }, @@ -39,7 +40,7 @@ { "path": "src/curve/transverse.rs", "source_sha256": "be9c695531f4cb0fe73af13e78040b51b9476c193d84562e701aadd07b3fd06e", "source_git_blob": null, "sha256": "be9c695531f4cb0fe73af13e78040b51b9476c193d84562e701aadd07b3fd06e" }, { "path": "src/generators.rs", "source_sha256": "cc9f2441546db9204219294c354449809dda77dffad06fec8a30f45df01e6fef", "source_git_blob": null, "sha256": "cc9f2441546db9204219294c354449809dda77dffad06fec8a30f45df01e6fef" }, { "path": "src/geom.rs", "source_sha256": "9878ffa6d4a13fa2c9149741c137205ca01acb626a5b9f86a3db75cf91b63a08", "source_git_blob": null, "sha256": "9878ffa6d4a13fa2c9149741c137205ca01acb626a5b9f86a3db75cf91b63a08" }, - { "path": "src/lib.rs", "source_sha256": "761c153c3b5c449569ff85c571344b9252ea64f7f0b0424fb4819041b03d13c6", "source_git_blob": null, "sha256": "761c153c3b5c449569ff85c571344b9252ea64f7f0b0424fb4819041b03d13c6" }, + { "path": "src/lib.rs", "source_sha256": "761c153c3b5c449569ff85c571344b9252ea64f7f0b0424fb4819041b03d13c6", "source_git_blob": null, "sha256": "e690f4ac214403c97b37b8dafce322630c90622837cbe6172e878e1c0b15112c" }, { "path": "src/num.rs", "source_sha256": "39ff85da50c500ce91cf6dea81aedc0dcca1db5e7d0506696dde2da118e93a2a", "source_git_blob": null, "sha256": "39ff85da50c500ce91cf6dea81aedc0dcca1db5e7d0506696dde2da118e93a2a" }, { "path": "src/order.rs", "source_sha256": "7e5b04eae8af134abb032e995f1d3c2ac473822923dfee8d463d9ade6ffeb596", "source_git_blob": null, "sha256": "7e5b04eae8af134abb032e995f1d3c2ac473822923dfee8d463d9ade6ffeb596" }, { "path": "src/perturbation.rs", "source_sha256": "fa274a822bbdf65f8e53e403eef78034dd87964b3f1d3134a064df4ec8cef9c5", "source_git_blob": null, "sha256": "fa274a822bbdf65f8e53e403eef78034dd87964b3f1d3134a064df4ec8cef9c5" }, @@ -65,7 +66,7 @@ { "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/topology.rs", "source_sha256": "9c9b48bc3853884425127e2d64e8ed957ba0d27e1696e2c457e95282e52d6a5b", "source_git_blob": null, "sha256": "d6d7d62e6b6aee5c6ffd1b0aeb32c44bd5b5f23bdfd88260ad0908a15f3e40e6" }, + { "path": "src/topology.rs", "source_sha256": "9c9b48bc3853884425127e2d64e8ed957ba0d27e1696e2c457e95282e52d6a5b", "source_git_blob": null, "sha256": "315162ea3b7c87abdce9419ee3b56278586f67efceb4440c328663e248d54945" }, { "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" }, { "path": "tests/fonts.rs", "source_sha256": "081604ebf560a19ff0427efd9a17eaaa0a3b46ad0bf58323fd6e21b6c0764400", "source_git_blob": null, "sha256": "081604ebf560a19ff0427efd9a17eaaa0a3b46ad0bf58323fd6e21b6c0764400" }, diff --git a/vendor/linesweeper/src/lib.rs b/vendor/linesweeper/src/lib.rs index 7d2500d095..1492f14cfe 100644 --- a/vendor/linesweeper/src/lib.rs +++ b/vendor/linesweeper/src/lib.rs @@ -74,6 +74,9 @@ pub enum Error { NaN, /// One of the inputs had a non-closed path. NonClosedPath(NonClosedPath), + /// The sweep gave winding numbers that disagree around a point, so the + /// contours of the output set could not be walked. + InconsistentWindingNumbers, } impl From for Error { @@ -88,6 +91,9 @@ impl std::fmt::Display for Error { Error::Infinity => write!(f, "one of the inputs was infinite"), Error::NaN => write!(f, "one of the inputs had a NaN"), Error::NonClosedPath(_) => write!(f, "one of the inputs had a non-closed path"), + Error::InconsistentWindingNumbers => { + write!(f, "the winding numbers disagree around a point") + } } } } @@ -170,7 +176,7 @@ pub fn binary_op_with_eps( } }; - Ok(top.contours(inside)) + top.try_contours(inside) } #[cfg(test)] @@ -279,6 +285,15 @@ mod tests { assert!(contours.contours().next().is_none()); } + #[test] + fn inconsistent_winding_numbers_are_an_error() { + // The sweep gives this path winding numbers that disagree around a + // point. + let path = BezPath::from_svg("M4,-1 C8,1 -7,-2 5,8 L-4,-8 L2,1 L1,1 Z").unwrap(); + let result = binary_op(&path, &BezPath::new(), FillRule::EvenOdd, BinaryOp::Union); + assert_eq!(result.err(), Some(Error::InconsistentWindingNumbers)); + } + #[test] fn repeated_points() { Topology::from_polylines_binary( diff --git a/vendor/linesweeper/src/topology.rs b/vendor/linesweeper/src/topology.rs index 4ae927e640..3bcf1e44ac 100644 --- a/vendor/linesweeper/src/topology.rs +++ b/vendor/linesweeper/src/topology.rs @@ -8,7 +8,7 @@ use std::collections::VecDeque; use kurbo::{BezPath, ParamCurve, Rect, Shape}; use crate::{ - FillRule, + Error, FillRule, curve::{Order, solve_t_for_y, y_subsegment}, geom::Point, order::ComparisonCache, @@ -1280,7 +1280,17 @@ impl Topology { /// if a point with that winding number should be in the resulting set. For example, /// to compute a boolean "and" using the non-zero winding rule, `inside` should be /// `|w| w.shape_a != 0 && w.shape_b != 0`. + /// + /// When the winding numbers disagree around a point, this returns no + /// contours. [`Topology::try_contours`] reports that case as an error. pub fn contours(&self, inside: impl Fn(&W) -> bool) -> Contours { + self.try_contours(inside).unwrap_or_default() + } + + /// Returns the contours of some set defined by this topology, as + /// [`Topology::contours`] does, or [`Error::InconsistentWindingNumbers`] + /// when the winding numbers disagree around a point. + pub fn try_contours(&self, inside: impl Fn(&W) -> bool) -> Result { let positions = self.compute_positions(); self.contours_for_positions(inside, positions) } @@ -1289,7 +1299,7 @@ impl Topology { &self, inside: impl Fn(&W) -> bool, positions: OutputSegVec, - ) -> Contours { + ) -> Result { // We walk contours in sweep-line order of their smallest point. This mostly ensures // that we visit outer contours before we visit their children. However, when the inner // and outer contours share a point, we run into a problem. For example: @@ -1358,7 +1368,9 @@ impl Topology { // That means they're our sibling. contour.parent = ret.contours[west_contour.0].parent; contour.outer = outside; - debug_assert!(outside || contour.parent.is_some()); + if !outside && contour.parent.is_none() { + return Err(Error::InconsistentWindingNumbers); + } } else { // They're an outer contour, and there's interior between us and them, // or they're an inner contour and there's exterior between us. @@ -1367,7 +1379,8 @@ impl Topology { contour.outer = !ret.contours[west_contour.0].outer; } } else { - panic!("I'm {idx:?}, west is {west:?}. Y u no have contour?"); + // The boundary segment to our west has no contour yet. + return Err(Error::InconsistentWindingNumbers); } }; // Reserve a space for the unfinished outer contour, as described above. @@ -1390,21 +1403,24 @@ impl Topology { loop { visited[next.idx.0] = true; - debug_assert!(inside(self.winding_counter_clockwise(next))); - debug_assert!(!inside(self.winding_clockwise(next))); + if !inside(self.winding_counter_clockwise(next)) + || inside(self.winding_clockwise(next)) + { + return Err(Error::InconsistentWindingNumbers); + } // Walk counter-clockwise around the point until we find the next segment // that's on the boundary. let mut nbr = self.point_neighbors[next].counter_clockwise; - debug_assert!(inside(self.winding_clockwise(nbr))); + if !inside(self.winding_clockwise(nbr)) { + return Err(Error::InconsistentWindingNumbers); + } let first_nbr = nbr; while inside(self.winding_counter_clockwise(nbr)) { nbr = self.point_neighbors[nbr].counter_clockwise; if nbr == first_nbr { - panic!( - "inconsistent winding numbers: no boundary segment leaves {:?}", - self.point_idx[next] - ); + // No boundary segment leaves this point. + return Err(Error::InconsistentWindingNumbers); } } @@ -1413,7 +1429,8 @@ impl Topology { break; } if visited[nbr.idx.0] { - panic!("inconsistent winding numbers: contour walk re-entered {nbr:?}"); + // The walk re-entered a segment it already walked. + return Err(Error::InconsistentWindingNumbers); } let p = self.point_idx[nbr]; @@ -1459,7 +1476,7 @@ impl Topology { ret.contours[contour_idx.0].path = self.segs_to_path(&segs, &positions); } - ret + Ok(ret) } /// Returns a rectangle bounding all of our segments. @@ -2272,7 +2289,7 @@ mod tests { use proptest::prelude::*; use crate::{ - FillRule, SegIdx, + Error, FillRule, SegIdx, geom::Point, order::ComparisonCache, perturbation::{ @@ -2280,7 +2297,7 @@ mod tests { }, }; - use super::{OneOfTwo, Topology}; + use super::{Contours, OneOfTwo, Topology}; fn p(x: f64, y: f64) -> Point { Point::new(x, y) @@ -2491,26 +2508,17 @@ mod tests { insta::assert_ron_snapshot!((top, contours)); } - // Checks that `contours` finishes on a path whose winding numbers come out - // inconsistent around a point: it either returns or panics, instead of - // walking forever. With debug assertions on, the walk's `debug_assert!` - // checks panic first; without them, the panic must come from the - // inconsistent-winding checks in the walk. + // Checks that the contour walk finishes on a path whose winding numbers + // come out inconsistent around a point, instead of walking forever: + // `try_contours` returns an error and `contours` returns no contours. fn contours_finish(svg: &str) { let bez = BezPath::from_svg(svg).unwrap(); let top = Topology::::from_path(&bez, 1e-6).unwrap(); - let result = - std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| top.contours(|w| *w != 0))); - if let Err(payload) = result - && !cfg!(debug_assertions) - { - let msg = payload - .downcast_ref::() - .cloned() - .or_else(|| payload.downcast_ref::<&str>().map(|s| s.to_string())) - .unwrap_or_default(); - assert!(msg.starts_with("inconsistent winding numbers"), "{msg}"); - } + assert_eq!( + top.try_contours(|w| *w != 0), + Err(Error::InconsistentWindingNumbers) + ); + assert_eq!(top.contours(|w| *w != 0), Contours::default()); } #[test]