1
//! Halfblock cells from an RGBA image, keeping transparency as the pane's background.
2

            
3
use image::imageops::FilterType;
4
use image::{DynamicImage, Rgba, RgbaImage};
5
use ratatui::buffer::Buffer;
6
use ratatui::layout::{Rect, Size};
7
use ratatui::style::Color;
8

            
9
/// Pixels with less alpha than this show the background.
10
const OPAQUE_FROM: u8 = 128;
11

            
12
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13
struct Half {
14
    glyph: char,
15
    fg: Option<Color>,
16
    bg: Option<Color>,
17
}
18

            
19
pub struct Halves {
20
    size: Size,
21
    cells: Vec<Half>,
22
}
23

            
24
impl Halves {
25
    /// One cell per two vertical pixels of `image` scaled to `size` cells by twice as many rows.
26
30
    pub fn new(image: &DynamicImage, size: Size) -> Self {
27
30
        let wide = premultiplied(image.to_rgba8());
28
30
        let scaled = DynamicImage::ImageRgba8(wide)
29
30
            .resize_exact(
30
30
                u32::from(size.width),
31
30
                u32::from(size.height) * 2,
32
30
                FilterType::Triangle,
33
30
            )
34
30
            .to_rgba8();
35
30
        let cells = (0..u32::from(size.height))
36
17160
            .flat_map(|row| (0..u32::from(size.width)).map(move |col| (col, row)))
37
17160
            .map(|(col, row)| {
38
17160
                half(
39
17160
                    color(scaled.get_pixel(col, row * 2)),
40
17160
                    color(scaled.get_pixel(col, row * 2 + 1)),
41
17160
                )
42
17160
            })
43
            .collect();
44
30
        Self { size, cells }
45
30
    }
46

            
47
    /// Draw into `area`, clipped to it.
48
    /// Transparent pixels take `background`.
49
27
    pub fn render(&self, area: Rect, buffer: &mut Buffer, background: Color) {
50
27
        let width = usize::from(self.size.width);
51
27
        for (index, half) in self.cells.iter().enumerate() {
52
15336
            let x = u16::try_from(index % width).unwrap_or(u16::MAX);
53
15336
            let y = u16::try_from(index / width).unwrap_or(u16::MAX);
54
15336
            if x >= area.width || y >= area.height {
55
                continue;
56
15336
            }
57
15336
            if let Some(cell) = buffer.cell_mut((area.x + x, area.y + y)) {
58
15336
                cell.set_char(half.glyph)
59
15336
                    .set_fg(half.fg.unwrap_or(background))
60
15336
                    .set_bg(half.bg.unwrap_or(background));
61
            }
62
        }
63
27
    }
64
}
65

            
66
/// Averaging colours of translucent pixels must not pull in their hidden RGB.
67
30
fn premultiplied(mut image: RgbaImage) -> RgbaImage {
68
30
    for Rgba([r, g, b, a]) in image.pixels_mut() {
69
10296000
        let scale = |channel: u8, alpha: u8| {
70
10296000
            u8::try_from((u16::from(channel) * u16::from(alpha) + 127) / 255).unwrap_or(u8::MAX)
71
10296000
        };
72
3432000
        *r = scale(*r, *a);
73
3432000
        *g = scale(*g, *a);
74
3432000
        *b = scale(*b, *a);
75
    }
76
30
    image
77
30
}
78

            
79
/// The pixel's colour, un-premultiplied; `None` when it is transparent.
80
34320
fn color(pixel: &Rgba<u8>) -> Option<Color> {
81
34320
    let Rgba([r, g, b, a]) = *pixel;
82
34320
    if a < OPAQUE_FROM {
83
5324
        return None;
84
28996
    }
85
86988
    let restore = |channel: u8| {
86
86988
        let alpha = u16::from(a);
87
86988
        u8::try_from((u16::from(channel) * 255 + alpha / 2) / alpha).unwrap_or(u8::MAX)
88
86988
    };
89
28996
    Some(Color::Rgb(restore(r), restore(g), restore(b)))
90
34320
}
91

            
92
17160
fn half(top: Option<Color>, bottom: Option<Color>) -> Half {
93
17160
    match (top, bottom) {
94
14494
        (Some(top), bottom) => Half {
95
14494
            glyph: '▀',
96
14494
            fg: Some(top),
97
14494
            bg: bottom,
98
14494
        },
99
8
        (None, Some(bottom)) => Half {
100
8
            glyph: '▄',
101
8
            fg: Some(bottom),
102
8
            bg: None,
103
8
        },
104
2658
        (None, None) => Half {
105
2658
            glyph: ' ',
106
2658
            fg: None,
107
2658
            bg: None,
108
2658
        },
109
    }
110
17160
}