1use crate::{Vec2, Vec4, vec2};
2
3#[repr(C)]
5#[derive(Clone, Copy, Debug, Default, PartialEq)]
6pub struct Rect {
7 pub x: f32,
8 pub y: f32,
9 pub w: f32,
10 pub h: f32,
11}
12impl Rect {
13 pub const ZERO: Self = Self::new(0.0, 0.0, 0.0, 0.0);
14 pub const fn new(x: f32, y: f32, w: f32, h: f32) -> Self {
15 Self { x, y, w, h }
16 }
17 pub const fn point(self) -> Vec2 {
18 vec2(self.x, self.y)
19 }
20 pub const fn size(self) -> Vec2 {
21 vec2(self.w, self.h)
22 }
23 pub fn center(self) -> Vec2 {
24 self.point() + self.size() * 0.5
25 }
26 pub const fn left(self) -> f32 {
27 self.x
28 }
29 pub const fn right(self) -> f32 {
30 self.x + self.w
31 }
32 pub const fn top(self) -> f32 {
33 self.y
34 }
35 pub const fn bottom(self) -> f32 {
36 self.y + self.h
37 }
38 pub fn is_finite(self) -> bool {
39 [self.x, self.y, self.w, self.h]
40 .into_iter()
41 .all(f32::is_finite)
42 }
43 pub fn contains(self, p: Vec2) -> bool {
44 self.is_finite()
45 && self.w >= 0.0
46 && self.h >= 0.0
47 && p.x >= self.x
48 && p.x <= self.right()
49 && p.y >= self.y
50 && p.y <= self.bottom()
51 }
52 pub fn overlaps(self, other: &Self) -> bool {
54 self.w > 0.0
55 && self.h > 0.0
56 && other.w > 0.0
57 && other.h > 0.0
58 && self.x < other.right()
59 && self.right() > other.x
60 && self.y < other.bottom()
61 && self.bottom() > other.y
62 }
63 pub fn intersect(self, other: Self) -> Option<Self> {
64 if !self.overlaps(&other) {
65 return None;
66 }
67 let point = self.point().max(other.point());
68 let end = vec2(self.right(), self.bottom()).min(vec2(other.right(), other.bottom()));
69 Some(Self::new(
70 point.x,
71 point.y,
72 end.x - point.x,
73 end.y - point.y,
74 ))
75 }
76 pub fn combine_with(self, other: Self) -> Self {
77 let p = self.point().min(other.point());
78 let end = vec2(self.right(), self.bottom()).max(vec2(other.right(), other.bottom()));
79 Self::new(p.x, p.y, end.x - p.x, end.y - p.y)
80 }
81 pub fn move_to(&mut self, p: Vec2) {
82 self.x = p.x;
83 self.y = p.y;
84 }
85 pub fn offset(self, delta: Vec2) -> Self {
86 Self::new(self.x + delta.x, self.y + delta.y, self.w, self.h)
87 }
88 pub fn normalized(self) -> Self {
89 Self::new(
90 self.x.min(self.right()),
91 self.y.min(self.bottom()),
92 self.w.abs(),
93 self.h.abs(),
94 )
95 }
96}
97
98#[derive(Clone, Copy, Debug, PartialEq, Eq)]
105pub enum ColorError {
106 NonFinite,
108 AlphaOutOfRange,
110 ConversionOverflow,
112}
113
114impl std::fmt::Display for ColorError {
115 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
116 f.write_str(match self {
117 Self::NonFinite => "color channels must be finite",
118 Self::AlphaOutOfRange => "color alpha must be in 0..=1",
119 Self::ConversionOverflow => "converted color channel overflows f32",
120 })
121 }
122}
123
124impl std::error::Error for ColorError {}
125
126#[repr(C)]
140#[derive(Clone, Copy, Debug, Default, PartialEq)]
141pub struct Color {
142 pub r: f32,
143 pub g: f32,
144 pub b: f32,
145 pub a: f32,
146}
147impl Color {
148 pub const fn new(r: f32, g: f32, b: f32, a: f32) -> Self {
150 Self { r, g, b, a }
151 }
152 pub fn try_new(r: f32, g: f32, b: f32, a: f32) -> Result<Self, ColorError> {
166 let color = Self::new(r, g, b, a);
167 if !color.is_finite() {
168 return Err(ColorError::NonFinite);
169 }
170 if !(0.0..=1.0).contains(&a) {
171 return Err(ColorError::AlphaOutOfRange);
172 }
173 Ok(color)
174 }
175 pub const fn from_rgba(r: u8, g: u8, b: u8, a: u8) -> Self {
177 Self::new(
178 r as f32 / 255.0,
179 g as f32 / 255.0,
180 b as f32 / 255.0,
181 a as f32 / 255.0,
182 )
183 }
184 pub const fn from_hex(rgb: u32) -> Self {
186 Self::from_rgba((rgb >> 16) as u8, (rgb >> 8) as u8, rgb as u8, 255)
187 }
188 pub const fn to_vec(self) -> Vec4 {
189 Vec4::new(self.r, self.g, self.b, self.a)
190 }
191 pub const fn to_array(self) -> [f32; 4] {
192 [self.r, self.g, self.b, self.a]
193 }
194 pub fn is_finite(self) -> bool {
202 self.to_array().into_iter().all(f32::is_finite)
203 }
204 pub fn try_clamped(self) -> Result<Self, ColorError> {
219 if !self.is_finite() {
220 return Err(ColorError::NonFinite);
221 }
222 Ok(Self::from(self.to_array().map(|c| c.clamp(0.0, 1.0))))
223 }
224 pub fn try_srgb_to_linear(self) -> Result<Self, ColorError> {
246 self.try_map_rgb(|c| {
247 if c.abs() <= 0.04045 {
248 c / 12.92
249 } else {
250 ((c.abs() + 0.055) / 1.055).powf(2.4).copysign(c)
251 }
252 })
253 }
254 pub fn try_linear_to_srgb(self) -> Result<Self, ColorError> {
273 self.try_map_rgb(|c| {
274 if c.abs() <= 0.0031308 {
275 12.92 * c
276 } else {
277 (1.055 * c.abs().powf(1.0 / 2.4) - 0.055).copysign(c)
278 }
279 })
280 }
281 fn try_map_rgb(self, convert: impl Fn(f64) -> f64) -> Result<Self, ColorError> {
282 Self::try_new(self.r, self.g, self.b, self.a)?;
283 let [r, g, b] = [self.r, self.g, self.b].map(|c| convert(f64::from(c)) as f32);
284 let color = Self::new(r, g, b, self.a);
285 if !color.is_finite() {
286 return Err(ColorError::ConversionOverflow);
287 }
288 Ok(color)
289 }
290 pub fn to_rgba(self) -> [u8; 4] {
296 self.to_array()
297 .map(|c| (c.clamp(0.0, 1.0) * 255.0).round() as u8)
298 }
299 pub const fn with_alpha(self, alpha: f32) -> Self {
300 Self { a: alpha, ..self }
301 }
302 pub fn lerp(self, other: Self, t: f32) -> Self {
305 Self::from(self.to_vec().lerp(other.to_vec(), t))
306 }
307 pub fn premultiplied(self) -> Self {
308 Self::new(self.r * self.a, self.g * self.a, self.b * self.a, self.a)
309 }
310}
311impl From<Vec4> for Color {
312 fn from(v: Vec4) -> Self {
313 Self::new(v.x, v.y, v.z, v.w)
314 }
315}
316impl From<[f32; 4]> for Color {
317 fn from(v: [f32; 4]) -> Self {
318 Self::new(v[0], v[1], v[2], v[3])
319 }
320}
321impl From<Color> for [f32; 4] {
322 fn from(v: Color) -> Self {
323 v.to_array()
324 }
325}
326impl From<Color> for Vec4 {
327 fn from(v: Color) -> Self {
328 v.to_vec()
329 }
330}
331
332#[cfg(test)]
333mod color_tests {
334 use super::{Color, ColorError};
335
336 fn near(actual: f32, expected: f32) {
337 let tolerance = 2.0e-7 * expected.abs().max(1.0);
338 assert!(
339 (actual - expected).abs() <= tolerance,
340 "{actual} != {expected} (tolerance {tolerance})"
341 );
342 }
343
344 #[test]
345 fn legacy_constructors_and_lerp_keep_raw_channel_semantics() {
346 const RAW: Color = Color::new(2.0, -1.0, 0.5, 3.0);
347 const BYTES: Color = Color::from_rgba(128, 64, 255, 32);
348 const HEX: Color = Color::from_hex(0x8040ff);
349 assert_eq!(RAW.to_array(), [2.0, -1.0, 0.5, 3.0]);
350 assert_eq!(RAW.to_rgba(), [255, 0, 128, 255]);
351 assert_eq!(
352 BYTES.to_array(),
353 [128.0 / 255.0, 64.0 / 255.0, 1.0, 32.0 / 255.0]
354 );
355 assert_eq!(HEX, BYTES.with_alpha(1.0));
356 assert_eq!(Color::from(RAW.to_vec()), RAW);
357 assert_eq!(Color::from(RAW.to_array()), RAW);
358
359 let black = Color::new(0.0, 0.0, 0.0, 0.0);
360 let white = Color::new(1.0, 1.0, 1.0, 1.0);
361 assert_eq!(black.lerp(white, 0.5).to_rgba(), [128; 4]);
362 assert_eq!(black.lerp(white, 1.5).to_array(), [1.5; 4]);
363 assert_eq!(black.lerp(white, -0.5).to_array(), [-0.5; 4]);
364 assert_eq!(white.with_alpha(0.5).premultiplied().to_array(), [0.5; 4]);
365 assert_eq!(
366 Color::new(f32::NAN, f32::NEG_INFINITY, f32::INFINITY, 0.5).to_rgba(),
367 [0, 0, 255, 128]
368 );
369 }
370
371 #[test]
372 fn checked_construction_accepts_hdr_but_rejects_invalid_alpha() {
373 let hdr = Color::try_new(-f32::MAX, f32::MAX, -0.25, -0.0).unwrap();
374 assert_eq!(hdr.to_array(), [-f32::MAX, f32::MAX, -0.25, -0.0]);
375 assert_eq!(hdr.a.to_bits(), (-0.0_f32).to_bits());
376 assert!(hdr.is_finite());
377 assert!(Color::try_new(1.0, 0.0, 0.0, 1.0).is_ok());
378 for alpha in [-f32::MAX, -f32::from_bits(1), 1.000_000_1, f32::MAX] {
379 let color = Color::new(0.25, 0.5, 0.75, alpha);
380 assert!(color.is_finite());
381 assert_eq!(
382 Color::try_new(0.25, 0.5, 0.75, alpha),
383 Err(ColorError::AlphaOutOfRange)
384 );
385 assert_eq!(color.try_srgb_to_linear(), Err(ColorError::AlphaOutOfRange));
386 assert_eq!(color.try_linear_to_srgb(), Err(ColorError::AlphaOutOfRange));
387 }
388 }
389
390 #[test]
391 fn all_checked_operations_reject_every_nonfinite_channel() {
392 for invalid in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
393 for index in 0..4 {
394 let mut channels = [0.5; 4];
395 channels[index] = invalid;
396 let color = Color::from(channels);
397 assert!(!color.is_finite());
398 assert_eq!(
399 Color::try_new(color.r, color.g, color.b, color.a),
400 Err(ColorError::NonFinite)
401 );
402 assert_eq!(color.try_srgb_to_linear(), Err(ColorError::NonFinite));
403 assert_eq!(color.try_linear_to_srgb(), Err(ColorError::NonFinite));
404 assert_eq!(color.try_clamped(), Err(ColorError::NonFinite));
405 }
406 }
407 assert_eq!(
409 Color::new(f32::NAN, 0.0, 0.0, 0.0).try_srgb_to_linear(),
410 Err(ColorError::NonFinite)
411 );
412 assert_eq!(
413 Color::try_new(f32::INFINITY, 0.0, 0.0, 2.0),
414 Err(ColorError::NonFinite)
415 );
416 }
417
418 #[test]
419 fn clamping_is_explicit_includes_alpha_and_does_not_convert() {
420 let color = Color::new(-1.0, 4.0, 0.5, 2.0);
421 let clipped = color.try_clamped().unwrap();
422 assert_eq!(clipped.to_array(), [0.0, 1.0, 0.5, 1.0]);
423 assert_eq!(clipped.try_clamped(), Ok(clipped));
424 assert_eq!(color.with_alpha(-2.0).try_clamped().unwrap().a, 0.0);
425 assert_eq!(color.to_array(), [-1.0, 4.0, 0.5, 2.0]);
426 assert_eq!(clipped.to_rgba(), [0, 255, 128, 255]);
427 }
428
429 #[test]
430 fn transfer_reference_values_and_endpoints() {
431 let color = Color::new(0.0, 0.5, 1.0, 0.25);
432 let decoded = color.try_srgb_to_linear().unwrap();
433 assert_eq!([decoded.r, decoded.b, decoded.a], [0.0, 1.0, 0.25]);
434 near(decoded.g, 0.214_041_14);
435 let encoded = color.try_linear_to_srgb().unwrap();
436 assert_eq!([encoded.r, encoded.b, encoded.a], [0.0, 1.0, 0.25]);
437 near(encoded.g, 0.735_357);
438 near(
439 Color::from_hex(0x808080).try_srgb_to_linear().unwrap().r,
440 0.215_860_5,
441 );
442 near(
443 Color::new(0.18, 0.18, 0.18, 1.0)
444 .try_linear_to_srgb()
445 .unwrap()
446 .r,
447 0.461_356_13,
448 );
449 }
450
451 #[test]
452 fn dark_segments_and_signed_extension_match_reference_values() {
453 let decoded = Color::new(0.02, -0.02, -0.5, 1.0)
454 .try_srgb_to_linear()
455 .unwrap();
456 near(decoded.r, 0.001_547_987_6);
457 assert_eq!(decoded.g, -decoded.r);
458 near(decoded.b, -0.214_041_14);
459 let encoded = Color::new(0.001, -0.001, -0.5, 1.0)
460 .try_linear_to_srgb()
461 .unwrap();
462 near(encoded.r, 0.012_92);
463 assert_eq!(encoded.g, -encoded.r);
464 near(encoded.b, -0.735_357);
465 }
466
467 #[test]
468 fn transfer_breakpoints_match_reference_samples_on_both_sides() {
469 for (bits, expected) in [
472 (0x3d25_aee5, 0.003_130_804_6),
473 (0x3d25_aee6, 0.003_130_804_8),
474 (0x3d25_aee7, 0.003_130_807_5),
475 ] {
476 let value = f32::from_bits(bits);
477 let decoded = Color::new(value, -value, 0.0, 1.0)
478 .try_srgb_to_linear()
479 .unwrap();
480 assert!((decoded.r - expected).abs() < 5.0e-10);
481 assert_eq!(decoded.g, -decoded.r);
482 }
483 for (bits, expected) in [
484 (0x3b4d_2e1b, 0.040_449_936),
485 (0x3b4d_2e1c, 0.040_449_91),
486 (0x3b4d_2e1d, 0.040_449_913),
487 ] {
488 let value = f32::from_bits(bits);
489 let encoded = Color::new(value, -value, 0.0, 1.0)
490 .try_linear_to_srgb()
491 .unwrap();
492 assert!((encoded.r - expected).abs() < 5.0e-9);
493 assert_eq!(encoded.g, -encoded.r);
494 }
495 }
496
497 #[test]
498 fn all_byte_channels_round_trip_with_alpha_unchanged() {
499 for value in 0..=u8::MAX {
500 let bytes = [value, 255 - value, value / 2, 255 - value];
501 let color = Color::from_rgba(bytes[0], bytes[1], bytes[2], bytes[3]);
502 let linear = color.try_srgb_to_linear().unwrap();
503 let encoded = linear.try_linear_to_srgb().unwrap();
504 assert_eq!(linear.a.to_bits(), color.a.to_bits());
505 assert_eq!(encoded.a.to_bits(), color.a.to_bits());
506 assert_eq!(encoded.to_rgba(), bytes);
507 }
508 }
509
510 #[test]
511 fn conversions_preserve_transparent_rgb_and_alpha_bits() {
512 for alpha in [-0.0, 0.0, f32::from_bits(1), 0.5, 1.0] {
513 let color = Color::new(0.5, 0.25, 0.75, alpha);
514 let decoded = color.try_srgb_to_linear().unwrap();
515 near(decoded.r, 0.214_041_14);
516 assert_eq!(decoded.a.to_bits(), alpha.to_bits());
517 let encoded = color.try_linear_to_srgb().unwrap();
518 near(encoded.r, 0.735_357);
519 assert_eq!(encoded.a.to_bits(), alpha.to_bits());
520 }
521 }
522
523 #[test]
524 fn hdr_and_out_of_gamut_channels_round_trip_without_clipping() {
525 for value in [
526 -1.0e10, -100.0, -4.0, -1.0, -0.25, 0.25, 1.0, 4.0, 100.0, 1.0e10,
527 ] {
528 let color = Color::try_new(value, -value, value / 2.0, 0.5).unwrap();
529 let decoded = color.try_srgb_to_linear().unwrap();
530 let encoded = color.try_linear_to_srgb().unwrap();
531 assert_eq!(decoded.r.is_sign_negative(), value.is_sign_negative());
532 assert_eq!(encoded.r.is_sign_negative(), value.is_sign_negative());
533 if value.abs() > 1.0 {
534 assert!(decoded.r.abs() > 1.0);
535 assert!(encoded.r.abs() > 1.0);
536 }
537 for (actual, expected) in decoded
538 .try_linear_to_srgb()
539 .unwrap()
540 .to_array()
541 .into_iter()
542 .zip(color.to_array())
543 {
544 near(actual, expected);
545 }
546 for (actual, expected) in encoded
547 .try_srgb_to_linear()
548 .unwrap()
549 .to_array()
550 .into_iter()
551 .zip(color.to_array())
552 {
553 near(actual, expected);
554 }
555 }
556 }
557
558 #[test]
559 fn decode_reports_overflow_and_encode_accepts_extreme_finite_rgb() {
560 for value in [f32::MAX, -f32::MAX] {
561 for index in 0..3 {
562 let mut channels = [0.5; 4];
563 channels[index] = value;
564 let color = Color::from(channels);
565 assert_eq!(
566 color.try_srgb_to_linear(),
567 Err(ColorError::ConversionOverflow)
568 );
569 let encoded = color.try_linear_to_srgb().unwrap();
570 assert!(encoded.is_finite());
571 assert!(encoded.to_array()[index].abs() > 1.0);
572 assert_eq!(
573 encoded.to_array()[index].is_sign_negative(),
574 value.is_sign_negative()
575 );
576 assert_eq!(color.to_array(), channels);
577 }
578 }
579 }
580
581 #[test]
582 fn signed_zero_and_subnormal_rounding_are_explicit() {
583 let color = Color::new(-0.0, -f32::from_bits(1), f32::from_bits(1), -0.0);
584 let decoded = color.try_srgb_to_linear().unwrap();
585 assert_eq!(decoded.r.to_bits(), (-0.0_f32).to_bits());
586 assert_eq!(decoded.g.to_bits(), (-0.0_f32).to_bits());
587 assert_eq!(decoded.b.to_bits(), 0.0_f32.to_bits());
588 let encoded = color.try_linear_to_srgb().unwrap();
589 assert_eq!(encoded.r.to_bits(), (-0.0_f32).to_bits());
590 assert!(encoded.g < 0.0 && encoded.b > 0.0);
591 assert_eq!(encoded.g, -encoded.b);
592 assert_eq!(encoded.a.to_bits(), (-0.0_f32).to_bits());
593 }
594
595 #[test]
596 fn linear_light_interpolation_is_opt_in() {
597 let black = Color::from_hex(0x000000);
598 let white = Color::from_hex(0xffffff);
599 let middle = black
600 .try_srgb_to_linear()
601 .unwrap()
602 .lerp(white.try_srgb_to_linear().unwrap(), 0.5)
603 .try_linear_to_srgb()
604 .unwrap();
605 assert_eq!(middle.to_rgba(), [188, 188, 188, 255]);
606 assert_eq!(black.lerp(white, 0.5).to_rgba(), [128, 128, 128, 255]);
607 }
608}