lichtung-plot 0.3.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
//! Owned raster samples and checked, temporarily borrowed pixel targets.

use std::sync::Arc;

use crate::{
    errors::{ErrorContext, OperationEffect, OperationFailure, OperationPhase},
    operation,
    style::OpaqueColor,
    Error, Result,
};

use super::{ExportRegion, PngSizing};

/// Interleaved sRGB byte samples and their alpha representation.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum PixelFormat {
    /// Straight R, G, B and A.
    #[default]
    Rgba8,
    /// Opaque R, G and B. Residual transparency requires a matte.
    Rgb8,
    /// R, G, B premultiplied by the linear alpha, followed by alpha.
    PremultipliedRgba8,
    /// B, G, R premultiplied by the linear alpha, followed by alpha.
    PremultipliedBgra8,
}

impl PixelFormat {
    /// Number of interleaved bytes per pixel.
    pub const fn channels(self) -> usize {
        match self {
            Self::Rgb8 => 3,
            Self::Rgba8 | Self::PremultipliedRgba8 | Self::PremultipliedBgra8 => 4,
        }
    }

    /// Canonical name of this complete sample representation.
    pub const fn name(self) -> &'static str {
        match self {
            Self::Rgba8 => "rgba8",
            Self::Rgb8 => "rgb8",
            Self::PremultipliedRgba8 => "premultiplied_rgba8",
            Self::PremultipliedBgra8 => "premultiplied_bgra8",
        }
    }
}

impl std::str::FromStr for PixelFormat {
    type Err = Error;

    fn from_str(value: &str) -> Result<Self> {
        match value {
            "rgba8" => Ok(Self::Rgba8),
            "rgb8" => Ok(Self::Rgb8),
            "premultiplied_rgba8" => Ok(Self::PremultipliedRgba8),
            "premultiplied_bgra8" => Ok(Self::PremultipliedBgra8),
            _ => Err(Error::Data(
                format!("unknown pixel format {value:?}").into(),
            )),
        }
    }
}

/// Physical row order of a raster buffer, independently of its channels.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum RowOrder {
    /// First row is the top of the figure.
    #[default]
    TopDown,
    /// First row is the bottom of the figure.
    BottomUp,
}

impl RowOrder {
    /// Canonical name of the row order.
    pub const fn name(self) -> &'static str {
        match self {
            Self::TopDown => "top_down",
            Self::BottomUp => "bottom_up",
        }
    }
}

impl std::str::FromStr for RowOrder {
    type Err = Error;
    fn from_str(value: &str) -> Result<Self> {
        match value {
            "top_down" => Ok(Self::TopDown),
            "bottom_up" => Ok(Self::BottomUp),
            _ => Err(Error::Data(
                format!("unknown pixel row order {value:?}").into(),
            )),
        }
    }
}

/// Options for reading pixels from the same frozen scene as PNG publication.
#[derive(Debug, Clone, Default, PartialEq)]
#[must_use]
pub struct PixelOptions {
    pub(crate) sizing: Option<PngSizing>,
    pub(crate) format: Option<PixelFormat>,
    pub(crate) row_order: Option<RowOrder>,
    pub(crate) matte: Option<OpaqueColor>,
    pub(crate) region: ExportRegion,
    pub(crate) transparent: bool,
}

impl PixelOptions {
    /// Select pixel dimensions explicitly. Omission means source size for
    /// owned reads, or the actual target dimensions for borrowed writes.
    pub const fn sizing(mut self, sizing: PngSizing) -> Self {
        self.sizing = Some(sizing);
        self
    }

    /// Select interleaved channels and their alpha representation.
    pub const fn pixel_format(mut self, format: PixelFormat) -> Self {
        self.format = Some(format);
        self
    }

    /// Select the physical row order.
    pub const fn row_order(mut self, order: RowOrder) -> Self {
        self.row_order = Some(order);
        self
    }

    /// Composite the final picture onto this opaque sRGB background.
    pub const fn matte(mut self, color: OpaqueColor) -> Self {
        self.matte = Some(color);
        self
    }

    /// Select the publication-only output frame.
    pub fn region(mut self, region: ExportRegion) -> Self {
        self.region = region;
        self
    }

    /// Remove actual native structural paper from the published pixels.
    pub const fn transparent(mut self, transparent: bool) -> Self {
        self.transparent = transparent;
        self
    }

