diff options
| author | HampusM <hampus@hampusmat.com> | 2026-08-19 22:49:17 +0200 |
|---|---|---|
| committer | HampusM <hampus@hampusmat.com> | 2026-08-19 22:49:17 +0200 |
| commit | e7f503a1e545aa83535e67eceafb0462780bfc2d (patch) | |
| tree | 1daf2289331d2ec352071c078ec0864320162bcb | |
| parent | bcc91b3db8cd50795c21860cd7797581199d5589 (diff) | |
feat(engine): add lossy Color conversion fns
| -rw-r--r-- | engine/src/data_types/color.rs | 68 |
1 files 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<u8> + impl<Component: PixelComponent> $ident<Component> { pub fn white() -> Self { Self { - $($component: 255),* + $($component: Component::COLOR_MAX),* } } } - impl $ident<f32> - { - pub fn white() -> Self - { - Self { - $($component: 1.0),* - } - } - } - - impl<Component> Pixel for $ident<Component> + impl<Component: PixelComponent> Pixel for $ident<Component> { type Component = Component; } @@ -52,6 +47,30 @@ pub enum Color<Component> Rgba(Rgba<Component>), } +impl<Component: PixelComponent> Color<Component> +{ + pub fn to_rgb_lossy(&self) -> Rgb<Component> + { + 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<Component> + { + 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<Component: Default> Default for Color<Component> { 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 {} |
