lichtung-plot 0.3.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
//! Exact visible support for fixed raster samples and simple static sources.
//! A report's enclosing rectangle is never used as a positive ink proof.

use crate::layout::{InkExtent, Rect};
use crate::Result;

use super::ImageRendering;

pub(super) fn map_rect(rect: Rect, source: Rect, target: Rect) -> Result<Rect> {
    let sx = target.width() / source.width();
    let sy = target.height() / source.height();
    Rect::new(
        target.left() + (rect.left() - source.left()) * sx,
        target.top() + (rect.top() - source.top()) * sy,
        rect.width() * sx,
        rect.height() * sy,
    )
}

pub(super) fn map_ink(ink: InkExtent, source: Rect, target: Rect) -> Result<InkExtent> {
    match ink {
        InkExtent::Bounds(bounds) => Ok(InkExtent::Bounds(map_rect(bounds, source, target)?)),
        other => Ok(other),
    }
}

pub(super) fn png_ink(
    samples: &super::PngSamples,
    object: Rect,
    clip: Rect,
    rendering: ImageRendering,
) -> Result<InkExtent> {
    let width = f64::from(samples.width);
    let height = f64::from(samples.height);
    let source = Rect::new(0., 0., width, height)?;
    let clip = map_rect(clip, object, source)?;
    let margin = if rendering == ImageRendering::CrispEdges {
        0.
    } else {
        0.5
    };
    let mut result = InkExtent::Empty;
    for (row, pixels) in samples
        .rgba
        .chunks_exact(samples.width as usize)
        .enumerate()
    {
        crate::operation::checkpoint()?;
        let y = f64::from(u32::try_from(row).expect("validated image rows"));
        let top = (y - margin).max(0.);
        let bottom = (y + 1. + margin).min(height);
        if bottom <= clip.top() || top >= clip.top() + clip.height() {
            continue;
        }
        for (column, pixel) in pixels.iter().enumerate() {
            if pixel[3] == 0 {
                continue;
            }
            let x = f64::from(u32::try_from(column).expect("validated image columns"));
            let left = (x - margin).max(0.);
            let right = (x + 1. + margin).min(width);
            let support = Rect::new(left, top, right - left, bottom - top)?;
            if let Some(bounds) = support.intersection(clip) {
                result = result.union(InkExtent::Bounds(bounds));
            }
        }
    }
    map_ink(result, source, object)
}

pub(super) fn svg_ink(source: &str, viewport: Rect, clip: Rect) -> Result<InkExtent> {
    crate::render::ink::svg_ink(
        source,
        viewport,
        clip,
        false,
        crate::render::ink::Precision::Continuous,
        InkExtent::Empty,
    )
}