Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / pdf / src / main / rust / src / images_part6.rs

images_part6.rs270 lines · 14.0 KiBRaw
1/// Type 1 (function-based) shading: sample the 2-D `/Domain` through the
2/// shading `/Function` and emit the result as an image, placed via `/Matrix`.
3fn rasterize_shading_function_based(doc: &Document, dict: &lopdf::Dictionary, base_ctm: &Mat, cs_resources: &HashMap<Vec<u8>, ObjectId>, size: u32) -> Option<(Mat, u32, u32, Vec<u8>)> {
4 if size == 0 || size > 1024 { return None; }
5 let domain: Vec<f64> = dict.get(b"Domain").ok().and_then(|o| deref(doc, o)).and_then(|o| o.as_array().ok())
6 .map(|a| a.iter().filter_map(|o| deref(doc, o).and_then(num)).collect()).unwrap_or_else(|| vec![0.0, 1.0, 0.0, 1.0]);
7 if domain.len() < 4 { return None; }
8 let (dx0, dx1, dy0, dy1) = (domain[0], domain[1], domain[2], domain[3]);
9 if (dx1 - dx0).abs() < 1e-9 || (dy1 - dy0).abs() < 1e-9 { return None; }
10
11 let matrix: Mat = dict.get(b"Matrix").ok().and_then(|o| deref(doc, o)).and_then(|o| o.as_array().ok())
12 .and_then(|a| {
13 let v: Vec<f64> = a.iter().filter_map(|o| deref(doc, o).and_then(num)).collect();
14 if v.len() == 6 { Some([v[0], v[1], v[2], v[3], v[4], v[5]]) } else { None }
15 }).unwrap_or(IDENTITY);
16
17 let func = dict.get(b"Function").ok().and_then(|o| PdfFunction::parse(doc, o))?;
18 let cs = dict.get(b"ColorSpace").ok().and_then(|o| parse_cs_kind(doc, Some(o), cs_resources)).unwrap_or(CsKind::DeviceRGB);
19
20 // §8.7.4.3 Table 78: /BBox is a common shading entry, not a type 2/3 one, and is
21 // "applied as a temporary clipping boundary when the shading is painted". Types 2
22 // and 3 use it as their raster's footprint and the mesh path intersects it with the
23 // /Decode extent, leaving type 1 as the only shading that ignored it — a /BBox
24 // smaller than the /Domain painted outside the box.
25 //
26 // It cannot be the footprint here, because a type 1 raster IS the /Domain rect. Its
27 // coordinates are in the shading's TARGET space, i.e. after /Matrix, so the test has
28 // to happen per pixel with /Matrix applied and cannot be folded into the raster's
29 // extent.
30 //
31 // §7.9.5 permits "any two diagonally opposite corners", so the corners are normalised
32 // BEFORE any width test: `read_rect` hands back the four numbers raw and only rejects
33 // non-finite ones, so an unnormalised [100 100 0 0] would otherwise read as degenerate
34 // and have its perfectly legitimate 100x100 clip discarded.
35 let clip_bbox = dict
36 .get(b"BBox")
37 .ok()
38 .and_then(|o| read_rect(doc, o))
39 .map(|b| [b[0].min(b[2]), b[1].min(b[3]), b[0].max(b[2]), b[1].max(b[3])]);
40 // A zero-area /BBox clips EVERYTHING away, and this returns None rather than ignoring
41 // it. That reverses my first instinct — that a degenerate entry silently deleting the
42 // graphic is the invisible-hole failure — and r5-color's counter-argument is right on
43 // all three counts:
44 //
45 // - It is not a special case, it is the endpoint of one already handled. A /BBox that
46 // simply does not intersect the domain (say [500 500 600 600] over a domain at the
47 // origin) paints nothing, and must. Ignoring only the exactly-zero case makes the
48 // behaviour DISCONTINUOUS in the data: a 1e-9-wide box paints nothing while a
49 // 0-wide box paints the whole domain. Leniency cannot be made consistent here;
50 // only honouring the clip can.
51 // - shading.rs:151-158 already returns None for a degenerate /BBox on types 4-7, so
52 // ignoring it here would split one Table 78 entry into two answers by ShadingType.
53 // That is the same shape of defect as the CCITT stride disagreement found earlier
54 // this round, and just as hard to trace from the rendering.
55 // - The non-finite precedent does not transfer. Falling back to a default for a
56 // non-finite /Matrix is right because the value has no meaning. A zero-area
57 // rectangle is well-formed data with defined clipping semantics; "I understand
58 // this and it says paint nothing" is not the same as "I cannot parse this".
59 //
60 // The counterweight points the same way once stated precisely: ignoring a clip makes
61 // content APPEAR that the file said to hide, which is the direction the removed
62 // transparency approximation failed in, not the opposite one.
63 //
64 // Same 1e-9 threshold as shading.rs, so the two paths agree at the boundary too.
65 if let Some(b) = clip_bbox {
66 if b[2] - b[0] < 1e-9 || b[3] - b[1] < 1e-9 {
67 image_warn!("function-based shading /BBox has zero area - nothing to paint");
68 return None;
69 }
70 }
71
72 // Image [0,1]^2 -> domain rect -> Matrix -> base CTM.
73 let unit_to_domain: Mat = [dx1 - dx0, 0.0, 0.0, dy1 - dy0, dx0, dy0];
74 let ctm = mat_mul(&mat_mul(&unit_to_domain, &matrix), base_ctm);
75 if !mat_is_finite(&ctm) {
76 image_warn!("function-based shading placement matrix is non-finite - shading dropped");
77 return None;
78 }
79
80 // Size each axis from its DEVICE-space extent instead of forcing a square. Types 2/3
81 // and the mesh types were fixed in round 1 but this one was missed: a /Domain of
82 // [0 600 0 5] still allocated size*size, up to ~100x the memory the shading covers
83 // and tripled across `prims`, the wire buffer and the Kotlin Bitmap. `ctm` maps the
84 // unit square, so a non-square raster is geometrically identical.
85 let (w, h) = {
86 let long = size.max(1);
87 let dev_x = (ctm[0] * ctm[0] + ctm[1] * ctm[1]).sqrt();
88 let dev_y = (ctm[2] * ctm[2] + ctm[3] * ctm[3]).sqrt();
89 if !dev_x.is_finite() || !dev_y.is_finite() || dev_x <= 0.0 || dev_y <= 0.0 {
90 (long, long)
91 } else if dev_x >= dev_y {
92 (long, ((long as f64 * dev_y / dev_x).round() as u32).clamp(1, long))
93 } else {
94 (((long as f64 * dev_x / dev_y).round() as u32).clamp(1, long), long)
95 }
96 };
97 // And bound the total bytes, as the other two paths already do — see
98 // MAX_SHADING_RASTER_BYTES. Scaling both axes by sqrt preserves the aspect ratio.
99 let (w, h) = {
100 let bytes = (w as usize).saturating_mul(h as usize).saturating_mul(4);
101 if bytes > MAX_SHADING_RASTER_BYTES {
102 let scale = (MAX_SHADING_RASTER_BYTES as f64 / bytes as f64).sqrt();
103 (
104 ((w as f64 * scale).round() as u32).max(1),
105 ((h as f64 * scale).round() as u32).max(1),
106 )
107 } else {
108 (w, h)
109 }
110 };
111
112 let (wu, hu) = (w as usize, h as usize);
113 let mut rgba = vec![0u8; wu * hu * 4];
114 for py in 0..hu {
115 for px in 0..wu {
116 let u = (px as f64 + 0.5) / wu as f64;
117 // Row 0 is the top of the image (v=1), so walk the domain's y DOWNWARD. See
118 // the axial/radial loop for why.
119 let v = 1.0 - (py as f64 + 0.5) / hu as f64;
120 let x = dx0 + u * (dx1 - dx0);
121 let y = dy0 + v * (dy1 - dy0);
122 // /BBox is in target space, so the domain point has to go through /Matrix
123 // before the containment test.
124 if let Some(b) = clip_bbox {
125 let (tx, ty) = transform(&matrix, x, y);
126 if tx < b[0] || tx > b[2] || ty < b[1] || ty > b[3] {
127 continue;
128 }
129 }
130 let comps = func.eval(&[x, y]);
131 let idx = (py * wu + px) * 4;
132 if let Some(argb) = eval_cs_to_rgb(doc, &cs, &comps, cs_resources) {
133 rgba[idx] = ((argb >> 16) & 0xFF) as u8;
134 rgba[idx + 1] = ((argb >> 8) & 0xFF) as u8;
135 rgba[idx + 2] = (argb & 0xFF) as u8;
136 rgba[idx + 3] = 255;
137 }
138 }
139 }
140 Some((ctm, w, h, rgba))
141}
142
143
144/// Apply a per-pixel soft-mask alpha (length `w*h`) to an RGBA buffer.
145/// Rasterize ONE tiling-pattern cell for a repeating-image fill (§8.7.3.3).
146///
147/// `cell_prims` must be the pattern cell's content interpreted in PATTERN space (the
148/// pattern `/Matrix` NOT yet applied), so `bbox`, `xstep` and `ystep` share their
149/// coordinate system. `device_scale` converts pattern-space units to device pixels and
150/// sets the raster resolution.
151///
152/// Returns `(w, h, rgba)` for a cell that can be tiled periodically, or `None` when the
153/// pattern CANNOT be expressed that way — in which case the caller must fall back to the
154/// per-tile path. This function owns the two rules that make a periodic repeat correct,
155/// because both are easy to violate silently:
156///
157/// 1. The raster covers `/XStep` × `/YStep`, NOT the `/BBox`. A `BitmapShader` in REPEAT
158/// mode has a period equal to the bitmap's own dimensions, and PDF's step is
159/// independent of the bbox — so a bbox-sized cell retiles at the wrong spacing, which
160/// looks like a pattern at subtly wrong density. Where step > bbox the margin is
161/// transparent padding, which falls out of rasterizing the STEP rect anchored at the
162/// bbox origin: nothing paints there.
163/// 2. Overlapping patterns (a step SMALLER than the bbox, 8.7.3.1) are still periodic,
164/// with period `(xstep, ystep)` - that is what makes them a lattice at all. What fails
165/// is rasterizing the cell ONCE, because content from neighbouring cells spills into
166/// every period window. So the cell is drawn at every lattice offset that can reach
167/// the window, composited in increasing lattice order to honour "later tiles paint
168/// over earlier".
169///
170/// This is EXACT, not an approximation. 8.7.3.2 replicates the cell across the entire
171/// plane and the fill path does the clipping, so the lattice has no boundary; with no
172/// boundary every point's set of overlapping contributions is identical modulo the
173/// period. Refused only when the bbox/step ratio is pathological.
174pub(crate) fn rasterize_pattern_cell(
175 cell_prims: &[Prim],
176 bbox: [f64; 4],
177 xstep: f64,
178 ystep: f64,
179 device_scale: f64,
180) -> Option<(u32, u32, Vec<u8>)> {
181 let bw = (bbox[2] - bbox[0]).abs();
182 let bh = (bbox[3] - bbox[1]).abs();
183 if !xstep.is_finite() || !ystep.is_finite() || xstep <= 0.0 || ystep <= 0.0 {
184 return None;
185 }
186 // Rule 2. An overlapping pattern IS periodic with period (xstep, ystep); the cell
187 // just has to be drawn at every offset that can reach one period window. Cell
188 // `(i, 0)` paints x in [bx0 + i*xstep, bx0 + i*xstep + bw), which meets the window
189 // [bx0, bx0 + xstep) exactly when -bw/xstep < i < 1, i.e. i in -(nx_off-1)..=0.
190 let nx_off = (bw / xstep).ceil().max(1.0);
191 let ny_off = (bh / ystep).ceil().max(1.0);
192 // A bbox 8x the step in both axes is already far beyond anything real; past that the
193 // compositing cost stops being worth it and the per-tile path is the honest answer.
194 const MAX_CELL_OVERLAP_COPIES: f64 = 64.0;
195 if !nx_off.is_finite() || !ny_off.is_finite() || nx_off * ny_off > MAX_CELL_OVERLAP_COPIES {
196 image_warn!(
197 "tiling pattern bbox {:.3}x{:.3} over step {:.3}x{:.3} needs {}x{} overlapping \
198 copies per period - using the per-tile path",
199 bw, bh, xstep, ystep, nx_off, ny_off
200 );
201 return None;
202 }
203 if !device_scale.is_finite() || device_scale <= 0.0 {
204 return None;
205 }
206 let mut w = (xstep * device_scale).round().max(1.0);
207 let mut h = (ystep * device_scale).round().max(1.0);
208 // Fit the cell into its budget, preserving the aspect so the period stays square in
209 // pattern space. Downscaling a cell only softens it; the tiling stays exact because
210 // the renderer's period is the bitmap, whatever its resolution.
211 let budget = MAX_TILE_RASTER_BYTES as f64 / 4.0;
212 if w * h > budget {
213 let s = (budget / (w * h)).sqrt();
214 w = (w * s).round().max(1.0);
215 h = (h * s).round().max(1.0);
216 }
217 let (w, h) = (w as usize, h as usize);
218 // Rule 1: the STEP rect, anchored at the bbox origin. Content is placed at the bbox
219 // origin and anything between the bbox edge and the step edge is simply never
220 // painted, which IS the transparent padding.
221 let step_box = [bbox[0], bbox[1], bbox[0] + xstep, bbox[1] + ystep];
222 // The common non-overlapping case needs no copies at all.
223 if nx_off <= 1.0 && ny_off <= 1.0 {
224 return rasterize_prims_to_rgba(cell_prims, step_box, w, h)
225 .map(|rgba| (w as u32, h as u32, rgba));
226 }
227 // Overlapping: draw the cell at each reaching offset, in increasing lattice order so
228 // later tiles composite over earlier ones (8.7.3.1).
229 let (nxo, nyo) = (nx_off as i64, ny_off as i64);
230 let mut spread: Vec<Prim> = Vec::with_capacity(cell_prims.len() * (nxo * nyo) as usize);
231 for jj in 0..nyo {
232 let dy = ((jj - (nyo - 1)) as f64 * ystep) as f32;
233 for ii in 0..nxo {
234 let dx = ((ii - (nxo - 1)) as f64 * xstep) as f32;
235 spread.extend(cell_prims.iter().filter_map(|p| translated_prim(p, dx, dy)));
236 }
237 }
238 rasterize_prims_to_rgba(&spread, step_box, w, h).map(|rgba| (w as u32, h as u32, rgba))
239}
240
241/// A `Prim::Fill` or `Prim::Stroke` translated by `(dx, dy)`, or `None` for any other
242/// variant. `Prim` is deliberately not `Clone` because it owns image pixel buffers, and
243/// these two are the only variants [`rasterize_prims_to_rgba`] draws anyway.
244fn translated_prim(p: &Prim, dx: f32, dy: f32) -> Option<Prim> {
245 match p {
246 Prim::Fill { argb, even_odd, contours, blend } => Some(Prim::Fill {
247 argb: *argb,
248 even_odd: *even_odd,
249 blend: *blend,
250 contours: contours
251 .iter()
252 .map(|c| c.iter().map(|&(x, y)| (x + dx, y + dy)).collect())
253 .collect(),
254 }),
255 Prim::Stroke { argb, width, dash, dash_phase, cap, join, miter, pts, blend } => {
256 Some(Prim::Stroke {
257 argb: *argb,
258 width: *width,
259 dash: dash.clone(),
260 dash_phase: *dash_phase,
261 cap: *cap,
262 join: *join,
263 miter: *miter,
264 blend: *blend,
265 pts: pts.iter().map(|&(x, y)| (x + dx, y + dy)).collect(),
266 })
267 }
268 _ => None,
269 }
270}