1use palette::{encoding, Hsla, IntoColor, LinSrgb, LinSrgba, Srgb, Srgba};
2
3#[derive(Clone, Copy, Debug, PartialEq)]
4pub struct Color {
5 pub red: f32,
6 pub green: f32,
7 pub blue: f32,
8 pub alpha: f32,
9}
10
11impl From<Color> for [f32; 4] {
12 fn from(c: Color) -> [f32; 4] {
13 [c.red, c.green, c.blue, c.alpha]
14 }
15}
16
17impl From<Color> for [u8; 4] {
18 fn from(c: Color) -> [u8; 4] {
19 [
20 (c.red * 255.0) as u8,
21 (c.green * 255.0) as u8,
22 (c.blue * 255.0) as u8,
23 (c.alpha * 255.0) as u8,
24 ]
25 }
26}
27
28impl From<Hsla<encoding::Linear<encoding::Srgb>, f32>> for Color {
29 fn from(hsla: Hsla<encoding::Linear<encoding::Srgb>, f32>) -> Self {
30 let linear: LinSrgba<f32> = hsla.into_color();
31 Self::from(linear)
32 }
33}
34
35impl From<LinSrgb<f32>> for Color {
36 fn from(color: LinSrgb<f32>) -> Self {
37 Self::new(color.red, color.green, color.blue, 1.0)
38 }
39}
40
41impl From<LinSrgba<f32>> for Color {
42 fn from(LinSrgba { color, alpha }: LinSrgba<f32>) -> Self {
43 Self::new(color.red, color.green, color.blue, alpha)
44 }
45}
46
47impl From<Srgb<f32>> for Color {
48 fn from(color: Srgb<f32>) -> Self {
49 Self::from(Srgba { color, alpha: 1.0 })
50 }
51}
52
53impl From<Srgba<f32>> for Color {
54 fn from(color: Srgba<f32>) -> Self {
55 let linear: LinSrgba<f32> = color.into_linear();
56 Self::from(linear)
57 }
58}
59
60impl Color {
61 pub const TRANSPARENT: Self = Self::new(0.0, 0.0, 0.0, 0.0);
62 pub const BLACK: Self = Self::new(0.0, 0.0, 0.0, 1.0);
63 pub const WHITE: Self = Self::new(1.0, 1.0, 1.0, 1.0);
64 pub const RED: Self = Self::new(1.0, 0.0, 0.0, 1.0);
65 pub const GREEN: Self = Self::new(0.0, 1.0, 0.0, 1.0);
66 pub const BLUE: Self = Self::new(0.0, 0.0, 1.0, 1.0);
67
68 pub const fn new(red: f32, green: f32, blue: f32, alpha: f32) -> Self {
69 Self {
70 red,
71 green,
72 blue,
73 alpha,
74 }
75 }
76
77 #[inline]
78 pub fn bgra(color: u32) -> Self {
79 let [b, g, r, a] = color.to_le_bytes();
80 Self::new_srgba8(r, g, b, a)
81 }
82
83 #[inline]
84 pub fn new_srgba8(r: u8, g: u8, b: u8, a: u8) -> Self {
85 let color: Srgba<f32> = Srgba::from([r, g, b, a]).into_format();
86 Self::from(color)
87 }
88
89 pub fn hsla(hue: f32, saturation: f32, lightness: f32, alpha: f32) -> Self {
92 let components = (hue, saturation, lightness, alpha);
93 let hsla: Hsla<encoding::Linear<encoding::Srgb>, f32> = Hsla::from_components(components);
94 Self::from(hsla)
95 }
96}