//! Pixel tools on a bitmap layer's raster: brush, pencil, eraser, fill bucket, magic wand, rectangle and lasso //! selections, delete and copy, adjustments, blur, sharpen, invert, clone stamp, and applying a matte (background //! removal). Each returns the rectangle it changed, so the caller can record one exact undo patch. use crate::model::{Document, PixelRect, Raster}; use crate::ops::Op; /// A selection: one coverage byte per pixel of the raster it belongs to. #[derive(Clone, Debug, PartialEq)] pub struct Mask { pub width: u32, pub height: u32, pub data: Vec, } impl Mask { pub fn empty(width: u32, height: u32) -> Mask { Mask { width, height, data: vec![0; width as usize * height as usize] } } pub fn rect(width: u32, height: u32, r: PixelRect) -> Mask { let mut m = Mask::empty(width, height); let r = r.clamp(width, height); for y in r.y..r.y + r.h { let row = y as usize * width as usize; m.data[row + r.x as usize..row + (r.x + r.w) as usize].fill(255); } m } /// A polygon (lasso), anti-aliased at its edge. pub fn polygon(width: u32, height: u32, points: &[(f32, f32)]) -> Mask { let mut m = Mask::empty(width, height); if points.len() < 3 { return m; } let mut pb = tiny_skia::PathBuilder::new(); pb.move_to(points[0].0, points[0].1); for p in &points[1..] { pb.line_to(p.0, p.1); } pb.close(); let (Some(path), Some(mut sm)) = (pb.finish(), tiny_skia::Mask::new(width, height)) else { return m }; sm.fill_path(&path, tiny_skia::FillRule::EvenOdd, true, tiny_skia::Transform::identity()); m.data.copy_from_slice(sm.data()); m } pub fn get(&self, x: u32, y: u32) -> u8 { self.data[y as usize * self.width as usize + x as usize] } pub fn is_empty(&self) -> bool { self.data.iter().all(|v| *v == 0) } pub fn bbox(&self) -> PixelRect { let (mut x0, mut y0, mut x1, mut y1) = (u32::MAX, u32::MAX, 0, 0); for y in 0..self.height { for x in 0..self.width { if self.get(x, y) > 0 { x0 = x0.min(x); y0 = y0.min(y); x1 = x1.max(x + 1); y1 = y1.max(y + 1); } } } if x0 == u32::MAX { PixelRect { x: 0, y: 0, w: 0, h: 0 } } else { PixelRect { x: x0, y: y0, w: x1 - x0, h: y1 - y0 } } } pub fn invert(&mut self) { for v in &mut self.data { *v = 255 - *v; } } /// The selection's edge as path data (pixel edges between inside and outside), for the marching ants. pub fn outline(&self) -> String { use std::fmt::Write; let inside = |x: i64, y: i64| { x >= 0 && y >= 0 && x < self.width as i64 && y < self.height as i64 && self.get(x as u32, y as u32) >= 128 }; let mut d = String::new(); // Horizontal edges, merged along each row. for y in 0..=self.height as i64 { let mut start: Option = None; for x in 0..=self.width as i64 { let edge = x < self.width as i64 && inside(x, y) != inside(x, y - 1); match (edge, start) { (true, None) => start = Some(x), (false, Some(s)) => { let _ = write!(d, "M{s} {y}H{x}"); start = None; } _ => {} } } } for x in 0..=self.width as i64 { let mut start: Option = None; for y in 0..=self.height as i64 { let edge = y < self.height as i64 && inside(x, y) != inside(x - 1, y); match (edge, start) { (true, None) => start = Some(y), (false, Some(s)) => { let _ = write!(d, "M{x} {s}V{y}"); start = None; } _ => {} } } } d } } fn sel(mask: Option<&Mask>, x: u32, y: u32) -> f32 { mask.map(|m| m.get(x, y) as f32 / 255.0).unwrap_or(1.0) } /// Source-over in straight alpha: `src` (straight RGBA) with extra coverage `cov` onto `dst`. fn blend(dst: &mut [u8], src: [u8; 4], cov: f32) { let sa = src[3] as f32 / 255.0 * cov; if sa <= 0.0 { return; } let da = dst[3] as f32 / 255.0; let oa = sa + da * (1.0 - sa); if oa <= 0.0 { dst.copy_from_slice(&[0, 0, 0, 0]); return; } for i in 0..3 { let v = (src[i] as f32 * sa + dst[i] as f32 * da * (1.0 - sa)) / oa; dst[i] = v.round().clamp(0.0, 255.0) as u8; } dst[3] = (oa * 255.0).round().clamp(0.0, 255.0) as u8; } #[derive(Clone, Copy, Debug)] pub struct Brush { /// Radius in pixels at full pressure. pub radius: f32, /// 0 = soft to the centre, 1 = a hard edge. pub hardness: f32, pub color: [u8; 4], /// 0..1 for the whole stroke (a stroke never builds up over itself). pub opacity: f32, pub erase: bool, } /// Stroke coverage (0..1) over a rectangle: dabs along the points, the maximum where they overlap. struct Coverage { rect: PixelRect, cov: Vec, } fn coverage(width: u32, height: u32, points: &[(f32, f32, f32)], radius: f32, hardness: f32) -> Coverage { let r = radius.max(0.5); let (mut x0, mut y0, mut x1, mut y1) = (f32::MAX, f32::MAX, f32::MIN, f32::MIN); for (x, y, _) in points { x0 = x0.min(x - r - 1.0); y0 = y0.min(y - r - 1.0); x1 = x1.max(x + r + 1.0); y1 = y1.max(y + r + 1.0); } let rect = PixelRect { x: x0.max(0.0) as u32, y: y0.max(0.0) as u32, w: (x1.min(width as f32).max(0.0) - x0.max(0.0)).max(0.0).ceil() as u32, h: (y1.min(height as f32).max(0.0) - y0.max(0.0)).max(0.0).ceil() as u32, } .clamp(width, height); let mut cov = vec![0f32; rect.w as usize * rect.h as usize]; let hard = hardness.clamp(0.0, 0.99); let mut dab = |cx: f32, cy: f32, pr: f32| { let rr = (r * pr.clamp(0.05, 1.0)).max(0.5); let bx0 = ((cx - rr - 1.0).floor().max(rect.x as f32)) as u32; let by0 = ((cy - rr - 1.0).floor().max(rect.y as f32)) as u32; let bx1 = ((cx + rr + 1.0).ceil().min((rect.x + rect.w) as f32)) as u32; let by1 = ((cy + rr + 1.0).ceil().min((rect.y + rect.h) as f32)) as u32; for y in by0..by1 { for x in bx0..bx1 { let d = (((x as f32 + 0.5 - cx).powi(2) + (y as f32 + 0.5 - cy).powi(2)).sqrt()) / rr; // A hard core, then a smooth fall to the edge; half a pixel of anti-aliasing at any size. let edge = 1.0 - (d * rr - rr + 0.5).clamp(0.0, 1.0); let a = if d <= hard { edge } else { let t = ((d - hard) / (1.0 - hard)).clamp(0.0, 1.0); (1.0 - t * t * (3.0 - 2.0 * t)).min(edge) }; let i = (y - rect.y) as usize * rect.w as usize + (x - rect.x) as usize; if a > cov[i] { cov[i] = a; } } } }; if let Some(&(x, y, p)) = points.first() { dab(x, y, p); } for w in points.windows(2) { let (ax, ay, ap) = w[0]; let (bx, by, bp) = w[1]; let len = ((bx - ax).powi(2) + (by - ay).powi(2)).sqrt(); let step = (r * ap.min(bp).clamp(0.05, 1.0) * 0.25).max(0.5); let n = (len / step).ceil().max(1.0) as usize; for i in 1..=n { let t = i as f32 / n as f32; dab(ax + (bx - ax) * t, ay + (by - ay) * t, ap + (bp - ap) * t); } } Coverage { rect, cov } } /// Brush or eraser along `points` (x, y, pressure 0..1). pub fn brush(r: &mut Raster, points: &[(f32, f32, f32)], b: &Brush, mask: Option<&Mask>) -> PixelRect { if points.is_empty() { return PixelRect { x: 0, y: 0, w: 0, h: 0 }; } let c = coverage(r.width, r.height, points, b.radius, b.hardness); for y in 0..c.rect.h { for x in 0..c.rect.w { let (px, py) = (c.rect.x + x, c.rect.y + y); let k = c.cov[(y * c.rect.w + x) as usize] * b.opacity.clamp(0.0, 1.0) * sel(mask, px, py); if k <= 0.0 { continue; } let i = (py as usize * r.width as usize + px as usize) * 4; let dst = &mut r.rgba[i..i + 4]; if b.erase { let a = dst[3] as f32 * (1.0 - k * b.color[3] as f32 / 255.0); dst[3] = a.round() as u8; } else { blend(dst, b.color, k); } } } c.rect } /// Pencil: hard square pixels of `size` along the points, no anti-aliasing. pub fn pencil( r: &mut Raster, points: &[(f32, f32)], size: u32, color: [u8; 4], erase: bool, mask: Option<&Mask>, ) -> PixelRect { let mut dirty = PixelRect { x: 0, y: 0, w: 0, h: 0 }; let s = size.max(1) as i64; let mut put = |x: i64, y: i64, r: &mut Raster| { let x0 = x - (s - 1) / 2; let y0 = y - (s - 1) / 2; for yy in y0..y0 + s { for xx in x0..x0 + s { if xx < 0 || yy < 0 || xx >= r.width as i64 || yy >= r.height as i64 { continue; } let k = sel(mask, xx as u32, yy as u32); if k <= 0.0 { continue; } let i = (yy as usize * r.width as usize + xx as usize) * 4; if erase { r.rgba[i + 3] = (r.rgba[i + 3] as f32 * (1.0 - k)).round() as u8; } else if k >= 1.0 { r.rgba[i..i + 4].copy_from_slice(&color); } else { blend(&mut r.rgba[i..i + 4], color, k); } dirty = dirty.union(PixelRect { x: xx as u32, y: yy as u32, w: 1, h: 1 }); } } }; let pts: Vec<(i64, i64)> = points.iter().map(|(x, y)| (x.floor() as i64, y.floor() as i64)).collect(); if let Some(&(x, y)) = pts.first() { put(x, y, r); } for w in pts.windows(2) { // Bresenham. let (mut x0, mut y0) = w[0]; let (x1, y1) = w[1]; let (dx, dy) = ((x1 - x0).abs(), -(y1 - y0).abs()); let (sx, sy) = (if x0 < x1 { 1 } else { -1 }, if y0 < y1 { 1 } else { -1 }); let mut err = dx + dy; loop { put(x0, y0, r); if x0 == x1 && y0 == y1 { break; } let e2 = 2 * err; if e2 >= dy { err += dy; x0 += sx; } if e2 <= dx { err += dx; y0 += sy; } } } dirty } /// Whether a pixel belongs with the seed: transparent with transparent (by alpha), visible with visible by colour /// alone, so a stroke's soft, half-transparent edge goes with the stroke. fn close(a: &[u8], b: [u8; 4], tol: u8) -> bool { if b[3] == 0 { return a[3] <= tol; } if a[3] == 0 { return false; } (0..3).all(|i| (a[i] as i16 - b[i] as i16).unsigned_abs() <= tol as u16) } /// The region around (x, y) whose pixels are within `tol` of its colour (4-connected). pub fn region(r: &Raster, x: u32, y: u32, tol: u8) -> Mask { let mut m = Mask::empty(r.width, r.height); if x >= r.width || y >= r.height { return m; } let seed = r.pixel(x, y); let w = r.width as usize; let mut stack = vec![(x, y)]; while let Some((sx, sy)) = stack.pop() { // Scanline fill: walk left and right, then queue the rows above and below. let row = sy as usize * w; if m.data[row + sx as usize] != 0 { continue; } let px = |xx: u32| &r.rgba[(row + xx as usize) * 4..(row + xx as usize) * 4 + 4]; let mut l = sx; while l > 0 && m.data[row + l as usize - 1] == 0 && close(px(l - 1), seed, tol) { l -= 1; } let mut rr = sx; while rr + 1 < r.width && m.data[row + rr as usize + 1] == 0 && close(px(rr + 1), seed, tol) { rr += 1; } for xx in l..=rr { m.data[row + xx as usize] = 255; } for ny in [sy.wrapping_sub(1), sy + 1] { if ny >= r.height { continue; } let nrow = ny as usize * w; let mut xx = l; while xx <= rr { let i = nrow + xx as usize; if m.data[i] == 0 && close(&r.rgba[i * 4..i * 4 + 4], seed, tol) { stack.push((xx, ny)); // Skip the rest of this run; it is filled from the pushed seed. while xx <= rr && close(&r.rgba[(nrow + xx as usize) * 4..(nrow + xx as usize) * 4 + 4], seed, tol) { xx += 1; } } else { xx += 1; } } } } m } /// Fill bucket: the region around (x, y) becomes `color` (inside the selection, if any). pub fn fill(r: &mut Raster, x: u32, y: u32, tol: u8, color: [u8; 4], mask: Option<&Mask>) -> PixelRect { let reg = region(r, x, y, tol); let b = reg.bbox(); for yy in b.y..b.y + b.h { for xx in b.x..b.x + b.w { if reg.get(xx, yy) == 0 { continue; } let k = sel(mask, xx, yy); let i = (yy as usize * r.width as usize + xx as usize) * 4; if k >= 1.0 { r.rgba[i..i + 4].copy_from_slice(&color); } else if k > 0.0 { let old: [u8; 4] = r.rgba[i..i + 4].try_into().unwrap(); for c in 0..4 { r.rgba[i + c] = (old[c] as f32 + (color[c] as f32 - old[c] as f32) * k).round() as u8; } } } } b } /// Delete: the selected pixels (or all) become transparent. pub fn clear(r: &mut Raster, mask: Option<&Mask>) -> PixelRect { let b = mask.map(|m| m.bbox()).unwrap_or(PixelRect { x: 0, y: 0, w: r.width, h: r.height }); for y in b.y..b.y + b.h { for x in b.x..b.x + b.w { let k = sel(mask, x, y); let i = (y as usize * r.width as usize + x as usize) * 4 + 3; r.rgba[i] = (r.rgba[i] as f32 * (1.0 - k)).round() as u8; } } b } /// Copy: the selected pixels (alpha × selection) in their bounding box, and where that box is. pub fn copy(r: &Raster, mask: Option<&Mask>) -> (Raster, PixelRect) { let b = mask.map(|m| m.bbox()).unwrap_or(PixelRect { x: 0, y: 0, w: r.width, h: r.height }); let mut out = r.crop(b); if let Some(m) = mask { for y in 0..b.h { for x in 0..b.w { let i = (y as usize * b.w as usize + x as usize) * 4 + 3; out.rgba[i] = (out.rgba[i] as u32 * m.get(b.x + x, b.y + y) as u32 / 255) as u8; } } } (out, b) } #[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)] #[serde(tag = "type", rename_all = "snake_case")] pub enum Adjust { /// −100..100. Brightness { amount: f32, }, /// −100..100. Contrast { amount: f32, }, /// Input black and white points (0..255), gamma (0.1..10), output black and white. Levels { in_black: f32, in_white: f32, gamma: f32, out_black: f32, out_white: f32, }, /// Hue in degrees, saturation and lightness −100..100. HueSaturation { hue: f32, saturation: f32, lightness: f32, }, Invert, /// Radius in pixels. Blur { radius: f32, }, /// Amount 0..5, radius in pixels. Sharpen { amount: f32, radius: f32, }, } fn rgb_to_hsl(r: f32, g: f32, b: f32) -> (f32, f32, f32) { let max = r.max(g).max(b); let min = r.min(g).min(b); let l = (max + min) / 2.0; if max == min { return (0.0, 0.0, l); } let d = max - min; let s = if l > 0.5 { d / (2.0 - max - min) } else { d / (max + min) }; let h = if max == r { (g - b) / d + if g < b { 6.0 } else { 0.0 } } else if max == g { (b - r) / d + 2.0 } else { (r - g) / d + 4.0 }; (h * 60.0, s, l) } fn hsl_to_rgb(h: f32, s: f32, l: f32) -> (f32, f32, f32) { if s == 0.0 { return (l, l, l); } let q = if l < 0.5 { l * (1.0 + s) } else { l + s - l * s }; let p = 2.0 * l - q; let hue = |mut t: f32| { t = t.rem_euclid(1.0); if t < 1.0 / 6.0 { p + (q - p) * 6.0 * t } else if t < 0.5 { q } else if t < 2.0 / 3.0 { p + (q - p) * (2.0 / 3.0 - t) * 6.0 } else { p } }; let h = h / 360.0; (hue(h + 1.0 / 3.0), hue(h), hue(h - 1.0 / 3.0)) } /// A box blur of premultiplied RGBA, three passes (close to a Gaussian). fn blurred(src: &Raster, radius: f32) -> Vec { let (w, h) = (src.width as usize, src.height as usize); let mut buf: Vec = Vec::with_capacity(w * h * 4); for p in src.rgba.as_chunks::<4>().0 { let a = p[3] as f32 / 255.0; buf.extend_from_slice(&[p[0] as f32 * a, p[1] as f32 * a, p[2] as f32 * a, p[3] as f32]); } let r = ((radius / 3.0f32.sqrt()).round() as usize).max(1); let mut tmp = vec![0f32; buf.len()]; for _ in 0..3 { for horizontal in [true, false] { let (n, m) = if horizontal { (h, w) } else { (w, h) }; for line in 0..n { let idx = |k: usize| if horizontal { (line * w + k) * 4 } else { (k * w + line) * 4 }; let mut acc = [0f32; 4]; let count = (2 * r + 1) as f32; // Edge pixels repeat beyond the border. for k in 0..(2 * r + 1) { let kk = (k as isize - r as isize).clamp(0, m as isize - 1) as usize; for c in 0..4 { acc[c] += buf[idx(kk) + c]; } } for k in 0..m { for c in 0..4 { tmp[idx(k) + c] = acc[c] / count; } let out = (k as isize - r as isize).clamp(0, m as isize - 1) as usize; let inn = (k as isize + r as isize + 1).clamp(0, m as isize - 1) as usize; for c in 0..4 { acc[c] += buf[idx(inn) + c] - buf[idx(out) + c]; } } } std::mem::swap(&mut buf, &mut tmp); } } buf } /// Writes the adjustment of `src` into `dst` (the same size), inside the selection; `dst` may start as a copy of /// `src` (a live preview re-runs this from the untouched original). pub fn adjust(src: &Raster, dst: &mut Raster, a: &Adjust, mask: Option<&Mask>) -> PixelRect { let b = mask.map(|m| m.bbox()).unwrap_or(PixelRect { x: 0, y: 0, w: src.width, h: src.height }); let blur = match a { Adjust::Blur { radius } | Adjust::Sharpen { radius, .. } => Some(blurred(src, radius.max(0.5))), _ => None, }; let lut = |f: &dyn Fn(f32) -> f32| -> [u8; 256] { let mut t = [0u8; 256]; for (i, v) in t.iter_mut().enumerate() { *v = f(i as f32).round().clamp(0.0, 255.0) as u8; } t }; let table: Option<[u8; 256]> = match *a { Adjust::Brightness { amount } => Some(lut(&|v| v + amount * 2.55)), Adjust::Contrast { amount } => { let c = amount.clamp(-100.0, 100.0) * 2.55; let f = (259.0 * (c + 255.0)) / (255.0 * (259.0 - c)); Some(lut(&|v| f * (v - 128.0) + 128.0)) } Adjust::Levels { in_black, in_white, gamma, out_black, out_white } => { let span = (in_white - in_black).max(1.0); let g = gamma.clamp(0.1, 10.0); Some(lut(&|v| { let t = ((v - in_black) / span).clamp(0.0, 1.0).powf(1.0 / g); out_black + t * (out_white - out_black) })) } Adjust::Invert => Some(lut(&|v| 255.0 - v)), _ => None, }; for y in b.y..b.y + b.h { for x in b.x..b.x + b.w { let k = sel(mask, x, y); let i = (y as usize * src.width as usize + x as usize) * 4; let s: [u8; 4] = src.rgba[i..i + 4].try_into().unwrap(); let out: [u8; 4] = match (a, &table, &blur) { (_, Some(t), _) => [t[s[0] as usize], t[s[1] as usize], t[s[2] as usize], s[3]], (Adjust::HueSaturation { hue, saturation, lightness }, _, _) => { let (h, sat, l) = rgb_to_hsl(s[0] as f32 / 255.0, s[1] as f32 / 255.0, s[2] as f32 / 255.0); let sat = (sat * (1.0 + saturation / 100.0)).clamp(0.0, 1.0); let l = if *lightness >= 0.0 { l + (1.0 - l) * lightness / 100.0 } else { l * (1.0 + lightness / 100.0) }; let (r, g, bb) = hsl_to_rgb(h + hue, sat, l.clamp(0.0, 1.0)); [(r * 255.0).round() as u8, (g * 255.0).round() as u8, (bb * 255.0).round() as u8, s[3]] } (Adjust::Blur { .. }, _, Some(bl)) => { let a = bl[i + 3]; if a <= 0.0 { [0, 0, 0, 0] } else { let f = 255.0 / a; [ (bl[i] * f).round().min(255.0) as u8, (bl[i + 1] * f).round().min(255.0) as u8, (bl[i + 2] * f).round().min(255.0) as u8, a.round() as u8, ] } } (Adjust::Sharpen { amount, .. }, _, Some(bl)) => { let a = (bl[i + 3] / 255.0).max(1e-3); let mut o = [0u8; 4]; for c in 0..3 { let blur_c = bl[i + c] / a; o[c] = (s[c] as f32 + amount * (s[c] as f32 - blur_c)).round().clamp(0.0, 255.0) as u8; } o[3] = s[3]; o } _ => s, }; let d = &mut dst.rgba[i..i + 4]; if k >= 1.0 { d.copy_from_slice(&out); } else if k > 0.0 { for c in 0..4 { d[c] = (s[c] as f32 + (out[c] as f32 - s[c] as f32) * k).round() as u8; } } else { d.copy_from_slice(&s); } } } b } /// Clone stamp: dabs that copy from `source` (the layer as it was when the stroke began) at an offset. pub fn clone_stamp( r: &mut Raster, source: &Raster, offset: (f32, f32), points: &[(f32, f32, f32)], b: &Brush, mask: Option<&Mask>, ) -> PixelRect { if points.is_empty() { return PixelRect { x: 0, y: 0, w: 0, h: 0 }; } let c = coverage(r.width, r.height, points, b.radius, b.hardness); for y in 0..c.rect.h { for x in 0..c.rect.w { let (px, py) = (c.rect.x + x, c.rect.y + y); let k = c.cov[(y * c.rect.w + x) as usize] * b.opacity.clamp(0.0, 1.0) * sel(mask, px, py); if k <= 0.0 { continue; } let sx = px as f32 + offset.0; let sy = py as f32 + offset.1; if sx < 0.0 || sy < 0.0 || sx >= source.width as f32 || sy >= source.height as f32 { continue; } let s = source.pixel(sx as u32, sy as u32); let i = (py as usize * r.width as usize + px as usize) * 4; blend(&mut r.rgba[i..i + 4], s, k); } } c.rect } /// Multiplies the alpha by a matte (0..255 per pixel, the raster's size): background removal as a layer action. pub fn apply_matte(r: &mut Raster, matte: &[u8]) -> PixelRect { for (p, m) in r.rgba.as_chunks_mut::<4>().0.iter_mut().zip(matte) { p[3] = (p[3] as u32 * *m as u32 / 255) as u8; } PixelRect { x: 0, y: 0, w: r.width, h: r.height } } /// Runs a pixel edit on an asset and returns the operation and its inverse (already applied), for /// `History::record`; none when nothing changed or the asset is missing. pub fn edit(doc: &mut Document, asset: &str, f: impl FnOnce(&mut Raster) -> PixelRect) -> Option<(Op, Op)> { let r = doc.assets.get_mut(asset)?; let before = r.clone(); let rect = f(r).clamp(r.width, r.height); if rect.is_empty() { return None; } let after = r.crop(rect); let old = before.crop(rect); if after == old { return None; } Some(( Op::Patch { asset: asset.to_string(), rect, pixels: after.rgba }, Op::Patch { asset: asset.to_string(), rect, pixels: old.rgba }, )) }