Skip to main content

rouge_render/
color.rs

1use rouge_theme::Rgba;
2
3#[derive(Clone, Copy, Debug, Default, PartialEq)]
4pub struct Color {
5    pub r: f32,
6    pub g: f32,
7    pub b: f32,
8    pub a: f32,
9}
10
11impl Color {
12    pub const TRANSPARENT: Color = Color::new(0.0, 0.0, 0.0, 0.0);
13    pub const BLACK: Color = Color::new(0.0, 0.0, 0.0, 1.0);
14    pub const WHITE: Color = Color::new(1.0, 1.0, 1.0, 1.0);
15    pub const RED: Color = Color::new(1.0, 0.0, 0.0, 1.0);
16    pub const GREEN: Color = Color::new(0.0, 1.0, 0.0, 1.0);
17    pub const BLUE: Color = Color::new(0.0, 0.0, 1.0, 1.0);
18
19    pub const fn new(r: f32, g: f32, b: f32, a: f32) -> Self {
20        Color { r, g, b, a }
21    }
22
23    pub const fn rgb(hex: u32) -> Self {
24        Color::from_rgba8((hex >> 16) as u8, (hex >> 8) as u8, hex as u8, 255)
25    }
26
27    pub const fn from_rgba8(r: u8, g: u8, b: u8, a: u8) -> Self {
28        Color::new(
29            r as f32 / 255.0,
30            g as f32 / 255.0,
31            b as f32 / 255.0,
32            a as f32 / 255.0,
33        )
34    }
35
36    #[expect(clippy::many_single_char_names)]
37    pub fn hsl(h: f32, s: f32, l: f32) -> Self {
38        let h = h.rem_euclid(360.0) / 60.0;
39        let c = (1.0 - (2.0 * l - 1.0).abs()) * s;
40        let x = c * (1.0 - (h % 2.0 - 1.0).abs());
41        let (r, g, b) = match h as u32 {
42            0 => (c, x, 0.0),
43            1 => (x, c, 0.0),
44            2 => (0.0, c, x),
45            3 => (0.0, x, c),
46            4 => (x, 0.0, c),
47            _ => (c, 0.0, x),
48        };
49        let m = l - c / 2.0;
50        Color::new(r + m, g + m, b + m, 1.0)
51    }
52
53    pub const fn with_alpha(self, a: f32) -> Self {
54        Color { a, ..self }
55    }
56
57    #[must_use]
58    pub fn over(self, background: Color) -> Color {
59        let below = background.a * (1.0 - self.a);
60        let a = self.a + below;
61        if a <= 0.0 {
62            return Color::TRANSPARENT;
63        }
64        let channel = |top: f32, bottom: f32| (top * self.a + bottom * below) / a;
65        Color::new(
66            channel(self.r, background.r),
67            channel(self.g, background.g),
68            channel(self.b, background.b),
69            a,
70        )
71    }
72
73    pub fn premultiplied(self) -> [f32; 4] {
74        [self.r * self.a, self.g * self.a, self.b * self.a, self.a]
75    }
76
77    pub fn to_array(self) -> [f32; 4] {
78        [self.r, self.g, self.b, self.a]
79    }
80
81    pub fn to_rgba8(self) -> [u8; 4] {
82        self.to_array()
83            .map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8)
84    }
85}
86
87impl From<Color> for Rgba {
88    fn from(value: Color) -> Self {
89        let [r, g, b, a] = value.to_rgba8();
90        Rgba::new(r, g, b, a)
91    }
92}
93
94impl From<Rgba> for Color {
95    fn from(value: Rgba) -> Self {
96        Color::from_rgba8(value.r, value.g, value.b, value.a)
97    }
98}