From 3a8dd89828b249470b88b1b964f6a99f2006cd95 Mon Sep 17 00:00:00 2001 From: Victoria Fischer Date: Sat, 16 Nov 2024 11:39:28 +0100 Subject: [PATCH] lib8: rewrite hsv2rgb implementation based on fastled --- src/lib8.rs | 37 ++++++++++++++++++++++--------------- 1 file changed, 22 insertions(+), 15 deletions(-) diff --git a/src/lib8.rs b/src/lib8.rs index c44897d..5b2bb3f 100644 --- a/src/lib8.rs +++ b/src/lib8.rs @@ -23,25 +23,32 @@ impl IntoRgb8 for RGB8 { } impl IntoRgb8 for palette::Hsv { + //TODO: Borrowed from FastLED fn into_rgb8(self) -> RGB8 { - if self.saturation == 0 { - return RGB8::new(self.value, self.value, self.value); - } + const HSV_SECTION_3: u8 = 0x40; - let region = self.hue.into_inner() / 43; - let remainder = (self.hue.into_inner() - (region * 43)) * 6; + let value: u8 = self.value; + let saturation: u8 = self.saturation; + let invsat: u8 = 255 - saturation; + let brightness_floor: u8 = (value as u16 * invsat as u16 / 256) as u8; - let p = self.value.wrapping_mul(255 - self.saturation).wrapping_shr(8); - let q = (self.value.wrapping_mul(255 - ((self.saturation.wrapping_mul(remainder)).wrapping_shr(8)))).wrapping_shr(8); - let t = (self.value.wrapping_mul(255 - ((self.saturation.wrapping_mul(255 - remainder)).wrapping_shr(8)))).wrapping_shr(8); + let color_amplitude: u8 = value - brightness_floor; + let section: u8 = self.hue.into_inner() / HSV_SECTION_3; + let offset: u8 = self.hue.into_inner() % HSV_SECTION_3; - match region { - 0 => RGB8::new(self.value, t, p), - 1 => RGB8::new(q, self.value, p), - 2 => RGB8::new(p, self.value, t), - 3 => RGB8::new(p, q, self.value), - 4 => RGB8::new(t, p, self.value), - _ => RGB8::new(self.value, p, q) + let rampup: u8 = offset; + let rampdown: u8 = (HSV_SECTION_3 - 1) - offset; + + let rampup_amp_adj: u8 = (rampup as u16 * color_amplitude as u16 / (256 / 4)) as u8; + let rampdown_amp_adj: u8 = (rampdown as u16 * color_amplitude as u16 / (256 / 4)) as u8; + + let rampup_adj_with_floor: u8 = rampup_amp_adj + brightness_floor; + let rampdown_adj_with_floor: u8 = rampdown_amp_adj + brightness_floor; + + match section { + 1 => RGB8::new(brightness_floor, rampdown_adj_with_floor, rampup_adj_with_floor), + 0 => RGB8::new(rampdown_adj_with_floor, rampup_adj_with_floor, brightness_floor), + _ => RGB8::new(rampup_adj_with_floor, brightness_floor, rampdown_adj_with_floor) } } }