1#[repr(C)]
3#[derive(Debug, Clone, Copy, PartialEq, bytemuck::Pod, bytemuck::Zeroable)]
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 WHITE: Color = Color::rgb(1.0, 1.0, 1.0);
13 pub const BLACK: Color = Color::rgb(0.0, 0.0, 0.0);
14 pub const RED: Color = Color::rgb(1.0, 0.0, 0.0);
15 pub const GREEN: Color = Color::rgb(0.0, 1.0, 0.0);
16 pub const BLUE: Color = Color::rgb(0.0, 0.0, 1.0);
17 pub const YELLOW: Color = Color::rgb(1.0, 1.0, 0.0);
18 pub const CYAN: Color = Color::rgb(0.0, 1.0, 1.0);
19 pub const MAGENTA: Color = Color::rgb(1.0, 0.0, 1.0);
20 pub const TRANSPARENT: Color = Color::rgba(0.0, 0.0, 0.0, 0.0);
21
22 pub const fn rgb(r: f32, g: f32, b: f32) -> Self {
23 Self { r, g, b, a: 1.0 }
24 }
25
26 pub const fn rgba(r: f32, g: f32, b: f32, a: f32) -> Self {
27 Self { r, g, b, a }
28 }
29
30 pub fn from_rgba_u8(r: u8, g: u8, b: u8, a: u8) -> Self {
31 Self {
32 r: r as f32 / 255.0,
33 g: g as f32 / 255.0,
34 b: b as f32 / 255.0,
35 a: a as f32 / 255.0,
36 }
37 }
38
39 pub fn from_rgb_u8(r: u8, g: u8, b: u8) -> Self {
40 Self::from_rgba_u8(r, g, b, 255)
41 }
42
43 pub fn from_hex(hex: u32) -> Self {
44 let r = ((hex >> 16) & 0xFF) as u8;
45 let g = ((hex >> 8) & 0xFF) as u8;
46 let b = (hex & 0xFF) as u8;
47 Self::from_rgb_u8(r, g, b)
48 }
49
50 pub fn from_hex_alpha(hex: u32) -> Self {
51 let r = ((hex >> 24) & 0xFF) as u8;
52 let g = ((hex >> 16) & 0xFF) as u8;
53 let b = ((hex >> 8) & 0xFF) as u8;
54 let a = (hex & 0xFF) as u8;
55 Self::from_rgba_u8(r, g, b, a)
56 }
57
58 pub fn to_wgpu(self) -> wgpu::Color {
59 wgpu::Color {
60 r: self.r as f64,
61 g: self.g as f64,
62 b: self.b as f64,
63 a: self.a as f64,
64 }
65 }
66
67 pub fn to_array(self) -> [f32; 4] {
68 [self.r, self.g, self.b, self.a]
69 }
70}
71
72impl Default for Color {
73 fn default() -> Self {
74 Self::WHITE
75 }
76}
77
78impl From<[f32; 4]> for Color {
79 fn from(arr: [f32; 4]) -> Self {
80 Self {
81 r: arr[0],
82 g: arr[1],
83 b: arr[2],
84 a: arr[3],
85 }
86 }
87}
88
89impl From<[f32; 3]> for Color {
90 fn from(arr: [f32; 3]) -> Self {
91 Self {
92 r: arr[0],
93 g: arr[1],
94 b: arr[2],
95 a: 1.0,
96 }
97 }
98}
99
100impl From<Color> for [f32; 4] {
101 fn from(color: Color) -> Self {
102 color.to_array()
103 }
104}