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
use std::fmt;

use serde::{Deserialize, Serialize};

use geom::{Line, Pt2D};

#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct Color {
    pub r: f32,
    pub g: f32,
    pub b: f32,
    pub a: f32,
}

impl fmt::Display for Color {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "Color(r={}, g={}, b={}, a={})",
            self.r, self.g, self.b, self.a
        )
    }
}

#[derive(Debug, Clone, PartialEq)]
pub enum Fill {
    Color(Color),
    LinearGradient(LinearGradient),

    /// Once uploaded, textures are addressed by their id, starting from 1, from left to right, top
    /// to bottom, like so:
    ///
    ///   ┌─┬─┬─┐
    ///   │1│2│3│
    ///   ├─┼─┼─┤
    ///   │4│5│6│
    ///   ├─┼─┼─┤
    ///   │7│8│9│
    ///   └─┴─┴─┘
    ///
    /// Texture(0) is reserved for a pure white (no-op) texture.
    Texture(Texture),

    /// The `color` parameter is multiplied by any color baked into the texture, so typically this
    /// only makes sense for grayscale textures.
    ColoredTexture(Color, Texture),
}

#[derive(Debug, Copy, Clone, PartialEq)]
pub struct Texture(pub u32);

#[allow(dead_code)]
impl Texture {
    pub const NOOP: Texture = Texture(0);
    // Note all of these are based on the default built-in spritesheet
    pub const GRASS: Texture = Texture(1);
    pub const STILL_WATER: Texture = Texture(2);
    pub const RUNNING_WATER: Texture = Texture(3);
    pub const CONCRETE: Texture = Texture(4);
    pub const SAND: Texture = Texture(5);
    pub const DIRT: Texture = Texture(6);
    pub const SNOW: Texture = Texture(7);
    pub const TREE: Texture = Texture(15);
    pub const PINE_TREE: Texture = Texture(16);
    pub const CACTUS: Texture = Texture(17);
    pub const SHRUB: Texture = Texture(18);
    pub const CROSS_HATCH: Texture = Texture(19);
    pub const SNOW_PERSON: Texture = Texture(29);
}

impl Color {
    // TODO Won't this confuse the shader?
    pub const CLEAR: Color = Color::rgba_f(1.0, 0.0, 0.0, 0.0);
    pub const BLACK: Color = Color::rgb_f(0.0, 0.0, 0.0);
    pub const WHITE: Color = Color::rgb_f(1.0, 1.0, 1.0);
    pub const RED: Color = Color::rgb_f(1.0, 0.0, 0.0);
    pub const GREEN: Color = Color::rgb_f(0.0, 1.0, 0.0);
    pub const BLUE: Color = Color::rgb_f(0.0, 0.0, 1.0);
    pub const CYAN: Color = Color::rgb_f(0.0, 1.0, 1.0);
    pub const YELLOW: Color = Color::rgb_f(1.0, 1.0, 0.0);
    pub const PURPLE: Color = Color::rgb_f(0.5, 0.0, 0.5);
    pub const PINK: Color = Color::rgb_f(1.0, 0.41, 0.71);
    pub const ORANGE: Color = Color::rgb_f(1.0, 0.55, 0.0);

    // TODO should assert stuff about the inputs

    // TODO Once f32 can be used in const fn, make these const fn too and clean up call sites
    // dividing by 255.0. https://github.com/rust-lang/rust/issues/57241
    pub fn rgb(r: usize, g: usize, b: usize) -> Color {
        Color::rgba(r, g, b, 1.0)
    }

    pub const fn rgb_f(r: f32, g: f32, b: f32) -> Color {
        Color { r, g, b, a: 1.0 }
    }

    pub fn rgba(r: usize, g: usize, b: usize, a: f32) -> Color {
        Color {
            r: (r as f32) / 255.0,
            g: (g as f32) / 255.0,
            b: (b as f32) / 255.0,
            a,
        }
    }

    pub const fn rgba_f(r: f32, g: f32, b: f32, a: f32) -> Color {
        Color { r, g, b, a }
    }

    pub const fn grey(f: f32) -> Color {
        Color::rgb_f(f, f, f)
    }

    /// Note this is incorrect for `Color::CLEAR`. Can't fix in a const fn.
    pub const fn alpha(&self, a: f32) -> Color {
        Color::rgba_f(self.r, self.g, self.b, a)
    }

    /// Multiply the color's current alpha by the `factor`, returning a new color.
    pub fn multiply_alpha(&self, factor: f32) -> Color {
        Color::rgba_f(self.r, self.g, self.b, self.a * factor)
    }

