Skip to main content

ply_engine/
color.rs

1/// An RGBA color with floating-point components (0.0–255.0 range).
2#[derive(Debug, Clone, Copy, PartialEq, Default)]
3#[repr(C)]
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 fn rgb(r: f32, g: f32, b: f32) -> Self {
13        Self { r, g, b, a: 255.0 }
14    }
15    pub const fn rgba(r: f32, g: f32, b: f32, a: f32) -> Self {
16        Self { r, g, b, a }
17    }
18
19    /// Allows using hex values to build colors
20    /// ```
21    /// use ply_engine::color::Color;
22    /// assert_eq!(Color::rgb(255.0, 255.0, 255.0), Color::u_rgb(0xFF, 0xFF, 0xFF));
23    /// ```
24    pub const fn u_rgb(r: u8, g: u8, b: u8) -> Self {
25        Self::rgb(r as f32, g as f32, b as f32)
26    }
27    /// Allows using hex values to build colors
28    /// ```
29    /// use ply_engine::color::Color;
30    /// assert_eq!(Color::rgba(255.0, 255.0, 255.0, 255.0), Color::u_rgba(0xFF, 0xFF, 0xFF, 0xFF));
31    /// ```
32    pub const fn u_rgba(r: u8, g: u8, b: u8, a: u8) -> Self {
33        Self::rgba(r as f32, g as f32, b as f32, a as f32)
34    }
35}
36
37impl From<(f32, f32, f32)> for Color {
38    fn from(value: (f32, f32, f32)) -> Self {
39        Self::rgb(value.0, value.1, value.2)
40    }
41}
42impl From<(f32, f32, f32, f32)> for Color {
43    fn from(value: (f32, f32, f32, f32)) -> Self {
44        Self::rgba(value.0, value.1, value.2, value.3)
45    }
46}
47
48impl From<(u8, u8, u8)> for Color {
49    fn from(value: (u8, u8, u8)) -> Self {
50        Self::u_rgb(value.0, value.1, value.2)
51    }
52}
53impl From<(u8, u8, u8, u8)> for Color {
54    fn from(value: (u8, u8, u8, u8)) -> Self {
55        Self::u_rgba(value.0, value.1, value.2, value.3)
56    }
57}
58
59impl From<i32> for Color {
60    fn from(hex: i32) -> Self {
61        let r = ((hex >> 16) & 0xFF) as f32;
62        let g = ((hex >> 8) & 0xFF) as f32;
63        let b = (hex & 0xFF) as f32;
64        Color::rgba(r, g, b, 255.0)
65    }
66}
67
68impl From<u32> for Color {
69    fn from(hex: u32) -> Self {
70        let r = ((hex >> 16) & 0xFF) as f32;
71        let g = ((hex >> 8) & 0xFF) as f32;
72        let b = (hex & 0xFF) as f32;
73        Color::rgba(r, g, b, 255.0)
74    }
75}
76
77impl From<macroquad::color::Color> for Color {
78    fn from(c: macroquad::color::Color) -> Self {
79        Color::rgba(c.r * 255.0, c.g * 255.0, c.b * 255.0, c.a * 255.0)
80    }
81}
82
83impl From<Color> for macroquad::color::Color {
84    fn from(c: Color) -> Self {
85        macroquad::color::Color::new(c.r / 255.0, c.g / 255.0, c.b / 255.0, c.a / 255.0)
86    }
87}