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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
#![allow(non_snake_case)]
use std::fmt;

use super::{ShapeTrait, ShapeFinished};
use crate::draw_commands::DrawCommand;
use crate::color::Color;
use crate::ShapeType;
use crate::point::Point;

/// Given two points return the points in their 1/3 and 2/3 of the segment from
/// a to b.
fn thirds(a: Point, b: Point) -> (Point, Point) {
    let v = b - a;

    (v*1.0/3.0 + a, v*2.0/3.0 + a)
}

/// return a vector of magnitude 1 that has the slope of the external bisector
/// of the angle described by the three given points.
///
/// B is the vertex of the angle. The returned vector points towads C
fn bisector(A: Point, B: Point, C: Point) -> Point {
    let Ap = (A - B) * -1.0 + B;
    let (a, b, c) = (B.distance(C), A.distance(C), A.distance(B));
    let incenter = (Ap * a + B * b + C * c) / (a + b + c);

    let vec = incenter - B;

    vec / vec.magnitude()
}

/// Given the last two commands of a path and a new point given as input compute
/// what the last two commands of the path should be.
///
/// This means that the command at the last position before the operation must
/// be replaced with the one provided first by this function.
fn add_smooth(sec: Option<PathCommand>, last: PathCommand, pos: Point) -> (PathCommand, Option<PathCommand>) {
    match last {
        PathCommand::MoveTo(p) | PathCommand::LineTo(p) => {
            // Second point, put pt1 and pt2 at 1/3 and 2/3 of the
            // segment, set `to` to p.
            if p == pos {
                (last, None)
            } else {
                let (pt1, pt2) = thirds(p, pos);

                (last, Some(PathCommand::CurveTo(CubicBezierCurve {
                    pt1,
                    pt2,
                    to: pos,
                })))
            }
        }
        PathCommand::CurveTo(c) => {
            if c.to == pos {
                (last, None)
            } else {
                // calcula la bisectriz entre el punto anteanterior, el
                // anterior y este. Calcula la perpendicular a esa bisectriz
                // que pasa por el punto anterior. Pon el manejador de la
                // curva anterior y el primer manejador de esta curva en esa
                // recta.
                //
                // El Segundo manejador va en el segmento que conecta los
                // dos últimos puntos
                let prev = sec.unwrap().point();
                let bis = bisector(prev, c.to, pos);

                let fixed_prev_handle = bis * (c.to - prev).magnitude()/-3.0 + c.to;
                let new_pt1 = bis * (pos - c.to).magnitude()/3.0 + c.to;
                let new_pt2 = (pos - c.to) * 2.0/3.0 + c.to;

                if fixed_prev_handle.is_nan() || new_pt1.is_nan() || new_pt2.is_nan() {
                    (last, None)
                } else {
                    (PathCommand::CurveTo(CubicBezierCurve {
                        pt2: fixed_prev_handle,
                        ..c
                    }), Some(PathCommand::CurveTo(CubicBezierCurve {
                        pt1: new_pt1,
                        pt2: new_pt2,
                        to: pos,
                    })))
                }
            }
        }
    }
}

fn add_point(commands: &mut Vec<PathCommand>, pos: Point) {
    let sub = commands
        .len()
        .checked_sub(2)
        .map(|index| commands.get(index))
        .flatten()
        .copied();
    let last = commands.pop().unwrap();

    let (last, new) = add_smooth(sub, last, pos);

    commands.push(last);

    if let Some(new) = new {
        commands.push(new);
    }
}

#[derive(Debug, PartialEq, Copy, Clone)]
pub struct CubicBezierCurve {
    /// The (x, y) coordinates of the first control point.
    pub pt1: Point,
    /// The (x, y) coordinates of the second control point.
    pub pt2: Point,
    /// The (x, y) coordinates of the end point of this path segment.
    pub to: Point,
}

