Skip to main content

cranpose_render_common/
brush_sampling.rs

1use cranpose_ui_graphics::{Brush, Color, Rect, TileMode};
2
3const TRANSPARENT: Color = Color(0.0, 0.0, 0.0, 0.0);
4
5#[doc(hidden)]
6pub fn color_to_rgba(color: Color) -> [f32; 4] {
7    [
8        color.0.clamp(0.0, 1.0),
9        color.1.clamp(0.0, 1.0),
10        color.2.clamp(0.0, 1.0),
11        color.3.clamp(0.0, 1.0),
12    ]
13}
14
15const LEVEL: f32 = 1.0 / 255.0;
16
17/// The ordered-dither offset a gradient gets at device pixel `(x, y)`, in
18/// output levels — the same value Skia adds, so a Cranpose gradient lands on
19/// the same bytes as the Jetpack Compose gradient it is standing in for.
20///
21/// Skia dithers a gradient it draws to an 8-bit target. The pattern is not
22/// noise: it is a 4x4 Bayer matrix built by striping the low two bits of the
23/// device coordinate — `(X:a1a2, Y:b1b2)` becomes `b1 a1 b2 a2` — and mapped
24/// onto `[-15/32, +15/32]`, half a level either way. Undithered, a slow ramp
25/// quantises into visible bands; dithered, the band edges break into the
26/// checkerboard every Android gradient has.
27///
28/// "A gradient", not "every gradient ever": this is the behaviour of the
29/// platforms Cranpose targets, and it has a floor. Captured on one emulator
30/// host from one APK, a Compose `radialGradient` over black comes back as
31/// `round(255*v + m/16 − 15/32)` of the analytic ramp on an android-34 Wear
32/// image at both 454x454 and 384x384, and as bare `round(255*v)` — no spatial
33/// structure, residual variance exactly the 1/12 of a plain rounding — on an
34/// android-30 one. Only the system image moves between those. So an
35/// android-30 capture is not a reference for this function and never was; a
36/// build compared against one reads as half a level wrong over most of every
37/// gradient it draws, which is exactly what it should read as.
38///
39/// ```text
40///  x→   0   1   2   3
41/// y 0   0   4   1   5
42///   1   8  12   9  13
43///   2   2   6   3   7
44///   3  10  14  11  15
45/// ```
46///
47/// Recovered from device captures rather than from memory: binning
48/// `compose − cranpose` over a radial gradient by `(x % 4, y % 4)` reproduces
49/// this matrix, and the per-cell means track `m / 16 − 15 / 32` to within the
50/// estimator's own bias.
51///
52/// Confirmed since without cranpose in the loop at all, which is the reading
53/// that matters — the difference of two builds cannot say which one carries
54/// the pattern. Against the gradient's own analytic ramp the Compose frame's
55/// residual, binned the same way, IS this table: rms 0.005 of a level per
56/// cell over 109k pixels, against 0.285 for the flat table an undithered
57/// build gives.
58///
59/// The pattern is anchored one pixel on from the coordinate handed in, and
60/// that is measured too. Evaluated at the fragment's own coordinate the
61/// dither came out as the mirror of Skia's — two dithers disagreeing is worse
62/// than one, and a captured frame went from 39.5% identical pixels against
63/// the Compose build to 23.6%. A probe shader that painted `floor(position)`
64/// straight into the frame said why: the fragment that lands on captured
65/// column N reports column N-1. The pattern is a phase as much as a matrix,
66/// so the phase is part of what has to match.
67pub fn gradient_dither_offset(x: f32, y: f32) -> f32 {
68    let px = x.floor().max(0.0) as u32 + 1;
69    let py = y.floor().max(0.0) as u32 + 1;
70    let m = ((py & 1) << 3) | ((px & 1) << 2) | (py & 2) | ((px & 2) >> 1);
71    m as f32 * (1.0 / 16.0) - (15.0 / 32.0)
72}
73
74fn dither_gradient(rgba: [f32; 4], x: f32, y: f32) -> [f32; 4] {
75    if rgba[3] <= 0.0 {
76        return rgba;
77    }
78    let offset = gradient_dither_offset(x, y) * LEVEL;
79    [
80        (rgba[0] + offset).clamp(0.0, 1.0),
81        (rgba[1] + offset).clamp(0.0, 1.0),
82        (rgba[2] + offset).clamp(0.0, 1.0),
83        rgba[3],
84    ]
85}
86
87fn sample_tiled_gradient_rgba(
88    t: f32,
89    tile_mode: TileMode,
90    colors: &[Color],
91    stops: Option<&[f32]>,
92    x: f32,
93    y: f32,
94) -> [f32; 4] {
95    match normalize_gradient_t(t, tile_mode) {
96        Some(sample_t) => dither_gradient(
97            color_to_rgba(interpolate_colors(colors, stops, sample_t)),
98            x,
99            y,
100        ),
101        None => color_to_rgba(TRANSPARENT),
102    }
103}
104
105#[doc(hidden)]
106pub fn sample_brush_rgba(brush: &Brush, rect: Rect, x: f32, y: f32) -> [f32; 4] {
107    match brush {
108        Brush::Solid(color) => color_to_rgba(*color),
109        Brush::LinearGradient {
110            colors,
111            stops,
112            start,
113            end,
114            tile_mode,
115        } => {
116            let sx = resolve_gradient_point(rect.x, rect.width, start.x);
117            let sy = resolve_gradient_point(rect.y, rect.height, start.y);
118            let ex = resolve_gradient_point(rect.x, rect.width, end.x);
119            let ey = resolve_gradient_point(rect.y, rect.height, end.y);
120            let dx = ex - sx;
121            let dy = ey - sy;
122            let denom = (dx * dx + dy * dy).max(f32::EPSILON);
123            let t = ((x - sx) * dx + (y - sy) * dy) / denom;
124            sample_tiled_gradient_rgba(t, *tile_mode, colors, stops.as_deref(), x, y)
125        }
126        Brush::RadialGradient {
127            colors,
128            stops,
129            center,
130            radius,
131            tile_mode,
132        } => {
133            let cx = rect.x + center.x;
134            let cy = rect.y + center.y;
135            let radius = (*radius).max(f32::EPSILON);
136            let dx = x - cx;
137            let dy = y - cy;
138            let distance = (dx * dx + dy * dy).sqrt();
139            let t = distance / radius;
140            sample_tiled_gradient_rgba(t, *tile_mode, colors, stops.as_deref(), x, y)
141        }
142        Brush::SweepGradient {
143            colors,
144            stops,
145            center,
146        } => {
147            let cx = rect.x + center.x;
148            let cy = rect.y + center.y;
149            let dx = x - cx;
150            let dy = y - cy;
151            let angle = dy.atan2(dx);
152            let t = (angle / std::f32::consts::TAU + 0.5).clamp(0.0, 1.0);
153            dither_gradient(
154                color_to_rgba(interpolate_colors(colors, stops.as_deref(), t)),
155                x,
156                y,
157            )
158        }
159    }
160}
161
162fn resolve_gradient_point(origin: f32, extent: f32, value: f32) -> f32 {
163    if value.is_finite() {
164        origin + value
165    } else if value.is_sign_positive() {
166        origin + extent
167    } else {
168        origin
169    }
170}
171
172#[doc(hidden)]
173pub fn normalize_gradient_t(t: f32, tile_mode: TileMode) -> Option<f32> {
174    match tile_mode {
175        TileMode::Clamp => Some(t.clamp(0.0, 1.0)),
176        TileMode::Decal => {
177            if (0.0..=1.0).contains(&t) {
178                Some(t)
179            } else {
180                None
181            }
182        }
183        TileMode::Repeated => Some(t.rem_euclid(1.0)),
184        TileMode::Mirror => {
185            let wrapped = t.rem_euclid(2.0);
186            if wrapped <= 1.0 {
187                Some(wrapped)
188            } else {
189                Some(2.0 - wrapped)
190            }
191        }
192    }
193}
194
195fn interpolate_colors(colors: &[Color], stops: Option<&[f32]>, t: f32) -> Color {
196    if colors.is_empty() {
197        return TRANSPARENT;
198    }
199    if colors.len() == 1 {
200        return colors[0];
201    }
202    let clamped = t.clamp(0.0, 1.0);
203
204    if let Some(stops) = stops
205        && stops.len() == colors.len()
206    {
207        if clamped <= stops[0] {
208            return colors[0];
209        }
210        for index in 0..(stops.len() - 1) {
211            let start = stops[index];
212            let end = stops[index + 1];
213            if clamped <= end {
214                let span = (end - start).max(f32::EPSILON);
215                let frac = ((clamped - start) / span).clamp(0.0, 1.0);
216                return lerp_color(colors[index], colors[index + 1], frac);
217            }
218        }
219        return last_color(colors);
220    }
221
222    let segments = (colors.len() - 1) as f32;
223    let scaled = clamped * segments;
224    let index = scaled.floor() as usize;
225    if index >= colors.len() - 1 {
226        return last_color(colors);
227    }
228    let frac = scaled - index as f32;
229    lerp_color(colors[index], colors[index + 1], frac)
230}
231
232fn last_color(colors: &[Color]) -> Color {
233    colors.last().copied().unwrap_or(TRANSPARENT)
234}
235
236fn lerp_color(a: Color, b: Color, t: f32) -> Color {
237    let lerp = |start: f32, end: f32| start + (end - start) * t;
238    Color(
239        lerp(a.0, b.0),
240        lerp(a.1, b.1),
241        lerp(a.2, b.2),
242        lerp(a.3, b.3),
243    )
244}
245
246#[cfg(test)]
247mod tests {
248    use cranpose_ui_graphics::Point;
249
250    use super::*;
251
252    fn sample_rect() -> Rect {
253        Rect {
254            x: 0.0,
255            y: 0.0,
256            width: 100.0,
257            height: 40.0,
258        }
259    }
260
261    #[test]
262    fn empty_gradient_samples_transparent_instead_of_panicking() {
263        let brush =
264            Brush::linear_gradient_range(Vec::new(), Point::new(0.0, 0.0), Point::new(100.0, 0.0));
265        assert_eq!(
266            sample_brush_rgba(&brush, sample_rect(), 50.0, 10.0),
267            [0.0, 0.0, 0.0, 0.0]
268        );
269    }
270
271    #[test]
272    fn clamped_gradient_samples_last_color_at_end() {
273        let brush = Brush::linear_gradient_range(
274            vec![Color::RED, Color::BLUE],
275            Point::new(0.0, 0.0),
276            Point::new(100.0, 0.0),
277        );
278        for y in 0..4 {
279            for x in 0..4 {
280                let sampled = sample_brush_rgba(&brush, sample_rect(), 120.0 + x as f32, y as f32);
281                let bytes: Vec<u8> = sampled.iter().map(|c| (c * 255.0).round() as u8).collect();
282                assert_eq!(bytes, vec![0, 0, 255, 255], "cell ({x}, {y})");
283            }
284        }
285    }
286
287    #[test]
288    fn mirror_tile_mode_normalizes_across_repeated_segments() {
289        assert_eq!(normalize_gradient_t(1.25, TileMode::Mirror), Some(0.75));
290        assert_eq!(normalize_gradient_t(1.75, TileMode::Mirror), Some(0.25));
291    }
292
293    const BAYER_4X4: [[u32; 4]; 4] = [[0, 4, 1, 5], [8, 12, 9, 13], [2, 6, 3, 7], [10, 14, 11, 15]];
294
295    #[test]
296    fn the_dither_lays_out_skias_bayer_matrix() {
297        for y in 0..4u32 {
298            for x in 0..4u32 {
299                let expected = BAYER_4X4[y as usize][x as usize] as f32 / 16.0 - 15.0 / 32.0;
300                assert_eq!(
301                    gradient_dither_offset(x as f32 - 1.0 + 4.0, y as f32 - 1.0 + 4.0),
302                    expected,
303                    "cell ({x}, {y})"
304                );
305            }
306        }
307    }
308
309    #[test]
310    fn the_dither_is_a_pixel_ahead_of_the_fragment() {
311        assert_eq!(
312            gradient_dither_offset(4.0, 4.0),
313            gradient_dither_offset(5.0 - 1.0, 5.0 - 1.0),
314        );
315        assert_eq!(
316            gradient_dither_offset(3.0, 3.0),
317            BAYER_4X4[0][0] as f32 / 16.0 - 15.0 / 32.0,
318        );
319    }
320
321    #[test]
322    fn the_dither_repeats_every_four_pixels_and_never_moves_a_whole_level() {
323        for y in 0..16u32 {
324            for x in 0..16u32 {
325                assert_eq!(
326                    gradient_dither_offset(x as f32, y as f32),
327                    gradient_dither_offset((x % 4) as f32, (y % 4) as f32),
328                );
329            }
330        }
331        let offsets: Vec<f32> = (0..4)
332            .flat_map(|y| (0..4).map(move |x| gradient_dither_offset(x as f32, y as f32)))
333            .collect();
334        assert!(offsets.iter().all(|offset| offset.abs() < 0.5));
335        let mean = offsets.iter().sum::<f32>() / offsets.len() as f32;
336        assert!(mean.abs() < 1e-6, "mean offset {mean}");
337    }
338
339    #[test]
340    fn a_solid_brush_is_left_alone() {
341        let brush = Brush::Solid(Color(0.25, 0.5, 0.75, 1.0));
342        for y in 0..4 {
343            for x in 0..4 {
344                assert_eq!(
345                    sample_brush_rgba(&brush, sample_rect(), x as f32, y as f32),
346                    [0.25, 0.5, 0.75, 1.0],
347                );
348            }
349        }
350    }
351
352    #[test]
353    fn the_dither_moves_a_flat_gradient_off_one_value_onto_two() {
354        let grey = 100.4 / 255.0;
355        let brush = Brush::linear_gradient_range(
356            vec![Color(grey, grey, grey, 1.0), Color(grey, grey, grey, 1.0)],
357            Point::new(0.0, 0.0),
358            Point::new(100.0, 0.0),
359        );
360        let mut levels = std::collections::BTreeSet::new();
361        for y in 0..4 {
362            for x in 0..4 {
363                let sampled = sample_brush_rgba(&brush, sample_rect(), x as f32, y as f32);
364                levels.insert((sampled[0] * 255.0).round() as u8);
365            }
366        }
367        assert_eq!(levels.into_iter().collect::<Vec<_>>(), vec![100, 101]);
368    }
369}