//! Pinnacle's vector renderer, built the way GPU renderers such as Vello //! are, so that a GPU can take its stages over later: //! //! 1. **Flatten**: each path's lines, quadratic and cubic curves become line //! segments (in parallel, a path a job). //! 2. **Bin**: segments are sorted into bands 16 pixel rows tall. //! 3. **Coverage**: within a band, each path's exact pixel coverage comes //! from signed-area accumulation; segments left of a pixel add their //! winding to it (the "backdrop") through a running sum along the row. //! 4. **Composite**: paths are blended in order, in linear light. //! //! Bands touch disjoint pixels, so stage 3–4 runs a band a job across a //! [`Device`]: the CPU's cores today (a thread pool), a GPU's compute units //! once Pinnacle has a GPU driver. #![no_std] extern crate alloc; use alloc::vec; use alloc::vec::Vec; /// Where a renderer's parallel jobs run. pub trait Device: Sync { /// Runs `work(0) .. work(jobs - 1)`, in any order, possibly at once, /// returning when all are done. fn run(&self, jobs: usize, work: &(dyn Fn(usize) + Sync)); } /// Jobs one after another, on the calling thread. pub struct Serial; impl Device for Serial { fn run(&self, jobs: usize, work: &(dyn Fn(usize) + Sync)) { (0..jobs).for_each(work); } } #[derive(Clone, Copy, Debug, PartialEq)] pub struct Point { pub x: f32, pub y: f32, } #[derive(Clone, Copy, Debug)] enum Seg { Move(Point), Line(Point), Quad(Point, Point), Cubic(Point, Point, Point), Close, } /// A shape: one or more contours of lines and curves, filled by the /// non-zero winding rule. #[derive(Clone, Default, Debug)] pub struct Path { segs: Vec, } impl Path { pub fn new() -> Path { Path { segs: Vec::new() } } pub fn move_to(&mut self, x: f32, y: f32) -> &mut Path { self.segs.push(Seg::Move(Point { x, y })); self } pub fn line_to(&mut self, x: f32, y: f32) -> &mut Path { self.segs.push(Seg::Line(Point { x, y })); self } pub fn quad_to(&mut self, cx: f32, cy: f32, x: f32, y: f32) -> &mut Path { self.segs.push(Seg::Quad(Point { x: cx, y: cy }, Point { x, y })); self } pub fn cubic_to(&mut self, c1x: f32, c1y: f32, c2x: f32, c2y: f32, x: f32, y: f32) -> &mut Path { self.segs.push(Seg::Cubic( Point { x: c1x, y: c1y }, Point { x: c2x, y: c2y }, Point { x, y }, )); self } pub fn close(&mut self) -> &mut Path { self.segs.push(Seg::Close); self } /// `other`'s contours added to this path's. pub fn append(&mut self, other: &Path) -> &mut Path { self.segs.extend(other.segs.iter().copied()); self } /// A rectangle with corners of `r`, its curves as cubics. pub fn rounded_rect(x: f32, y: f32, w: f32, h: f32, r: f32) -> Path { let r = r.min(w / 2.0).min(h / 2.0); // The cubic that best follows a quarter circle. let k = r * (1.0 - 0.552_284_8); let mut p = Path::new(); p.move_to(x + r, y) .line_to(x + w - r, y) .cubic_to(x + w - k, y, x + w, y + k, x + w, y + r) .line_to(x + w, y + h - r) .cubic_to(x + w, y + h - k, x + w - k, y + h, x + w - r, y + h) .line_to(x + r, y + h) .cubic_to(x + k, y + h, x, y + h - k, x, y + h - r) .line_to(x, y + r) .cubic_to(x, y + k, x + k, y, x + r, y) .close(); p } pub fn circle(cx: f32, cy: f32, r: f32) -> Path { Path::rounded_rect(cx - r, cy - r, 2.0 * r, 2.0 * r, r) } /// The path moved by (dx, dy) and scaled by `s` about the origin first. pub fn transformed(&self, s: f32, dx: f32, dy: f32) -> Path { let t = |p: Point| Point { x: p.x * s + dx, y: p.y * s + dy, }; Path { segs: self .segs .iter() .map(|seg| match *seg { Seg::Move(p) => Seg::Move(t(p)), Seg::Line(p) => Seg::Line(t(p)), Seg::Quad(c, p) => Seg::Quad(t(c), t(p)), Seg::Cubic(a, b, p) => Seg::Cubic(t(a), t(b), t(p)), Seg::Close => Seg::Close, }) .collect(), } } /// Stage 1: the path as line segments, each curve cut fine enough that /// it strays from the true curve by about a tenth of a pixel at most. pub fn flatten(&self) -> Vec<(Point, Point)> { let mut out = Vec::new(); let (mut start, mut at) = (Point { x: 0.0, y: 0.0 }, Point { x: 0.0, y: 0.0 }); for seg in &self.segs { match *seg { Seg::Move(p) => { if at != start { out.push((at, start)); } start = p; at = p; } Seg::Line(p) => { out.push((at, p)); at = p; } Seg::Quad(c, p) => { let dev = (at.x - 2.0 * c.x + p.x).abs() + (at.y - 2.0 * c.y + p.y).abs(); let n = steps(dev); let mut prev = at; for i in 1..=n { let t = i as f32 / n as f32; let u = 1.0 - t; let q = Point { x: u * u * at.x + 2.0 * u * t * c.x + t * t * p.x, y: u * u * at.y + 2.0 * u * t * c.y + t * t * p.y, }; out.push((prev, q)); prev = q; } at = p; } Seg::Cubic(a, b, p) => { let dev = (at.x - 2.0 * a.x + b.x).abs().max((a.x - 2.0 * b.x + p.x).abs()) + (at.y - 2.0 * a.y + b.y).abs().max((a.y - 2.0 * b.y + p.y).abs()); let n = steps(dev * 1.5); let mut prev = at; for i in 1..=n { let t = i as f32 / n as f32; let u = 1.0 - t; let (w0, w1, w2, w3) = (u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t); let q = Point { x: w0 * at.x + w1 * a.x + w2 * b.x + w3 * p.x, y: w0 * at.y + w1 * a.y + w2 * b.y + w3 * p.y, }; out.push((prev, q)); prev = q; } at = p; } Seg::Close => { if at != start { out.push((at, start)); } at = start; } } } if at != start { out.push((at, start)); } out } } /// Segments for a curve whose second differences sum to `dev` pixels: /// the error falls with the square of the count. fn steps(dev: f32) -> usize { let mut n = 1; while (n * n) as f32 * 0.4 < dev && n < 64 { n += 1; } n } fn floor(x: f32) -> f32 { let i = x as i32 as f32; if i > x { i - 1.0 } else { i } } fn ceil(x: f32) -> f32 { let i = x as i32 as f32; if i < x { i + 1.0 } else { i } } /// What a path is filled with: an opaque colour (0x00RRGGBB) at `alpha`. #[derive(Clone, Copy, Debug)] pub struct Paint { pub color: u32, pub alpha: u8, } /// Linear light from 8-bit sRGB-ish values (gamma 2: the square), scaled /// to 0..=65025, and back by integer square root: blending in linear light /// keeps antialiased edges and thin strokes as bright as they should be. fn to_linear(v: u32) -> u32 { v * v } fn from_linear(v: u32) -> u32 { v.isqrt().min(255) } fn blend(dst: u32, color: u32, coverage: u32) -> u32 { if coverage == 0 { return dst; } if coverage >= 255 { return color; } let mut out = 0; for shift in [0, 8, 16] { let d = to_linear((dst >> shift) & 255); let s = to_linear((color >> shift) & 255); let v = (s * coverage + d * (255 - coverage)) / 255; out |= from_linear(v) << shift; } out } /// A list of filled paths, drawn in order. #[derive(Default)] pub struct Scene { items: Vec<(Path, Paint)>, } impl Scene { pub fn new() -> Scene { Scene::default() } pub fn fill(&mut self, path: Path, paint: Paint) { self.items.push((path, paint)); } pub fn len(&self) -> usize { self.items.len() } pub fn is_empty(&self) -> bool { self.items.is_empty() } } /// The coverage of `path` over a `width` × `height` mask at the origin /// (0–255, `width` a row): how glyphs become pixels once, to be cached and /// blended many times. pub fn mask(path: &Path, width: usize, height: usize) -> Vec { let stride = width + 2; let mut acc = vec![0.0; stride * height]; for (a, b) in path.flatten() { accumulate(&mut acc, stride, height, a, b, 0.0, 0.0); } let mut out = vec![0u8; width * height]; for (row, cells) in out.chunks_exact_mut(width.max(1)).zip(acc.chunks_exact(stride)) { let mut sum = 0.0; for (o, a) in row.iter_mut().zip(cells) { sum += a; *o = (sum.abs().min(1.0) * 255.0 + 0.5) as u8; } } out } const BAND: usize = 16; /// A flattened path and the bounds of its segments. struct Flat { lines: Vec<(Point, Point)>, x0: f32, x1: f32, y0: f32, y1: f32, } /// A raw pointer to the target, which each band job writes its own rows of. struct Target(*mut u32); // SAFETY: jobs write disjoint rows (one band each). unsafe impl Sync for Target {} impl Target { /// A method, not the field, so that closures capture the whole (Sync) wrapper. fn at(&self, offset: usize) -> *mut u32 { // SAFETY: callers stay inside the target. unsafe { self.0.add(offset) } } } /// Renders `scene` over `target` (`width` × `height` pixels, `stride` a row). pub fn render( scene: &Scene, target: &mut [u32], width: usize, height: usize, stride: usize, device: &dyn Device, ) { assert!(target.len() >= stride * height.saturating_sub(1) + width); // Stage 1, a path a job. let flats: Vec>> = (0..scene.items.len()) .map(|_| core::cell::UnsafeCell::new(None)) .collect(); struct Slots<'a>(&'a [core::cell::UnsafeCell>]); // SAFETY: each job fills its own slot. unsafe impl Sync for Slots<'_> {} impl Slots<'_> { /// SAFETY: only job `i` may call this for `i`. unsafe fn set(&self, i: usize, flat: Flat) { unsafe { *self.0[i].get() = Some(flat) }; } } let slots = Slots(&flats); device.run(scene.items.len(), &|i| { let lines = scene.items[i].0.flatten(); let (mut x0, mut x1, mut y0, mut y1) = (f32::MAX, f32::MIN, f32::MAX, f32::MIN); for (a, b) in &lines { x0 = x0.min(a.x).min(b.x); x1 = x1.max(a.x).max(b.x); y0 = y0.min(a.y).min(b.y); y1 = y1.max(a.y).max(b.y); } // SAFETY: slot i is this job's alone. unsafe { slots.set( i, Flat { lines, x0, x1, y0, y1, }, ) }; }); let flats: Vec = flats.into_iter().map(|c| c.into_inner().unwrap()).collect(); // Stages 2–4, a band a job. let bands = height.div_ceil(BAND); let target_ptr = Target(target.as_mut_ptr()); device.run(bands, &|band| { let top = band * BAND; let rows = BAND.min(height - top); let mut acc: Vec = Vec::new(); for (flat, (_, paint)) in flats.iter().zip(&scene.items) { if flat.y1 <= top as f32 || flat.y0 >= (top + rows) as f32 || flat.x1 <= 0.0 || flat.x0 >= width as f32 { continue; } // The path's columns within the target, and a spare one each side. let left = floor(flat.x0.max(0.0)) as usize; let right = (ceil(flat.x1) as usize).min(width); let w = right - left; let stride_acc = w + 2; acc.clear(); acc.resize(stride_acc * rows, 0.0); for &(a, b) in &flat.lines { accumulate(&mut acc, stride_acc, rows, a, b, left as f32, top as f32); } let color = paint.color & 0x00ff_ffff; let alpha = u32::from(paint.alpha); for r in 0..rows { let mut sum = 0.0; // SAFETY: row top + r belongs to this band alone. let row = target_ptr.at((top + r) * stride + left); for x in 0..w { sum += acc[r * stride_acc + x]; let coverage = (sum.abs().min(1.0) * 255.0 + 0.5) as u32; if coverage > 0 { // SAFETY: as above; x < w ≤ width − left. unsafe { let p = row.add(x); *p = blend(*p, color, coverage * alpha / 255); } } } } } }); } /// Adds line (a, b) to a band's area accumulator (font-rs's method): each /// pixel row it crosses gets the signed area it leaves to its right, the /// part left of the band's first column landing on that column, so a /// running sum along the row gives coverage, backdrop included. fn accumulate(acc: &mut [f32], stride: usize, rows: usize, a: Point, b: Point, left: f32, top: f32) { let (p0, p1) = ( Point { x: a.x - left, y: a.y - top, }, Point { x: b.x - left, y: b.y - top, }, ); if p0.y == p1.y { return; } let (dir, p0, p1) = if p0.y < p1.y { (1.0, p0, p1) } else { (-1.0, p1, p0) }; if p1.y <= 0.0 || p0.y >= rows as f32 { return; } let dxdy = (p1.x - p0.x) / (p1.y - p0.y); let y_start = p0.y.max(0.0); let mut x = p0.x + (y_start - p0.y) * dxdy; let y_end = p1.y.min(rows as f32); let max_cell = stride as isize - 1; let mut y = floor(y_start) as usize; while (y as f32) < y_end { let row = y * stride; let dy = (y as f32 + 1.0).min(y_end) - (y as f32).max(y_start); let xnext = x + dxdy * dy; let d = dy * dir; let (x0, x1) = if x < xnext { (x, xnext) } else { (xnext, x) }; let mut add = |i: isize, v: f32| acc[row + i.clamp(0, max_cell) as usize] += v; if x1 <= 0.0 { // All left of the band's columns: the whole step is backdrop. add(0, d); } else { let x0f = floor(x0); let x0i = x0f as isize; let x1c = ceil(x1); let x1i = x1c as isize; if x1i <= x0i + 1 { let xmf = 0.5 * (x + xnext) - x0f; add(x0i, d - d * xmf); add(x0i + 1, d * xmf); } else { let s = 1.0 / (x1 - x0); let x0frac = x0 - x0f; let a0 = 0.5 * s * (1.0 - x0frac) * (1.0 - x0frac); let x1frac = x1 - x1c + 1.0; let am = 0.5 * s * x1frac * x1frac; add(x0i, d * a0); if x1i == x0i + 2 { add(x0i + 1, d * (1.0 - a0 - am)); } else { let a1 = s * (1.5 - x0frac); add(x0i + 1, d * (a1 - a0)); for xi in x0i + 2..x1i - 1 { add(xi, d * s); } let a2 = a1 + (x1i - x0i - 3) as f32 * s; add(x1i - 1, d * (1.0 - a2 - am)); } add(x1i, d * am); } } x = xnext; y += 1; } } #[cfg(test)] mod tests { extern crate std; use super::*; #[test] fn a_rectangle_fills_its_pixels_exactly() { let mut scene = Scene::new(); let mut p = Path::new(); p.move_to(10.0, 10.0) .line_to(30.0, 10.0) .line_to(30.0, 40.0) .line_to(10.0, 40.0) .close(); scene.fill( p, Paint { color: 0xffffff, alpha: 255, }, ); let mut target = vec![0u32; 64 * 64]; render(&scene, &mut target, 64, 64, 64, &Serial); assert_eq!(target[20 * 64 + 20], 0xffffff); assert_eq!(target[20 * 64 + 9], 0); assert_eq!(target[20 * 64 + 30], 0); assert_eq!(target.iter().filter(|&&p| p == 0xffffff).count(), 20 * 30); } #[test] fn a_circle_has_the_area_of_a_circle() { let mut scene = Scene::new(); scene.fill( Path::circle(32.0, 32.0, 20.0), Paint { color: 0xffffff, alpha: 255, }, ); let mut target = vec![0u32; 64 * 64]; render(&scene, &mut target, 64, 64, 64, &Serial); // Sum coverage back from the green channel (gamma 2 undone). let area: f32 = target .iter() .map(|&p| { let g = ((p >> 8) & 255) as f32 / 255.0; g * g }) .sum(); let expected = 3.141_592_7 * 400.0; assert!( (area - expected).abs() < expected * 0.01, "area {area}, expected {expected}" ); } #[test] fn a_hole_stays_empty() { // An outer square clockwise and an inner one counter-clockwise. let mut p = Path::new(); p.move_to(0.0, 0.0) .line_to(40.0, 0.0) .line_to(40.0, 40.0) .line_to(0.0, 40.0) .close(); p.move_to(10.0, 10.0) .line_to(10.0, 30.0) .line_to(30.0, 30.0) .line_to(30.0, 10.0) .close(); let mut scene = Scene::new(); scene.fill( p, Paint { color: 0xffffff, alpha: 255, }, ); let mut target = vec![0u32; 48 * 48]; render(&scene, &mut target, 48, 48, 48, &Serial); assert_eq!(target[20 * 48 + 20], 0); assert_eq!(target[5 * 48 + 5], 0xffffff); } #[test] fn shapes_beyond_the_left_edge_still_cover() { let mut p = Path::new(); p.move_to(-30.0, 0.0) .line_to(20.0, 0.0) .line_to(20.0, 32.0) .line_to(-30.0, 32.0) .close(); let mut scene = Scene::new(); scene.fill( p, Paint { color: 0xffffff, alpha: 255, }, ); let mut target = vec![0u32; 32 * 32]; render(&scene, &mut target, 32, 32, 32, &Serial); assert_eq!(target[10 * 32], 0xffffff); assert_eq!(target[10 * 32 + 19], 0xffffff); assert_eq!(target[10 * 32 + 20], 0); } #[test] fn half_a_pixel_is_half_covered() { let mut p = Path::new(); p.move_to(0.0, 0.0) .line_to(1.5, 0.0) .line_to(1.5, 4.0) .line_to(0.0, 4.0) .close(); let m = mask(&p, 4, 4); assert_eq!(&m[..4], &[255, 128, 0, 0]); } }