diff --git a/crates/prepress/src/flatten/compose.rs b/crates/prepress/src/flatten/compose.rs index fc5f2ef4b..433f11f58 100644 --- a/crates/prepress/src/flatten/compose.rs +++ b/crates/prepress/src/flatten/compose.rs @@ -303,6 +303,7 @@ fn flatten_group( isolated: false, knockout: false, clip: None, + clip_rule: FillRule::NonZero, mask: None, actual_text: Some(text), children, @@ -614,7 +615,7 @@ impl<'a> Builder<'a> { let outer = self.push_tag(g.actual_text.as_deref()); if let Some(clip) = &g.clip { self.clip_stack.push(self.clips.len()); - self.clips.push(ClipPath { path: clip.clone(), rule: FillRule::NonZero }); + self.clips.push(ClipPath { path: clip.clone(), rule: g.clip_rule }); } let masked = masked || g.mask.is_some(); let (plain_path, knockout_path) = (self.plain_path, self.knockout_path); @@ -900,7 +901,17 @@ mod tests { } fn group(opacity: f32, blend: BlendMode, children: Vec) -> GroupItem { - GroupItem { opacity, blend, isolated: false, knockout: false, clip: None, mask: None, actual_text: None, children } + GroupItem { + opacity, + blend, + isolated: false, + knockout: false, + clip: None, + clip_rule: FillRule::NonZero, + mask: None, + actual_text: None, + children, + } } fn list(inks: InkSet, items: Vec) -> DisplayList { @@ -1017,6 +1028,18 @@ mod tests { assert_eq!(at(&flat(&list(InkSet::new(), vec![Item::Group(g)])), 75.0, 50.0, &[C, M]).1, [0.0, 0.5]); } + #[test] + fn even_odd_clip_leaves_its_hole_unpainted() { + // Two nested squares drawn in the same direction: filled even-odd, the inner one is a hole. + let mut ring = Rect::new(0.0, 0.0, 100.0, 100.0).to_path(0.1); + ring.extend(Rect::new(25.0, 25.0, 75.0, 75.0).to_path(0.1)); + let half_black = Item::Group(group(0.5, BlendMode::Normal, vec![solid(Rect::new(0.0, 0.0, 100.0, 100.0), &[(K, 1.0)])])); + let clip = GroupItem { clip: Some(ring), clip_rule: FillRule::EvenOdd, ..group(1.0, BlendMode::Normal, vec![half_black]) }; + let f = flat(&list(InkSet::new(), vec![solid(Rect::new(0.0, 0.0, 100.0, 100.0), &[(C, 1.0)]), Item::Group(clip)])); + assert_eq!(at(&f, 10.0, 50.0, &[C, K]).1, [0.5, 0.5]); + assert_eq!(at(&f, 50.0, 50.0, &[C, K]).1, [1.0, 0.0], "the hole shows the cyan under it"); + } + #[test] fn isolated_group_blends_without_the_backdrop() { let scene = |isolated| { diff --git a/crates/prepress/src/flatten/mod.rs b/crates/prepress/src/flatten/mod.rs index 860d9ed7b..1aa5c4392 100644 --- a/crates/prepress/src/flatten/mod.rs +++ b/crates/prepress/src/flatten/mod.rs @@ -156,8 +156,11 @@ pub struct GroupItem { pub blend: BlendMode, pub isolated: bool, pub knockout: bool, - /// Nonzero clip in page space. + /// Clip in page space, filled by `clip_rule`. pub clip: Option, + /// The fill rule of `clip`. The PDF reader rebuilds an even-odd clip as a nonzero path, + /// and keeps the path even-odd when the rebuild fails. + pub clip_rule: FillRule, pub mask: Option>, /// The Unicode text the children show, for content drawn as items that is text in the /// source, such as a colored Type 3 glyph. diff --git a/crates/prepress/src/flatten/pdf.rs b/crates/prepress/src/flatten/pdf.rs index 2a472f460..0e7108fc0 100644 --- a/crates/prepress/src/flatten/pdf.rs +++ b/crates/prepress/src/flatten/pdf.rs @@ -320,7 +320,22 @@ struct Reader<'s, 'a> { } fn plain_group(clip: Option) -> GroupItem { - GroupItem { opacity: 1.0, blend: BlendMode::Normal, isolated: false, knockout: false, clip, mask: None, actual_text: None, children: Vec::new() } + GroupItem { + opacity: 1.0, + blend: BlendMode::Normal, + isolated: false, + knockout: false, + clip, + clip_rule: FillRule::NonZero, + mask: None, + actual_text: None, + children: Vec::new(), + } +} + +/// A plain group clipping to `clip` filled by `rule`. +fn clip_group((clip, rule): (BezPath, FillRule)) -> GroupItem { + GroupItem { clip_rule: rule, ..plain_group(Some(clip)) } } impl<'s, 'a> Reader<'s, 'a> { @@ -601,16 +616,16 @@ impl<'s, 'a> Reader<'s, 'a> { fn area_fill(&mut self, path: BezPath, rule: FillRule, paint: &PdfPaint<'a>, stroke: bool) { let PdfPaint::Pattern(pattern) = paint else { return }; self.flush(); - let clip = nonzero(&path, rule); + let (clip, rule) = nonzero(&path, rule); let (op, big_op, _) = self.overprint; let flag = if stroke { big_op } else { op }; match pattern.as_ref() { - Pattern::Shading(sp) => self.shading_area(clip, sp, flag), - Pattern::Tiling(t) => self.tiling_area(clip, t, flag, stroke), + Pattern::Shading(sp) => self.shading_area(clip, rule, sp, flag), + Pattern::Tiling(t) => self.tiling_area(clip, rule, t, flag, stroke), } } - fn shading_area(&mut self, clip: BezPath, sp: &ShadingPattern, flag: bool) { + fn shading_area(&mut self, clip: BezPath, rule: FillRule, sp: &ShadingPattern, flag: bool) { let look = self.look(sp.opacity); let cs = &sp.shading.color_space; // Nonzero overprint mode is for colors set in DeviceCMYK, not shadings or images @@ -625,12 +640,12 @@ impl<'s, 'a> Reader<'s, 'a> { if let Some((inks, channels)) = self.space_inks(&space, cs) { let kind = inks.stop_inks(); let paint = Paint::Solid(shade::stop_color(&kind, &channels.apply_f32(&values))); - children.push(Item::Fill(FillItem { path: clip.clone(), rule: FillRule::NonZero, paint, overprint })); + children.push(Item::Fill(FillItem { path: clip.clone(), rule, paint, overprint })); } } let shaded = if matches!(sp.shading.shading_type.as_ref(), ShadingType::RadialAxial { .. }) { self.gradient(sp).map(|(paint, extent)| { - let fill = Item::Fill(FillItem { path: clip.clone(), rule: FillRule::NonZero, paint, overprint }); + let fill = Item::Fill(FillItem { path: clip.clone(), rule, paint, overprint }); match extent { Some(extent) => Item::Group(GroupItem { children: vec![fill], ..plain_group(Some(extent)) }), None => fill, @@ -646,7 +661,7 @@ impl<'s, 'a> Reader<'s, 'a> { } } if !children.is_empty() { - self.push(Item::Group(GroupItem { children, ..plain_group(Some(clip)) }), &look); + self.push(Item::Group(GroupItem { children, ..clip_group((clip, rule)) }), &look); } } @@ -684,7 +699,7 @@ impl<'s, 'a> Reader<'s, 'a> { /// A tiling pattern over `clip`: its cells, each read like page content, or an image past /// [`MAX_TILING_CELLS`] or [`MAX_TILING_ITEMS`]. - fn tiling_area(&mut self, clip: BezPath, t: &TilingPattern<'a>, flag: bool, stroke: bool) { + fn tiling_area(&mut self, clip: BezPath, rule: FillRule, t: &TilingPattern<'a>, flag: bool, stroke: bool) { let area = clip.bounding_box().intersect(self.clip_bounds()); if !(area.width() > 0.0 && area.height() > 0.0) { return; @@ -757,7 +772,7 @@ impl<'s, 'a> Reader<'s, 'a> { self.shared.report.rasterized_tilings += 1; vec![Item::Image(image)] }; - self.push(Item::Group(GroupItem { children: child, ..plain_group(Some(clip)) }), &look); + self.push(Item::Group(GroupItem { children: child, ..clip_group((clip, rule)) }), &look); } fn raster_image(&mut self, image: &RasterImage<'_>, transform: Affine) { @@ -948,14 +963,23 @@ impl<'s, 'a> Reader<'s, 'a> { let unicode = glyph.as_unicode().map(unicode); // A glyph that only fills in the text's paint (`d1`, or `d0` painting that color) is a // shape: it joins the run. + // Its outline is filled nonzero, so an even-odd fill that can't be rebuilt as nonzero + // keeps the glyph a group. let shape = items.iter().all(|item| matches!(item, Item::Fill(f) if Some(&f.paint) == run_paint.as_ref())); - if let (true, Some(run_paint)) = (shape, run_paint) { + let outline = shape.then(|| { let mut outline = BezPath::new(); for item in &items { if let Item::Fill(f) = item { - outline.extend(nonzero(&f.path, f.rule).iter()); + let (path, rule) = nonzero(&f.path, f.rule); + if rule != FillRule::NonZero { + return None; + } + outline.extend(path.iter()); } } + Some(outline) + }); + if let (Some(outline), Some(run_paint)) = (outline.flatten(), run_paint) { self.add_glyph(None, 0, transform * glyph_transform, outline, unicode, run_paint, look, overprint); } else if !items.is_empty() { self.flush(); @@ -988,7 +1012,7 @@ impl<'a> Device<'a> for Reader<'_, 'a> { fn push_clip_path(&mut self, clip_path: &ClipPath) { self.flush(); let clip = nonzero(&clip_path.path, fill_rule(clip_path.fill)); - self.frames.push(Frame { kind: FrameKind::Clip, group: plain_group(Some(clip)) }); + self.frames.push(Frame { kind: FrameKind::Clip, group: clip_group(clip) }); } fn push_transparency_group(&mut self, opacity: f32, mask: Option>, blend_mode: PdfBlend) { @@ -1287,11 +1311,12 @@ fn dash_pattern(path: &BezPath, dashes: &[f32]) -> Option> { (pieces.is_finite() && pieces <= MAX_DASHES_PER_STROKE).then(|| dashes.iter().map(|d| f64::from(*d)).collect()) } -/// `path` filled by `rule`, as a path filled nonzero. An even-odd path is rebuilt from its -/// boundary; if that fails it is kept as it is. -fn nonzero(path: &BezPath, rule: FillRule) -> BezPath { +/// `path` filled by `rule`, as a path and the rule it is filled by. An even-odd path is +/// rebuilt from its boundary as a path filled nonzero; if that fails it is kept closed and +/// filled even-odd. +fn nonzero(path: &BezPath, rule: FillRule) -> (BezPath, FillRule) { if rule == FillRule::NonZero { - return path.clone(); + return (path.clone(), FillRule::NonZero); } let closed = closed(path); match linesweeper::binary_op(&closed, &BezPath::new(), linesweeper::FillRule::EvenOdd, linesweeper::BinaryOp::Union) { @@ -1300,9 +1325,9 @@ fn nonzero(path: &BezPath, rule: FillRule) -> BezPath { for contour in contours.contours() { out.extend(contour.path.iter()); } - out + (out, FillRule::NonZero) } - Err(_) => closed, + Err(_) => (closed, FillRule::EvenOdd), } } @@ -1369,4 +1394,24 @@ mod tests { }); assert_eq!(item_count(&[fill]), 1 + path.elements().len()); } + + #[test] + fn even_odd_paths_keep_their_rule_when_the_rebuild_fails() { + // Two nested squares drawn in the same direction: even-odd leaves a hole, nonzero fills it. + let mut nested = Rect::new(0.0, 0.0, 100.0, 100.0).to_path(0.1); + nested.extend(Rect::new(25.0, 25.0, 75.0, 75.0).to_path(0.1)); + let (rebuilt, rule) = nonzero(&nested, FillRule::EvenOdd); + assert_eq!(rule, FillRule::NonZero); + assert_eq!(rebuilt.winding(Point::new(50.0, 50.0)), 0, "the hole"); + assert_ne!(rebuilt.winding(Point::new(10.0, 50.0)), 0); + + // An infinite coordinate makes the rebuild fail. + let mut broken = nested.clone(); + broken.move_to((f64::INFINITY, 0.0)); + broken.line_to((f64::INFINITY, 10.0)); + let (kept, rule) = nonzero(&broken, FillRule::EvenOdd); + assert_eq!(rule, FillRule::EvenOdd, "the path is still filled even-odd"); + assert_eq!(kept, closed(&broken)); + assert_eq!(nonzero(&broken, FillRule::NonZero), (broken.clone(), FillRule::NonZero)); + } } diff --git a/crates/prepress/src/flatten/raster.rs b/crates/prepress/src/flatten/raster.rs index 9b2516b39..5c7ddd81a 100644 --- a/crates/prepress/src/flatten/raster.rs +++ b/crates/prepress/src/flatten/raster.rs @@ -163,6 +163,7 @@ impl<'a> Rasterizer<'a> { isolated: g.isolated, knockout: g.knockout, clip: g.clip.clone(), + clip_rule: g.clip_rule, mask, actual_text: g.actual_text.clone(), children, @@ -231,6 +232,7 @@ impl<'a> Rasterizer<'a> { isolated: false, knockout: false, clip: None, + clip_rule: FillRule::NonZero, mask: None, actual_text: None, children: vec![Item::Image(image)], diff --git a/crates/prepress/src/flatten/shade.rs b/crates/prepress/src/flatten/shade.rs index a67d4f340..df2cfba81 100644 --- a/crates/prepress/src/flatten/shade.rs +++ b/crates/prepress/src/flatten/shade.rs @@ -373,7 +373,7 @@ impl<'a> Canvas<'a> { Item::Image(im) => self.image(im, clip, opacity), Item::Group(g) => { let own = g.clip.as_ref().map(|c| { - let mut cov = self.coverage(c, FillRule::NonZero); + let mut cov = self.coverage(c, g.clip_rule); if let Some(outer) = clip { cov.iter_mut().zip(outer).for_each(|(a, b)| *a *= b); } @@ -832,3 +832,45 @@ pub(super) fn rect_path(r: Rect, t: Affine) -> BezPath { path.close_path(); path } + +#[cfg(test)] +mod tests { + use kurbo::Shape; + + use super::*; + use crate::flatten::{BlendMode, FillItem, GroupItem}; + + #[test] + fn canvas_clips_by_the_clip_rule() { + // Two nested squares drawn in the same direction: even-odd leaves a hole, nonzero fills it. + let mut ring = Rect::new(0.0, 0.0, 100.0, 100.0).to_path(0.1); + ring.extend(Rect::new(25.0, 25.0, 75.0, 75.0).to_path(0.1)); + let black = InkColor::Tints(vec![(InkId::process(Process::Black), 1.0)]); + let fill = Item::Fill(FillItem { + path: Rect::new(0.0, 0.0, 100.0, 100.0).to_path(0.1), + rule: FillRule::NonZero, + paint: Paint::Solid(black), + overprint: Overprint::default(), + }); + let inks = InkSet::new(); + let alpha = |clip_rule| { + let group = GroupItem { + opacity: 1.0, + blend: BlendMode::Normal, + isolated: false, + knockout: false, + clip: Some(ring.clone()), + clip_rule, + mask: None, + actual_text: None, + children: vec![fill.clone()], + }; + let Some(mut canvas) = Canvas::new(Rect::new(0.0, 0.0, 100.0, 100.0), 1.0, &inks) else { panic!("no canvas") }; + canvas.draw(&[Item::Group(group)]); + let at = |x, y| canvas.sample(Point::new(x, y)).map(|(_, a)| a); + (at(10.5, 50.5), at(50.5, 50.5)) + }; + assert_eq!(alpha(FillRule::NonZero), (Some(1.0), Some(1.0))); + assert_eq!(alpha(FillRule::EvenOdd), (Some(1.0), Some(0.0)), "the hole"); + } +} diff --git a/crates/prepress/src/flatten/write.rs b/crates/prepress/src/flatten/write.rs index 06fcc4850..3167ff9f6 100644 --- a/crates/prepress/src/flatten/write.rs +++ b/crates/prepress/src/flatten/write.rs @@ -255,10 +255,7 @@ impl<'a> Painter<'a, '_> { fn fill(&mut self, s: &mut Surface<'_>, f: &FillItem, opacity: f32) -> Result<(), WriteError> { let Some(path) = to_path(&f.path) else { return Ok(()) }; - let rule = match f.rule { - FillRule::NonZero => KFillRule::NonZero, - FillRule::EvenOdd => KFillRule::EvenOdd, - }; + let rule = k_fill_rule(f.rule); let (paint, overprint) = self.paint(&f.paint, f.overprint, Affine::IDENTITY)?; with_overprint(s, overprint, |s| { s.set_fill(Some(Fill { paint, opacity: normalized(opacity), rule })); @@ -424,7 +421,7 @@ impl<'a> Painter<'a, '_> { None => None, }; if let Some(clip) = clip { - s.push_clip_path(&clip, &KFillRule::NonZero); + s.push_clip_path(&clip, &k_fill_rule(g.clip_rule)); pushed += 1; } let tag = match &g.actual_text { @@ -694,6 +691,13 @@ fn to_transform(a: Affine) -> Transform { Transform::from_row(a, b, c, d, e, f) } +fn k_fill_rule(rule: FillRule) -> KFillRule { + match rule { + FillRule::NonZero => KFillRule::NonZero, + FillRule::EvenOdd => KFillRule::EvenOdd, + } +} + /// `None` for an empty path, which paints nothing. fn to_path(path: &BezPath) -> Option { let mut b = PathBuilder::new(); diff --git a/crates/prepress/tests/flatten_raster.rs b/crates/prepress/tests/flatten_raster.rs index 7f9af1c25..6d088c451 100644 --- a/crates/prepress/tests/flatten_raster.rs +++ b/crates/prepress/tests/flatten_raster.rs @@ -204,7 +204,17 @@ fn solid(r: Rect, tints: &[(InkId, f32)]) -> Item { } fn group(opacity: f32, blend: BlendMode, children: Vec) -> Item { - Item::Group(GroupItem { opacity, blend, isolated: false, knockout: false, clip: None, mask: None, actual_text: None, children }) + Item::Group(GroupItem { + opacity, + blend, + isolated: false, + knockout: false, + clip: None, + clip_rule: FillRule::NonZero, + mask: None, + actual_text: None, + children, + }) } fn ramp(r: Rect, from: InkColor, to: InkColor) -> Item { diff --git a/crates/prepress/tests/flatten_timings.rs b/crates/prepress/tests/flatten_timings.rs index 842c9c50c..37e8ca30e 100644 --- a/crates/prepress/tests/flatten_timings.rs +++ b/crates/prepress/tests/flatten_timings.rs @@ -158,6 +158,7 @@ fn heavy(size: f64, gradients: usize) -> DisplayList { isolated: false, knockout: false, clip: None, + clip_rule: FillRule::NonZero, mask: None, actual_text: None, children: vec![fill], diff --git a/crates/prepress/tests/flatten_write.rs b/crates/prepress/tests/flatten_write.rs index 8e0c98750..6836e9637 100644 --- a/crates/prepress/tests/flatten_write.rs +++ b/crates/prepress/tests/flatten_write.rs @@ -50,6 +50,7 @@ fn group(opacity: f32, children: Vec) -> Item { isolated: false, knockout: false, clip: None, + clip_rule: FillRule::NonZero, mask: None, actual_text: None, children, @@ -119,6 +120,21 @@ fn group_opacity_applies_to_the_group_not_to_each_child() { } } +#[test] +fn an_even_odd_clip_keeps_its_hole_written_or_flattened() { + // Two nested squares drawn in the same direction: filled even-odd, the inner one is a hole. + let mut ring = Rect::new(0.0, 0.0, 100.0, 100.0).to_path(0.1); + ring.extend(Rect::new(25.0, 25.0, 75.0, 75.0).to_path(0.1)); + let Item::Group(half_black) = group(0.5, vec![solid(Rect::new(0.0, 0.0, 100.0, 100.0), &[(K, 1.0)])]) else { unreachable!() }; + let clipped = Item::Group(GroupItem { clip: Some(ring), clip_rule: FillRule::EvenOdd, ..half_black }); + let list = page(InkSet::new(), vec![solid(Rect::new(0.0, 0.0, 100.0, 100.0), &[(C, 1.0)]), clipped]); + for written in [pdf(&list), flat_pdf(&list)] { + let p = separate(&written); + assert_inks(&p, 10, 50, &[("Cyan", 128), ("Black", 128)]); + assert_inks(&p, 50, 50, &[("Cyan", 255), ("Black", 0)]); + } +} + #[test] fn black_overprint_keeps_the_cyan_under_it() { let list = page(