mirror of
https://github.com/storytold/cadcraft.git
synced 2026-12-02 20:22:15 -05:00
PDF plots write a filled primitive as the outline of its triangles, not one subpath per triangle (#3459) (#3614)
A solid hatch, wide polyline, wipeout mask or filled glyph reached the PDF writer as a triangle list, and each triangle became its own closed subpath. The writer now cancels edges that two triangles share in opposite directions and chains what is left into closed loops, written as one nonzero fill. The winding number at every point depends only on the net directed edges, so the filled area is the same for overlapping, mixed- orientation, zero-area and T-junction triangles; vertices are matched by the exact bits of the f32 coordinates written. O(n log n) time, O(n) memory, no recursion. For a 400-vertex solid hatch with a square island the page content stream goes from 30,086 to 9,922 bytes (457 to 3 subpaths) and the compressed file from 5,874 to 4,223 bytes. Co-authored-by: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
fe6530dec5
commit
02461788e6
4 files changed
+299
-4
No files matched your search
@@ -36,6 +36,7 @@ use kr::text::{GlyphId, KrillaGlyph};
|
||||
use crate::{IoError, Result};
|
||||
|
||||
mod fonts;
|
||||
mod outline;
|
||||
|
||||
/// PDF points per millimetre.
|
||||
const PT_PER_MM: f64 = 72.0 / 25.4;
|
||||
@@ -867,7 +868,7 @@ fn krilla_failure(e: KrillaError) -> Failure {
|
||||
/// transparent primitive is stroked on its own (one path is painted once), so where
|
||||
/// primitives overlap they build up, as in PNG plots and on screen. Block contents and
|
||||
/// viewport contents share their reference's handle, so this goes by primitive, not by object.
|
||||
/// Each filled primitive is one path of its triangles.
|
||||
/// Each filled primitive is one path: the outline of its triangles.
|
||||
///
|
||||
/// Primitives that stand for a glyph in an embeddable font (see [`fonts::Fonts`]) are written
|
||||
/// as text instead: the glyph at font size 1 under its glyph matrix (the matrix axes are one
|
||||
@@ -983,14 +984,16 @@ fn stroke_run(s: &mut Surface<'_>, batch: &mut Option<(StrokeStyle, PathBuilder)
|
||||
}
|
||||
}
|
||||
|
||||
/// Fill a set of triangles, clipped to the plot area.
|
||||
/// Fill a set of triangles, clipped to the plot area, as the loops of their outline (see
|
||||
/// [`outline`]), which fill the same as the triangles with far less path data.
|
||||
fn fill_tris(s: &mut Surface<'_>, p: &SheetPage, raw: &[Vec2], rgb: Rgb, t: u8) {
|
||||
let mapped: Vec<Vec2> = raw.iter().map(|q| p.map.pt(*q)).collect();
|
||||
// With a vertex out of range, keep the parts inside the plot area.
|
||||
let tris = if mapped.iter().all(|q| coord(*q).is_some()) { mapped } else { clip::clip_triangles(&mapped, &p.clip_pt) };
|
||||
let tris: Vec<[outline::Pt; 3]> = tris.as_chunks::<3>().0.iter().filter_map(|[a, b, c]| Some([coord(*a)?, coord(*b)?, coord(*c)?])).collect();
|
||||
let rings = outline::loops(&tris).unwrap_or_else(|| tris.iter().map(|t| t.to_vec()).collect());
|
||||
let mut pb = PathBuilder::new();
|
||||
for tri in tris.as_chunks::<3>().0 {
|
||||
let Some(v) = tri.iter().map(|q| coord(*q)).collect::<Option<Vec<_>>>() else { continue };
|
||||
for v in &rings {
|
||||
for (j, (x, y)) in v.iter().enumerate() {
|
||||
if j == 0 {
|
||||
pb.move_to(*x, *y);
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
//! The outline of a set of filled triangles: closed loops that fill, under the nonzero rule,
|
||||
//! exactly what the triangles fill as one path of one subpath each.
|
||||
//!
|
||||
//! A filled path's nonzero winding number at a point is the sum, over its directed edges, of
|
||||
//! the crossings of a ray from the point. So it depends only on how many times each directed
|
||||
//! edge occurs, less the times it occurs reversed. An edge shared by two neighbouring
|
||||
//! triangles in opposite directions cancels, and so does a zero-length edge. What is left
|
||||
//! enters each vertex as often as it leaves it (each triangle does, and a cancelled pair takes
|
||||
//! one entry and one exit from both its ends), so it splits into closed loops, and any such
|
||||
//! split winds the same as the triangles everywhere off the edges. This holds for overlapping
|
||||
//! triangles, mixed orientations, zero-area triangles and T-junctions alike: edges that do not
|
||||
//! pair stay in the outline, which is then larger but still fills the same.
|
||||
//!
|
||||
//! Vertices are matched by the exact bits of the `f32` coordinates that are written, never by a
|
||||
//! tolerance, so two distinct written points are never merged.
|
||||
|
||||
/// A written vertex.
|
||||
pub(super) type Pt = (f32, f32);
|
||||
|
||||
/// The bits of a vertex, the key it is matched by.
|
||||
fn key(p: Pt) -> u64 {
|
||||
(u64::from(p.0.to_bits()) << 32) | u64::from(p.1.to_bits())
|
||||
}
|
||||
|
||||
/// The loops (each closed back to its first vertex) whose nonzero fill is that of `tris`, or
|
||||
/// `None` when they cannot be traced (which the reasoning above rules out; the caller then
|
||||
/// writes the triangles). Time is `O(n log n)` and memory `O(n)` in the triangle count.
|
||||
pub(super) fn loops(tris: &[[Pt; 3]]) -> Option<Vec<Vec<Pt>>> {
|
||||
let mut keys: Vec<u64> = tris.iter().flatten().map(|p| key(*p)).collect();
|
||||
keys.sort_unstable();
|
||||
keys.dedup();
|
||||
let pts: Vec<Pt> = keys.iter().map(|k| (f32::from_bits((k >> 32) as u32), f32::from_bits(*k as u32))).collect();
|
||||
let id = |p: &Pt| keys.binary_search(&key(*p)).ok().and_then(|i| u32::try_from(i).ok());
|
||||
// Each edge as (lower id, higher id, +1 when it runs from the lower to the higher).
|
||||
let mut undirected: Vec<(u32, u32, i8)> = Vec::with_capacity(tris.len().saturating_mul(3));
|
||||
for t in tris {
|
||||
let v = [id(&t[0])?, id(&t[1])?, id(&t[2])?];
|
||||
for (a, b) in [(v[0], v[1]), (v[1], v[2]), (v[2], v[0])] {
|
||||
match a.cmp(&b) {
|
||||
std::cmp::Ordering::Less => undirected.push((a, b, 1)),
|
||||
std::cmp::Ordering::Greater => undirected.push((b, a, -1)),
|
||||
std::cmp::Ordering::Equal => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
undirected.sort_unstable_by_key(|e| (e.0, e.1));
|
||||
// What is left of each edge once opposite directions cancel, by start vertex.
|
||||
let mut edges: Vec<(u32, u32)> = Vec::new();
|
||||
for run in undirected.chunk_by(|x, y| (x.0, x.1) == (y.0, y.1)) {
|
||||
let Some(&(a, b, _)) = run.first() else { continue };
|
||||
let net: i64 = run.iter().map(|e| i64::from(e.2)).sum();
|
||||
let e = if net > 0 { (a, b) } else { (b, a) };
|
||||
edges.extend(std::iter::repeat_n(e, usize::try_from(net.unsigned_abs()).ok()?));
|
||||
}
|
||||
drop(undirected);
|
||||
edges.sort_unstable();
|
||||
// `next[v]..end[v]`: the unused edges leaving vertex `v`.
|
||||
let mut end = vec![0usize; pts.len()];
|
||||
for e in &edges {
|
||||
*end.get_mut(e.0 as usize)? += 1;
|
||||
}
|
||||
let mut next = vec![0usize; pts.len()];
|
||||
let mut at = 0usize;
|
||||
for (n, e) in next.iter_mut().zip(end.iter_mut()) {
|
||||
*n = at;
|
||||
at += *e;
|
||||
*e = at;
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for start in 0..pts.len() {
|
||||
while next.get(start)? < end.get(start)? {
|
||||
// Follow unused edges from `start` until one leads back to it. Each step uses an
|
||||
// edge, so this ends; balance means only `start` can be left with no edge out.
|
||||
let mut ring = vec![*pts.get(start)?];
|
||||
let mut cur = start;
|
||||
loop {
|
||||
let i = *next.get(cur)?;
|
||||
if i >= *end.get(cur)? {
|
||||
return None;
|
||||
}
|
||||
*next.get_mut(cur)? += 1;
|
||||
let to = edges.get(i)?.1 as usize;
|
||||
if to == start {
|
||||
break;
|
||||
}
|
||||
ring.push(*pts.get(to)?);
|
||||
cur = to;
|
||||
}
|
||||
out.push(ring);
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Fill paths of one subpath per closed ring with the nonzero rule, as a PDF viewer would.
|
||||
/// Aliased, so a pixel is filled exactly when the winding at its sample point is nonzero;
|
||||
/// with anti-aliasing, coverage sums along the triangles' inner edges round differently by
|
||||
/// a level in a few pixels.
|
||||
fn raster(rings: &[Vec<Pt>]) -> Vec<u8> {
|
||||
let mut pb = tiny_skia::PathBuilder::new();
|
||||
for r in rings {
|
||||
for (j, (x, y)) in r.iter().enumerate() {
|
||||
if j == 0 {
|
||||
pb.move_to(*x, *y);
|
||||
} else {
|
||||
pb.line_to(*x, *y);
|
||||
}
|
||||
}
|
||||
pb.close();
|
||||
}
|
||||
let mut pm = tiny_skia::Pixmap::new(64, 64).unwrap();
|
||||
if let Some(path) = pb.finish() {
|
||||
let mut paint = tiny_skia::Paint::default();
|
||||
paint.set_color_rgba8(0, 0, 0, 255);
|
||||
paint.anti_alias = false;
|
||||
pm.fill_path(&path, &paint, tiny_skia::FillRule::Winding, tiny_skia::Transform::identity(), None);
|
||||
}
|
||||
pm.data().to_vec()
|
||||
}
|
||||
|
||||
fn soup(tris: &[[Pt; 3]]) -> Vec<Vec<Pt>> {
|
||||
tris.iter().map(|t| t.to_vec()).collect()
|
||||
}
|
||||
|
||||
fn vertices(rings: &[Vec<Pt>]) -> usize {
|
||||
rings.iter().map(Vec::len).sum()
|
||||
}
|
||||
|
||||
/// A fan of a regular polygon around its centre, `n` triangles.
|
||||
fn fan(c: Pt, r: f32, n: usize, ccw: bool) -> Vec<[Pt; 3]> {
|
||||
let p = |i: usize| {
|
||||
let a = std::f32::consts::TAU * (i % n) as f32 / n as f32;
|
||||
(c.0 + r * a.cos(), c.1 + r * a.sin())
|
||||
};
|
||||
(0..n).map(|i| if ccw { [c, p(i), p(i + 1)] } else { [c, p(i + 1), p(i)] }).collect()
|
||||
}
|
||||
|
||||
/// The outline fills the same pixels as the triangles, and is no larger.
|
||||
fn same_fill(tris: &[[Pt; 3]]) -> Vec<Vec<Pt>> {
|
||||
let rings = loops(tris).expect("traced");
|
||||
let (a, b) = (raster(&rings), raster(&soup(tris)));
|
||||
let differ = a.iter().zip(&b).filter(|(x, y)| x != y).count();
|
||||
assert_eq!(differ, 0, "{rings:?}");
|
||||
assert!(vertices(&rings) <= 3 * tris.len());
|
||||
rings
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fan_becomes_its_rim() {
|
||||
let tris = fan((32.0, 32.0), 25.0, 40, true);
|
||||
let rings = same_fill(&tris);
|
||||
assert_eq!(rings.len(), 1);
|
||||
assert!(vertices(&rings) < tris.len() + 1, "{} vertices for {} triangles", vertices(&rings), tris.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_ring_with_a_hole_keeps_the_hole() {
|
||||
// A square annulus: outer 8..56, hole 24..40, as eight triangles.
|
||||
let (o0, o1, i0, i1) = (8.0, 56.0, 24.0, 40.0);
|
||||
let q = |a: Pt, b: Pt, c: Pt, d: Pt| [[a, b, c], [a, c, d]];
|
||||
let mut tris = Vec::new();
|
||||
tris.extend(q((o0, o0), (o1, o0), (i1, i0), (i0, i0)));
|
||||
tris.extend(q((o1, o0), (o1, o1), (i1, i1), (i1, i0)));
|
||||
tris.extend(q((o1, o1), (o0, o1), (i0, i1), (i1, i1)));
|
||||
tris.extend(q((o0, o1), (o0, o0), (i0, i0), (i0, i1)));
|
||||
let rings = same_fill(&tris);
|
||||
assert_eq!(rings.len(), 2, "{rings:?}");
|
||||
let centre = raster(&rings)[(32 * 64 + 32) * 4 + 3];
|
||||
assert_eq!(centre, 0, "the hole stays empty");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixed_orientations_overlaps_degenerates_and_t_junctions_fill_the_same() {
|
||||
let mut tris = fan((20.0, 20.0), 15.0, 12, true);
|
||||
// Overlapping, the other way round: where they overlap the windings cancel.
|
||||
tris.extend(fan((34.0, 30.0), 15.0, 9, false));
|
||||
// The same triangle twice.
|
||||
tris.push([(40.0, 40.0), (60.0, 42.0), (50.0, 60.0)]);
|
||||
tris.push([(40.0, 40.0), (60.0, 42.0), (50.0, 60.0)]);
|
||||
// A T-junction: one big triangle beside two that split its edge.
|
||||
tris.push([(2.0, 50.0), (2.0, 62.0), (14.0, 56.0)]);
|
||||
tris.push([(2.0, 50.0), (-4.0, 53.0), (2.0, 56.0)]);
|
||||
tris.push([(2.0, 56.0), (-4.0, 59.0), (2.0, 62.0)]);
|
||||
// Zero-area triangles: collinear, and with a repeated vertex.
|
||||
tris.push([(5.0, 5.0), (10.0, 10.0), (15.0, 15.0)]);
|
||||
tris.push([(30.0, 5.0), (30.0, 5.0), (40.0, 8.0)]);
|
||||
// Vertices a rounding step apart are not merged.
|
||||
tris.push([(50.0, 10.0), (60.0, 10.0), (55.0, 20.0)]);
|
||||
tris.push([(60.0, 10.0), (50.0, 10.000_001), (55.0, 2.0)]);
|
||||
same_fill(&tris);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_in_nothing_out() {
|
||||
assert_eq!(loops(&[]), Some(Vec::new()));
|
||||
assert_eq!(loops(&[[(1.0, 1.0); 3]]), Some(Vec::new()));
|
||||
}
|
||||
}
|
||||
@@ -77,6 +77,7 @@ mod ole2frame_roundtrip;
|
||||
mod ole_frame;
|
||||
mod paperview_marker;
|
||||
mod passthrough_image_roundtrip;
|
||||
mod pdf_fill_outline;
|
||||
mod pdf_followups;
|
||||
mod pdf_import;
|
||||
mod pdf_layers;
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
//! A solid fill is plotted to PDF as the outline of its triangles (#3459): far less path data,
|
||||
//! the same filled area, islands still empty.
|
||||
|
||||
use cadcraft_doc::{Common, Drawing, EntityKind, Hatch, HatchLoop, Space};
|
||||
use cadcraft_geom::{PolyVertex, Vec2};
|
||||
use cadcraft_io::plotter;
|
||||
use serde_json::json;
|
||||
|
||||
/// Vertices of the outer boundary.
|
||||
const RIM: usize = 400;
|
||||
/// Radius of the outer boundary.
|
||||
const R: f64 = 100.0;
|
||||
/// Half the width of the square island.
|
||||
const HALF: f64 = 20.0;
|
||||
|
||||
fn ring(points: impl Iterator<Item = (f64, f64)>, outer: bool) -> HatchLoop {
|
||||
HatchLoop { vertices: points.map(|(x, y)| PolyVertex::new(Vec2::new(x, y))).collect(), outer, boundary_flags: None, sources: Vec::new() }
|
||||
}
|
||||
|
||||
/// A solid hatch: a many-sided outer loop around a square island.
|
||||
fn drawing() -> Drawing {
|
||||
let rim = (0..RIM).map(|i| {
|
||||
let a = std::f64::consts::TAU * i as f64 / RIM as f64;
|
||||
(R * a.cos(), R * a.sin())
|
||||
});
|
||||
let island = [(-HALF, -HALF), (HALF, -HALF), (HALF, HALF), (-HALF, HALF)].into_iter();
|
||||
let hatch = Hatch {
|
||||
pattern: "SOLID".into(),
|
||||
solid: true,
|
||||
loops: vec![ring(rim, true), ring(island, false)],
|
||||
scale: 1.0,
|
||||
angle: 0.0,
|
||||
associative: false,
|
||||
style: 0,
|
||||
elevation: 0.0,
|
||||
gradient: None,
|
||||
origin: Vec2::ZERO,
|
||||
background: None,
|
||||
pattern_lines: Vec::new(),
|
||||
};
|
||||
let mut d = Drawing::new_metric();
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Hatch(hatch)).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_solid_hatch_plots_as_its_outline_with_the_island_empty() {
|
||||
let bytes = plotter::plot(&drawing(), &Space::Model, &json!({"paper": "A4", "compress": false})).unwrap();
|
||||
let doc = crate::pdf_read::read(&bytes);
|
||||
let drawn = crate::pdf_read::drawn(doc.content());
|
||||
let fills = drawn.iter().filter(|o| o.op == "f").count();
|
||||
assert_eq!(fills, 1, "one fill for the hatch");
|
||||
let path: Vec<&crate::pdf_read::Op> = drawn.iter().filter(|o| matches!(o.op.as_str(), "m" | "l")).collect();
|
||||
// The triangles of a fill around an island number at least its boundary vertices; one
|
||||
// subpath per triangle would give that many `m` and twice as many `l`.
|
||||
let subpaths = path.iter().filter(|o| o.op == "m").count();
|
||||
assert!(subpaths < RIM / 10, "{subpaths} subpaths for {RIM} boundary vertices");
|
||||
assert!(path.len() < 2 * RIM, "{} path vertices for {RIM} boundary vertices", path.len());
|
||||
|
||||
// Fill the path as a viewer does and compare with the shape.
|
||||
let mut pb = tiny_skia::PathBuilder::new();
|
||||
let (mut lo, mut hi) = ((f32::MAX, f32::MAX), (f32::MIN, f32::MIN));
|
||||
for o in &path {
|
||||
let (x, y) = (o.nums[0] as f32, o.nums[1] as f32);
|
||||
(lo, hi) = ((lo.0.min(x), lo.1.min(y)), (hi.0.max(x), hi.1.max(y)));
|
||||
if o.op == "m" {
|
||||
pb.close();
|
||||
pb.move_to(x, y);
|
||||
} else {
|
||||
pb.line_to(x, y);
|
||||
}
|
||||
}
|
||||
pb.close();
|
||||
let size = 400u32;
|
||||
let k = size as f32 / (hi.0 - lo.0).max(hi.1 - lo.1);
|
||||
let mut pm = tiny_skia::Pixmap::new(size, size).unwrap();
|
||||
let mut paint = tiny_skia::Paint::default();
|
||||
paint.set_color_rgba8(0, 0, 0, 255);
|
||||
let to_px = tiny_skia::Transform::from_row(k, 0.0, 0.0, k, -lo.0 * k, -lo.1 * k);
|
||||
pm.fill_path(&pb.finish().unwrap(), &paint, tiny_skia::FillRule::Winding, to_px, None);
|
||||
let alpha = |fx: f64, fy: f64| pm.pixel((fx * f64::from(size)) as u32, (fy * f64::from(size)) as u32).unwrap().alpha();
|
||||
assert_eq!(alpha(0.5, 0.5), 0, "the island is empty");
|
||||
assert_eq!(alpha(0.5 + 0.3, 0.5), 255, "the ring between island and rim is filled");
|
||||
assert_eq!(alpha(0.03, 0.03), 0, "outside the rim is empty");
|
||||
// The filled share of the bounding square matches the ring's.
|
||||
let covered: f64 = pm.pixels().iter().map(|p| f64::from(p.alpha()) / 255.0).sum::<f64>() / f64::from(size * size);
|
||||
let want = (std::f64::consts::PI * R * R - 4.0 * HALF * HALF) / (4.0 * R * R);
|
||||
assert!((covered - want).abs() < 0.01, "covered {covered}, the ring covers {want}");
|
||||
}
|
||||
Reference in new issue
Block a user