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
//! Draw rectangle
//!
//! This module contains the definintion of a rectangle with possibly rounded
//! corners. It contains the code to draw the rectangle and defines properties
//! like color and shape. The rectangle dimensions and location are specified by
//! `types::Rectangle`.
//!
//! To draw a square with side 10 and top left corner in (0, 0), do the
//! following:
//! ```ignore
//! let rectangle = Rectangle::new(color::BLACK);
//! let dims = square(0.0, 0.0, 10.0);
//! rectangle.draw(dims, &draw_state::Default::default(), transform, g);
//! ```

use types::{Color, Radius, Resolution};
use {types, triangulation, Graphics, DrawState};
use math::{Matrix2d, Scalar};

pub use math::margin_rectangle as margin;


/// Create `types::Rectangle` by the two opposite corners.
///
/// The corners are in (x0, y0) and (x1, y1).
pub fn rectangle_by_corners(x0: Scalar, y0: Scalar, x1: Scalar, y1: Scalar) -> types::Rectangle {
    let (xmin, w) = if x0 <= x1 {
        (x0, x1 - x0)
    } else {
        (x1, x0 - x1)
    };

    let (ymin, h) = if y0 <= y1 {
        (y0, y1 - y0)
    } else {
        (y1, y0 - y1)
    };

    [xmin, ymin, w, h]
}

/// Use x, y, half-width, half-height
pub fn centered(rect: types::Rectangle) -> types::Rectangle {
    [rect[0] - rect[2], rect[1] - rect[3], 2.0 * rect[2], 2.0 * rect[3]]
}

/// Create `types::Rectangle` for a square with a center in (`x`, `y`) and side
/// `2 * radius`.
pub fn centered_square(x: Scalar, y: Scalar, radius: Scalar) -> types::Rectangle {
    [x - radius, y - radius, 2.0 * radius, 2.0 * radius]
}

/// Create `types::Rectangle` for a square with a top-left corner in (`x`, `y`)
/// and side `size`.
pub fn square(x: Scalar, y: Scalar, size: Scalar) -> types::Rectangle {
    [x, y, size, size]
}

/// The shape of the rectangle corners
#[derive(Copy, Clone)]
pub enum Shape {
    /// Square corners
    Square,
    /// Round corners, with resolution per corner.
    Round(Radius, Resolution),
    /// Bevel corners
    Bevel(Radius),
}

/// The border of the rectangle
#[derive(Copy, Clone)]
pub struct Border {
    /// The color of the border
    pub color: Color,
    /// The radius of the border. The half-width of the line by which border is
    /// drawn.
    pub radius: Radius,
}

/// A filled rectangle
#[derive(Copy, Clone)]
pub struct Rectangle {
    /// The rectangle color
    pub color: Color,
    /// The roundness of the rectangle
    pub shape: Shape,
    /// The border
    pub border: Option<Border>,
}

impl Rectangle {
    /// Creates a new rectangle.
    pub fn new(color: Color) -> Rectangle {
        Rectangle {
            color: color,
            shape: Shape::Square,
            border: None,
        }
    }

    /// Creates a new rectangle with rounded corners.
    pub fn new_round(color: Color, round_radius: Radius) -> Rectangle {
        Rectangle {
            color: color,
            shape: Shape::Round(round_radius, 32),
            border: None,
        }
    }

    /// Creates a new rectangle border.
    pub fn new_border(color: Color, radius: Radius) -> Rectangle {
        Rectangle {
            color: [0.0; 4],
            shape: Shape::Square,
            border: Some(Border {
                color: color,
                radius: radius,
            }),
        }
    }

    /// Creates a new rectangle border with rounded corners.
    pub fn new_round_border(color: Color,
                            round_radius: Radius,
                            border_radius: Radius)
                            -> Rectangle {
        Rectangle {
            color: [0.0; 4],
            shape: Shape::Round(round_radius, 32),
            border: Some(Border {
                color: color,
                radius: border_radius,
            }),
        }
    }

    /// Sets color.
    pub fn color(mut self, value: Color) -> Self {
        self.color = value;
        self
    }

    /// Sets shape of the corners.
    pub fn shape(mut self, value: Shape) -> Self {
        self.shape = value;
        self
    }

    /// Sets border properties.
    pub fn border(mut self, value: Border) -> Self {
        self.border = Some(value);
        self
    }

