From b21cdef8b0c25b9eb8f1553b0579b159f9db1786 Mon Sep 17 00:00:00 2001 From: Torrie Fischer Date: Sun, 15 Dec 2024 17:48:20 +0100 Subject: [PATCH] lib8: interpolate: optimize some edge cases for blending --- src/lib8/interpolate.rs | 33 +++++++++++++++++++++++---------- 1 file changed, 23 insertions(+), 10 deletions(-) diff --git a/src/lib8/interpolate.rs b/src/lib8/interpolate.rs index a338931..b23def6 100644 --- a/src/lib8/interpolate.rs +++ b/src/lib8/interpolate.rs @@ -12,12 +12,21 @@ pub trait Fract8Ops { impl Fract8Ops for u8 { fn scale8(self, scale: Fract8) -> Self { - // borrowed from FastLED - (self as u16 * (1 + scale as u16)).unsigned_shr(8) as u8 + match scale { + 0 => 0, + 255 => self, + _ => + // borrowed from FastLED + (self as u16 * (1 + scale as u16)).unsigned_shr(8) as u8 + } } fn blend8(self, other: Self, scale: Fract8) -> Self { - ((((self as u16).unsigned_shl(8).bitor(other as u16)) as u16).wrapping_add(other as u16 * scale as u16).wrapping_sub(self as u16 * scale as u16)).unsigned_shr(8) as u8 + match scale { + 0 => self, + 255 => other, + _ => ((((self as u16).unsigned_shl(8).bitor(other as u16)) as u16).wrapping_add(other as u16 * scale as u16).wrapping_sub(self as u16 * scale as u16)).unsigned_shr(8) as u8 + } } } @@ -31,13 +40,17 @@ impl Fract8Ops for Rgb { } fn blend8(self, other: Self, scale: Fract8) -> Self { - match (other.r, other.g, other.b) { - (0, 0, 0) => self, - _ => Rgb::new( - self.r.blend8(other.r, scale), - self.g.blend8(other.g, scale), - self.b.blend8(other.b, scale) - ) + match scale { + 0 => self, + 255 => other, + _ => match (other.r, other.g, other.b) { + (0, 0, 0) => self, + _ => Rgb::new( + self.r.blend8(other.r, scale), + self.g.blend8(other.g, scale), + self.b.blend8(other.b, scale) + ) + } } } }