From b06d33b66e70453451bc5eb5ade9164defea4849 Mon Sep 17 00:00:00 2001 From: Akshay Date: Sun, 28 Mar 2021 09:51:41 +0530 Subject: implement flood fill; new fill brush --- src/bitmap.rs | 37 +++++++++++++++++++++++++++++-------- 1 file changed, 29 insertions(+), 8 deletions(-) (limited to 'src/bitmap.rs') diff --git a/src/bitmap.rs b/src/bitmap.rs index c7e8fd4..41af745 100644 --- a/src/bitmap.rs +++ b/src/bitmap.rs @@ -54,8 +54,8 @@ impl Add for MapPoint { type Output = Self; fn add(self, rhs: Self) -> Self::Output { MapPoint { - x: self.x + rhs.x, - y: self.y + rhs.y, + x: self.x.saturating_add(rhs.x), + y: self.y.saturating_add(rhs.y), } } } @@ -64,8 +64,8 @@ impl Sub for MapPoint { type Output = Self; fn sub(self, rhs: Self) -> Self::Output { MapPoint { - x: self.x - rhs.x, - y: self.y - rhs.y, + x: self.x.saturating_sub(rhs.x), + y: self.y.saturating_sub(rhs.y), } } } @@ -102,7 +102,7 @@ impl MapPoint { impl Pixmap where - T: Copy + Clone + Default, + T: Copy + Clone + Default + PartialEq, { pub fn new(width: u32, height: u32) -> Self { let data = vec![Default::default(); (width * height) as usize]; @@ -121,7 +121,7 @@ where } } - pub fn is_inside>(&self, pt: P) -> bool { + pub fn contains>(&self, pt: P) -> bool { let MapPoint { x, y } = pt.into(); x < self.width && y < self.height } @@ -181,7 +181,7 @@ where circle .into_iter() .flat_map(|pt| MapPoint::try_from(pt)) - .filter(|&pt| self.is_inside(pt)) + .filter(|&pt| self.contains(pt)) .collect() } @@ -226,9 +226,30 @@ where coordinates .into_iter() .flat_map(|pt| MapPoint::try_from(pt)) - .filter(|&pt| self.is_inside(pt)) + .filter(|&pt| self.contains(pt)) .collect() } + + pub fn flood_fill( + &mut self, + start: MapPoint, + target: T, + replacement: T, + pts: &mut Vec, + ) { + if !self.contains(start) || self.get(start) != target || self.get(start) == replacement { + return; + } else { + pts.push(start); + self.set(start, replacement); + for (x, y) in [(1, 0), (0, 1), (-1, 0), (0, -1)].iter() { + let dir = MapPoint::try_from((start.x as i64 - x, start.y as i64 + y)); + if let Ok(pt) = dir { + self.flood_fill(pt, target, replacement, pts); + } + } + } + } } impl Pixmap { -- cgit v1.2.3