    pub(crate) fn for_target(mut self, target: &PixelTarget<'_>) -> Result<Self> {
        if self.format.is_some_and(|format| format != target.format)
            || self.row_order.is_some_and(|order| order != target.order)
        {
            return Err(Error::Data(
                "pixel options do not match the target representation".into(),
            ));
        }
        self.format = Some(target.format);
        self.row_order = Some(target.order);
        Ok(self)
    }
}

/// Immutable, tightly packed, owned sRGB pixel storage.
#[derive(Debug, Clone)]
pub struct PixelBuffer {
    bytes: Arc<Vec<u8>>,
    width: u32,
    height: u32,
    format: PixelFormat,
    order: RowOrder,
    dpi: Option<f64>,
}

impl PixelBuffer {
    pub(crate) fn new(
        bytes: Vec<u8>,
        width: u32,
        height: u32,
        format: PixelFormat,
        order: RowOrder,
        dpi: Option<f64>,
    ) -> Self {
        Self {
            bytes: Arc::new(bytes),
            width,
            height,
            format,
            order,
            dpi,
        }
    }
    /// Pixel width, independent of the source CSS viewport.
    pub const fn width(&self) -> u32 {
        self.width
    }
    /// Pixel height.
    pub const fn height(&self) -> u32 {
        self.height
    }
    /// Number of bytes from one stored row to the next.
    pub fn stride(&self) -> usize {
        self.width as usize * self.format.channels()
    }
    /// Complete interleaved sample representation.
    pub const fn pixel_format(&self) -> PixelFormat {
        self.format
    }
    /// Physical row orientation.
    pub const fn row_order(&self) -> RowOrder {
        self.order
    }
    /// Explicitly requested DPI, if any. Other sizing modes have no density.
    pub const fn dpi(&self) -> Option<f64> {
        self.dpi
    }
    /// The interpretation of RGB bytes in this buffer.
    pub const fn color_space(&self) -> &'static str {
        "srgb"
    }
    /// Borrow the complete immutable packed sample allocation.
    pub fn as_bytes(&self) -> &[u8] {
        &self.bytes
    }

    // PNG assets need top-down straight bytes. Do not re-rasterize or train
    // a color scale when adapting an already colored pixel buffer.
    pub(crate) fn straight_rgba(&self) -> Result<std::borrow::Cow<'_, [u8]>> {
        if self.format == PixelFormat::Rgba8 && self.order == RowOrder::TopDown {
            return Ok(std::borrow::Cow::Borrowed(&self.bytes));
        }
        let mut bytes = Vec::new();
        let len = self.width as usize * self.height as usize * 4;
        bytes
            .try_reserve_exact(len)
            .map_err(|error| Error::Render(format!("pixel asset reservation: {error}").into()))?;
        let stride = self.stride();
        for row in 0..self.height as usize {
            operation::checkpoint()?;
            let row = match self.order {
                RowOrder::TopDown => row,
                RowOrder::BottomUp => self.height as usize - 1 - row,
            };
            for sample in
                self.bytes[row * stride..(row + 1) * stride].chunks_exact(self.format.channels())
            {
                match self.format {
                    PixelFormat::Rgb8 => {
                        bytes.extend_from_slice(&[sample[0], sample[1], sample[2], 255]);
                    }
                    PixelFormat::Rgba8 => bytes.extend_from_slice(sample),
                    PixelFormat::PremultipliedRgba8 | PixelFormat::PremultipliedBgra8 => {
                        let alpha = sample[3];
                        let component = |value: u8| {
                            if alpha == 0 {
                                0
                            } else {
                                let numerator = u32::from(value) * 255;
                                let divisor = u32::from(alpha);
                                let quotient = numerator / divisor;
                                let remainder = numerator % divisor;
                                let up = remainder * 2 > divisor
                                    || (remainder * 2 == divisor && quotient % 2 == 1);
                                u8::try_from((quotient + u32::from(up)).min(255))
                                    .expect("byte sample")
                            }
                        };
                        let (red, blue) = if self.format == PixelFormat::PremultipliedRgba8 {
                            (sample[0], sample[2])
                        } else {
                            (sample[2], sample[0])
                        };
                        bytes.extend_from_slice(&[
                            component(red),
                            component(sample[1]),
                            component(blue),
                            alpha,
                        ]);
                    }
                }
            }
        }
        Ok(std::borrow::Cow::Owned(bytes))
    }
}

type RowWriter<'a> = dyn FnMut(u32, &[u8], &mut bool) -> Result<()> + 'a;

