Skip to main content

pdf2_render/
canvas.rs

1//! The RGBA8 canvas and the clip mask that goes with it.
2
3/// A colour with straight (non-premultiplied) components.
4#[derive(Debug, Clone, Copy, PartialEq)]
5pub struct Color {
6    /// Red, 0–1.
7    pub r: f64,
8    /// Green, 0–1.
9    pub g: f64,
10    /// Blue, 0–1.
11    pub b: f64,
12}
13
14impl Color {
15    /// Black.
16    pub const BLACK: Self = Self::rgb(0.0, 0.0, 0.0);
17    /// White.
18    pub const WHITE: Self = Self::rgb(1.0, 1.0, 1.0);
19
20    /// A colour from three components in 0–1.
21    pub const fn rgb(r: f64, g: f64, b: f64) -> Self {
22        Self { r, g, b }
23    }
24
25    /// A colour from three bytes.
26    pub fn from_bytes(r: u8, g: u8, b: u8) -> Self {
27        Self::rgb(
28            f64::from(r) / 255.0,
29            f64::from(g) / 255.0,
30            f64::from(b) / 255.0,
31        )
32    }
33
34    /// The colour as three bytes, clamped.
35    pub fn to_bytes(self) -> [u8; 3] {
36        [
37            component_to_byte(self.r),
38            component_to_byte(self.g),
39            component_to_byte(self.b),
40        ]
41    }
42
43    /// CMYK to RGB, the naive conversion PDF's `/DeviceCMYK` implies without a
44    /// colour space.
45    pub fn from_cmyk(c: f64, m: f64, y: f64, k: f64) -> Self {
46        let c = c.clamp(0.0, 1.0);
47        let m = m.clamp(0.0, 1.0);
48        let y = y.clamp(0.0, 1.0);
49        let k = k.clamp(0.0, 1.0);
50        Self::rgb(
51            (1.0 - c) * (1.0 - k),
52            (1.0 - m) * (1.0 - k),
53            (1.0 - y) * (1.0 - k),
54        )
55    }
56}
57
58fn component_to_byte(value: f64) -> u8 {
59    let scaled = (value.clamp(0.0, 1.0) * 255.0).round();
60    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
61    let byte = scaled as u8;
62    byte
63}
64
65/// An RGBA8 raster.
66#[derive(Debug, Clone, PartialEq)]
67pub struct Canvas {
68    width: u32,
69    height: u32,
70    pixels: Vec<u8>,
71}
72
73impl Canvas {
74    /// A canvas filled with `background`.
75    pub fn new(width: u32, height: u32, background: Color) -> Self {
76        let [r, g, b] = background.to_bytes();
77        let mut pixels = Vec::with_capacity((width as usize) * (height as usize) * 4);
78        for _ in 0..(width as usize) * (height as usize) {
79            pixels.extend_from_slice(&[r, g, b, 255]);
80        }
81        Self {
82            width,
83            height,
84            pixels,
85        }
86    }
87
88    /// Width in pixels.
89    pub fn width(&self) -> u32 {
90        self.width
91    }
92
93    /// Height in pixels.
94    pub fn height(&self) -> u32 {
95        self.height
96    }
97
98    /// The raw RGBA8 pixels, row-major from the top.
99    pub fn pixels(&self) -> &[u8] {
100        &self.pixels
101    }
102
103    /// The RGBA value at `(x, y)`, or `None` outside the canvas.
104    pub fn pixel(&self, x: u32, y: u32) -> Option<[u8; 4]> {
105        if x >= self.width || y >= self.height {
106            return None;
107        }
108        let index = ((y as usize) * (self.width as usize) + (x as usize)) * 4;
109        let slice = &self.pixels[index..index + 4];
110        Some([slice[0], slice[1], slice[2], slice[3]])
111    }
112
113    /// Paint one pixel with `color` at `alpha`, source-over.
114    pub fn blend(&mut self, x: u32, y: u32, color: Color, alpha: f64) {
115        if x >= self.width || y >= self.height || alpha <= 0.0 {
116            return;
117        }
118        let alpha = alpha.clamp(0.0, 1.0);
119        let [r, g, b] = color.to_bytes();
120        let index = ((y as usize) * (self.width as usize) + (x as usize)) * 4;
121        let target = &mut self.pixels[index..index + 4];
122        let mix = |source: u8, destination: u8| -> u8 {
123            let source = f64::from(source);
124            let destination = f64::from(destination);
125            #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
126            let value = (source * alpha + destination * (1.0 - alpha)).round() as u8;
127            value
128        };
129        target[0] = mix(r, target[0]);
130        target[1] = mix(g, target[1]);
131        target[2] = mix(b, target[2]);
132        target[3] = 255;
133    }
134}
135
136/// A per-pixel inclusion mask produced by clipping.
137///
138/// `None` means "no clip": every pixel is inside. A `Some(mask)` is row-major,
139/// one bool per pixel, and painting is restricted to the set entries.
140#[derive(Debug, Clone, PartialEq)]
141pub struct ClipMask {
142    width: u32,
143    height: u32,
144    inside: Vec<bool>,
145}
146
147impl ClipMask {
148    /// A mask that contains every pixel of a `width × height` canvas.
149    pub fn all(width: u32, height: u32) -> Self {
150        Self {
151            width,
152            height,
153            inside: vec![true; (width as usize) * (height as usize)],
154        }
155    }
156
157    /// An empty mask: no pixel is inside.
158    pub fn none(width: u32, height: u32) -> Self {
159        Self {
160            width,
161            height,
162            inside: vec![false; (width as usize) * (height as usize)],
163        }
164    }
165
166    /// Whether `(x, y)` is inside the mask.
167    pub fn contains(&self, x: u32, y: u32) -> bool {
168        if x >= self.width || y >= self.height {
169            return false;
170        }
171        self.inside[(y as usize) * (self.width as usize) + (x as usize)]
172    }
173
174    /// Intersect this mask with a new coverage mask of the same size.
175    pub fn intersect(&mut self, other: &Self) {
176        if other.width != self.width || other.height != self.height {
177            return;
178        }
179        for (inside, other) in self.inside.iter_mut().zip(&other.inside) {
180            *inside = *inside && *other;
181        }
182    }
183
184    /// Set one pixel.
185    pub fn set(&mut self, x: u32, y: u32, inside: bool) {
186        if x < self.width && y < self.height {
187            self.inside[(y as usize) * (self.width as usize) + (x as usize)] = inside;
188        }
189    }
190
191    /// How many pixels are inside, for tests.
192    pub fn count(&self) -> usize {
193        self.inside.iter().filter(|inside| **inside).count()
194    }
195}
196
197#[cfg(test)]
198mod tests {
199    use super::{Canvas, ClipMask, Color};
200
201    #[test]
202    fn a_new_canvas_is_uniformly_filled() {
203        let canvas = Canvas::new(3, 2, Color::WHITE);
204        assert_eq!(canvas.width(), 3);
205        assert_eq!(canvas.height(), 2);
206        assert_eq!(canvas.pixels().len(), 3 * 2 * 4);
207        for y in 0..2 {
208            for x in 0..3 {
209                assert_eq!(canvas.pixel(x, y), Some([255, 255, 255, 255]));
210            }
211        }
212        assert_eq!(canvas.pixel(3, 0), None);
213    }
214
215    #[test]
216    fn blending_mixes_towards_the_source() {
217        let mut canvas = Canvas::new(1, 1, Color::WHITE);
218        canvas.blend(0, 0, Color::BLACK, 1.0);
219        assert_eq!(canvas.pixel(0, 0), Some([0, 0, 0, 255]));
220        let mut canvas = Canvas::new(1, 1, Color::BLACK);
221        canvas.blend(0, 0, Color::WHITE, 0.5);
222        assert_eq!(canvas.pixel(0, 0), Some([128, 128, 128, 255]));
223        canvas.blend(0, 0, Color::WHITE, 0.0);
224        assert_eq!(canvas.pixel(0, 0), Some([128, 128, 128, 255]));
225    }
226
227    #[test]
228    fn cmyk_conversion_is_the_naive_one() {
229        let red = Color::from_cmyk(0.0, 1.0, 1.0, 0.0);
230        assert_eq!(red.to_bytes(), [255, 0, 0]);
231        assert_eq!(Color::from_cmyk(0.0, 0.0, 0.0, 1.0).to_bytes(), [0, 0, 0]);
232    }
233
234    #[test]
235    fn clip_masks_intersect() {
236        let mut mask = ClipMask::all(4, 2);
237        assert_eq!(mask.count(), 8);
238        mask.set(1, 1, false);
239        assert!(!mask.contains(1, 1));
240        let mut other = ClipMask::all(4, 2);
241        other.set(0, 0, false);
242        mask.intersect(&other);
243        assert!(!mask.contains(0, 0));
244        assert!(mask.contains(2, 0));
245        assert_eq!(mask.count(), 6);
246        assert!(!mask.contains(4, 0));
247    }
248}