Skip to main content

vello_common/
rect.rs

1// Copyright 2025 the Vello Authors
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3
4//! Fast pixel-aligned rectangle rendering directly into strips.
5
6use crate::kurbo::Rect;
7#[cfg(not(feature = "std"))]
8use crate::kurbo::common::FloatFuncs as _;
9use crate::strip::Strip;
10use crate::tile::Tile;
11use alloc::vec::Vec;
12use fearless_simd::*;
13
14/// Render a pixel-aligned rectangle directly into strips.
15///
16/// This bypasses the full path processing pipeline (flatten → tiles → strips)
17/// by directly creating strip coverage data for the rectangle.
18///
19/// The rect bounds should already be clamped to the viewport.
20pub fn render(level: Level, rect: Rect, strip_buf: &mut Vec<Strip>, alpha_buf: &mut Vec<u8>) {
21    dispatch!(level, simd => render_impl(simd, rect, strip_buf, alpha_buf));
22}
23
24/// Generates strip data for an axis-aligned rectangle.
25///
26/// # Strip layout strategy
27///
28/// Tile rows are classified into two kinds:
29///
30/// - **Edge rows** (top/bottom of rect): the rect boundary crosses partway
31///   through the tile vertically, so individual pixels need per-cell alpha.
32///   We emit a *single wide strip* spanning all tile columns, with alpha =
33///   `x_alpha` * `y_alpha` (so the intersection of the alpha mask in each direction).
34///
35/// - **Interior rows**: every pixel in the tile has full vertical coverage,
36///   so we only need to handle the left and right partial-column edges.
37///   We emit a **left edge strip** (with its x-alpha mask) and, when the rect
38///   spans more than one tile column, a **right edge strip** with `fill_gap =
39///   true` so the renderer fills solid 0xFF between them.
40///
41/// The x-alpha masks for the left/right edge tiles are y-independent, so they
42/// are precomputed once and reused across all interior rows.
43#[inline(always)]
44fn render_impl<S: Simd>(s: S, rect: Rect, strip_buf: &mut Vec<Strip>, alpha_buf: &mut Vec<u8>) {
45    if rect.is_zero_area() {
46        return;
47    }
48
49    let rect_x0 = rect.x0 as f32;
50    let rect_y0 = rect.y0 as f32;
51    let rect_x1 = rect.x1 as f32;
52    let rect_y1 = rect.y1 as f32;
53
54    // Integer pixel bounds.
55    let px_x0 = rect_x0.floor() as u16;
56    let px_y0 = rect_y0.floor() as u16;
57    let px_y1 = rect_y1.ceil() as u16;
58
59    let left_tile_x = (px_x0 / Tile::WIDTH) * Tile::WIDTH;
60    // Inclusive, so don't use `ceil` here but just `rect_x1` directly.
61    let right_tile_x = (rect_x1 as u16 / Tile::WIDTH) * Tile::WIDTH;
62
63    let y0 = u32::from((px_y0 / Tile::HEIGHT) * Tile::HEIGHT);
64    let y1 = (u32::from(px_y1) + u32::from(Tile::HEIGHT - 1)) / u32::from(Tile::HEIGHT)
65        * u32::from(Tile::HEIGHT);
66    // Include one tile past the right edge so the right-edge tile column is
67    // covered by the edge-row wide-strip loop.
68    let x_end = u32::from(right_tile_x) + u32::from(Tile::WIDTH);
69
70    if x_end <= u32::from(left_tile_x) || y1 <= y0 {
71        return;
72    }
73
74    let tile_start_y = y0 / u32::from(Tile::HEIGHT);
75    let tile_end_y = y1 / u32::from(Tile::HEIGHT);
76
77    // A right strip is only needed when the rect spans more than one tile column.
78    let needs_right_strip = right_tile_x > left_tile_x;
79
80    let left_x_cov = coverage(left_tile_x, rect_x0, rect_x1);
81    let right_x_cov = coverage(right_tile_x, rect_x0, rect_x1);
82    let left_x_mask = alpha_mask_from_x_coverage(s, &left_x_cov);
83    let right_x_mask = alpha_mask_from_x_coverage(s, &right_x_cov);
84
85    for tile_y in tile_start_y..tile_end_y {
86        let strip_y = tile_y * u32::from(Tile::HEIGHT);
87        let strip_y = strip_y as u16;
88        let strip_y_f = strip_y as f32;
89        let strip_y_end_f = strip_y as f32 + Tile::HEIGHT as f32;
90
91        // A row is an "edge" if the rect's top or bottom boundary falls
92        // *inside* it (i.e. partial vertical coverage).
93        let is_top_edge = strip_y_f < rect_y0 && rect_y0 < strip_y_end_f;
94        let is_bottom_edge = strip_y_f < rect_y1 && rect_y1 < strip_y_end_f;
95
96        if is_top_edge || is_bottom_edge {
97            let alpha_start = alpha_buf.len() as u32;
98
99            let y_cov = coverage(strip_y, rect_y0, rect_y1);
100            let mut col = u32::from(left_tile_x);
101            while col + u32::from(Tile::WIDTH) <= x_end {
102                // TODO: We could optimize this so this is only computed for the left-most and right-most
103                // tile of the edge, all intermediate tiles have full horizontal coverage.
104                let x_cov = coverage(col as u16, rect_x0, rect_x1);
105                let combined = combined_tile_alpha(s, &x_cov, &y_cov);
106                alpha_buf.extend_from_slice(combined.as_slice());
107                col += u32::from(Tile::WIDTH);
108            }
109
110            strip_buf.push(Strip::new(left_tile_x, strip_y, alpha_start, false));
111        } else {
112            let alpha_start = alpha_buf.len() as u32;
113            alpha_buf.extend_from_slice(left_x_mask.as_slice());
114            strip_buf.push(Strip::new(left_tile_x, strip_y, alpha_start, false));
115
116            if needs_right_strip {
117                // `fill_gap = true` tells the renderer to fill solid 0xFF
118                // between the previous strip's end and this strip's start.
119                let alpha_start = alpha_buf.len() as u32;
120                alpha_buf.extend_from_slice(right_x_mask.as_slice());
121                strip_buf.push(Strip::new(right_tile_x, strip_y, alpha_start, true));
122            }
123        }
124    }
125
126    // Sentinel strip: marks the end of the strip list for this shape.
127    let last_strip_y = ((tile_end_y - 1) * u32::from(Tile::HEIGHT)) as u16;
128    strip_buf.push(Strip::sentinel(last_strip_y, alpha_buf.len() as u32));
129}
130
131/// Compute fractional pixel coverage for `N` consecutive pixels starting at `start`.
132#[inline(always)]
133fn coverage<const N: usize>(start: u16, rect_lo: f32, rect_hi: f32) -> [f32; N] {
134    let mut cov = [0.0_f32; N];
135
136    #[allow(clippy::needless_range_loop, reason = "better clarity")]
137    for i in 0..N {
138        let px = (start as usize + i) as f32;
139        cov[i] = (rect_hi.min(px + 1.0) - rect_lo.max(px)).clamp(0.0, 1.0);
140    }
141    cov
142}
143
144/// Build an alpha mask for the 4x4 tile from the given horizontal coverages,
145/// splatting them across the other dimension.
146#[inline(always)]
147fn alpha_mask_from_x_coverage<S: Simd>(s: S, cov: &[f32; Tile::WIDTH as usize]) -> u8x16<S> {
148    let mut buf = [0_u8; 16];
149
150    #[allow(clippy::needless_range_loop, reason = "better clarity")]
151    for col in 0..Tile::WIDTH as usize {
152        let alpha = (cov[col] * 255.0 + 0.5) as u8;
153        let base = col * Tile::HEIGHT as usize;
154        buf[base..base + Tile::HEIGHT as usize].fill(alpha);
155    }
156
157    u8x16::from_slice(s, &buf)
158}
159
160/// Compute the alphas for a single 4x4 tile, taking horizontal as well as vertical coverage
161/// of the rectangle into account.
162#[inline(always)]
163fn combined_tile_alpha<S: Simd>(
164    s: S,
165    x_cov: &[f32; Tile::WIDTH as usize],
166    y_cov: &[f32; Tile::HEIGHT as usize],
167) -> u8x16<S> {
168    let mut buf = [0_u8; 16];
169    for (col, xc) in x_cov.iter().copied().enumerate() {
170        for (row, yc) in y_cov.iter().copied().enumerate() {
171            buf[col * Tile::HEIGHT as usize + row] = (xc * yc * 255.0 + 0.5) as u8;
172        }
173    }
174
175    u8x16::from_slice(s, &buf)
176}
177
178#[cfg(test)]
179mod tests {
180    use super::*;
181    use alloc::vec::Vec;
182
183    #[test]
184    fn render_edge_row_at_u16_right_edge() {
185        let mut strips = Vec::new();
186        let mut alphas = Vec::new();
187        let rect = Rect::new(f64::from(u16::MAX - 3), 0.5, f64::from(u16::MAX), 3.5);
188
189        render(Level::baseline(), rect, &mut strips, &mut alphas);
190
191        assert_eq!(strips.len(), 2);
192        assert_eq!(strips[0].x, u16::MAX - 3);
193        assert_eq!(strips[0].alpha_idx(), 0);
194        assert_eq!(
195            alphas.len(),
196            usize::from(Tile::WIDTH) * usize::from(Tile::HEIGHT)
197        );
198        assert!(strips[1].is_sentinel());
199    }
200
201    #[test]
202    fn render_edge_row_at_u16_bottom_edge() {
203        let mut strips = Vec::new();
204        let mut alphas = Vec::new();
205        let rect = Rect::new(0.5, f64::from(u16::MAX - 3), 3.5, f64::from(u16::MAX));
206
207        render(Level::baseline(), rect, &mut strips, &mut alphas);
208
209        assert_eq!(strips.len(), 2);
210        assert_eq!(strips[0].y, u16::MAX - 3);
211        assert_eq!(strips[0].alpha_idx(), 0);
212        assert_eq!(
213            alphas.len(),
214            usize::from(Tile::WIDTH) * usize::from(Tile::HEIGHT)
215        );
216        assert!(strips[1].is_sentinel());
217    }
218}