enum Storage<'a> {
    Borrowed {
        bytes: &'a mut [u8],
        stride: usize,
        reverse: bool,
    },
    Rows(&'a mut RowWriter<'a>),
}

/// Checked borrowed storage for one synchronous pixel publication.
/// Padding and storage outside the active pixel rows are never written.
pub struct PixelTarget<'a> {
    width: u32,
    height: u32,
    format: PixelFormat,
    order: RowOrder,
    storage: Storage<'a>,
}

impl<'a> PixelTarget<'a> {
    /// Borrow a straight top-down RGBA8 buffer with its actual byte stride.
    pub fn rgba8(bytes: &'a mut [u8], width: u32, height: u32, stride: isize) -> Result<Self> {
        Self::new(
            bytes,
            width,
            height,
            stride,
            PixelFormat::Rgba8,
            RowOrder::TopDown,
        )
    }

    /// Borrow checked rows from a storage slice. For negative stride, logical
    /// row zero starts at the last row's offset from the slice's low address.
    pub fn new(
        bytes: &'a mut [u8],
        width: u32,
        height: u32,
        stride: isize,
        format: PixelFormat,
        order: RowOrder,
    ) -> Result<Self> {
        let row_bytes = row_bytes(width, height, format)?;
        let pitch = stride.unsigned_abs();
        let required = pitch
            .checked_mul(height as usize - 1)
            .and_then(|offset| offset.checked_add(row_bytes));
        if pitch < row_bytes || required.is_none_or(|required| required > bytes.len()) {
            return Err(Error::Data(
                "pixel target stride or storage does not contain the active rows".into(),
            ));
        }
        Ok(Self {
            width,
            height,
            format,
            order,
            storage: Storage::Borrowed {
                bytes,
                stride: pitch,
                reverse: stride < 0,
            },
        })
    }

    /// Host bindings may supply a prevalidated row writer instead of an
    /// addressable Rust slice. The writer is borrowed only for this operation
    /// and must restrict its writes to the specified logical row. It sets the
    /// supplied flag before the first potentially modifying host call.
    #[doc(hidden)]
    pub fn host_rows(
        width: u32,
        height: u32,
        format: PixelFormat,
        order: RowOrder,
        writer: &'a mut RowWriter<'a>,
    ) -> Result<Self> {
        row_bytes(width, height, format)?;
        Ok(Self {
            width,
            height,
            format,
            order,
            storage: Storage::Rows(writer),
        })
    }

    pub(crate) fn dimensions(&self) -> (u32, u32) {
        (self.width, self.height)
    }

    pub(crate) fn copy(mut self, pixels: &PixelBuffer) -> Result<()> {
        if self.dimensions() != (pixels.width, pixels.height)
            || self.format != pixels.format
            || self.order != pixels.order
        {
            return Err(Error::Data(
                "pixel target does not match the requested sampling or representation".into(),
            ));
        }
        let mut started = false;
        let result = (|| {
            for (row, samples) in pixels.bytes.chunks_exact(pixels.stride()).enumerate() {
                operation::checkpoint()?;
                match &mut self.storage {
                    Storage::Borrowed {
                        bytes,
                        stride,
                        reverse,
                    } => {
                        let row = if *reverse {
                            self.height as usize - 1 - row
                        } else {
                            row
                        };
                        let offset = row * *stride;
                        started = true;
                        bytes[offset..offset + samples.len()].copy_from_slice(samples);
                    }
                    Storage::Rows(write) => {
                        let mut attempted = false;
                        let result = operation::external(|| {
                            write(
                                u32::try_from(row).expect("admitted pixel row"),
                                samples,
                                &mut attempted,
                            )
                        });
                        started |= attempted || result.is_ok();
                        result?;
                    }
                }
            }
            Ok(())
        })();
        result.map_err(|cause| {
            if started {
                Error::Operation(Box::new(OperationFailure::new(
                    OperationPhase::Write,
                    ErrorContext::new().with_operation(OperationPhase::Write),
                    OperationEffect::PixelTargetIndeterminate,
                    cause,
                )))
            } else {
                cause
            }
        })
    }
}

fn row_bytes(width: u32, height: u32, format: PixelFormat) -> Result<usize> {
    if width == 0 || height == 0 {
        return Err(Error::Data(
            "pixel target dimensions must be positive".into(),
        ));
    }
    (width as usize)
        .checked_mul(format.channels())
        .ok_or_else(|| Error::Data("pixel row storage size overflows".into()))
}