cranpose_render_common/
text_mask_gamma.rs1use std::sync::OnceLock;
14
15use cranpose_ui_graphics::{Brush, Color};
16
17const LUMINANCE_BITS: u32 = 3;
18const LUMINANCE_CLASSES: usize = 1 << LUMINANCE_BITS;
19const CONTRAST: f32 = 0.5;
20
21type CorrectionTable = [u8; 256];
22
23#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
27pub struct TextLuminance(u8);
28
29impl TextLuminance {
30 pub fn of_color(color: Color) -> Self {
32 let channel = |value: f32| u32::from(unit_to_u8(value));
33 let luminance =
34 (channel(color.0) * 54 + channel(color.1) * 183 + channel(color.2) * 19) >> 8;
35 Self((luminance >> (8 - LUMINANCE_BITS)) as u8)
36 }
37
38 pub fn of_brush(brush: &Brush) -> Self {
41 match brush {
42 Brush::Solid(color) => Self::of_color(*color),
43 _ => Self::of_color(Color(0.5, 0.5, 0.5, 1.0)),
44 }
45 }
46
47 pub fn correction(self) -> MaskGammaCorrection {
49 MaskGammaCorrection(&correction_tables()[usize::from(self.0)])
50 }
51}
52
53#[derive(Clone, Copy)]
56pub struct MaskGammaCorrection(&'static CorrectionTable);
57
58impl MaskGammaCorrection {
59 pub fn apply(self, coverage: f32) -> u8 {
61 self.0[usize::from(unit_to_u8(coverage))]
62 }
63
64 pub fn apply_unit(self, coverage: f32) -> f32 {
66 f32::from(self.apply(coverage)) / 255.0
67 }
68}
69
70fn unit_to_u8(value: f32) -> u8 {
71 (value.clamp(0.0, 1.0) * 255.0).round() as u8
72}
73
74fn correction_tables() -> &'static [CorrectionTable; LUMINANCE_CLASSES] {
75 static TABLES: OnceLock<[CorrectionTable; LUMINANCE_CLASSES]> = OnceLock::new();
76 TABLES.get_or_init(|| std::array::from_fn(correction_table))
77}
78
79fn correction_table(class: usize) -> CorrectionTable {
84 let class = class as u32;
85 let representative = (class << 5) | (class << 2) | (class >> 1);
86 let src = representative as f32 / 255.0;
87 let dst = 1.0 - src;
88 let linear_src = srgb_to_linear(src);
89 let linear_dst = srgb_to_linear(dst);
90 let contrast = CONTRAST * linear_dst;
91 std::array::from_fn(|index| {
92 let raw = index as f32 / 255.0;
93 let boosted = raw + (1.0 - raw) * contrast * raw;
94 let blended = linear_to_srgb(linear_src * boosted + (1.0 - boosted) * linear_dst);
95 unit_to_u8((blended - dst) / (src - dst))
96 })
97}
98
99fn srgb_to_linear(value: f32) -> f32 {
100 if value <= 0.04045 {
101 value / 12.92
102 } else {
103 ((value + 0.055) / 1.055).powf(2.4)
104 }
105}
106
107fn linear_to_srgb(value: f32) -> f32 {
108 if value <= 0.003_130_8 {
109 value * 12.92
110 } else {
111 1.055 * value.powf(1.0 / 2.4) - 0.055
112 }
113}
114
115#[cfg(test)]
116#[path = "tests/text_mask_gamma_tests.rs"]
117mod tests;