use std::fmt::Write as _;
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Rgba {
pub r: f64,
pub g: f64,
pub b: f64,
pub a: f64,
}
crate::archive_struct!(Rgba { r, g, b, a });
impl Rgba {
pub const BLACK: Self = Self::new(0.0, 0.0, 0.0, 1.0);
pub const WHITE: Self = Self::new(1.0, 1.0, 1.0, 1.0);
pub const TRANSPARENT: Self = Self::new(0.0, 0.0, 0.0, 0.0);
pub const fn new(r: f64, g: f64, b: f64, a: f64) -> Self {
Self { r, g, b, a }
}
pub const fn opaque(r: f64, g: f64, b: f64) -> Self {
Self::new(r, g, b, 1.0)
}
pub fn from_rgba8([r, g, b, a]: [u8; 4]) -> Self {
let unit = |v: u8| f64::from(v) / 255.0;
Self::new(unit(r), unit(g), unit(b), unit(a))
}
#[must_use]
pub const fn with_alpha(self, a: f64) -> Self {
Self { a, ..self }
}
#[must_use]
pub fn fade(self, factor: f64) -> Self {
self.with_alpha(self.a * factor)
}
pub fn is_transparent(self) -> bool {
self.a <= 0.0
}
pub const fn to_array(self) -> [f64; 4] {
[self.r, self.g, self.b, self.a]
}
pub fn to_rgba8(self) -> [u8; 4] {
let q = |v: f64| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
[q(self.r), q(self.g), q(self.b), q(self.a)]
}
pub fn to_hex(self, keep_alpha: bool) -> String {
let channels = self.to_array();
let channels = if keep_alpha {
&channels[..]
} else {
&channels[..3]
};
channels.iter().fold(String::from("#"), |mut hex, v| {
let byte = (v * 255.0).round_ties_even() as u8;
write!(hex, "{byte:02x}").expect("writing to a String cannot fail");
hex
})
}
pub fn luminance(self) -> f64 {
0.2126 * self.r + 0.7152 * self.g + 0.0722 * self.b
}
}
impl From<[f64; 4]> for Rgba {
fn from([r, g, b, a]: [f64; 4]) -> Self {
Self::new(r, g, b, a)
}
}
impl From<[f64; 3]> for Rgba {
fn from([r, g, b]: [f64; 3]) -> Self {
Self::opaque(r, g, b)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn quantisation_rounds_half_up_and_clamps() {
assert_eq!(Rgba::new(0.5, 1.0, 0.0, 1.0).to_rgba8(), [128, 255, 0, 255]);
assert_eq!(Rgba::new(-1.0, 2.0, 0.2, 0.0).to_rgba8(), [0, 255, 51, 0]);
}
#[test]
fn hex_rounds_half_to_even_and_saturates() {
assert_eq!(Rgba::opaque(0.5, 1.0, 0.0).to_hex(false), "#80ff00");
assert_eq!(
Rgba::opaque(0.121_568_63, 0.466_666_67, 0.705_882_35).to_hex(false),
"#1f77b4"
);
assert_eq!(Rgba::new(0.5, 1.0, 0.0, 0.5).to_hex(true), "#80ff0080");
assert_eq!(Rgba::opaque(2.5 / 255.0, 0.0, 0.0).to_hex(false), "#020000");
assert_eq!(
Rgba::new(-1.0, 2.0, f64::NAN, 1.0).to_hex(true),
"#00ff00ff"
);
}
#[test]
fn round_trip_8bit() {
let c = [12, 34, 56, 78];
assert_eq!(Rgba::from_rgba8(c).to_rgba8(), c);
}
#[test]
fn alpha_helpers() {
let c = Rgba::opaque(0.1, 0.2, 0.3);
assert_eq!(c.with_alpha(0.5).a, 0.5);
assert_eq!(c.fade(0.5).fade(0.5).a, 0.25);
assert!(Rgba::TRANSPARENT.is_transparent());
}
}