impl CubicBezierCurve {
    pub fn is_nan(&self) -> bool {
        self.pt1.is_nan() || self.pt2.is_nan() || self.to.is_nan()
    }
}

#[derive(Debug, PartialEq, Copy, Clone)]
pub enum Sweep {
    Negative,
    Positive,
}

#[derive(Debug, PartialEq, Copy, Clone)]
pub enum PathCommand {
    MoveTo(Point),
    LineTo(Point),
    CurveTo(CubicBezierCurve),
}

impl PathCommand {
    pub fn is_nan(&self) -> bool {
        match self {
            PathCommand::MoveTo(p) => p.is_nan(),
            PathCommand::LineTo(p) => p.is_nan(),
            PathCommand::CurveTo(c) => c.is_nan(),
        }
    }

    fn min_x(&self) -> f64 {
        match self {
            PathCommand::MoveTo(p) => p.x,
            PathCommand::LineTo(p) => p.x,
            PathCommand::CurveTo(c) => c.pt1.x.min(c.pt2.x).min(c.to.x),
        }
    }

    fn min_y(&self) -> f64 {
        match self {
            PathCommand::MoveTo(p) => p.y,
            PathCommand::LineTo(p) => p.y,
            PathCommand::CurveTo(c) => c.pt1.y.min(c.pt2.y).min(c.to.y),
        }
    }

    fn max_x(&self) -> f64 {
        match self {
            PathCommand::MoveTo(p) => p.x,
            PathCommand::LineTo(p) => p.x,
            PathCommand::CurveTo(c) => c.pt1.x.max(c.pt2.x).max(c.to.x),
        }
    }

    fn max_y(&self) -> f64 {
        match self {
            PathCommand::MoveTo(p) => p.y,
            PathCommand::LineTo(p) => p.y,
            PathCommand::CurveTo(c) => c.pt1.y.max(c.pt2.y).max(c.to.y),
        }
    }

    fn distance(&self, p: Point) -> f64 {
        self.point().distance(p)
    }

    pub fn point(&self) -> Point {
        match *self {
            PathCommand::MoveTo(p) => p,
            PathCommand::LineTo(p) => p,
            PathCommand::CurveTo(c) => c.to,
        }
    }

    pub fn move_to(&self) -> Option<Point> {
        match self {
            PathCommand::MoveTo(p) => Some(*p),
            PathCommand::LineTo(p) => Some(*p),
            PathCommand::CurveTo(_) => None,
        }
    }

    pub fn curve_to(&self) -> Option<CubicBezierCurve> {
        match self {
            PathCommand::MoveTo(_) => None,
            PathCommand::LineTo(_) => None,
            PathCommand::CurveTo(c) => Some(*c),
        }
    }
}

impl fmt::Display for PathCommand {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            PathCommand::MoveTo(p) => write!(f, "M {} ", p),
            PathCommand::LineTo(p) => write!(f, "L {} ", p),
            PathCommand::CurveTo(c) => write!(f, "C {}, {}, {} ", c.pt1, c.pt2, c.to),
        }
    }
}

#[derive(Debug, PartialEq)]
pub struct Path {
    commands: Vec<PathCommand>,
    thickness: f64,
    color: Color,
}

impl Path {
    pub fn new(color: Color, initial: Point, thickness: f64) -> Path {
        let mut commands = Vec::with_capacity(1000);

        commands.push(PathCommand::MoveTo(initial));

        Path {
            commands,
            thickness,
            color,
        }
    }

    pub fn with_params(color: Color, commands: Vec<PathCommand>, thickness: f64) -> Path {
        Path {
            commands, color, thickness,
        }
    }
}

impl ShapeTrait for Path {
    // 1. The first point is an absolute move.
    //
    // 2. The second point is a flat curve, with the handles put on the line
    //    that joins it with the previous one and its lengths set to 1/3 of the
    //    distance between the two points.
    //
    // 3. Every new point fixes the previous one, setting the slope of its last
    //    control point respecting its length. It sets correctly the length of
    //    its two control points but the last one sits in the segment between
    //    the last two points.
    fn handle_mouse_moved(&mut self, pos: Point) {
        add_point(&mut self.commands, pos);
    }

