This commit is contained in:
bflatastic
2026-11-19 01:12:29 +07:00
3 changed files with 255 additions and 22 deletions
+36 -22
View File
@@ -1,4 +1,4 @@
use super::paint::is_mesh;
use super::paint::{is_mesh, polygon, shading_extent};
use super::state::{GState, Space};
use super::{
Affine, Color, FillRule, Interp, Key, LineCap, LineJoin, MAX_DASH_ENTRIES, MAX_DASHES, MAX_GSAVE, MAX_PATH, Obj, Op, Paint, Point, PsError, Rc,
@@ -519,29 +519,43 @@ impl Interp<'_> {
}
self.stroke_path(bp)?;
}
ShFill => {
let d = self.pop_dict()?;
if self.g.null {
return Ok(());
}
if is_mesh(&d) {
let m = self.xf();
return self.mesh_fill(&d, m);
}
let m = self.xf();
if let Some(g) = self.gradient(&d, m)? {
let area = self.clip_bounds()?;
let paint = Paint::Gradient(Box::new(g));
let clips = self.g.clips.clone();
self.out.fill(area.to_path(0.1), FillRule::NonZero, paint, self.g.overprint, &clips);
if let Some((_, n)) = self.out.drawn.last() {
let id = n.id;
self.out.shadings.insert(id);
}
}
}
ShFill => self.shfill()?,
_ => self.data_op(op)?,
}
Ok(())
}
/// `shfill`: shading `sh` over the clip, as a gradient mesh or a gradient fill.
fn shfill(&mut self) -> Res {
let d = self.pop_dict()?;
if self.g.null {
return Ok(());
}
if is_mesh(&d) {
let m = self.xf();
return self.mesh_fill(&d, m);
}
let m = self.xf();
if let Some(g) = self.gradient(&d, m)? {
let area = self.clip_bounds()?;
// Not extended, it paints only between its ends.
let extent = shading_extent(&d, m, area);
let path = match &extent {
Some(pts) if pts.len() < 3 => return Ok(()),
Some(pts) => polygon(pts),
None => area.to_path(0.1),
};
let paint = Paint::Gradient(Box::new(g));
let clips = self.g.clips.clone();
self.out.fill(path, FillRule::NonZero, paint, self.g.overprint, &clips);
// Only a fill of the whole clip can stand in for the clip's shape.
if extent.is_none()
&& let Some((_, n)) = self.out.drawn.last()
{
let id = n.id;
self.out.shadings.insert(id);
}
}
Ok(())
}
}
+129
View File
@@ -450,6 +450,135 @@ fn is_gradient(sh: &DictRef) -> bool {
matches!(sh.borrow().get(&Key::name("ShadingType")).and_then(Obj::as_num), Some(2.0 | 3.0))
}
/// How far (points) the sides of the polygon a radial shading's circle is cut to may lie inside it.
const RING_TOLERANCE: f64 = 0.01;
/// Most sides of that polygon.
const MAX_RING: usize = 1024;
/// The part of `area` (in the document) that axial or radial shading `sh`, mapped into the
/// document by `m`, paints, as a convex polygon; `None` when it paints all of it. Without
/// `Extend` an axial shading paints only between the lines through its ends across its axis, and
/// a radial one only over its circles (PLRM 3rd ed. §4.9.3, shading types 2 and 3: `Extend`
/// defaults to `[false false]`). A radial shading extended at one end only, or starting from a
/// circle with a radius, is not bounded here (it paints all of `area`).
pub(super) fn shading_extent(sh: &DictRef, m: Affine, area: Rect) -> Option<Vec<Point>> {
let d = sh.borrow();
let nums = |k: &str| -> Vec<f64> {
d.get(&Key::name(k)).and_then(Obj::items).map(|i| i.borrow().iter().filter_map(Obj::as_num).collect()).unwrap_or_default()
};
let extend: Vec<bool> = d
.get(&Key::name("Extend"))
.and_then(Obj::items)
.map(|i| i.borrow().iter().map(|o| matches!(o, Obj::Bool(true))).collect())
.unwrap_or_default();
let (e0, e1) = (extend.first().copied().unwrap_or(false), extend.get(1).copied().unwrap_or(false));
if (e0 && e1) || area.width() <= 0.0 || area.height() <= 0.0 || m.determinant().abs() < 1e-12 || !m.as_coeffs().iter().all(|v| v.is_finite()) {
return None;
}
let inv = m.inverse();
// `area` in the shading's own space, where its axis and circles are.
let corners: Vec<Point> =
[(area.x0, area.y0), (area.x1, area.y0), (area.x1, area.y1), (area.x0, area.y1)].map(|(x, y)| inv * Point::new(x, y)).to_vec();
let mut poly = corners.clone();
let c = nums("Coords");
let at = |i: usize| c.get(i).copied().filter(|v| v.is_finite()).unwrap_or(0.0);
match d.get(&Key::name("ShadingType")).and_then(Obj::as_num) {
Some(2.0) => {
let (p0, p1) = (Point::new(at(0), at(1)), Point::new(at(2), at(3)));
let axis = p1 - p0;
if axis.hypot2() < 1e-18 {
return None;
}
if !e0 {
poly = clip_half(&poly, |p| (p - p0).dot(axis));
}
if !e1 {
poly = clip_half(&poly, |p| (p1 - p).dot(axis));
}
}
Some(3.0) if !e0 && !e1 && at(2) <= 0.0 && at(5) > 0.0 => {
// The circles from a point to a circle cover the hull of that point and circle.
let (p0, c1, r1) = (Point::new(at(0), at(1)), Point::new(at(3), at(4)), at(5));
// Enough sides that each lies within `RING_TOLERANCE` of the circle in the document
// (the radius scaled by the most `m` stretches any direction), from 64 to `MAX_RING`.
let [a, b, c, d, ..] = m.as_coeffs();
let (sum, det) = (a * a + b * b + c * c + d * d, a * d - b * c);
let stretch = ((sum + (sum * sum - 4.0 * det * det).max(0.0).sqrt()) / 2.0).sqrt();
let r = r1 * stretch;
let sides = (std::f64::consts::PI / (1.0 - RING_TOLERANCE / r).clamp(-1.0, 1.0).acos()).ceil();
let sides = if sides.is_finite() { (sides as usize).clamp(64, MAX_RING) } else { MAX_RING };
let ring: Vec<Point> = (0..sides).map(|i| c1 + Vec2::from_angle(i as f64 * std::f64::consts::TAU / sides as f64) * r1).collect();
for edge in hull(&[ring, vec![p0]].concat()).windows(2) {
if let [a, b] = edge {
let (a, b) = (*a, *b);
poly = clip_half(&poly, |p| (b - a).cross(p - a));
}
}
}
_ => return None,
}
// Nothing cut: it paints the whole area.
if poly.len() == 4 && poly.iter().zip(&corners).all(|(a, b)| (*a - *b).hypot2() < 1e-18) {
return None;
}
Some(poly.into_iter().map(|p| m * p).collect())
}
/// Convex polygon `poly` cut to where `f` (a linear function) is zero or more.
fn clip_half(poly: &[Point], f: impl Fn(Point) -> f64) -> Vec<Point> {
let mut out = Vec::with_capacity(poly.len() + 1);
for (i, &a) in poly.iter().enumerate() {
let Some(&b) = poly.get((i + 1) % poly.len()) else { continue };
let (fa, fb) = (f(a), f(b));
if fa >= 0.0 {
out.push(a);
}
if (fa >= 0.0) != (fb >= 0.0) {
out.push(a.lerp(b, fa / (fa - fb)));
}
}
out
}
/// The convex hull of `pts`, counter-clockwise, its first point repeated at the end.
fn hull(pts: &[Point]) -> Vec<Point> {
let mut p = pts.to_vec();
p.sort_by(|a, b| a.x.total_cmp(&b.x).then(a.y.total_cmp(&b.y)));
let mut h: Vec<Point> = Vec::with_capacity(p.len() * 2);
let turn = |h: &[Point], q: Point| match h {
[.., a, b] => (*b - *a).cross(q - *a) <= 0.0,
_ => false,
};
for &q in &p {
while turn(&h, q) {
h.pop();
}
h.push(q);
}
let lower = h.len() + 1;
for &q in p.iter().rev().skip(1) {
while h.len() >= lower && turn(&h, q) {
h.pop();
}
h.push(q);
}
h
}
/// A closed path through `pts`.
pub(super) fn polygon(pts: &[Point]) -> kurbo::BezPath {
let mut bp = kurbo::BezPath::new();
for (i, p) in pts.iter().enumerate() {
if i == 0 {
bp.move_to(*p);
} else {
bp.line_to(*p);
}
}
bp.close_path();
bp
}
/// Is shading `sh` one [`Interp::mesh_fill`] paints?
pub(super) fn is_mesh(sh: &DictRef) -> bool {
matches!(sh.borrow().get(&Key::name("ShadingType")).and_then(Obj::as_num), Some(1.0 | 4.0 | 5.0 | 6.0 | 7.0))
+90
View File
@@ -1180,6 +1180,96 @@ fn filter_output_counts_against_the_memory_budget() {
assert!(err.contains("too much memory"), "{err}");
}
/// A shading painted with `shfill` and not extended paints only between its ends: an axial one
/// between the lines through them across its axis, a radial one from a point over its circles
/// (PLRM 3rd ed. §4.9.3: `Extend` is `[false false]` by default). Extended both ways it paints
/// the whole clip.
#[test]
fn shadings_not_extended_paint_only_between_their_ends() {
let shade = |kind: u8, coords: &str, extend: &str| {
let r = read(&format!(
"<< /ShadingType {kind} /ColorSpace /DeviceRGB /Coords [{coords}] {extend} \
/Function << /FunctionType 2 /Domain [0 1] /C0 [1 0 0] /C1 [0 0 1] /N 1 >> >> shfill"
));
let n = all(&r.document).into_iter().find(|n| matches!(fill(n), Some(Paint::Gradient(_)))).expect("a gradient fill");
bounds(&n)
};
// Axial, from x 10 to 90 (and its reflection in y: the document's y runs down).
let b = shade(2, "10 0 90 0", "");
assert!(near(b, Rect::new(10.0, 0.0, 90.0, 100.0)), "{b:?}");
let b = shade(2, "10 0 90 0", "/Extend [false true]");
assert!(near(b, Rect::new(10.0, 0.0, 100.0, 100.0)), "{b:?}");
let b = shade(2, "10 0 90 0", "/Extend [true true]");
assert!(near(b, Rect::new(0.0, 0.0, 100.0, 100.0)), "{b:?}");
// Radial from the centre point to a circle of radius 30.
let b = shade(3, "50 50 0 50 50 30", "");
assert!((b.width() - 60.0).abs() < 0.5 && (b.height() - 60.0).abs() < 0.5 && (b.center().x - 50.0).abs() < 0.5, "{b:?}");
// Its circle is cut to a polygon whose sides lie within 0.01 pt of it, also for a large one.
let r = read(
"<< /ShadingType 3 /ColorSpace /DeviceRGB /Coords [50 50 0 50 50 45] \
/Function << /FunctionType 2 /Domain [0 1] /C0 [1 0 0] /C1 [0 0 1] /N 1 >> >> shfill",
);
let n = all(&r.document).into_iter().find(|n| matches!(fill(n), Some(Paint::Gradient(_)))).expect("a gradient fill");
let NodeKind::Path { path, .. } = &n.kind else { panic!("{n:?}") };
let ring: Vec<Point> = path.subpaths.iter().flat_map(|s| s.anchors.iter().map(|a| a.p)).collect();
let centre = Point::new(50.0, 50.0);
for (a, b) in ring.iter().zip(ring.iter().cycle().skip(1)) {
assert!((a.distance(centre) - 45.0).abs() < 1e-6, "{a:?}");
assert!(a.midpoint(*b).distance(centre) > 45.0 - 0.01, "{a:?} {b:?}");
}
// Stretched 4 times across and squashed to a quarter down (areas unchanged), the sides still
// lie within 0.01 pt of the ellipse it becomes.
let r = read(
"50 50 translate 4 0.25 scale << /ShadingType 3 /ColorSpace /DeviceRGB /Coords [0 0 0 0 0 10] \
/Function << /FunctionType 2 /Domain [0 1] /C0 [1 0 0] /C1 [0 0 1] /N 1 >> >> shfill",
);
let n = all(&r.document).into_iter().find(|n| matches!(fill(n), Some(Paint::Gradient(_)))).expect("a gradient fill");
let NodeKind::Path { path, .. } = &n.kind else { panic!("{n:?}") };
let sides = path.subpaths.iter().map(|s| s.anchors.len()).sum::<usize>();
// A side of a regular polygon in the circle lies 1 - cos(pi / sides) of the radius inside it;
// stretched to 40 pt across, that is at most 0.01 pt.
assert!(40.0 * (1.0 - (std::f64::consts::PI / sides as f64).cos()) <= 0.01 + 1e-9, "{sides} sides");
let b = shade(3, "50 50 0 50 50 30", "/Extend [true true]");
assert!(near(b, Rect::new(0.0, 0.0, 100.0, 100.0)), "{b:?}");
// Axial along y, and extended at its start only.
let b = shade(2, "0 20 0 70", "");
assert!(near(b, Rect::new(0.0, 30.0, 100.0, 80.0)), "{b:?}");
let b = shade(2, "10 0 90 0", "/Extend [true false]");
assert!(near(b, Rect::new(0.0, 0.0, 90.0, 100.0)), "{b:?}");
// Diagonal: from (60, 60) to (90, 90) it paints where x + y lies from 120 to 180, a strip
// across the square's top-right corner whose own corners are cut off.
let r = read(
"<< /ShadingType 2 /ColorSpace /DeviceRGB /Coords [60 60 90 90] \
/Function << /FunctionType 2 /Domain [0 1] /C0 [1 0 0] /C1 [0 0 1] /N 1 >> >> shfill",
);
let n = all(&r.document).into_iter().find(|n| matches!(fill(n), Some(Paint::Gradient(_)))).expect("a gradient fill");
assert!(near(bounds(&n), Rect::new(20.0, 0.0, 100.0, 80.0)), "{:?}", bounds(&n));
let NodeKind::Path { path, .. } = &n.kind else { panic!("{n:?}") };
for a in path.subpaths.iter().flat_map(|s| s.anchors.iter()) {
// Back in PostScript's y-up space.
let s = a.p.x + (100.0 - a.p.y);
assert!((120.0 - 1e-6..=180.0 + 1e-6).contains(&s), "{a:?}");
}
// The current transformation turns the axis: rotated a quarter turn about the centre, an axis
// from -40 to 40 along x runs up the page from y 10 to 90.
let r = read(
"50 50 translate 90 rotate << /ShadingType 2 /ColorSpace /DeviceRGB /Coords [-40 0 40 0] \
/Function << /FunctionType 2 /Domain [0 1] /C0 [1 0 0] /C1 [0 0 1] /N 1 >> >> shfill",
);
let n = all(&r.document).into_iter().find(|n| matches!(fill(n), Some(Paint::Gradient(_)))).expect("a gradient fill");
assert!(near(bounds(&n), Rect::new(0.0, 10.0, 100.0, 90.0)), "{:?}", bounds(&n));
// Radial from a point off the circle's centre covers the hull of that point and the circle.
let b = shade(3, "20 50 0 60 50 30", "");
assert!((b.x0 - 20.0).abs() < 0.5 && (b.x1 - 90.0).abs() < 0.5 && (b.y0 - 20.0).abs() < 0.5 && (b.y1 - 80.0).abs() < 0.5, "{b:?}");
// Radial shadings this doesn't bound (extended at one end, or starting from a circle) still
// paint the whole area.
for (coords, extend) in [("50 50 0 50 50 30", "/Extend [true false]"), ("50 50 0 50 50 30", "/Extend [false true]"), ("50 50 10 50 50 30", "")] {
let b = shade(3, coords, extend);
assert!(near(b, Rect::new(0.0, 0.0, 100.0, 100.0)), "{coords} {extend}: {b:?}");
}
}
/// A sampled function of one input in an axial shading: interpolated linearly, its gradient has a
/// stop at every sample (exact, not sampled evenly); with `Order 3` it is a cubic through the
/// samples (PLRM 3rd ed. §3.10.1, Table 3.36), kept in its range.