    /// Sets optional border.
    pub fn maybe_border(mut self, value: Option<Border>) -> Self {
        self.border = value;
        self
    }

    /// Draws the rectangle by corners using the default method.
    #[inline(always)]
    pub fn draw_from_to<P: Into<types::Vec2d>, G>(&self,
                                              from: P,
                                              to: P,
                                              draw_state: &DrawState,
                                              transform: Matrix2d,
                                              g: &mut G)
        where G: Graphics
    {
        let from = from.into();
        let to = to.into();
        g.rectangle(self, rectangle_by_corners(from[0], from[1], to[0], to[1]), draw_state, transform);
    }

    /// Draws the rectangle using the default method.
    ///
    /// `rectangle` defines the rectangle's location and dimensions,
    /// `draw_state` draw state, `draw_state::Default::default()` can be used
    /// as a default, `transform` is the transformation matrix, `g` is the
    /// `Graphics` implementation, that is used to actually draw the rectangle.s
    #[inline(always)]
    pub fn draw<R: Into<types::Rectangle>, G>(&self,
                                              rectangle: R,
                                              draw_state: &DrawState,
                                              transform: Matrix2d,
                                              g: &mut G)
        where G: Graphics
    {
        g.rectangle(self, rectangle, draw_state, transform);
    }

    /// Draws the rectangle using triangulation.
    ///
    /// This is the default implementation of draw() that will be used if `G`
    /// does not redefine `Graphics::rectangle()`.
    pub fn draw_tri<R: Into<types::Rectangle>, G>(&self,
                                                  rectangle: R,
                                                  draw_state: &DrawState,
                                                  transform: Matrix2d,
                                                  g: &mut G)
        where G: Graphics
    {
        let rectangle = rectangle.into();
        if self.color[3] != 0.0 {
            match self.shape {
                Shape::Square => {
                    g.tri_list(draw_state,
                               &self.color,
                               |f| f(&triangulation::rect_tri_list_xy(transform, rectangle)));
                }
                Shape::Round(round_radius, resolution) => {
                    g.tri_list(draw_state, &self.color, |f| {
                        triangulation::with_round_rectangle_tri_list(resolution,
                                                                     transform,
                                                                     rectangle,
                                                                     round_radius,
                                                                     |vertices| f(vertices))
                    });
                }
                Shape::Bevel(bevel_radius) => {
                    g.tri_list(draw_state, &self.color, |f| {
                        triangulation::with_round_rectangle_tri_list(2,
                                                                     transform,
                                                                     rectangle,
                                                                     bevel_radius,
                                                                     |vertices| f(vertices))
                    });
                }
            }
        }

        if let Some(Border { color, radius: border_radius }) = self.border {
            if color[3] == 0.0 {
                return;
            }
            match self.shape {
                Shape::Square => {
                    g.tri_list(draw_state, &color, |f| {
                        f(&triangulation::rect_border_tri_list_xy(transform,
                                                                  rectangle,
                                                                  border_radius))
                    });
                }
                Shape::Round(round_radius, resolution) => {
                    g.tri_list(draw_state, &color, |f| {
                        triangulation::with_round_rectangle_border_tri_list(resolution,
                                                                            transform,
                                                                            rectangle,
                                                                            round_radius,
                                                                            border_radius,
                                                                            |vertices| f(vertices))
                    });
                }
                Shape::Bevel(bevel_radius) => {
                    g.tri_list(draw_state, &color, |f| {
                        triangulation::with_round_rectangle_border_tri_list(2,
                                                                            transform,
                                                                            rectangle,
                                                                            bevel_radius,
                                                                            border_radius,
                                                                            |vertices| f(vertices))
                    });
                }
            }
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_rectangle() {
        let _rectangle = Rectangle::new([1.0; 4])
            .color([0.0; 4])
            .shape(Shape::Round(10.0, 32))
            .border(Border {
                color: [0.0; 4],
                radius: 4.0,
            });
    }

    #[test]
    fn test_rectangle_by_corners() {
        assert_eq!(rectangle_by_corners(1.0, -1.0, 2.0, 3.0),
                   [1.0, -1.0, 1.0, 4.0]);
        assert_eq!(rectangle_by_corners(2.0, 3.0, 1.0, -1.0),
                   [1.0, -1.0, 1.0, 4.0]);
    }
}