    fn handle_button_pressed(&mut self, _pos: Point) { }

    fn handle_button_released(&mut self, _pos: Point) -> ShapeFinished {
        ShapeFinished::Yes
    }

    fn draw_commands(&self) -> DrawCommand {
        DrawCommand::Path {
            commands: self.commands.clone(),
            thickness: self.thickness,
            color: self.color,
        }
    }

    // The bounding box of the path needs to consider the beizer handles
    fn bbox(&self) -> [[f64; 2]; 2] {
        let bbox = self.commands.iter().fold([
            [std::f64::INFINITY, std::f64::INFINITY], // bottom-left corner
            [std::f64::NEG_INFINITY, std::f64::NEG_INFINITY], // top right corner
        ], |acc, cmd| {
            [
                [
                    cmd.min_x().min(acc[0][0]),
                    cmd.min_y().min(acc[0][1]),
                ],
                [
                    cmd.max_x().max(acc[1][0]),
                    cmd.max_y().max(acc[1][1]),
                ],
            ]
        });

        assert_ne!(bbox[0][0], std::f64::INFINITY);
        assert_ne!(bbox[0][1], std::f64::INFINITY);
        assert_ne!(bbox[1][0], std::f64::NEG_INFINITY);
        assert_ne!(bbox[1][1], std::f64::NEG_INFINITY);

        bbox
    }

    fn shape_type(&self) -> ShapeType {
        ShapeType::Path
    }

    fn intersects_circle(&self, center: Point, radius: f64) -> bool {
        for c in self.commands.iter() {
            if c.distance(center) <= radius {
                return true;
            }
        }

        false
    }

    fn color(&self) -> Color {
        self.color
    }
}

#[cfg(test)]
mod tests {
    use super::{Path, thirds, bisector};
    use crate::shape::ShapeTrait;
    use crate::color::Color;
    use crate::point::Point;

    #[test]
    fn test_thirds() {
        assert_eq!(thirds(Point::new(3.0, 0.0), Point::new(6.0, 0.0)), (Point::new(4.0, 0.0), Point::new(5.0, 0.0)));
        assert_eq!(thirds(Point::new(0.0, 0.0), Point::new(6.0, 6.0)), (Point::new(2.0, 2.0), Point::new(4.0, 4.0)));
        assert_eq!(thirds(Point::new(-15.0, 30.0), Point::new(-18.0, 27.0)), (Point::new(-16.0, 29.0), Point::new(-17.0, 28.0)));
    }

    #[test]
    fn test_bisector() {
        let a = (-2.0, 3.0).into();
        let b = (1.0, 6.0).into();
        let c = (5.0, 2.0).into();
        let expected_bisector = Point::new(1.0, 0.0);
        let given_bisector = bisector(a, b, c);

        assert!(expected_bisector.x - given_bisector.x.abs() < 0.001);
        assert!(expected_bisector.y - given_bisector.y.abs() < 0.001);
    }

    #[test]
    fn test_bbox() {
        let mut line = Path::new(Color::green(), Point::new(1.0, 0.0), 4.0);

        line.handle_mouse_moved(Point::new(0.0, 1.0));

        assert_eq!(line.bbox(), [[0.0, 0.0], [1.0, 1.0]]);
    }

    #[test]
    fn test_bbox_twisted_line() {
        let mut line = Path::new(Color::green(), Point::new(-12.0, -1.0), 1.0);

        line.handle_mouse_moved(Point::new(-5.0, 0.0));
        line.handle_mouse_moved(Point::new(-2.0, 7.0));
        line.handle_mouse_moved(Point::new(2.0, -8.0));

        assert_eq!(line.bbox(), [[-12.0, -8.0], [3.161263886380917, 7.182987048373279]]);
    }
}