/
rgba.rs
executable file
·479 lines (431 loc) · 14.1 KB
/
rgba.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
use crate::prelude::{HtmlColorConversionError, HSV, RGB};
use std::convert::From;
use std::ops;
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(PartialEq, Copy, Clone, Default, Debug)]
/// Represents an R/G/B triplet, in the range 0..1 (32-bit float)
pub struct RGBA {
pub r: f32,
pub g: f32,
pub b: f32,
pub a: f32,
}
// Implement operator overloading
/// Support adding a float to a color. The result is clamped via the constructor.
impl ops::Add<f32> for RGBA {
type Output = Self;
#[must_use]
fn add(mut self, rhs: f32) -> Self {
self.r += rhs;
self.g += rhs;
self.b += rhs;
self.a += rhs;
self
}
}
/// Support adding an RGB to a color. The result is clamped via the constructor.
impl ops::Add<RGBA> for RGBA {
type Output = Self;
#[must_use]
fn add(mut self, rhs: Self) -> Self {
self.r += rhs.r;
self.g += rhs.g;
self.b += rhs.b;
self.a += rhs.a;
self
}
}
/// Support subtracting a float from a color. The result is clamped via the constructor.
impl ops::Sub<f32> for RGBA {
type Output = Self;
#[must_use]
fn sub(mut self, rhs: f32) -> Self {
self.r -= rhs;
self.g -= rhs;
self.b -= rhs;
self.a -= rhs;
self
}
}
/// Support subtracting an RGB from a color. The result is clamped via the constructor.
impl ops::Sub<RGBA> for RGBA {
type Output = Self;
#[must_use]
fn sub(mut self, rhs: Self) -> Self {
self.r -= rhs.r;
self.g -= rhs.g;
self.b -= rhs.b;
self.a -= rhs.a;
self
}
}
/// Support multiplying a color by a float. The result is clamped via the constructor.
impl ops::Mul<f32> for RGBA {
type Output = Self;
#[must_use]
fn mul(mut self, rhs: f32) -> Self {
self.r *= rhs;
self.g *= rhs;
self.b *= rhs;
self.a *= rhs;
self
}
}
/// Support multiplying a color by another color. The result is clamped via the constructor.
impl ops::Mul<RGBA> for RGBA {
type Output = Self;
#[must_use]
fn mul(mut self, rhs: Self) -> Self {
self.r *= rhs.r;
self.g *= rhs.g;
self.b *= rhs.b;
self.a *= rhs.a;
self
}
}
impl RGBA {
/// Constructs a new, zeroed (black) RGB triplet.
#[must_use]
pub fn new() -> Self {
Self {
r: 0.0,
g: 0.0,
b: 0.0,
a: 0.0,
}
}
/// Constructs a new RGB color, from 3 32-bit floats in the range 0..1
#[inline]
#[must_use]
pub fn from_f32(r: f32, g: f32, b: f32, a: f32) -> Self {
let r_clamped = f32::min(1.0, f32::max(0.0, r));
let g_clamped = f32::min(1.0, f32::max(0.0, g));
let b_clamped = f32::min(1.0, f32::max(0.0, b));
let a_clamped = f32::min(1.0, f32::max(0.0, a));
Self {
r: r_clamped,
g: g_clamped,
b: b_clamped,
a: a_clamped,
}
}
/// Constructs a new RGB color, from 3 bytes in the range 0..255
#[inline]
#[must_use]
pub fn from_u8(r: u8, g: u8, b: u8, a: u8) -> Self {
Self {
r: f32::from(r) / 255.0,
g: f32::from(g) / 255.0,
b: f32::from(b) / 255.0,
a: f32::from(a) / 255.0,
}
}
/// Construct an RGB color from a tuple of u8, or a named constant
#[inline]
#[must_use]
pub fn named(col: (u8, u8, u8)) -> Self {
Self::from_u8(col.0, col.1, col.2, 255)
}
/// Constructs from an HTML color code (e.g. "#eeffeeff")
///
/// # Errors
#[allow(clippy::cast_precision_loss)]
pub fn from_hex<S: AsRef<str>>(code: S) -> Result<Self, HtmlColorConversionError> {
let mut full_code = code.as_ref().chars();
if let Some(hash) = full_code.next() {
if hash != '#' {
return Err(HtmlColorConversionError::MissingHash);
}
} else {
return Err(HtmlColorConversionError::InvalidStringLength);
}
let red1 = match full_code.next() {
Some(red) => match red.to_digit(16) {
Some(red) => red * 16,
None => return Err(HtmlColorConversionError::InvalidCharacter),
},
None => return Err(HtmlColorConversionError::InvalidStringLength),
};
let red2 = match full_code.next() {
Some(red) => match red.to_digit(16) {
Some(red) => red,
None => return Err(HtmlColorConversionError::InvalidCharacter),
},
None => return Err(HtmlColorConversionError::InvalidStringLength),
};
let green1 = match full_code.next() {
Some(green) => match green.to_digit(16) {
Some(green) => green * 16,
None => return Err(HtmlColorConversionError::InvalidCharacter),
},
None => return Err(HtmlColorConversionError::InvalidStringLength),
};
let green2 = match full_code.next() {
Some(green) => match green.to_digit(16) {
Some(green) => green,
None => return Err(HtmlColorConversionError::InvalidCharacter),
},
None => return Err(HtmlColorConversionError::InvalidStringLength),
};
let blue1 = match full_code.next() {
Some(blue) => match blue.to_digit(16) {
Some(blue) => blue * 16,
None => return Err(HtmlColorConversionError::InvalidCharacter),
},
None => return Err(HtmlColorConversionError::InvalidStringLength),
};
let blue2 = match full_code.next() {
Some(blue) => match blue.to_digit(16) {
Some(blue) => blue,
None => return Err(HtmlColorConversionError::InvalidCharacter),
},
None => return Err(HtmlColorConversionError::InvalidStringLength),
};
let alpha1 = match full_code.next() {
Some(alpha) => match alpha.to_digit(16) {
Some(alpha) => alpha * 16,
None => return Err(HtmlColorConversionError::InvalidCharacter),
},
None => return Err(HtmlColorConversionError::InvalidStringLength),
};
let alpha2 = match full_code.next() {
Some(alpha) => match alpha.to_digit(16) {
Some(alpha) => alpha,
None => return Err(HtmlColorConversionError::InvalidCharacter),
},
None => return Err(HtmlColorConversionError::InvalidStringLength),
};
if full_code.next().is_some() {
return Err(HtmlColorConversionError::InvalidStringLength);
}
Ok(Self {
r: (red1 + red2) as f32 / 255.0,
g: (green1 + green2) as f32 / 255.0,
b: (blue1 + blue2) as f32 / 255.0,
a: (alpha1 + alpha2) as f32 / 255.0,
})
}
/// Converts to an RGB, dropping the alpha component
#[inline]
#[must_use]
pub fn to_rgb(&self) -> RGB {
RGB::from_f32(self.r, self.g, self.b)
}
/// Applies a quick grayscale conversion to the color
#[inline]
#[must_use]
pub fn to_greyscale(&self) -> Self {
let linear = (self.r * 0.2126) + (self.g * 0.7152) + (self.b * 0.0722);
Self::from_f32(linear, linear, linear, self.a)
}
/// Applies a lengthier desaturate (via HSV) to the color
#[inline]
#[must_use]
pub fn desaturate(&self) -> Self {
let mut hsv = self.to_rgb().to_hsv();
hsv.s = 0.0;
hsv.to_rgb().to_rgba(self.a)
}
/// Lerps by a specified percentage (from 0 to 1) between this color and another
#[inline]
#[must_use]
pub fn lerp(&self, color: Self, percent: f32) -> Self {
let range = (
color.r - self.r,
color.g - self.g,
color.b - self.b,
color.a - self.a,
);
Self {
r: self.r + range.0 * percent,
g: self.g + range.1 * percent,
b: self.b + range.2 * percent,
a: self.a + range.3 * percent,
}
}
/// Lerps only the alpha channel, by a specified percentage (from 0 to 1) between this color and another
#[inline]
#[must_use]
pub fn lerp_alpha(&self, color: Self, percent: f32) -> Self {
let range = color.a - self.a;
Self {
r: self.r,
g: self.g,
b: self.b,
a: self.a + range * percent,
}
}
}
/// Support conversion from RGB
impl From<RGB> for RGBA {
fn from(item: RGB) -> Self {
Self::from_f32(item.r, item.g, item.b, 1.0)
}
}
/// Support conversion from HSV
impl From<HSV> for RGBA {
fn from(item: HSV) -> Self {
item.to_rgba(1.0)
}
}
/// Support conversion from a color tuple
impl From<(u8, u8, u8, u8)> for RGBA {
fn from(vals: (u8, u8, u8, u8)) -> Self {
Self::from_u8(vals.0, vals.1, vals.2, vals.3)
}
}
/// Support conversion from a color tuple
impl From<(u8, u8, u8)> for RGBA {
fn from(vals: (u8, u8, u8)) -> Self {
Self::from_u8(vals.0, vals.1, vals.2, 255)
}
}
#[cfg(feature = "crossterm")]
mod crossterm_features {
use super::RGBA;
use crossterm::style::Color;
use std::convert::TryFrom;
impl TryFrom<RGBA> for Color {
type Error = &'static str;
fn try_from(rgb: RGBA) -> Result<Self, Self::Error> {
let (r, g, b) = (rgb.r, rgb.g, rgb.b);
for c in [r, g, b].iter() {
if *c < 0.0 {
return Err("Value < 0.0 found!");
}
if *c > 1.0 {
return Err("Value > 1.0 found!");
}
}
let (r, g, b) = ((r * 255.0) as u8, (g * 255.0) as u8, (b * 255.0) as u8);
let rgb = Color::Rgb { r, g, b };
Ok(rgb)
}
}
#[cfg(test)]
mod tests {
use crate::prelude::RGBA;
use crossterm::style::Color;
use std::convert::TryInto;
#[test]
fn basic_conversion() {
let rgb = RGBA {
r: 0.0,
g: 0.5,
b: 1.0,
a: 1.0,
};
let rgb: Color = rgb.try_into().unwrap();
match rgb {
Color::Rgb { r, g, b } => {
assert_eq!(r, 0);
assert_eq!(g, 127);
assert_eq!(b, 255);
}
_ => unreachable!(),
}
}
#[test]
fn negative_rgb() {
let rgb = RGBA {
r: 0.0,
g: 0.5,
b: -1.0,
a: 1.0,
};
let rgb: Result<Color, _> = rgb.try_into();
assert!(rgb.is_err());
}
#[test]
fn too_large_rgb() {
let rgb = RGBA {
r: 0.0,
g: 0.5,
b: 1.1,
a: 1.0,
};
let rgb: Result<Color, _> = rgb.try_into();
assert!(rgb.is_err());
}
}
}
// Unit tests for the color system
#[cfg(test)]
mod tests {
use crate::prelude::*;
#[test]
// Tests that we make an RGB triplet at defaults and it is black.
fn make_rgba_minimal() {
let black = RGBA::new();
assert!(black.r < std::f32::EPSILON);
assert!(black.g < std::f32::EPSILON);
assert!(black.b < std::f32::EPSILON);
assert!(black.a < std::f32::EPSILON);
}
#[test]
// Tests that we make an HSV triplet at defaults and it is black.
fn convert_olive_to_rgb() {
let grey = HSV::from_f32(60.0 / 360.0, 1.0, 0.501_960_8);
let rgb = grey.to_rgba(1.0);
assert!(f32::abs(rgb.r - 128.0 / 255.0) < std::f32::EPSILON);
assert!(f32::abs(rgb.g - 128.0 / 255.0) < std::f32::EPSILON);
assert!(rgb.b < std::f32::EPSILON);
assert!((rgb.a - 1.0).abs() < std::f32::EPSILON);
}
#[test]
// Tests that we make an HSV triplet at defaults and it is black.
fn test_red_hex() {
let rgb = RGBA::from_hex("#FF0000FF").expect("Invalid hex string");
assert!(f32::abs(rgb.r - 1.0) < std::f32::EPSILON);
assert!(rgb.g < std::f32::EPSILON);
assert!(rgb.b < std::f32::EPSILON);
assert!((rgb.a - 1.0).abs() < std::f32::EPSILON);
}
#[test]
// Tests that we make an HSV triplet at defaults and it is black.
fn test_green_hex() {
let rgb = RGBA::from_hex("#00FF00FF").expect("Invalid hex string");
assert!(rgb.r < std::f32::EPSILON);
assert!(f32::abs(rgb.g - 1.0) < std::f32::EPSILON);
assert!(rgb.b < std::f32::EPSILON);
assert!((rgb.a - 1.0).abs() < std::f32::EPSILON);
}
#[test]
// Tests that we make an HSV triplet at defaults and it is black.
fn test_blue_hex() {
let rgb = RGBA::from_hex("#0000FFFF").expect("Invalid hex string");
assert!(rgb.r < std::f32::EPSILON);
assert!(rgb.g < std::f32::EPSILON);
assert!(f32::abs(rgb.b - 1.0) < std::f32::EPSILON);
assert!((rgb.a - 1.0).abs() < std::f32::EPSILON);
}
#[test]
// Tests that we make an HSV triplet at defaults and it is black.
fn test_blue_named() {
let rgb = RGBA::named(BLUE);
assert!(rgb.r < std::f32::EPSILON);
assert!(rgb.g < std::f32::EPSILON);
assert!(f32::abs(rgb.b - 1.0) < std::f32::EPSILON);
assert!((rgb.a - 1.0).abs() < std::f32::EPSILON);
}
#[test]
// Test the lerp function
fn test_lerp() {
let black = RGBA::named(BLACK);
let white = RGBA::named(WHITE);
assert!(black.lerp(white, 0.0) == black);
assert!(black.lerp(white, 1.0) == white);
}
#[test]
// Test the lerp function
fn test_lerp_alpha() {
let black = RGB::named(BLACK).to_rgba(0.0);
let white = RGB::named(WHITE).to_rgba(1.0);
let l0 = black.lerp_alpha(white, 0.0);
let l1 = black.lerp_alpha(white, 1.0);
assert!(l0.a < std::f32::EPSILON);
assert!((l1.a - 1.0).abs() < std::f32::EPSILON);
assert!(l0.to_rgb() == RGB::named(BLACK));
assert!(l1.to_rgb() == RGB::named(BLACK));
}
}