//! Drawing into a buffer of 0x00RRGGBB pixels: rectangles (with rounded, //! anti-aliased corners), alpha blending, copies between buffers, and text //! from a TrueType font (`font`), each glyph rasterised once a size. //! //! Everything clips to the canvas's clip rectangle; only a glyph drawn //! for the first time allocates. #![no_std] extern crate alloc; pub mod font; pub use font::Font; /// An opaque colour, 0x00RRGGBB. #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub struct Color(pub u32); impl Color { pub const fn rgb(r: u8, g: u8, b: u8) -> Color { Color((r as u32) << 16 | (g as u32) << 8 | b as u32) } pub const WHITE: Color = Color(0x00ff_ffff); pub const BLACK: Color = Color(0); } #[derive(Clone, Copy, PartialEq, Eq, Debug, Default)] pub struct Rect { pub x: i32, pub y: i32, pub width: i32, pub height: i32, } impl Rect { pub const fn new(x: i32, y: i32, width: i32, height: i32) -> Rect { Rect { x, y, width, height } } pub fn right(&self) -> i32 { self.x + self.width } pub fn bottom(&self) -> i32 { self.y + self.height } pub fn is_empty(&self) -> bool { self.width <= 0 || self.height <= 0 } pub fn intersect(&self, other: &Rect) -> Rect { let (x, y) = (self.x.max(other.x), self.y.max(other.y)); let (right, bottom) = (self.right().min(other.right()), self.bottom().min(other.bottom())); Rect::new(x, y, (right - x).max(0), (bottom - y).max(0)) } /// The smallest rectangle holding both (an empty one holds nothing). pub fn union(&self, other: &Rect) -> Rect { if self.is_empty() { return *other; } if other.is_empty() { return *self; } let (x, y) = (self.x.min(other.x), self.y.min(other.y)); Rect::new( x, y, self.right().max(other.right()) - x, self.bottom().max(other.bottom()) - y, ) } pub fn contains(&self, x: i32, y: i32) -> bool { x >= self.x && y >= self.y && x < self.right() && y < self.bottom() } pub fn inset(&self, by: i32) -> Rect { Rect::new( self.x + by, self.y + by, self.width - 2 * by, self.height - 2 * by, ) } } /// Blends `color` over `pixel` with coverage `alpha` (0–255). #[inline] pub fn blend(pixel: u32, color: u32, alpha: u32) -> u32 { if alpha >= 255 { return color; } // Red and blue together, then green: two multiplies a pixel. let rb = ((color & 0xff00ff) * alpha + (pixel & 0xff00ff) * (255 - alpha) + 0x800080) >> 8 & 0xff00ff; let g = ((color & 0xff00) * alpha + (pixel & 0xff00) * (255 - alpha) + 0x8000) >> 8 & 0xff00; rb | g } /// A view of pixels to draw into. pub struct Canvas<'a> { pixels: &'a mut [u32], pub width: i32, pub height: i32, /// Pixels from one row to the next. stride: usize, clip: Rect, } impl<'a> Canvas<'a> { pub fn new(pixels: &'a mut [u32], width: u32, height: u32) -> Canvas<'a> { assert!(pixels.len() >= (width * height) as usize); let (width, height) = (width as i32, height as i32); Canvas { pixels, width, height, stride: width as usize, clip: Rect::new(0, 0, width, height), } } /// Limits drawing to `rect` (within the canvas). pub fn set_clip(&mut self, rect: Rect) { self.clip = rect.intersect(&Rect::new(0, 0, self.width, self.height)); } pub fn clip(&self) -> Rect { self.clip } pub fn pixels(&self) -> &[u32] { self.pixels } #[inline] fn row(&mut self, y: i32, from: i32, to: i32) -> &mut [u32] { let start = y as usize * self.stride; &mut self.pixels[start + from as usize..start + to as usize] } pub fn fill(&mut self, color: Color) { let clip = self.clip; self.fill_rect(clip, color); } pub fn fill_rect(&mut self, rect: Rect, color: Color) { let r = rect.intersect(&self.clip); for y in r.y..r.bottom() { self.row(y, r.x, r.right()).fill(color.0); } } /// Fills `rect` with `color` at opacity `alpha`. pub fn blend_rect(&mut self, rect: Rect, color: Color, alpha: u8) { let r = rect.intersect(&self.clip); for y in r.y..r.bottom() { for pixel in self.row(y, r.x, r.right()) { *pixel = blend(*pixel, color.0, u32::from(alpha)); } } } /// A rectangle with corners of `radius`, their edges anti-aliased. pub fn fill_rounded(&mut self, rect: Rect, radius: i32, color: Color) { let radius = radius.min(rect.width / 2).min(rect.height / 2).max(0); if radius == 0 { return self.fill_rect(rect, color); } // The middle band, then each corner row by row. self.fill_rect( Rect::new(rect.x, rect.y + radius, rect.width, rect.height - 2 * radius), color, ); let clip = self.clip; for dy in 0..radius { // Distance from the corner circle's centre, in 1/16 pixels, // sampled at the pixel centre. let cy = (radius - dy) * 16 - 8; for (y, top) in [(rect.y + dy, true), (rect.bottom() - 1 - dy, false)] { if y < clip.y || y >= clip.bottom() { continue; } let _ = top; for dx in 0..radius { let cx = (radius - dx) * 16 - 8; let alpha = coverage(cx, cy, radius * 16); if alpha == 0 { continue; } for x in [rect.x + dx, rect.right() - 1 - dx] { if x >= clip.x && x < clip.right() { let pixel = &mut self.pixels[y as usize * self.stride + x as usize]; *pixel = blend(*pixel, color.0, alpha); } } } let inner = Rect::new(rect.x + radius, y, rect.width - 2 * radius, 1).intersect(&clip); if !inner.is_empty() { self.row(y, inner.x, inner.right()).fill(color.0); } } } } /// A rectangle with each corner its own radius (top-left, top-right, /// bottom-right, bottom-left), `alpha` see-through (255 opaque), its /// corners anti-aliased: what a stylesheet's `border-radius` and a /// translucent background ask for. pub fn fill_round_rect(&mut self, rect: Rect, radii: [i32; 4], color: Color, alpha: u8) { let radii = clamp_radii(&rect, radii); self.cover( &rect, |x, y| round_cover(&rect, &radii, x, y), color, alpha, Some(&radii), ); } /// The ring between `rect` and `rect` inset by `widths` (top, right, /// bottom, left), corners rounded as [`Canvas::fill_round_rect`]: a /// border. pub fn stroke_round_rect( &mut self, rect: Rect, radii: [i32; 4], widths: [i32; 4], color: Color, alpha: u8, ) { let radii = clamp_radii(&rect, radii); let [t, r, b, l] = widths; let inner = Rect::new(rect.x + l, rect.y + t, rect.width - l - r, rect.height - t - b); let inner_radii = [ (radii[0] - t.max(l)).max(0), (radii[1] - t.max(r)).max(0), (radii[2] - b.max(r)).max(0), (radii[3] - b.max(l)).max(0), ]; let ring = |x: i32, y: i32| { let outer = round_cover(&rect, &radii, x, y); let hole = if inner.is_empty() { 0 } else { round_cover(&inner, &inner_radii, x, y) }; outer.saturating_sub(hole) }; // Only the bands the ring can touch: the top and bottom rows whole, // the rows between at their two ends. let area = rect.intersect(&self.clip); if area.is_empty() || alpha == 0 { return; } let a = u32::from(alpha); let top = rect.y + t.max(radii[0]).max(radii[1]); let bottom = rect.bottom() - b.max(radii[2]).max(radii[3]); let left = rect.x + l.max(radii[0]).max(radii[3]); let right = rect.right() - r.max(radii[1]).max(radii[2]); for y in area.y..area.bottom() { let start = y as usize * self.stride; let spans: [(i32, i32); 2] = if y < top || y >= bottom || right <= left { [(area.x, area.right()), (0, 0)] } else { [ (area.x, left.min(area.right())), (right.max(area.x), area.right()), ] }; for (from, to) in spans { for x in from..to { let c = ring(x, y); if c == 0 { continue; } let pixel = &mut self.pixels[start + x as usize]; *pixel = blend(*pixel, color.0, c * a / 255); } } } } /// Blends `color` over `rect` (within the clip) by `coverage` of each /// pixel times `alpha`. With `solid` (the corner radii of a filled /// shape), a row clear of the corners is covered whole: blended in one /// pass, or filled when opaque. fn cover( &mut self, rect: &Rect, coverage: impl Fn(i32, i32) -> u32, color: Color, alpha: u8, solid: Option<&[i32; 4]>, ) { let area = rect.intersect(&self.clip); if area.is_empty() || alpha == 0 { return; } let a = u32::from(alpha); for y in area.y..area.bottom() { let start = y as usize * self.stride; if let Some(radii) = solid { let clear = y >= rect.y + radii[0].max(radii[1]) && y < rect.bottom() - radii[2].max(radii[3]); if clear { let row = &mut self.pixels[start + area.x as usize..start + area.right() as usize]; if a == 255 { row.fill(color.0); } else { for pixel in row { *pixel = blend(*pixel, color.0, a); } } continue; } } for x in area.x..area.right() { let c = coverage(x, y); if c == 0 { continue; } let pixel = &mut self.pixels[start + x as usize]; *pixel = blend(*pixel, color.0, c * a / 255); } } } /// A circle of `radius` around (cx, cy), its edge anti-aliased. pub fn fill_circle(&mut self, cx: i32, cy: i32, radius: i32, color: Color) { self.fill_rounded( Rect::new(cx - radius, cy - radius, 2 * radius, 2 * radius), radius, color, ); } /// Copies `rect` of `from` (the same size as this canvas) here. pub fn copy_from(&mut self, from: &[u32], rect: Rect) { let r = rect.intersect(&self.clip); for y in r.y..r.bottom() { let start = y as usize * self.stride; let (a, b) = (start + r.x as usize, start + r.right() as usize); self.pixels[a..b].copy_from_slice(&from[a..b]); } } /// Copies `source` (`width` pixels a row) with its top left at (x, y). pub fn blit(&mut self, source: &[u32], width: i32, height: i32, x: i32, y: i32) { let r = Rect::new(x, y, width, height).intersect(&self.clip); for row in r.y..r.bottom() { let from = ((row - y) * width + (r.x - x)) as usize; let count = r.width as usize; let to = row as usize * self.stride + r.x as usize; self.pixels[to..to + count].copy_from_slice(&source[from..from + count]); } } /// Blends 8-bit coverage `alpha` (`width` a row) in `color` at (x, y). pub fn draw_mask(&mut self, alpha: &[u8], width: i32, height: i32, x: i32, y: i32, color: Color) { let r = Rect::new(x, y, width, height).intersect(&self.clip); for row in r.y..r.bottom() { let from = ((row - y) * width + (r.x - x)) as usize; let to = row as usize * self.stride + r.x as usize; for i in 0..r.width as usize { let a = u32::from(alpha[from + i]); if a != 0 { self.pixels[to + i] = blend(self.pixels[to + i], color.0, a); } } } } /// Blends an image of its own colours at (x, y): `colors` 0x00RRGGBB /// and `alpha` its coverage (0–255), both `width` a row. An app icon. pub fn draw_image(&mut self, colors: &[u32], alpha: &[u8], width: i32, height: i32, x: i32, y: i32) { let r = Rect::new(x, y, width, height).intersect(&self.clip); for row in r.y..r.bottom() { let from = ((row - y) * width + (r.x - x)) as usize; let to = row as usize * self.stride + r.x as usize; for i in 0..r.width as usize { let a = u32::from(alpha[from + i]); if a != 0 { self.pixels[to + i] = blend(self.pixels[to + i], colors[from + i], a); } } } } /// A line through `points`, `width` thick, with round ends and joins, /// its edges anti-aliased: a tick, a pen's stroke. pub fn stroke_polyline(&mut self, points: &[(f32, f32)], width: f32, color: Color, alpha: u8) { let Some(&(x0, y0)) = points.first() else { return; }; let r = width / 2.0; let (mut left, mut top, mut right, mut bottom) = (x0, y0, x0, y0); for &(x, y) in points { left = left.min(x); top = top.min(y); right = right.max(x); bottom = bottom.max(y); } let ox = (left - r) as i32 - 2; let oy = (top - r) as i32 - 2; let w = (right + r) as i32 + 3 - ox; let h = (bottom + r) as i32 + 3 - oy; if Rect::new(ox, oy, w, h).intersect(&self.clip).is_empty() { return; } let (fx, fy) = (ox as f32, oy as f32); // Every piece wound the same way as the circles, so where they // overlap they add rather than cancel. let mut path = pinnacle_vector::Path::new(); for &(x, y) in points { path.append(&pinnacle_vector::Path::circle(x - fx, y - fy, r)); } for pair in points.windows(2) { let ((ax, ay), (bx, by)) = ((pair[0].0 - fx, pair[0].1 - fy), (pair[1].0 - fx, pair[1].1 - fy)); let (dx, dy) = (bx - ax, by - ay); let len = sqrt(dx * dx + dy * dy); if len < 0.01 { continue; } let (nx, ny) = (-dy / len * r, dx / len * r); let mut quad = [ (ax + nx, ay + ny), (bx + nx, by + ny), (bx - nx, by - ny), (ax - nx, ay - ny), ]; let area: f32 = (0..4) .map(|i| { let (p, q) = (quad[i], quad[(i + 1) % 4]); p.0 * q.1 - q.0 * p.1 }) .sum(); if area < 0.0 { quad.reverse(); } path.move_to(quad[0].0, quad[0].1); for p in &quad[1..] { path.line_to(p.0, p.1); } path.close(); } let mut mask = pinnacle_vector::mask(&path, w as usize, h as usize); if alpha != 255 { for a in &mut mask { *a = ((u32::from(*a) * u32::from(alpha) + 127) / 255) as u8; } } self.draw_mask(&mask, w, h, ox, oy, color); } /// Draws `text` with its baseline at `y`, starting at `x`. Returns the /// x after the last glyph. pub fn text(&mut self, font: &Font, x: i32, y: i32, text: &str, color: Color) -> i32 { let (glyphs, width) = font.layout(text); for placed in &glyphs { let glyph = &placed.glyph; let pen = x * 16 + placed.x; let (gx, gy) = (pen / 16 + glyph.left, y + placed.y / 16 - glyph.top); self.draw_mask(&glyph.coverage, glyph.width, glyph.height, gx, gy, color); } (x * 16 + width) / 16 } /// Draws `text` centred in `rect`, vertically by the font's line. pub fn text_centered(&mut self, font: &Font, rect: Rect, text: &str, color: Color) { let width = font.measure(text); let x = rect.x + (rect.width - width) / 2; let y = rect.y + (rect.height + font.ascent - font.descent) / 2; self.text(font, x, y, text, color); } } /// The square root, by Newton's method from the exponent's halving (there /// is no `f32::sqrt` without `std`). fn sqrt(v: f32) -> f32 { if v <= 0.0 { return 0.0; } let mut x = f32::from_bits((v.to_bits() >> 1) + 0x1fbd_1df5); for _ in 0..3 { x = 0.5 * (x + v / x); } x } /// Radii no larger than half the shorter side. fn clamp_radii(rect: &Rect, radii: [i32; 4]) -> [i32; 4] { let half = rect.width.min(rect.height) / 2; radii.map(|r| r.clamp(0, half.max(0))) } /// How much (0–255) of pixel (x, y) lies inside `rect` with corner `radii`. fn round_cover(rect: &Rect, radii: &[i32; 4], x: i32, y: i32) -> u32 { if !rect.contains(x, y) { return 0; } let (r, cx, cy) = if x < rect.x + radii[0] && y < rect.y + radii[0] { (radii[0], rect.x + radii[0], rect.y + radii[0]) } else if x >= rect.right() - radii[1] && y < rect.y + radii[1] { (radii[1], rect.right() - radii[1], rect.y + radii[1]) } else if x >= rect.right() - radii[2] && y >= rect.bottom() - radii[2] { (radii[2], rect.right() - radii[2], rect.bottom() - radii[2]) } else if x < rect.x + radii[3] && y >= rect.bottom() - radii[3] { (radii[3], rect.x + radii[3], rect.bottom() - radii[3]) } else { return 255; }; // From the corner circle's centre to the pixel's, in 1/16 pixels. coverage(x * 16 + 8 - cx * 16, y * 16 + 8 - cy * 16, r * 16) } /// How much of a pixel at (x, y) from a circle's centre, in 1/16 pixels, lies /// inside a circle of radius `r` (also 1/16 pixels): 0–255 across the one /// pixel of the edge. fn coverage(x: i32, y: i32, r: i32) -> u32 { let d2 = (x * x + y * y) as u32; let inner = (r - 8).max(0) as u32; let outer = (r + 8) as u32; if d2 <= inner * inner { 255 } else if d2 >= outer * outer { 0 } else { // Linear across the edge's 16 sixteenths, by squared distance. let span = outer * outer - inner * inner; 255 - (d2 - inner * inner) * 255 / span } }