From e7f503a1e545aa83535e67eceafb0462780bfc2d Mon Sep 17 00:00:00 2001 From: HampusM Date: Wed, 19 Aug 2026 22:49:17 +0200 Subject: feat(engine): add lossy Color conversion fns --- engine/src/data_types/color.rs | 68 +++++++++++++++++++++++++++++++++--------- 1 file changed, 54 insertions(+), 14 deletions(-) diff --git a/engine/src/data_types/color.rs b/engine/src/data_types/color.rs index 4b981fd..9803088 100644 --- a/engine/src/data_types/color.rs +++ b/engine/src/data_types/color.rs @@ -2,7 +2,12 @@ use std::ops::{Add, Div, Mul, Sub}; pub trait Pixel: sealed::Sealed { - type Component; + type Component: PixelComponent; +} + +pub trait PixelComponent: Clone + Copy + sealed::Sealed +{ + const COLOR_MAX: Self; } macro_rules! gen_color { @@ -13,27 +18,17 @@ macro_rules! gen_color { $(pub $component: Component),+ } - impl $ident + impl $ident { pub fn white() -> Self { Self { - $($component: 255),* + $($component: Component::COLOR_MAX),* } } } - impl $ident - { - pub fn white() -> Self - { - Self { - $($component: 1.0),* - } - } - } - - impl Pixel for $ident + impl Pixel for $ident { type Component = Component; } @@ -52,6 +47,30 @@ pub enum Color Rgba(Rgba), } +impl Color +{ + pub fn to_rgb_lossy(&self) -> Rgb + { + match self { + Self::Rgb(rgb) => rgb.clone(), + Self::Rgba(rgba) => Rgb { r: rgba.r, g: rgba.g, b: rgba.b }, + } + } + + pub fn to_rgba_lossy(&self) -> Rgba + { + match self { + Self::Rgb(rgb) => Rgba { + r: rgb.r, + g: rgb.g, + b: rgb.b, + a: Component::COLOR_MAX, + }, + Self::Rgba(rgba) => rgba.clone(), + } + } +} + impl Default for Color { fn default() -> Self @@ -124,6 +143,27 @@ gen_enum_scalar_math_op_impl!(Color, Sub, sub, variants = (Rgb, Rgba)); gen_enum_scalar_math_op_impl!(Color, Mul, mul, variants = (Rgb, Rgba)); gen_enum_scalar_math_op_impl!(Color, Div, div, variants = (Rgb, Rgba)); +impl PixelComponent for u8 +{ + const COLOR_MAX: Self = u8::MAX; +} + +impl sealed::Sealed for u8 {} + +impl PixelComponent for u16 +{ + const COLOR_MAX: Self = u16::MAX; +} + +impl sealed::Sealed for u16 {} + +impl PixelComponent for f32 +{ + const COLOR_MAX: Self = 1.0; +} + +impl sealed::Sealed for f32 {} + mod sealed { pub trait Sealed {} -- cgit v1.2.3-18-g5258