From 01cec31da009ac8756d4a91ee7dd1c2fe708aca3 Mon Sep 17 00:00:00 2001 From: Shadow Cat Date: Sat, 20 Sep 2025 17:30:53 -0400 Subject: [PATCH] add darken and brighten color fns --- src/layout/color.rs | 77 ++++++++++++++++++++++++++------------------- src/testing/mod.rs | 4 +-- 2 files changed, 46 insertions(+), 35 deletions(-) diff --git a/src/layout/color.rs b/src/layout/color.rs index d058f5f..4b4d98e 100644 --- a/src/layout/color.rs +++ b/src/layout/color.rs @@ -44,48 +44,45 @@ impl Color { } } -pub trait ColorNum { - const MIN: Self; - const MID: Self; - const MAX: Self; -} - -impl ColorNum for u8 { - const MIN: Self = u8::MIN; - const MID: Self = u8::MAX / 2; - const MAX: Self = u8::MAX; -} - -impl ColorNum for f32 { - const MIN: Self = 0.0; - const MID: Self = 0.5; - const MAX: Self = 1.0; -} - -unsafe impl bytemuck::Pod for Color {} - #[const_trait] pub trait F32Conversion { fn to(self) -> f32; fn from(x: f32) -> Self; } +pub trait ColorNum { + const MIN: Self; + const MID: Self; + const MAX: Self; +} + impl Color { - pub fn mul_rgb(self, x: impl F32Conversion) -> Self { - let x = x.to(); - Self { - r: T::from(self.r.to() * x), - g: T::from(self.g.to() * x), - b: T::from(self.b.to() * x), - a: self.a, - } + pub fn mul_rgb(self, amt: impl F32Conversion) -> Self { + let amt = amt.to(); + self.map_rgb(|x| T::from(x.to() * amt)) } - pub fn add_rgb(self, x: impl F32Conversion) -> Self { - let x = x.to(); + + pub fn add_rgb(self, amt: impl F32Conversion) -> Self { + let amt = amt.to(); + self.map_rgb(|x| T::from(x.to() + amt)) + } + + pub fn darken(self, amt: f32) -> Self { + self.mul_rgb(1.0 - amt) + } + + pub fn brighten(self, amt: f32) -> Self { + self.map_rgb(|x| { + let x = x.to(); + T::from(x + (1.0 - x) * amt) + }) + } + + pub fn map_rgb(self, f: impl Fn(T) -> T) -> Self { Self { - r: T::from(self.r.to() + x), - g: T::from(self.g.to() + x), - b: T::from(self.b.to() + x), + r: f(self.r), + g: f(self.g), + b: f(self.b), a: self.a, } } @@ -109,6 +106,20 @@ fn s_to_l(x: T) -> T { }) } +impl ColorNum for u8 { + const MIN: Self = u8::MIN; + const MID: Self = u8::MAX / 2; + const MAX: Self = u8::MAX; +} + +impl ColorNum for f32 { + const MIN: Self = 0.0; + const MID: Self = 0.5; + const MAX: Self = 1.0; +} + +unsafe impl bytemuck::Pod for Color {} + impl const F32Conversion for f32 { fn to(self) -> f32 { self diff --git a/src/testing/mod.rs b/src/testing/mod.rs index 76caa69..aacddb2 100644 --- a/src/testing/mod.rs +++ b/src/testing/mod.rs @@ -157,10 +157,10 @@ impl Client { let rect = rect(color) .id_on(Sense::click(), move |id, ctx: &mut Client, _| { ctx.ui[main].inner.set_static(to); - ctx.ui[id].color = color.mul_rgb(0.7); + ctx.ui[id].color = color.darken(0.3); }) .edit_on(Sense::HoverStart | Sense::unclick(), move |r, _| { - r.color = color.add_rgb(0.2); + r.color = color.brighten(0.2); }) .edit_on(Sense::HoverEnd, move |r, _| { r.color = color;