drawing_stuff/
color.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
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RGBA {
    pub r: u8,
    pub g: u8,
    pub b: u8,
    pub a: u8,
}

impl RGBA {
    pub fn new(r: u8, g: u8, b: u8, a: u8) -> Self {
        Self { r, g, b, a }
    }

    pub fn to_rgb(self) -> (RGB, u8) {
        (
            RGB {
                r: self.r,
                g: self.g,
                b: self.b,
            },
            self.a,
        )
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RGB {
    pub r: u8,
    pub g: u8,
    pub b: u8,
}

impl RGB {
    /// Adds an RGBA value onto a RGB value returning the result.
    /// This simply performs a linear interpolation between the two.
    pub fn add_rgba(self, other: RGBA) -> Self {
        let (other, alpha) = other.to_rgb();
        self.lerp(&other, alpha as f64 / 255.0)
    }

    /// Performs a linear interpolation between two RGB values returning the result.
    pub fn lerp(&self, other: &Self, a: f64) -> Self {
        RGB {
            r: ((1.0 - a) * self.r as f64 + a * other.r as f64) as u8,
            g: ((1.0 - a) * self.g as f64 + a * other.g as f64) as u8,
            b: ((1.0 - a) * self.b as f64 + a * other.b as f64) as u8,
        }
    }
}

//== constants =====

pub const TRANSPARANT: RGBA = RGBA {
    r: 0,
    g: 0,
    b: 0,
    a: 0,
};

pub const BLACK: RGBA = RGBA {
    r: 0,
    g: 0,
    b: 0,
    a: 255,
};

pub const WHITE: RGBA = RGBA {
    r: 255,
    g: 255,
    b: 255,
    a: 255,
};

pub const RED: RGBA = RGBA {
    r: 255,
    g: 0,
    b: 0,
    a: 255,
};

pub const GREEN: RGBA = RGBA {
    r: 0,
    g: 255,
    b: 0,
    a: 255,
};

pub const BLUE: RGBA = RGBA {
    r: 0,
    g: 0,
    b: 255,
    a: 255,
};