From 9c865fe2eaf98cc342298932e532002e55a57c26 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 30 Nov 2026 22:00:41 -0800 Subject: [PATCH] PDF export: keep joins between opaque mesh patches smooth (cherry picked from commit 82f948fdc2057977e41c9c319d0ac55b2fc6f5f5) --- crates/pdf/src/export/nodes.rs | 44 ++++++++++++++++- crates/pdf/src/tests/mesh_export.rs | 74 +++++++++++++++++++++++++++++ 2 files changed, 116 insertions(+), 2 deletions(-) diff --git a/crates/pdf/src/export/nodes.rs b/crates/pdf/src/export/nodes.rs index b3b5de36a4..a093ecc9c0 100644 --- a/crates/pdf/src/export/nodes.rs +++ b/crates/pdf/src/export/nodes.rs @@ -1,5 +1,7 @@ use std::collections::HashMap; +use vectorcraft_geom::Vec2; + use super::exporter::{UNDECODED, address, blend, color, constant_mask, cover, in_range, norm, rects_overlap, rule, to_path, writable, xf}; use super::{ Affine, AppearanceItem, BezPath, BlendMode, Document, Exporter, Fill, FillRule, GradientKind, LineCap, LineJoin, Mark, Node, NodeKind, @@ -19,6 +21,37 @@ fn brushed(b: Option, reach: f64) -> Option { if reach > 0.0 { b.map(|b| b.inflate(reach, reach)) } else { b } } +/// Can the patch shade its own outline without folding across it? The differences of adjacent +/// tensor control points bound each directional derivative in a convex cone. If every pair of +/// derivatives has the same strict orientation, averaging them along any segment keeps them +/// independent, so distinct parameter points cannot map to the same point. +fn unfolded_patch(points: [(f32, f32); 12]) -> bool { + let p = points.map(|(x, y)| Vec2::new(f64::from(x), f64::from(y))); + let top = [p[0], p[11], p[10], p[9]]; + let bottom = [p[3], p[4], p[5], p[6]]; + let left = [p[0], p[1], p[2], p[3]]; + let right = [p[9], p[8], p[7], p[6]]; + // Raise the linear blending terms of the Coons surface to cubic degree in each direction. + let net: [[Vec2; 4]; 4] = std::array::from_fn(|row| { + let v = row as f64 / 3.0; + std::array::from_fn(|col| { + let u = col as f64 / 3.0; + let bilinear = (p[0] * (1.0 - u) + p[9] * u) * (1.0 - v) + (p[3] * (1.0 - u) + p[6] * u) * v; + top[col] * (1.0 - v) + bottom[col] * v + left[row] * (1.0 - u) + right[row] * u - bilinear + }) + }); + let du: [[Vec2; 3]; 4] = std::array::from_fn(|row| std::array::from_fn(|col| net[row][col + 1] - net[row][col])); + let dv: [[Vec2; 4]; 3] = std::array::from_fn(|row| std::array::from_fn(|col| net[row + 1][col] - net[row][col])); + let orientation = du[0][0].cross(dv[0][0]).signum(); + du.into_iter().flatten().all(|u| { + dv.iter().flatten().all(|v| { + let cross = u.cross(*v) * orientation; + // Keep near-parallel directions on the existing clipped path through PDF quantization. + cross > 0.0 && cross * cross > 1e-12 * u.hypot2() * v.hypot2() + }) + }) +} + #[cfg(test)] std::thread_local! { /// The objects this thread has measured for the walk and for the links (tests). @@ -542,7 +575,7 @@ impl Exporter<'_> { } } - /// Gradient mesh `m` as one PDF Type 6 (Coons patch) shading filling its outline (ISO 32000-1, + /// Gradient mesh `m` as one PDF Type 6 (Coons patch) shading (ISO 32000-1, /// 8.7.4.5.7): each patch blends its corner colours bilinearly, as the canvas draws it, and /// the viewer or RIP does so smoothly at its own resolution. Cutting the mesh into flat quads /// instead banded, left seams between them, and made files with many meshes very large. @@ -560,7 +593,6 @@ impl Exporter<'_> { if !writable(s, Affine::IDENTITY, bounds) { return false; } - let Some(path) = to_path(s, &m.outline().to_bezpath()) else { return false }; let page: Vec = m.points.iter().map(|p| self.page_color(&p.color)).collect(); let mixed = page.windows(2).any(|w| w[0].model() != w[1].model()); let rgb = page.iter().any(|c| matches!(c, vectorcraft_color::Color::Rgb { .. } | vectorcraft_color::Color::Lab { .. })); @@ -584,6 +616,14 @@ impl Exporter<'_> { patches.push(krilla::paint::MeshPatch { points, colors, opacities: [NormalizedF32::ONE; 4] }); } } + // An unfolded single patch shades its own outline. Filling that exact outline makes some + // readers antialias it twice and leave seams where patches touch. Keep the outline for + // folded geometry and for meshes with more than one patch, which can overlap themselves. + let bounds_path = match patches.as_slice() { + [patch] if unfolded_patch(patch.points) => to_path(s, &bounds.inflate(1.0, 1.0).to_path(0.1)), + _ => None, + }; + let Some(path) = bounds_path.or_else(|| to_path(s, &m.outline().to_bezpath())) else { return false }; let mesh = krilla::paint::MeshGradient { patches, transform: xf(Affine::IDENTITY), anti_alias: false }; s.set_stroke(None); s.set_fill(Some(Fill { paint: mesh.into(), opacity: NormalizedF32::ONE, rule: krilla::paint::FillRule::NonZero })); diff --git a/crates/pdf/src/tests/mesh_export.rs b/crates/pdf/src/tests/mesh_export.rs index cf8ad25e3b..29f4dfd58d 100644 --- a/crates/pdf/src/tests/mesh_export.rs +++ b/crates/pdf/src/tests/mesh_export.rs @@ -2,12 +2,16 @@ //! viewer blends each patch's corner colours smoothly, instead of the mesh being cut into small //! flat-coloured paths that band, show seams and make the file large. +use craft::pdf::syntax::content::{TypedIter, ops::TypedInstruction}; +use craft::pdf::syntax::object::{Name, Object}; use vectorcraft_color::Color; use vectorcraft_doc::live::{GradientMesh, MeshAppearance}; use vectorcraft_doc::{ColorMode, Document, Node, NodeKind}; use vectorcraft_geom::{Rect, shapes}; +use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf_with}; use vectorcraft_testkit::raster::{assert_similar, render_artboard}; +use super::import_fidelity::stream; use crate::*; /// A 200 × 200 pt document with a 2 × 2 mesh over (20, 20)–(180, 180), its nine points coloured @@ -44,6 +48,76 @@ fn kinds(d: &Document) -> (usize, usize) { (meshes, paths) } +fn import_patches(boundaries: &[[(u8, u8); 12]]) -> Document { + use std::fmt::Write as _; + let mut data = String::new(); + for boundary in boundaries { + data.push_str("00"); // Every patch supplies all its vertices. + for (x, y) in boundary { + write!(data, "{x:02X}{y:02X}").unwrap(); + } + data.push_str(&"28465A".repeat(4)); + } + data.push('>'); + let shading = stream( + "/ShadingType 6 /ColorSpace /DeviceRGB /BitsPerCoordinate 8 /BitsPerComponent 8 /BitsPerFlag 8 \ + /Decode [0 255 0 255 0 1 0 1 0 1] /Filter /ASCIIHexDecode", + &data, + ); + let page = PdfPage { + resources: format!("/Shading << /Mesh {} 0 R >>", first_extra(1)), + ..PdfPage::new(100.0, 100.0, "q 0.8 0 0 0.8 10 10 cm /Mesh sh Q") + }; + let imported = import(&pdf_with(&[page], &[&shading], None)).unwrap(); + assert_eq!(kinds(&imported).0, boundaries.len()); + imported +} + +fn has_curved_outline(bytes: &[u8]) -> bool { + let output = crate::pages::open(bytes, None).unwrap(); + let pages = output.pages(); + let has_curve = |content: &[u8]| { + let mut ops = TypedIter::new(content); + while let Some(op) = ops.next() { + if matches!(op, TypedInstruction::CubicTo(_) | TypedInstruction::CubicStartTo(_) | TypedInstruction::CubicEndTo(_)) { + return true; + } + } + false + }; + if has_curve(pages.iter().next().unwrap().page_stream().unwrap()) { + return true; + } + output.objects().into_iter().any(|object| match object { + Object::Stream(form) if form.dict().get::>(b"Subtype").is_some_and(|name| name.as_ref() == b"Form") => { + has_curve(&form.decoded().unwrap()) + } + _ => false, + }) +} + +#[test] +fn joined_opaque_pdf_meshes_keep_their_shading_edges_on_export() { + // The same cubic, in opposite directions, is the two patches' inner edge. + let imported = import_patches(&[ + [(10, 95), (10, 65), (10, 35), (10, 5), (25, 5), (40, 5), (55, 5), (61, 30), (41, 70), (45, 95), (35, 95), (22, 95)], + [(45, 95), (41, 70), (61, 30), (55, 5), (68, 5), (82, 5), (90, 5), (90, 35), (90, 65), (90, 95), (75, 95), (60, 95)], + ]); + let bytes = export(&imported, &PdfOptions::default()).unwrap(); + assert!(!has_curved_outline(&bytes), "the writer must leave the shared curved edge to the shading itself"); + let reimported = import(&bytes).unwrap(); + assert_eq!(kinds(&reimported).0, 2, "both patches still export as vector shadings"); + assert_similar(&render_artboard(&imported), &render_artboard(&reimported), 6.0, 0.01); +} + +#[test] +fn folded_pdf_mesh_still_uses_its_outline() { + let imported = + import_patches(&[[(10, 95), (92, 65), (93, 35), (10, 5), (25, 5), (40, 5), (90, 5), (4, 30), (3, 70), (90, 95), (65, 95), (42, 95)]]); + let bytes = export(&imported, &PdfOptions::default()).unwrap(); + assert!(has_curved_outline(&bytes), "a rectangle would expose folded paint outside the intended outline"); +} + #[test] fn a_gradient_mesh_is_written_as_a_smooth_patch_shading() { let d = doc(rgb, 1.0);