ecolor/
color32.rs

1use crate::{fast_round, linear_f32_from_linear_u8, Rgba};
2
3/// This format is used for space-efficient color representation (32 bits).
4///
5/// Instead of manipulating this directly it is often better
6/// to first convert it to either [`Rgba`] or [`crate::Hsva`].
7///
8/// Internally this uses 0-255 gamma space `sRGBA` color with premultiplied alpha.
9/// Alpha channel is in linear space.
10///
11/// The special value of alpha=0 means the color is to be treated as an additive color.
12#[repr(C)]
13#[derive(Clone, Copy, Default, Eq, Hash, PartialEq)]
14#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
15#[cfg_attr(feature = "bytemuck", derive(bytemuck::Pod, bytemuck::Zeroable))]
16pub struct Color32(pub(crate) [u8; 4]);
17
18impl std::fmt::Debug for Color32 {
19    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
20        let [r, g, b, a] = self.0;
21        write!(f, "#{r:02X}_{g:02X}_{b:02X}_{a:02X}")
22    }
23}
24
25impl std::ops::Index<usize> for Color32 {
26    type Output = u8;
27
28    #[inline]
29    fn index(&self, index: usize) -> &u8 {
30        &self.0[index]
31    }
32}
33
34impl std::ops::IndexMut<usize> for Color32 {
35    #[inline]
36    fn index_mut(&mut self, index: usize) -> &mut u8 {
37        &mut self.0[index]
38    }
39}
40
41impl Color32 {
42    // Mostly follows CSS names:
43
44    pub const TRANSPARENT: Self = Self::from_rgba_premultiplied(0, 0, 0, 0);
45    pub const BLACK: Self = Self::from_rgb(0, 0, 0);
46    #[doc(alias = "DARK_GREY")]
47    pub const DARK_GRAY: Self = Self::from_rgb(96, 96, 96);
48    #[doc(alias = "GREY")]
49    pub const GRAY: Self = Self::from_rgb(160, 160, 160);
50    #[doc(alias = "LIGHT_GREY")]
51    pub const LIGHT_GRAY: Self = Self::from_rgb(220, 220, 220);
52    pub const WHITE: Self = Self::from_rgb(255, 255, 255);
53
54    pub const BROWN: Self = Self::from_rgb(165, 42, 42);
55    pub const DARK_RED: Self = Self::from_rgb(0x8B, 0, 0);
56    pub const RED: Self = Self::from_rgb(255, 0, 0);
57    pub const LIGHT_RED: Self = Self::from_rgb(255, 128, 128);
58
59    pub const YELLOW: Self = Self::from_rgb(255, 255, 0);
60    pub const ORANGE: Self = Self::from_rgb(255, 165, 0);
61    pub const LIGHT_YELLOW: Self = Self::from_rgb(255, 255, 0xE0);
62    pub const KHAKI: Self = Self::from_rgb(240, 230, 140);
63
64    pub const DARK_GREEN: Self = Self::from_rgb(0, 0x64, 0);
65    pub const GREEN: Self = Self::from_rgb(0, 255, 0);
66    pub const LIGHT_GREEN: Self = Self::from_rgb(0x90, 0xEE, 0x90);
67
68    pub const DARK_BLUE: Self = Self::from_rgb(0, 0, 0x8B);
69    pub const BLUE: Self = Self::from_rgb(0, 0, 255);
70    pub const LIGHT_BLUE: Self = Self::from_rgb(0xAD, 0xD8, 0xE6);
71
72    pub const GOLD: Self = Self::from_rgb(255, 215, 0);
73
74    pub const DEBUG_COLOR: Self = Self::from_rgba_premultiplied(0, 200, 0, 128);
75
76    /// An ugly color that is planned to be replaced before making it to the screen.
77    ///
78    /// This is an invalid color, in that it does not correspond to a valid multiplied color,
79    /// nor to an additive color.
80    ///
81    /// This is used as a special color key,
82    /// i.e. often taken to mean "no color".
83    pub const PLACEHOLDER: Self = Self::from_rgba_premultiplied(64, 254, 0, 128);
84
85    #[deprecated = "Renamed to PLACEHOLDER"]
86    pub const TEMPORARY_COLOR: Self = Self::PLACEHOLDER;
87
88    #[inline]
89    pub const fn from_rgb(r: u8, g: u8, b: u8) -> Self {
90        Self([r, g, b, 255])
91    }
92
93    #[inline]
94    pub const fn from_rgb_additive(r: u8, g: u8, b: u8) -> Self {
95        Self([r, g, b, 0])
96    }
97
98    /// From `sRGBA` with premultiplied alpha.
99    #[inline]
100    pub const fn from_rgba_premultiplied(r: u8, g: u8, b: u8, a: u8) -> Self {
101        Self([r, g, b, a])
102    }
103
104    /// From `sRGBA` WITHOUT premultiplied alpha.
105    #[inline]
106    pub fn from_rgba_unmultiplied(r: u8, g: u8, b: u8, a: u8) -> Self {
107        use std::sync::OnceLock;
108        match a {
109            // common-case optimization
110            0 => Self::TRANSPARENT,
111            // common-case optimization
112            255 => Self::from_rgb(r, g, b),
113            a => {
114                static LOOKUP_TABLE: OnceLock<Box<[u8]>> = OnceLock::new();
115                let lut = LOOKUP_TABLE.get_or_init(|| {
116                    use crate::{gamma_u8_from_linear_f32, linear_f32_from_gamma_u8};
117                    (0..=u16::MAX)
118                        .map(|i| {
119                            let [value, alpha] = i.to_ne_bytes();
120                            let value_lin = linear_f32_from_gamma_u8(value);
121                            let alpha_lin = linear_f32_from_linear_u8(alpha);
122                            gamma_u8_from_linear_f32(value_lin * alpha_lin)
123                        })
124                        .collect()
125                });
126
127                let [r, g, b] =
128                    [r, g, b].map(|value| lut[usize::from(u16::from_ne_bytes([value, a]))]);
129                Self::from_rgba_premultiplied(r, g, b, a)
130            }
131        }
132    }
133
134    #[doc(alias = "from_grey")]
135    #[inline]
136    pub const fn from_gray(l: u8) -> Self {
137        Self([l, l, l, 255])
138    }
139
140    #[inline]
141    pub const fn from_black_alpha(a: u8) -> Self {
142        Self([0, 0, 0, a])
143    }
144
145    #[inline]
146    pub fn from_white_alpha(a: u8) -> Self {
147        Rgba::from_white_alpha(linear_f32_from_linear_u8(a)).into()
148    }
149
150    #[inline]
151    pub const fn from_additive_luminance(l: u8) -> Self {
152        Self([l, l, l, 0])
153    }
154
155    #[inline]
156    pub const fn is_opaque(&self) -> bool {
157        self.a() == 255
158    }
159
160    #[inline]
161    pub const fn r(&self) -> u8 {
162        self.0[0]
163    }
164
165    #[inline]
166    pub const fn g(&self) -> u8 {
167        self.0[1]
168    }
169
170    #[inline]
171    pub const fn b(&self) -> u8 {
172        self.0[2]
173    }
174
175    #[inline]
176    pub const fn a(&self) -> u8 {
177        self.0[3]
178    }
179
180    /// Returns an opaque version of self
181    #[inline]
182    pub fn to_opaque(self) -> Self {
183        Rgba::from(self).to_opaque().into()
184    }
185
186    /// Returns an additive version of self
187    #[inline]
188    pub const fn additive(self) -> Self {
189        let [r, g, b, _] = self.to_array();
190        Self([r, g, b, 0])
191    }
192
193    /// Is the alpha=0 ?
194    #[inline]
195    pub fn is_additive(self) -> bool {
196        self.a() == 0
197    }
198
199    /// Premultiplied RGBA
200    #[inline]
201    pub const fn to_array(&self) -> [u8; 4] {
202        [self.r(), self.g(), self.b(), self.a()]
203    }
204
205    /// Premultiplied RGBA
206    #[inline]
207    pub const fn to_tuple(&self) -> (u8, u8, u8, u8) {
208        (self.r(), self.g(), self.b(), self.a())
209    }
210
211    #[inline]
212    pub fn to_srgba_unmultiplied(&self) -> [u8; 4] {
213        Rgba::from(*self).to_srgba_unmultiplied()
214    }
215
216    /// Multiply with 0.5 to make color half as opaque, perceptually.
217    ///
218    /// Fast multiplication in gamma-space.
219    ///
220    /// This is perceptually even, and faster that [`Self::linear_multiply`].
221    #[inline]
222    pub fn gamma_multiply(self, factor: f32) -> Self {
223        debug_assert!(0.0 <= factor && factor.is_finite());
224        let Self([r, g, b, a]) = self;
225        Self([
226            (r as f32 * factor + 0.5) as u8,
227            (g as f32 * factor + 0.5) as u8,
228            (b as f32 * factor + 0.5) as u8,
229            (a as f32 * factor + 0.5) as u8,
230        ])
231    }
232
233    /// Multiply with 0.5 to make color half as opaque in linear space.
234    ///
235    /// This is using linear space, which is not perceptually even.
236    /// You likely want to use [`Self::gamma_multiply`] instead.
237    #[inline]
238    pub fn linear_multiply(self, factor: f32) -> Self {
239        debug_assert!(0.0 <= factor && factor.is_finite());
240        // As an unfortunate side-effect of using premultiplied alpha
241        // we need a somewhat expensive conversion to linear space and back.
242        Rgba::from(self).multiply(factor).into()
243    }
244
245    /// Converts to floating point values in the range 0-1 without any gamma space conversion.
246    ///
247    /// Use this with great care! In almost all cases, you want to convert to [`crate::Rgba`] instead
248    /// in order to obtain linear space color values.
249    #[inline]
250    pub fn to_normalized_gamma_f32(self) -> [f32; 4] {
251        let Self([r, g, b, a]) = self;
252        [
253            r as f32 / 255.0,
254            g as f32 / 255.0,
255            b as f32 / 255.0,
256            a as f32 / 255.0,
257        ]
258    }
259
260    /// Lerp this color towards `other` by `t` in gamma space.
261    pub fn lerp_to_gamma(&self, other: Self, t: f32) -> Self {
262        use emath::lerp;
263
264        Self::from_rgba_premultiplied(
265            fast_round(lerp((self[0] as f32)..=(other[0] as f32), t)),
266            fast_round(lerp((self[1] as f32)..=(other[1] as f32), t)),
267            fast_round(lerp((self[2] as f32)..=(other[2] as f32), t)),
268            fast_round(lerp((self[3] as f32)..=(other[3] as f32), t)),
269        )
270    }
271}
272
273impl std::ops::Mul for Color32 {
274    type Output = Self;
275
276    /// Fast gamma-space multiplication.
277    #[inline]
278    fn mul(self, other: Self) -> Self {
279        Self([
280            fast_round(self[0] as f32 * other[0] as f32 / 255.0),
281            fast_round(self[1] as f32 * other[1] as f32 / 255.0),
282            fast_round(self[2] as f32 * other[2] as f32 / 255.0),
283            fast_round(self[3] as f32 * other[3] as f32 / 255.0),
284        ])
285    }
286}