pdf: blend each element of a non-isolated knockout group with its backdrop (#1137)

This commit is contained in:
Ken Mantle authored and GitHub committed 2026-11-16 21:32:26 -05:00
1 parent 94ad5948a8
commit b8eaa8e2f3
9 files changed
+557 -41

No files matched your search

+206
View File
@@ -0,0 +1,206 @@
//! #870: a non-isolated knockout group (`/I false /K true`) starts from the backdrop under it
//! (ISO 32000-2 §11.4.7, §11.4.8), so each element blends with the page there, in its own blend
//! mode, and replaces the elements before it under its shape. White with `/BM /Difference` over
//! magenta is green; drawn into a layer of its own starting transparent, it stayed white.
//! Adapted from PdfCraft #4898 (`it::knockout_backdrop` in pdfcraft-render at
//! 6a76d280168ebad42198de184d03ac11bf31f647, MIT OR Apache-2.0).
#![cfg(feature = "raster")]
use craft_pdf::interpret::InterpreterSettings;
use craft_pdf::{
open_slice,
raster::{self, Options, RenderCache},
};
const MAGENTA: [u8; 3] = [255, 0, 255];
const GREEN: [u8; 3] = [0, 255, 0];
const WHITE: [u8; 3] = [255, 255, 255];
fn pdf(objects: &[String]) -> Vec<u8> {
let mut out = b"%PDF-1.7\n".to_vec();
let mut offsets = Vec::new();
for (i, body) in objects.iter().enumerate() {
offsets.push(out.len());
out.extend_from_slice(format!("{} 0 obj\n{body}\nendobj\n", i + 1).as_bytes());
}
let xref = out.len();
out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).as_bytes());
for offset in offsets {
out.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
}
out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objects.len() + 1).as_bytes());
out
}
fn stream(dict: &str, content: &str) -> String {
format!("<< {dict} /Length {} >>\nstream\n{content}\nendstream", content.len())
}
/// Renders a 200 x 200 page: magenta, then the group `/Fk` with group attributes `group` and
/// content `content`. Its resources have `/D` (`/BM /Difference`), `/N` (`/BM /Normal`), `/H`
/// (`/ca 0.5`), `/W`, a white square from 40 to 160 in a group of its own, `/Nest`, a group
/// holding a non-isolated knockout group with a white Difference square from 80 to 120, and
/// `/Img`, a white 1 x 1 image, `/Img2`, a blue 2 x 1 image whose soft mask is opaque on the
/// left and transparent on the right, `/St`, a 2 x 1 stencil mask painting its left pixel, and
/// the shading `/Sh0`, a mesh whose one triangle lies off the page, and `/Sh1`, a red mesh
/// triangle from (90, 90) to (110, 90) and (100, 110).
/// Returns a lookup of the colour at PDF point (x, y).
fn render(group: &str, content: &str) -> impl Fn(u32, u32) -> [u8; 3] {
let gs = "/ExtGState << /D << /BM /Difference >> /H << /ca 0.5 >> /N << /BM /Normal >> >>";
let objects = [
"<< /Type /Catalog /Pages 2 0 R >>".to_string(),
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string(),
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents 4 0 R /Group << /S /Transparency /CS /DeviceRGB >> /Resources << /XObject << /Fk 5 0 R >> >> >>"
.to_string(),
stream("", "1 0 1 rg 0 0 200 200 re f /Fk Do"),
stream(
&format!("/Type /XObject /Subtype /Form /BBox [0 0 200 200] /Group << /S /Transparency /CS /DeviceRGB {group} >> /Resources << {gs} /XObject << /W 6 0 R /Nest 7 0 R /Img 9 0 R /Img2 10 0 R /St 12 0 R >> /Shading << /Sh0 13 0 R /Sh1 14 0 R >> >>"),
content,
),
stream("/Type /XObject /Subtype /Form /BBox [0 0 200 200] /Group << /S /Transparency >>", "1 1 1 rg 40 40 120 120 re f"),
stream("/Type /XObject /Subtype /Form /BBox [0 0 200 200] /Group << /S /Transparency >> /Resources << /XObject << /K2 8 0 R >> >>", "/K2 Do"),
stream(
&format!("/Type /XObject /Subtype /Form /BBox [0 0 200 200] /Group << /S /Transparency /I false /K true >> /Resources << {gs} >>"),
"/D gs 1 1 1 rg 80 80 40 40 re f",
),
stream("/Type /XObject /Subtype /Image /Width 1 /Height 1 /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /ASCIIHexDecode", "FFFFFF>"),
stream(
"/Type /XObject /Subtype /Image /Width 2 /Height 1 /ColorSpace /DeviceRGB /BitsPerComponent 8 /SMask 11 0 R /Filter /ASCIIHexDecode",
"0000FF0000FF>",
),
stream("/Type /XObject /Subtype /Image /Width 2 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8 /Filter /ASCIIHexDecode", "FF00>"),
stream("/Type /XObject /Subtype /Image /Width 2 /Height 1 /ImageMask true /BitsPerComponent 1 /Filter /ASCIIHexDecode", "40>"),
stream(
"/ShadingType 4 /ColorSpace /DeviceRGB /BitsPerCoordinate 8 /BitsPerComponent 8 /BitsPerFlag 8 /Decode [300 310 300 310 0 1 0 1 0 1] /Filter /ASCIIHexDecode",
"000000FF0000 00FF00FF0000 0000FFFF0000>",
),
stream(
"/ShadingType 4 /ColorSpace /DeviceRGB /BitsPerCoordinate 8 /BitsPerComponent 8 /BitsPerFlag 8 /Decode [0 255 0 255 0 1 0 1 0 1] /Filter /ASCIIHexDecode",
"005A5AFF0000 006E5AFF0000 00646EFF0000>",
),
];
let pdf = pdf(&objects);
let doc = open_slice(&pdf, None).unwrap();
let options = Options { background: [255; 4], ..Default::default() };
let raster = raster::render(&doc.pages()[0], &RenderCache::new(), &InterpreterSettings::default(), &options).unwrap();
let (rgba, width) = (raster.bytes().to_vec(), raster.width);
move |x, y| {
// Pixel rows run top down.
let offset = usize::try_from(((200 - y) * width + x) * 4).unwrap();
[rgba[offset], rgba[offset + 1], rgba[offset + 2]]
}
}
fn check(at: &impl Fn(u32, u32) -> [u8; 3], x: u32, y: u32, want: [u8; 3], what: &str) {
let got = at(x, y);
assert!(got.iter().zip(want).all(|(a, b)| a.abs_diff(b) <= 2), "{what} at ({x}, {y}): {got:?}, expected {want:?}");
}
const NON_ISOLATED: &str = "/I false /K true";
const SQUARES: &str = "/D gs 1 1 1 rg 20 20 110 110 re f 70 70 110 110 re f";
#[cfg_attr(not(target_arch = "wasm32"), test)]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
fn a_non_isolated_knockout_group_blends_each_element_with_the_page() {
let squares = render(NON_ISOLATED, SQUARES);
check(&squares, 40, 40, GREEN, "first square");
check(&squares, 160, 160, GREEN, "second square");
// The second square blends with the page, not with the first: green, not magenta again.
check(&squares, 100, 100, GREEN, "overlap");
check(&squares, 190, 10, MAGENTA, "page outside the group's elements");
}
#[cfg_attr(not(target_arch = "wasm32"), test)]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
fn the_last_element_over_a_point_decides_its_blend_mode() {
// Normal blue at 50 % after a Difference square: blue over the page where they overlap.
let blue_last = render(NON_ISOLATED, "/D gs 1 1 1 rg 20 20 110 110 re f /N gs 0 0 1 rg q /H gs 70 70 110 110 re f Q");
check(&blue_last, 40, 40, GREEN, "Difference alone");
check(&blue_last, 100, 100, [128, 0, 255], "Normal blue last");
check(&blue_last, 160, 160, [128, 0, 255], "Normal blue alone");
// The other way round: the Difference square replaces the blue and blends with the page.
let white_last = render(NON_ISOLATED, "q /H gs 0 0 1 rg 20 20 110 110 re f Q /D gs 1 1 1 rg 70 70 110 110 re f");
check(&white_last, 40, 40, [128, 0, 255], "Normal blue alone");
check(&white_last, 100, 100, GREEN, "Difference last");
}
#[cfg_attr(not(target_arch = "wasm32"), test)]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
fn a_nested_group_in_a_non_isolated_knockout_group_blends_with_the_page() {
let nested = render(NON_ISOLATED, "0 0 1 rg 20 20 160 160 re f /D gs /W Do");
check(&nested, 100, 100, GREEN, "nested group drawn with Difference over the knocked-out blue");
check(&nested, 30, 30, [0, 0, 255], "blue beside the nested group");
}
#[cfg_attr(not(target_arch = "wasm32"), test)]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
fn an_isolated_knockout_group_still_starts_transparent() {
let isolated = render("/I true /K true", SQUARES);
check(&isolated, 40, 40, WHITE, "isolated: nothing to blend with");
check(&isolated, 100, 100, WHITE, "isolated overlap");
}
#[cfg_attr(not(target_arch = "wasm32"), test)]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
fn an_image_and_a_partly_transparent_element_blend_with_the_page() {
let image = render(NON_ISOLATED, "/D gs q 120 0 0 120 40 40 cm /Img Do Q");
check(&image, 100, 100, GREEN, "white image drawn with Difference");
check(&image, 20, 20, MAGENTA, "page beside the image");
// Difference at 50 %: half the page, half the blend result (green).
let half = render(NON_ISOLATED, "/D gs /H gs 1 1 1 rg 40 40 120 120 re f");
check(&half, 100, 100, [128, 128, 128], "Difference at 50 %");
}
/// A knockout group nested in another one's element is drawn first in that element's erase
/// pass, which must leave the outer group's passes alone.
#[cfg_attr(not(target_arch = "wasm32"), test)]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
fn a_knockout_group_inside_an_element_keeps_the_outer_groups_passes() {
let nested = render(NON_ISOLATED, "/D gs 1 1 1 rg 10 10 50 50 re f /N gs /Nest Do /D gs 1 1 1 rg 140 140 50 50 re f");
check(&nested, 30, 30, GREEN, "Difference square before the nested groups");
check(&nested, 165, 165, GREEN, "Difference square after the nested groups");
}
/// A masked image (or, below, a stencil) in another pass than its own replaces what is under
/// its mask there too: a blue image over a white Difference square stays blue where its mask is
/// opaque, and leaves the square to blend with the page where it is transparent.
#[cfg_attr(not(target_arch = "wasm32"), test)]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
fn a_masked_image_replaces_what_is_under_its_mask_in_every_pass() {
let masked = render(NON_ISOLATED, "/D gs 1 1 1 rg 40 40 120 120 re f /N gs q 120 0 0 120 40 40 cm /Img2 Do Q");
check(&masked, 60, 100, [0, 0, 255], "image over the square, mask opaque");
check(&masked, 140, 100, GREEN, "square under the transparent half of the mask");
}
#[cfg_attr(not(target_arch = "wasm32"), test)]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
fn a_stencil_replaces_what_is_under_it_in_every_pass() {
let stencil = render(NON_ISOLATED, "/D gs 1 1 1 rg 40 40 120 120 re f /N gs 0 0 1 rg q 120 0 0 120 40 40 cm /St Do Q");
check(&stencil, 60, 100, [0, 0, 255], "stencil over the square");
check(&stencil, 140, 100, GREEN, "square beside the stencil");
}
/// A shading that paints nothing (a mesh off the page) replaces nothing in another pass either.
#[cfg_attr(not(target_arch = "wasm32"), test)]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
fn a_shading_that_paints_nothing_clears_nothing_in_another_pass() {
let mesh = render(NON_ISOLATED, "0 0 1 rg 20 20 160 160 re f /D gs /Sh0 sh");
check(&mesh, 100, 100, [0, 0, 255], "blue under an off-page Difference mesh");
}
/// A shading replaces only what is under the part it paints: a small mesh triangle over a
/// square leaves the rest of the square, in its own pass, in another pass and in an isolated
/// knockout group.
#[cfg_attr(not(target_arch = "wasm32"), test)]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
fn a_small_mesh_replaces_only_what_is_under_its_triangle() {
let square = "0 0 1 rg 20 20 160 160 re f";
for (group, mode) in [(NON_ISOLATED, ""), (NON_ISOLATED, "/D gs"), ("/K true", "")] {
let content = format!("{square} {mode} /Sh1 sh");
let mesh = render(group, &content);
check(&mesh, 40, 40, [0, 0, 255], &format!("{group} {mode}: square beside the triangle"));
if mode.is_empty() {
check(&mesh, 100, 97, [255, 0, 0], &format!("{group}: triangle"));
}
}
}
+25
View File
@@ -516,6 +516,31 @@ fn a_knockout_group_separates_with_only_the_top_object_in_the_overlap() {
assert_eq!(blended.at(20, 20), [25, 50, 0, 0], "both squares without /K");
}
/// #870: in a non-isolated knockout group each element composites with the group's backdrop in
/// its own blend mode (ISO 32000-2 §11.4.6, §11.4.8). Magenta, then cyan over it, both Multiply,
/// over a yellow page keep the yellow under them, and the cyan replaces the magenta where they
/// overlap. Drawn into a layer starting transparent, the yellow was knocked out.
#[cfg_attr(not(target_arch = "wasm32"), test)]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
fn a_non_isolated_knockout_group_multiplies_each_element_with_its_backdrop() {
let form = "/M gs 0 1 0 0 k 5 5 20 20 re f 1 0 0 0 k 15 15 20 20 re f";
let pdf = page_pdf(
"0 0 1 0 k 0 0 40 40 re f /Fm Do",
"/XObject << /Fm 5 0 R >>",
&[stream(
"/Type /XObject /Subtype /Form /BBox [0 0 40 40] /Group << /S /Transparency /CS /DeviceCMYK /K true >> /Resources << /ExtGState << /M << /BM /Multiply >> >> >>",
form.as_bytes(),
)],
);
// Device rows run top down: magenta alone at (8, 32), the overlap at (20, 20), cyan alone at
// (32, 8), the page alone at (37, 37).
let s = plates(&pdf, &inks(&[]), true, None);
assert_eq!(s.at(8, 32), [0, 100, 100, 0], "magenta multiplied with the yellow");
assert_eq!(s.at(20, 20), [100, 0, 100, 0], "cyan replaces the magenta, multiplied with the yellow");
assert_eq!(s.at(32, 8), [100, 0, 100, 0], "cyan multiplied with the yellow");
assert_eq!(s.at(37, 37), [0, 0, 100, 0], "the page");
}
/// PdfCraft #3018: `/DefaultCMYK` and `/DefaultGray` change how device color looks, not the
/// inks it prints with. Under them DeviceCMYK still separates as its components (and keeps the
/// nonzero overprint mode), a DeviceCMYK image sample by sample, and DeviceGray on black alone,
+6
View File
@@ -59,6 +59,7 @@ where noted below.
|---|---|---|---|---|
| [#2770](https://github.com/storytold/pdfcraft/pull/2770) | Guillem Hermida (guillehr2) | [6fcf2a4](https://github.com/guillehr2/pdfcraft/commit/6fcf2a4aca29e943e28cb69017ff8f87d00656c6) | hayro-interpret `color.rs`, `interpret/mod.rs`, `interpret/path.rs`, `interpret/state.rs`, `pattern.rs`, `shading.rs`, `soft_mask.rs`, `x_object.rs` | Patches 35 and 36, plate mode: `InterpreterSettings::plate` draws one ink's separation as a gray film (`color::Plate`, `ColorSpace::ink_use`/`ink_tint`); the graphics state reads `OP`, `op` and `OPM` and an overprinting paint that doesn't specify the plate's ink leaves the plate as it is (ISO 32000-2 §8.6.7); `InterpreterSettings::ink_sink` reports spot inks; `color::CmykSimulation` converts process color to an output intent's CMYK. Only the vendored interpreter part is ported; PdfCraft's `separations.rs` and Output Preview UI are not |
| [#2974](https://github.com/storytold/pdfcraft/pull/2974) | mtlcl410 | [bae6981](https://github.com/mtlcl410/pdfcraft/commit/bae69819594a6385a027fec1f67e6b3c36c259b4) | hayro-interpret `device.rs`, `x_object.rs`; hayro `renderer.rs` | Knockout groups (`/K true`) knock out: while one is innermost, fills, strokes, glyph outlines and shadings are drawn with `Compose::Copy` (weighted by coverage); an unmasked image's rectangle (`Device::knockout_image`) and a nested group's shape (an erase pass between `Device::begin_knockout_erase` and `end_knockout_erase`) are cleared before their layer composites; a transparency group drawn in a knockout group always gets a layer of its own. Masked images and stencils composite as before |
| [#4898](https://github.com/storytold/pdfcraft/pull/4898) | KenM76 | [6a76d28](https://github.com/KenM76/pdfcraft/commit/6a76d280168ebad42198de184d03ac11bf31f647) | hayro-interpret `device.rs`, `ocg.rs`, `x_object.rs`; hayro `renderer.rs` | A non-isolated knockout group entered at full opacity, without a soft mask and with Normal blending, composites each element with the backdrop in the element's own blend mode: the group is drawn once per blend mode its elements use (`Device::begin_knockout_pass`, `end_knockout_pass`), each pass a layer composited in its mode, in which elements of other modes clear their shape; a shading in a knockout group clears only where it paints (`Compose::DestOut`), so a mesh or a `/BBox` no longer clears its whole path |
Code comments label #2974's changes `Knockout patch (pdfcraft #2974)` instead of a number: the
pull request numbers them hayro-interpret patch 39 and hayro patch 19, and PdfCraft may
@@ -67,6 +68,11 @@ test in `crates/pdf/tests/plates.rs` checks that a knockout group separates with
object where two objects overlap. The erase pass resolves the group's resources with
`Resources::from_scope`, as the group's own draw does in this tree.
#4898 was merged in PdfCraft (b0555cb) after this tree's snapshot. Its comments keep the label
`Knockout patch (pdfcraft #4898)`, beside #2974's. `crates/pdf/tests/knockout_backdrop.rs`
adapts its tests; a plate-mode test in `crates/pdf/tests/plates.rs` checks the case of craft-libs
#870, a Multiply knockout group over a yellow page.
A craft-libs patch, labeled `Craft patch (CMYK masks)` in code comments,
takes a luminosity soft mask whose group is DeviceCMYK from the group's inks: ISO 32000-2
§11.6.5.2 and §10.4.2.2 give `1 - min(1, 0.3c + 0.59m + 0.11y + k)`, where the colors as
+3 -3
View File
@@ -200,7 +200,7 @@
"path": "src/device.rs",
"source_sha256": "6f0c1203d1e60724cdd11e9a230249247a70f578c4a7ccb9bf39a23411b32db6",
"source_git_blob": "36c64a23fd23f6c4abad941077cf93296a67841f",
"sha256": "4465153ace47c6893958f187a37579dd87139e04505749483aea139f5f2bac99"
"sha256": "8fff824fd81c36dc20a194697b10cd752928b09301f9287b0bb6ed00978ac723"
},
{
"path": "src/encode.rs",
@@ -398,7 +398,7 @@
"path": "src/ocg.rs",
"source_sha256": "439455f65b8ad6ed9b0306536c2f75fa5f3fdda42ed4ca351ec3d340c38dc330",
"source_git_blob": "c59b70df4be6a83485360dacd76bead9f80c7f94",
"sha256": "802fd4c330f5066bcb2070aa0986dc869cd6f1f443e8e92857a598f7336266b7"
"sha256": "35dadd9fc07e3e5754e208fc5c0c588776ff6bff249aa0eee9848a8fde8b4f08"
},
{
"path": "src/pattern.rs",
@@ -434,7 +434,7 @@
"path": "src/x_object.rs",
"source_sha256": "e1c51e96a335c32c122011b2d05c5020c36a33c2c73342ba173c28a3e2fe0219",
"source_git_blob": "21b134ce8cd9604399cd0776febf923d69c02673",
"sha256": "bc13ae42935851fa0f2117ad74a4e6d4cf5a86aae933fb6362f911b0d6a3ce52"
"sha256": "d752a8c44c0a3918e9fc130c4e59a1708ae7bfa2a3c95b700dfe77da15f43f66"
}
],
"compatibility_reference": {
+13
View File
@@ -107,6 +107,19 @@ pub trait Device<'a> {
fn begin_knockout_erase(&mut self) {}
/// Knockout patch (pdfcraft #2974): see `knockout_erase_wanted`.
fn end_knockout_erase(&mut self) {}
/// Knockout patch (pdfcraft #4898): the knockout group just pushed (`set_knockout`) is drawn
/// once per blend mode its elements use, each pass into a layer of its own composited with
/// that mode. In this pass only elements whose blend mode is `mode` paint; every other
/// element clears what is under its shape, as it would replace it. Each pixel then holds the
/// last element covering it in exactly one pass, which composites it with the group's
/// backdrop in that element's own blend mode (#870).
fn begin_knockout_pass(&mut self, _mode: BlendMode) {}
/// Knockout patch (pdfcraft #4898): ends the pass `begin_knockout_pass` started, before the
/// layer is popped. Returns the other blend modes the pass's elements used, each once. A
/// device that doesn't track them returns none, and the group is drawn in one Normal pass.
fn end_knockout_pass(&mut self) -> Vec<BlendMode> {
Vec::new()
}
/// Craft patch (flatten): the overprint parameters for the paints that follow, until the
/// next call: `op` (`fill`, for fills, glyph fills and images), `OP` (`stroke`) and `OPM`
/// (`mode`, 0 or 1; ISO 32000-2 §8.6.7). Called where `set_blend_mode` is called for a
+11
View File
@@ -13,6 +13,17 @@ pub(crate) struct OcgState {
}
impl OcgState {
/// Knockout patch (pdfcraft #4898): the marked-content visibility now, to put back after
/// content that may leave it unbalanced is interpreted once more (`draw_knockout_passes`).
pub(crate) fn visibility(&self) -> Vec<bool> {
self.visibility_stack.clone()
}
/// Knockout patch (pdfcraft #4898): see `visibility`.
pub(crate) fn set_visibility(&mut self, visibility: Vec<bool>) {
self.visibility_stack = visibility;
}
fn dummy() -> Self {
Self {
inactive_ocgs: HashSet::default(),
+79 -1
View File
@@ -157,13 +157,14 @@ pub(crate) fn draw_form_xobject<'a, 'b>(
// starts from a blank backdrop by definition, and a knockout group or one entered at partial
// opacity, under a soft mask or with a blend mode keeps its layer, where the group's
// elements still composite with a blank backdrop (an approximation of §11.4.7 for them).
let neutral = !x_object.is_isolated && !x_object.is_knockout && {
let entered_plainly = {
let state = &context.get().graphics_state;
state.non_stroke_alpha >= 1.0
&& state.stroke_alpha >= 1.0
&& state.soft_mask.is_none()
&& state.blend_mode == BlendMode::Normal
};
let neutral = !x_object.is_isolated && !x_object.is_knockout && entered_plainly;
// Knockout patch (pdfcraft #2974): a group drawn as an element of a knockout group replaces
// what that group drew under its shape, the union of its own elements' shapes (pdfcraft #2971).
// The shape is cleared by drawing the group's content once in the device's erase mode; the
@@ -195,6 +196,26 @@ pub(crate) fn draw_form_xobject<'a, 'b>(
context.restore_state(device);
context.path_mut().truncate(0);
}
// Knockout patch (pdfcraft #4898): a non-isolated knockout group entered the same way
// composites each element with the backdrop already on the page, in the element's own blend
// mode (#870). A layer of its own starts transparent, where a blend mode has nothing to blend
// with, so the group is drawn in passes, one per blend mode, each composited onto the page in
// its mode (`Device::begin_knockout_pass`).
if x_object.is_transparency_group
&& x_object.is_knockout
&& !x_object.is_isolated
&& entered_plainly
&& !knockout_element
{
draw_knockout_passes(x_object, resources, context, device);
context.pop_root_transform();
context.restore_state(device);
if has_oc {
context.ocg_state.end_marked_content();
}
context.end_nested_interpretation();
return;
}
let own_layer = x_object.is_transparency_group && (!neutral || knockout_element);
if own_layer {
@@ -254,6 +275,63 @@ pub(crate) fn draw_form_xobject<'a, 'b>(
context.end_nested_interpretation();
}
/// Knockout patch (pdfcraft #4898): draws a non-isolated knockout group entered at full opacity,
/// without a soft mask and with Normal blending, once per blend mode its elements use. The
/// Normal pass finds the other modes; there are at most as many passes as blend modes.
fn draw_knockout_passes<'a>(
x_object: &FormXObject<'a>,
resources: &Resources<'a>,
context: &mut Context<'a>,
device: &mut impl Device<'a>,
) {
let clip = ClipPath {
path: context.get().ctm
* Rect::new(
x_object.bbox[0] as f64,
x_object.bbox[1] as f64,
x_object.bbox[2] as f64,
x_object.bbox[3] as f64,
)
.to_path(0.1),
fill: FillRule::NonZero,
};
// Each pass starts from the same marked-content state, also after a stream that leaves a
// `BDC` open.
let visibility = context.ocg_state.visibility();
let mut modes = vec![BlendMode::Normal];
let mut pass = 0;
while let Some(&mode) = modes.get(pass) {
context.ocg_state.set_visibility(visibility.clone());
context.save_state();
device.push_transparency_group(1.0, None, mode);
device.set_knockout();
device.begin_knockout_pass(mode);
device.set_soft_mask(None);
device.set_blend_mode(BlendMode::Normal);
device.push_clip_path(&clip);
interpret(
TypedIter::new(x_object.decoded.as_ref()),
&Resources::from_scope(x_object.resources.clone(), resources.clone()),
context,
device,
);
device.pop_clip_path();
let others = device.end_knockout_pass();
device.pop_transparency_group();
context.restore_state(device);
context.path_mut().truncate(0);
if pass == 0 {
for other in others {
if !modes.contains(&other) {
modes.push(other);
}
}
}
pass += 1;
}
context.ocg_state.set_visibility(visibility);
}
pub(crate) fn draw_image_xobject<'a, 'b>(
x_object: &ImageXObject<'b>,
context: &mut Context<'a>,
+1 -1
View File
@@ -68,7 +68,7 @@
"path": "src/renderer.rs",
"source_sha256": "f7ff7bd088ceb43823ede33151138384af331cf71403f7d23f7b2937212efc3b",
"source_git_blob": "6aa53716ad2d0203a8058b2f7271515b4fc1db22",
"sha256": "02d256f43d9b8bceb68cee9f9f9ed0bcb48bb70d7068f2d1c6d6a9d85e3f4e64"
"sha256": "d9cf21375b8957684a8d18b84ed8aac4c340212e9d6154b09f26ab7981b83a95"
}
]
}
+213 -36
View File
@@ -452,6 +452,9 @@ pub(crate) struct Renderer {
/// (nothing is layered while erasing).
erasing: bool,
erase_groups: usize,
/// Knockout patch (pdfcraft #4898): the knockout groups drawn in blend-mode passes
/// (`Device::begin_knockout_pass`), innermost last.
knockout_passes: Vec<KnockoutPass>,
pub(crate) inside_pattern: bool,
/// Soft masks drawn during this render. PdfCraft note: it belongs to one `Renderer` (one
/// render, every nested renderer starting empty) and so to one `preview` setting: a mask
@@ -481,6 +484,33 @@ impl Renderer {
self.knockout.last().copied().unwrap_or(false)
}
/// Knockout patch (pdfcraft #4898): the blend-mode pass of the innermost group, when that
/// group is a knockout group drawn in passes, so the element now drawn is one of its own
/// elements.
fn knockout_pass(&mut self) -> Option<&mut KnockoutPass> {
let depth = self.knockout.len();
if !self.in_knockout() {
return None;
}
self.knockout_passes.last_mut().filter(|pass| pass.depth == depth)
}
/// Knockout patch (pdfcraft #4898): whether an element of blend mode `mode` belongs to
/// another pass than the current one, so here it clears what is under its shape instead of
/// painting. Records the mode for its own pass.
fn knockout_pass_skips(&mut self, mode: BlendMode) -> bool {
let Some(pass) = self.knockout_pass() else {
return false;
};
if mode == pass.mode {
return false;
}
if !pass.other_modes.contains(&mode) {
pass.other_modes.push(mode);
}
true
}
pub(crate) fn new(
width: u16,
height: u16,
@@ -495,6 +525,7 @@ impl Renderer {
in_annotations: false,
knockout: Vec::new(),
erasing: false,
knockout_passes: Vec::new(),
erase_groups: 0,
inside_pattern: false,
soft_mask_cache: HashMap::default(),
@@ -599,6 +630,7 @@ impl Renderer {
in_annotations: false,
knockout: Vec::new(),
erasing: false,
knockout_passes: Vec::new(),
erase_groups: 0,
inside_pattern: false,
soft_mask_cache: HashMap::default(),
@@ -1105,18 +1137,89 @@ impl Renderer {
fn set_paint(&mut self, paint: &Paint<'_>, path: &BezPath, is_stroke: bool) -> PaintSetup {
// Knockout patch (pdfcraft #2974): in a knockout erase pass every paint clears what is
// under its shape (a transparent fill with `Compose::Copy`, weighted by coverage).
if self.erasing {
// Knockout patch (pdfcraft #4898): so does an element of another pass than the current
// one (`Device::begin_knockout_pass`).
let element_mode = self.knockout_pass().map(|pass| pass.element_mode);
let other_pass =
!self.erasing && element_mode.is_some_and(|mode| self.knockout_pass_skips(mode));
if self.erasing || other_pass {
if is_shading(paint) {
self.knockout_shading(paint, path, is_stroke, false);
return PaintSetup::Nothing;
}
self.ctx.set_blend_mode(knockout_blend_mode());
self.ctx.set_paint(AlphaColor::<Srgb>::new([0.0, 0.0, 0.0, 0.0]));
// A shading's `/BBox` clips what it paints, so it clips what it clears too.
return PaintSetup::Clip(match paint {
Paint::Pattern(p) => match p.as_ref() {
Pattern::Shading(s) => s.shading.clip_path.clone(),
_ => None,
},
_ => None,
});
return PaintSetup::Clip(None);
}
if self.in_knockout() && is_shading(paint) {
self.knockout_shading(paint, path, is_stroke, true);
return PaintSetup::Nothing;
}
self.paint_setup(paint, path, is_stroke)
}
/// Knockout patch (pdfcraft #4898): a shading in a knockout group replaces what is under it
/// where it paints, which a mesh's triangles or the shading's `/BBox` may make less than the
/// path, so it can't be copied over the path like other paints. The shading at full opacity,
/// composited with `Compose::DestOut`, clears its shape; then, when `paint_it`, the shading
/// is painted over the cleared area. A shading that paints nothing clears nothing. The
/// caller paints nothing more.
fn knockout_shading(
&mut self,
paint: &Paint<'_>,
path: &BezPath,
is_stroke: bool,
paint_it: bool,
) {
let PaintSetup::Clip(clip) = self.paint_setup(&shape_of(paint), path, is_stroke) else {
return;
};
if let Some(clip) = clip.as_ref() {
self.push_clip_path_inner(clip, FillRule::NonZero);
}
self.ctx
.set_blend_mode(peniko::BlendMode::new(Mix::Normal, Compose::DestOut));
self.draw_shape(path, is_stroke);
if paint_it && let PaintSetup::Clip(_) = self.paint_setup(paint, path, is_stroke) {
self.ctx
.set_blend_mode(peniko::BlendMode::new(Mix::Normal, Compose::SrcOver));
self.draw_shape(path, is_stroke);
}
if clip.is_some() {
self.ctx.pop_clip_path();
}
self.ctx.set_blend_mode(knockout_blend_mode());
}
fn draw_shape(&mut self, path: &BezPath, is_stroke: bool) {
if is_stroke {
self.ctx.stroke_path(path);
} else {
self.ctx.fill_path(path);
}
}
/// The device-space area a shading painted on `path` covers: the path's bounding box, with
/// the stroke width around it for a stroke, on the canvas.
fn shading_bbox(&self, path: &BezPath, is_stroke: bool) -> Rect {
let path_transform = self.ctx.transform();
let mut bbox = (*path_transform * path.clone()).bounding_box();
if is_stroke {
// Try to account for stroke in bbox.
let (a1, a2) = x_y_advances(path_transform);
let factor = a1.length().max(a2.length()) * self.ctx.stroke().width;
bbox = bbox.inflate(factor, factor);
}
bbox.intersect(Rect::new(
0.0,
0.0,
self.ctx.width() as f64,
self.ctx.height() as f64,
))
}
/// The paint `paint` draws on `path` with, set on the context (see [`PaintSetup`]).
fn paint_setup(&mut self, paint: &Paint<'_>, path: &BezPath, is_stroke: bool) -> PaintSetup {
let mut paint_transform = Affine::IDENTITY;
let mut clip_path = None;
// PdfCraft patch (#3296): `Extend::Repeat` tiles the texture over the path; a mesh
@@ -1134,21 +1237,7 @@ impl Renderer {
match *p {
Pattern::Shading(s) => {
clip_path = s.shading.clip_path.clone();
let mut bbox = (*path_transform * path.clone()).bounding_box();
if is_stroke {
// Try to account for stroke in bbox.
let (a1, a2) = x_y_advances(path_transform);
let factor = a1.length().max(a2.length()) * self.ctx.stroke().width;
bbox = bbox.inflate(factor, factor);
}
bbox = bbox.intersect(Rect::new(
0.0,
0.0,
self.ctx.width() as f64,
self.ctx.height() as f64,
));
let mut bbox = self.shading_bbox(path, is_stroke);
// PdfCraft patch: mesh shadings are sampled only inside `bbox` (and a
// pixel around it: texels at a fractional edge look one pixel further).
@@ -1161,18 +1250,11 @@ impl Renderer {
// one-triangle meshes on a plan cost 310 full tiles per tile, and the
// watchdog gave the page up. A mesh with no triangle on the canvas
// paints nothing at all.
if let Some(extent) = encoded.extent {
// An empty extent (no triangle in the area) is `Rect::ZERO`, which
// sits at the canvas origin: test it before intersecting, or a
// 1 × 1 transparent texture would still be painted over the whole
// path (310 of them cost 230 ms per tile).
if extent.width() <= 0.0 || extent.height() <= 0.0 {
if encoded.extent.is_some() {
let Some(area) = mesh_area(bbox, &encoded) else {
return PaintSetup::Nothing;
}
bbox = bbox.intersect(extent.inflate(1.0, 1.0));
if bbox.width() <= 0.0 || bbox.height() <= 0.0 {
return PaintSetup::Nothing;
}
};
bbox = area;
extend = peniko::Extend::Pad;
}
@@ -1267,6 +1349,7 @@ impl Renderer {
in_annotations: false,
knockout: Vec::new(),
erasing: false,
knockout_passes: Vec::new(),
erase_groups: 0,
cur_mask: None,
inside_pattern: true,
@@ -1324,6 +1407,7 @@ impl Renderer {
in_annotations: false,
knockout: Vec::new(),
erasing: false,
knockout_passes: Vec::new(),
erase_groups: 0,
cur_mask: None,
inside_pattern: true,
@@ -1626,6 +1710,7 @@ impl<'a> Device<'a> for Renderer {
in_annotations: false,
knockout: Vec::new(),
erasing: false,
knockout_passes: Vec::new(),
erase_groups: 0,
inside_pattern: false,
soft_mask_cache: HashMap::default(),
@@ -1709,6 +1794,15 @@ impl<'a> Device<'a> for Renderer {
self.erase_groups += 1;
return;
}
// Knockout patch (pdfcraft #4898): an image or group of another pass than the current
// one clears what is under its shape instead of painting: its layer, drawn at full
// opacity with no soft mask, composites with `Compose::DestOut`. That clears the coverage
// of a masked image's or a stencil's mask too, which `knockout_image` leaves alone.
let (opacity, mask, layer_blend) = if self.knockout_pass_skips(blend_mode) {
(1.0, None, peniko::BlendMode::new(Mix::Normal, Compose::DestOut))
} else {
(opacity, mask, convert_blend_mode(blend_mode))
};
let settings = *self.ctx.render_settings();
let force_images_may_have_transparency = mask.is_some()
|| blend_mode != BlendMode::Normal
@@ -1719,7 +1813,7 @@ impl<'a> Device<'a> for Renderer {
.unwrap_or(false);
self.ctx.push_layer(
None,
Some(convert_blend_mode(blend_mode)),
Some(layer_blend),
Some(opacity),
// TODO: Deduplicate
mask.map(|m| {
@@ -1787,6 +1881,32 @@ impl<'a> Device<'a> for Renderer {
self.ctx.set_blend_mode(knockout_blend_mode());
}
fn begin_knockout_pass(&mut self, mode: BlendMode) {
if self.in_knockout() && !self.erasing {
self.knockout_passes.push(KnockoutPass {
depth: self.knockout.len(),
mode,
element_mode: BlendMode::Normal,
other_modes: Vec::new(),
});
}
}
fn end_knockout_pass(&mut self) -> Vec<BlendMode> {
// In an erase pass `begin_knockout_pass` started nothing; the pass at this depth belongs
// to the knockout group being erased into, and stays.
if self.erasing {
return Vec::new();
}
let depth = self.knockout.len();
match self.knockout_passes.last() {
Some(pass) if pass.depth == depth => {
self.knockout_passes.pop().map(|pass| pass.other_modes).unwrap_or_default()
}
_ => Vec::new(),
}
}
fn in_knockout_group(&mut self) -> bool {
self.in_knockout()
}
@@ -1928,6 +2048,13 @@ impl<'a> Device<'a> for Renderer {
}
fn set_blend_mode(&mut self, blend_mode: BlendMode) {
// Knockout patch (pdfcraft #4898): the blend mode of the element about to paint, for its
// pass (an erase pass paints nothing, and its content's modes are not the element's).
if !self.erasing
&& let Some(pass) = self.knockout_pass()
{
pass.element_mode = blend_mode;
}
// Knockout patch (pdfcraft #2974): inside a knockout group every element replaces what it
// covers.
let mode = if self.in_knockout() {
@@ -2022,6 +2149,7 @@ fn soft_mask_renderer(settings: &RenderSettings, width: u16, height: u16, previe
in_annotations: false,
knockout: Vec::new(),
erasing: false,
knockout_passes: Vec::new(),
erase_groups: 0,
inside_pattern: false,
cur_mask: None,
@@ -2161,12 +2289,61 @@ fn convert_fill_rule(fill_rule: FillRule) -> Fill {
}
}
/// Knockout patch (pdfcraft #4898): one blend-mode pass over a knockout group
/// (`Device::begin_knockout_pass`).
struct KnockoutPass {
/// `knockout.len()` with the group pushed: its own elements are drawn at this depth.
depth: usize,
/// The blend mode whose elements paint in this pass.
mode: BlendMode,
/// The blend mode of the element painting now (`set_blend_mode`).
element_mode: BlendMode,
/// The other blend modes this pass's elements used, each once (at most one per mode).
other_modes: Vec<BlendMode>,
}
/// Knockout patch (pdfcraft #4898): `paint` at full opacity, for the shape it covers.
fn shape_of<'a>(paint: &Paint<'a>) -> Paint<'a> {
match paint {
Paint::Pattern(p) => match p.as_ref() {
Pattern::Shading(s) => {
let mut s = s.clone();
s.opacity = 1.0;
Paint::Pattern(Box::new(Pattern::Shading(s)))
}
Pattern::Tiling(_) => paint.clone(),
},
Paint::Color(_) => paint.clone(),
}
}
/// Knockout patch (pdfcraft #4898): whether `paint` is a shading.
fn is_shading(paint: &Paint<'_>) -> bool {
matches!(paint, Paint::Pattern(p) if matches!(p.as_ref(), Pattern::Shading(_)))
}
/// Knockout patch (pdfcraft #2974): how an element of a knockout group is drawn (see
/// `set_knockout`).
fn knockout_blend_mode() -> peniko::BlendMode {
peniko::BlendMode::new(Mix::Normal, Compose::Copy)
}
/// PdfCraft patch (#3296): the part of `bbox` a shading encoded within it paints. A mesh paints
/// only around its triangles, and nothing (`None`) when none is in `bbox`; its empty extent is
/// `Rect::ZERO`, at the canvas origin, so it is tested before intersecting, or a 1 × 1
/// transparent texture would still be painted over the whole path (310 of them cost 230 ms per
/// tile). Any other shading paints all of `bbox`.
fn mesh_area(bbox: Rect, encoded: &EncodedShadingPattern) -> Option<Rect> {
let Some(extent) = encoded.extent else {
return Some(bbox);
};
if extent.width() <= 0.0 || extent.height() <= 0.0 {
return None;
}
let area = bbox.intersect(extent.inflate(1.0, 1.0));
(area.width() > 0.0 && area.height() > 0.0).then_some(area)
}
fn convert_blend_mode(blend_mode: BlendMode) -> peniko::BlendMode {
let mix = match blend_mode {
BlendMode::Normal => Mix::Normal,