Skip to main content

teksilo_render/
text_contrast.rs

1// SPDX-License-Identifier: MPL-2.0
2// SPDX-FileCopyrightText: 2026 FernTech
3
4//! How a glyph's antialiased edge is blended onto the page.
5//!
6//! The surface is an sRGB format, so the GPU blends in linear light. That is
7//! right for images and gradients and wrong for text: a glyph's coverage
8//! blended in linear light paints a half-covered edge pixel of black text on
9//! white at 188/255 where FreeType, Skia, DirectWrite and Core Text paint it
10//! near 128. Every stem has two such edges, so text reads thinner and greyer
11//! than in any other application on the same screen.
12//!
13//! [`TextContrast`] remaps a glyph's coverage before the blend so that the
14//! linear blend lands where a blend in a perceptual space would have, which
15//! is the correction Skia applies to its glyph masks (its "preblend" tables)
16//! and Firefox's WebRender inherited. The page under the glyph is unknown to
17//! the shader, so, as in Skia, it is taken to be the opposite of the text's
18//! luminance: dark text is corrected for a light page and light text for a
19//! dark one. Text whose luminance is near the middle gets the contrast boost
20//! only.
21//!
22//! [`TextContrast::corrected_coverage`] is the CPU statement of the remap and
23//! `shaders/quad.wgsl`'s `text_coverage` is its GPU twin; the tests here pin
24//! the first and `renderer.rs`'s GPU test checks the second against it.
25
26/// The coverage remap applied to monochrome glyphs (see the module docs).
27#[derive(Clone, Copy, Debug, PartialEq)]
28pub struct TextContrast {
29    /// The exponent, relative to sRGB-encoded values, of the space the glyph
30    /// edge is blended in: `1.0` blends in sRGB-encoded values as FreeType
31    /// and most toolkits do, larger values move toward linear light (about
32    /// `2.2`), smaller values darken edges further. `0.0` turns the
33    /// correction off and the coverage is blended in linear light as is.
34    /// Clamped to `0.0..=4.0`.
35    pub gamma: f32,
36    /// Extra weight given to partly covered pixels, `coverage + (1 −
37    /// coverage) · contrast · coverage`, scaled down as the text gets
38    /// lighter (Skia's contrast term). `0.0` adds none. Clamped to
39    /// `0.0..=1.0`.
40    pub contrast: f32,
41}
42
43impl TextContrast {
44    /// No correction: coverage is blended in linear light, as before this
45    /// type existed.
46    pub const OFF: Self = Self {
47        gamma: 0.0,
48        contrast: 0.0,
49    };
50
51    /// The correction a renderer starts with.
52    pub const DEFAULT: Self = Self {
53        gamma: 1.2,
54        contrast: 0.2,
55    };
56
57    /// Heavier edges on dark text than [`DEFAULT`](Self::DEFAULT): the
58    /// blend of sRGB-encoded values, plus half the contrast term.
59    pub const STRONGER: Self = Self {
60        gamma: 1.0,
61        contrast: 0.5,
62    };
63
64    /// The heaviest edges this type offers: the blend of sRGB-encoded
65    /// values, plus the full contrast term.
66    pub const STRONGEST: Self = Self {
67        gamma: 1.0,
68        contrast: 1.0,
69    };
70
71    /// Whether this value changes anything.
72    pub fn is_off(self) -> bool {
73        self.gamma <= 0.0
74    }
75
76    /// The two parameters as the shader reads them: unorm16 `gamma / 4` in
77    /// the low half, unorm16 `contrast` in the high half, `0` when off.
78    pub(crate) fn packed(self) -> u32 {
79        if self.is_off() {
80            return 0;
81        }
82        let g = ((self.gamma.clamp(0.0, 4.0) / 4.0) * 65535.0).round() as u32;
83        // A gamma that rounds to zero would read as "off" in the shader.
84        let g = g.max(1);
85        let c = (self.contrast.clamp(0.0, 1.0) * 65535.0).round() as u32;
86        g | (c << 16)
87    }
88
89    /// The parameters [`packed`](Self::packed) stores, as the shader reads
90    /// them back.
91    fn unpacked(packed: u32) -> Option<(f32, f32)> {
92        if packed == 0 {
93            return None;
94        }
95        let g = (packed & 0xffff) as f32 / 65535.0 * 4.0;
96        let c = (packed >> 16) as f32 / 65535.0;
97        Some((g, c))
98    }
99
100    /// The coverage to blend in linear light for a glyph pixel of
101    /// `coverage` in text of linear colour `text_rgb`, so that the result
102    /// looks as if it had been blended in the space [`gamma`](Self::gamma)
103    /// names. The CPU twin of the shader's `text_coverage`; it reads the
104    /// parameters through the same packing so both see the same values.
105    pub fn corrected_coverage(self, coverage: f32, text_rgb: [f32; 3]) -> f32 {
106        let Some((gamma, contrast)) = Self::unpacked(self.packed()) else {
107            return coverage;
108        };
109        let coverage = coverage.clamp(0.0, 1.0);
110        let src_lin = luminance(text_rgb);
111        let src = srgb_encode(src_lin);
112        // The page is unknown; take it to be the text's opposite.
113        let dst = 1.0 - src;
114        let dst_lin = srgb_decode(dst);
115        let dst_g = dst.powf(gamma);
116        // Skia's contrast term, fading out as the text gets lighter.
117        let c = contrast * dst_g;
118        let a = coverage + (1.0 - coverage) * c * coverage;
119        if (src - dst).abs() < 1.0 / 256.0 {
120            return a.clamp(0.0, 1.0);
121        }
122        let src_g = src.powf(gamma);
123        let out = (dst_g + (src_g - dst_g) * a).max(0.0).powf(1.0 / gamma);
124        ((srgb_decode(out) - dst_lin) / (src_lin - dst_lin)).clamp(0.0, 1.0)
125    }
126}
127
128impl Default for TextContrast {
129    fn default() -> Self {
130        Self::DEFAULT
131    }
132}
133
134/// Rec. 709 luminance of a linear colour.
135fn luminance([r, g, b]: [f32; 3]) -> f32 {
136    0.2126 * r + 0.7152 * g + 0.0722 * b
137}
138
139fn srgb_encode(x: f32) -> f32 {
140    let x = x.clamp(0.0, 1.0);
141    if x <= 0.003_130_8 {
142        x * 12.92
143    } else {
144        1.055 * x.powf(1.0 / 2.4) - 0.055
145    }
146}
147
148fn srgb_decode(x: f32) -> f32 {
149    let x = x.clamp(0.0, 1.0);
150    if x <= 0.04045 {
151        x / 12.92
152    } else {
153        ((x + 0.055) / 1.055).powf(2.4)
154    }
155}
156
157#[cfg(test)]
158mod tests {
159    use super::*;
160
161    const BLACK: [f32; 3] = [0.0, 0.0, 0.0];
162    const WHITE: [f32; 3] = [1.0, 1.0, 1.0];
163
164    /// The sRGB byte a linear blend of `text` over `page` at `alpha` writes.
165    fn blended_byte(text: f32, page: f32, alpha: f32) -> u8 {
166        let lin = srgb_decode(page) + (srgb_decode(text) - srgb_decode(page)) * alpha;
167        (srgb_encode(lin) * 255.0).round() as u8
168    }
169
170    #[test]
171    fn off_leaves_coverage_alone() {
172        for i in 0..=10 {
173            let a = i as f32 / 10.0;
174            assert_eq!(TextContrast::OFF.corrected_coverage(a, BLACK), a);
175        }
176    }
177
178    #[test]
179    fn empty_and_full_coverage_are_kept() {
180        for text in [BLACK, WHITE, [0.2, 0.05, 0.6], [0.5, 0.5, 0.5]] {
181            let t = TextContrast::DEFAULT;
182            assert!(t.corrected_coverage(0.0, text).abs() < 1e-4, "{text:?}");
183            assert!(
184                (t.corrected_coverage(1.0, text) - 1.0).abs() < 1e-4,
185                "{text:?}"
186            );
187        }
188    }
189
190    #[test]
191    fn gamma_one_blends_black_on_white_as_srgb_values() {
192        let t = TextContrast {
193            gamma: 1.0,
194            contrast: 0.0,
195        };
196        // Half-covered black on white: 128 in sRGB space, 188 in linear.
197        assert_eq!(blended_byte(0.0, 1.0, 0.5), 188);
198        let a = t.corrected_coverage(0.5, BLACK);
199        let byte = blended_byte(0.0, 1.0, a);
200        assert!((127..=129).contains(&byte), "got {byte}");
201    }
202
203    #[test]
204    fn gamma_one_blends_white_on_black_as_srgb_values() {
205        let t = TextContrast {
206            gamma: 1.0,
207            contrast: 0.0,
208        };
209        // Half-covered white on black: 128 in sRGB space, 188 in linear,
210        // so the correction thins light text instead.
211        let a = t.corrected_coverage(0.5, WHITE);
212        let byte = blended_byte(1.0, 0.0, a);
213        assert!((127..=129).contains(&byte), "got {byte}");
214    }
215
216    #[test]
217    fn dark_text_edges_darken_and_light_text_edges_lighten() {
218        let t = TextContrast::DEFAULT;
219        for i in 1..10 {
220            let a = i as f32 / 10.0;
221            assert!(t.corrected_coverage(a, BLACK) > a, "dark text at {a}");
222            assert!(t.corrected_coverage(a, WHITE) < a, "light text at {a}");
223        }
224    }
225
226    #[test]
227    fn coverage_stays_monotonic() {
228        for text in [BLACK, WHITE, [0.3, 0.3, 0.3], [0.05, 0.1, 0.5]] {
229            let t = TextContrast::DEFAULT;
230            let mut last = -1.0;
231            for i in 0..=255 {
232                let a = t.corrected_coverage(i as f32 / 255.0, text);
233                assert!(a >= last - 1e-6, "{text:?} at {i}: {a} < {last}");
234                last = a;
235            }
236        }
237    }
238
239    #[test]
240    fn mid_grey_text_gets_the_contrast_term_only() {
241        // sRGB-encoded luminance 0.5: the guessed page is the same, so no
242        // gamma correction can be computed.
243        let grey = srgb_decode(0.5);
244        let t = TextContrast {
245            gamma: 1.0,
246            contrast: 0.0,
247        };
248        let a = t.corrected_coverage(0.3, [grey; 3]);
249        assert!((a - 0.3).abs() < 1e-3, "got {a}");
250    }
251
252    #[test]
253    fn packing_round_trips_within_a_step() {
254        let t = TextContrast {
255            gamma: 1.37,
256            contrast: 0.42,
257        };
258        let (g, c) = TextContrast::unpacked(t.packed()).unwrap();
259        assert!((g - 1.37).abs() < 1e-4 && (c - 0.42).abs() < 1e-4);
260        assert_eq!(TextContrast::OFF.packed(), 0);
261        assert_ne!(
262            TextContrast {
263                gamma: 1e-9,
264                contrast: 0.0
265            }
266            .packed(),
267            0
268        );
269    }
270}