chromashift/
a98_rgb.rs

1use crate::{LinearRgb, ToAlpha, round_dp};
2use core::fmt;
3
4/// An RGB colour space with defined chromacities.
5/// The components are:
6/// - Red - a number between 0.0 and 1.0
7/// - Blue - a number between 0.0 and 1.0
8/// - Green - a number between 0.0 and 1.0
9/// - Alpha - a number between 0.0 and 100.0
10#[derive(Debug, Clone, Copy, PartialEq)]
11pub struct A98Rgb {
12	pub red: f64,
13	pub green: f64,
14	pub blue: f64,
15	pub alpha: f32,
16}
17
18impl A98Rgb {
19	pub fn new(red: f64, green: f64, blue: f64, alpha: f32) -> Self {
20		Self { red, green, blue, alpha: alpha.clamp(0.0, 100.0) }
21	}
22}
23
24impl ToAlpha for A98Rgb {
25	fn to_alpha(&self) -> f32 {
26		self.alpha
27	}
28}
29
30impl fmt::Display for A98Rgb {
31	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32		let Self { red, green, blue, alpha } = self;
33		write!(f, "color(a98-rgb {} {}% {}%", round_dp(*red, 2), round_dp(*green, 2), round_dp(*blue, 2))?;
34		if *alpha < 100.0 {
35			write!(f, " / {}", round_dp(*alpha as f64, 2))?;
36		}
37		write!(f, ")")
38	}
39}
40
41impl From<LinearRgb> for A98Rgb {
42	fn from(value: LinearRgb) -> Self {
43		let LinearRgb { red, green, blue, alpha } = value;
44		const INV_GAMMA: f64 = 256.0 / 563.0;
45		let gamma_red = red.signum() * red.abs().powf(INV_GAMMA);
46		let gamma_green = green.signum() * green.abs().powf(INV_GAMMA);
47		let gamma_blue = blue.signum() * blue.abs().powf(INV_GAMMA);
48		A98Rgb::new(gamma_red, gamma_green, gamma_blue, alpha)
49	}
50}
51
52impl From<A98Rgb> for LinearRgb {
53	fn from(value: A98Rgb) -> Self {
54		let A98Rgb { red, green, blue, alpha } = value;
55		const GAMMA: f64 = 563.0 / 256.0;
56		let linear_red = red.signum() * red.abs().powf(GAMMA);
57		let linear_green = green.signum() * green.abs().powf(GAMMA);
58		let linear_blue = blue.signum() * blue.abs().powf(GAMMA);
59		LinearRgb::new(linear_red, linear_green, linear_blue, alpha)
60	}
61}