store color in linear

This commit is contained in:
2025-09-20 13:34:04 -04:00
parent e35e72402f
commit 3653f24e06
3 changed files with 25 additions and 22 deletions

View File

@@ -1,5 +1,6 @@
#![allow(clippy::multiple_bound_locations)]
/// stored in linear for sane manipulation
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Zeroable, Debug)]
pub struct Color<T: ColorNum> {
@@ -63,6 +64,7 @@ impl ColorNum for f32 {
unsafe impl bytemuck::Pod for Color<u8> {}
#[const_trait]
pub trait F32Conversion {
fn to(self) -> f32;
fn from(x: f32) -> Self;
@@ -87,9 +89,27 @@ impl<T: ColorNum + F32Conversion> Color<T> {
a: self.a,
}
}
pub fn srgb(r: T, g: T, b: T) -> Self {
Self {
r: s_to_l(r),
g: s_to_l(g),
b: s_to_l(b),
a: T::MAX,
}
}
}
impl F32Conversion for f32 {
fn s_to_l<T: F32Conversion>(x: T) -> T {
let x = x.to();
T::from(if x <= 0.0405 {
x / 12.92
} else {
((x + 0.055) / 1.055).powf(2.4)
})
}
impl const F32Conversion for f32 {
fn to(self) -> f32 {
self
}
@@ -98,7 +118,7 @@ impl F32Conversion for f32 {
}
}
impl F32Conversion for u8 {
impl const F32Conversion for u8 {
fn to(self) -> f32 {
self as f32 / 255.0
}