Added StableInterpolate implementations for linear colors. (#18601)

# Objective

Colors currently do not implement `StableInterpolate`, which makes them
ineligible for functions like `smooth_nudge` and make some generic APIs
awkward.

## Solution

Implemented `StableInterpolate` for linear color types that should be
uncontroversial. Non-linear types like `Hsl` are not implemented in this
PR.

## Testing

Added a test that checks implementations are correct.
This commit is contained in:
Mincong Lu 2025-05-06 07:58:56 +08:00 committed by GitHub
parent 798e1c5498
commit 818459113e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 44 additions and 0 deletions

View File

@ -0,0 +1,37 @@
//! TODO: Implement for non-linear colors.
#[cfg(test)]
mod test {
use bevy_math::StableInterpolate;
use crate::{Gray, Laba, LinearRgba, Oklaba, Srgba, Xyza};
#[test]
pub fn test_color_stable_interpolate() {
let b = Srgba::BLACK;
let w = Srgba::WHITE;
assert_eq!(
b.interpolate_stable(&w, 0.5),
Srgba::new(0.5, 0.5, 0.5, 1.0),
);
let b = LinearRgba::BLACK;
let w = LinearRgba::WHITE;
assert_eq!(
b.interpolate_stable(&w, 0.5),
LinearRgba::new(0.5, 0.5, 0.5, 1.0),
);
let b = Xyza::BLACK;
let w = Xyza::WHITE;
assert_eq!(b.interpolate_stable(&w, 0.5), Xyza::gray(0.5),);
let b = Laba::BLACK;
let w = Laba::WHITE;
assert_eq!(b.interpolate_stable(&w, 0.5), Laba::new(0.5, 0.0, 0.0, 1.0),);
let b = Oklaba::BLACK;
let w = Oklaba::WHITE;
assert_eq!(b.interpolate_stable(&w, 0.5), Oklaba::gray(0.5),);
}
}

View File

@ -105,6 +105,7 @@ mod color_range;
mod hsla;
mod hsva;
mod hwba;
mod interpolate;
mod laba;
mod lcha;
mod linear_rgba;
@ -265,6 +266,12 @@ macro_rules! impl_componentwise_vector_space {
$($element: 0.0,)+
};
}
impl bevy_math::StableInterpolate for $ty {
fn interpolate_stable(&self, other: &Self, t: f32) -> Self {
bevy_math::VectorSpace::lerp(*self, *other, t)
}
}
};
}