    pub fn hex(raw: &str) -> Color {
        // Skip the leading '#'
        let r = usize::from_str_radix(&raw[1..3], 16).unwrap();
        let g = usize::from_str_radix(&raw[3..5], 16).unwrap();
        let b = usize::from_str_radix(&raw[5..7], 16).unwrap();
        Color::rgb(r, g, b)
    }

    pub fn as_hex(&self) -> String {
        format!(
            "#{:02X}{:02X}{:02X}",
            (self.r * 255.0) as usize,
            (self.g * 255.0) as usize,
            (self.b * 255.0) as usize
        )
    }

    pub fn lerp(self, other: Color, pct: f64) -> Color {
        Color::rgba_f(
            lerp(pct, (self.r, other.r)),
            lerp(pct, (self.g, other.g)),
            lerp(pct, (self.b, other.b)),
            lerp(pct, (self.a, other.a)),
        )
    }

    // Mix the color with black
    pub fn shade(self, black_ratio: f64) -> Color {
        self.lerp(Color::BLACK, black_ratio)
    }

    // Mix the color with white
    pub fn tint(self, white_ratio: f64) -> Color {
        self.lerp(Color::WHITE, white_ratio)
    }

    // A theme agnostic way to get a more/less intense color without affecting alpha.
    pub fn dull(self, ratio: f64) -> Color {
        self.lerp(Color::grey(0.5), ratio)
    }

    pub fn invert(self) -> Color {
        Color::rgba_f(1.0 - self.r, 1.0 - self.g, 1.0 - self.b, self.a)
    }
}

// https://developer.mozilla.org/en-US/docs/Web/CSS/linear-gradient is the best reference I've
// found, even though it's technically for CSS, not SVG. Ah, and
// https://www.w3.org/TR/SVG11/pservers.html
#[derive(Debug, Clone, PartialEq)]
pub struct LinearGradient {
    pub line: Line,
    pub stops: Vec<(f64, Color)>,
}

impl LinearGradient {
    pub(crate) fn new_fill(lg: &usvg::LinearGradient) -> Fill {
        let line = Line::must_new(Pt2D::new(lg.x1, lg.y1), Pt2D::new(lg.x2, lg.y2));
        let mut stops = Vec::new();
        for stop in &lg.stops {
            let color = Color::rgba(
                stop.color.red as usize,
                stop.color.green as usize,
                stop.color.blue as usize,
                stop.opacity.get() as f32,
            );
            stops.push((stop.offset.get(), color));
        }
        Fill::LinearGradient(LinearGradient { line, stops })
    }

    fn interp(&self, pt: Pt2D) -> Color {
        let pct = self
            .line
            .percent_along_of_point(self.line.to_polyline().project_pt(pt))
            .unwrap();
        if pct < self.stops[0].0 {
            return self.stops[0].1;
        }
        if pct > self.stops.last().unwrap().0 {
            return self.stops.last().unwrap().1;
        }
        // In between two
        for ((pct1, c1), (pct2, c2)) in self.stops.iter().zip(self.stops.iter().skip(1)) {
            if pct >= *pct1 && pct <= *pct2 {
                return c1.lerp(*c2, to_pct(pct, (*pct1, *pct2)));
            }
        }
        unreachable!()
    }
}

fn to_pct(value: f64, (low, high): (f64, f64)) -> f64 {
    assert!(low <= high);
    assert!(value >= low);
    assert!(value <= high);
    (value - low) / (high - low)
}

fn lerp(pct: f64, (x1, x2): (f32, f32)) -> f32 {
    x1 + (pct as f32) * (x2 - x1)
}

impl Fill {
    pub(crate) fn shader_style(&self, pt: Pt2D) -> [f32; 5] {
        match self {
            Fill::Color(c) => [c.r, c.g, c.b, c.a, 0.0],
            Fill::LinearGradient(ref lg) => {
                let c = lg.interp(pt);
                [c.r, c.g, c.b, c.a, 0.0]
            }
            Fill::Texture(texture) => [1.0, 1.0, 1.0, 1.0, texture.0 as f32],
            Fill::ColoredTexture(color, texture) => {
                [color.r, color.g, color.b, color.a, texture.0 as f32]
            }
        }
    }
}

impl std::convert::From<Color> for Fill {
    fn from(color: Color) -> Fill {
        Fill::Color(color)
    }
}

impl std::convert::From<Texture> for Fill {
    fn from(texture: Texture) -> Fill {
        Fill::Texture(texture)
    }
}