Skip to main content

boa_engine/vm/flowgraph/
color.rs

1use std::fmt::Display;
2
3/// Represents the color of a node or edge.
4#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5pub enum Color {
6    /// Represents the default color.
7    None,
8    /// Represents the color red.
9    Red,
10    /// Represents the color green.
11    Green,
12    /// Represents the color blue.
13    Blue,
14    /// Represents the color yellow.
15    Yellow,
16    /// Represents the color purple.
17    Purple,
18    /// Represents a RGB color.
19    Rgb {
20        /// Red.
21        r: u8,
22        /// Green.
23        g: u8,
24        /// Blue.
25        b: u8,
26    },
27}
28
29impl Color {
30    /// Function for converting HSV to RGB color format.
31    #[allow(clippy::many_single_char_names)]
32    #[must_use]
33    pub fn hsv_to_rgb(h: f64, s: f64, v: f64) -> Self {
34        let h_i = (h * 6.0) as i64;
35        let f = h.mul_add(6.0, -h_i as f64);
36        let p = v * (1.0 - s);
37        let q = v * f.mul_add(-s, 1.0);
38        let t = v * (1.0 - f).mul_add(-s, 1.0);
39
40        let (r, g, b) = match h_i {
41            0 => (v, t, p),
42            1 => (q, v, p),
43            2 => (p, v, t),
44            3 => (p, q, v),
45            4 => (t, p, v),
46            5 => (v, p, q),
47            _ => unreachable!(),
48        };
49
50        let r = (r * 256.0) as u8;
51        let g = (g * 256.0) as u8;
52        let b = (b * 256.0) as u8;
53
54        Self::Rgb { r, g, b }
55    }
56
57    /// This function takes a random value and converts it to
58    /// a pleasant to look at RGB color.
59    #[inline]
60    #[must_use]
61    pub fn from_random_number(mut random: f64) -> Self {
62        const GOLDEN_RATIO_CONJUGATE: f64 = 0.618_033_988_749_895;
63        random += GOLDEN_RATIO_CONJUGATE;
64        random %= 1.0;
65
66        Self::hsv_to_rgb(random, 0.7, 0.95)
67    }
68
69    /// Check if the color is [`Self::None`].
70    #[inline]
71    #[must_use]
72    pub fn is_none(&self) -> bool {
73        *self == Self::None
74    }
75}
76
77impl Display for Color {
78    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79        match self {
80            Self::None => f.write_str(""),
81            Self::Red => f.write_str("red"),
82            Self::Green => f.write_str("green"),
83            Self::Blue => f.write_str("blue"),
84            Self::Yellow => f.write_str("yellow"),
85            Self::Purple => f.write_str("purple"),
86            Self::Rgb { r, g, b } => write!(f, "#{r:02X}{b:02X}{g:02X}"),
87        }
88    }
89}