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
//! PathBuilder

use crate::{
    models::{Arc, Cubic, Ellipse, Line, Quad},
    path::{Path, PathItem},
    point::Point,
};
use std::f64::consts::PI;

/// Path builder.
#[derive(Debug, Clone)]
pub struct PathBuilder {
    items: Vec<PathItem>,
    last_pos: Option<Point>,
    path_start: Option<Point>,
}

impl PathBuilder {
    /// Create [`PathBuilder`].
    pub fn new() -> PathBuilder {
        PathBuilder {
            items: vec![],
            last_pos: None,
            path_start: None,
        }
    }

    fn push(&mut self, pi: PathItem) {
        if !pi.is_zero() {
            self.items.push(pi);
        }
    }

    fn set_pos(&mut self, p: Point) {
        if self.path_start == None {
            self.path_start = Some(p);
        }
        self.last_pos = Some(p);
    }

    /// Set current position.
    pub fn move_to(&mut self, x: f64, y: f64) {
        match self.items.last() {
            Some(PathItem::CloseAndJump) | Some(PathItem::Jump) | None => {}
            Some(_) => {
                self.push(PathItem::Jump);
                self.path_start = None;
            }
        }
        self.set_pos(Point(x, y));
    }

    /// Add a segment that from current position to specified position. And then set the end position to current position.
    pub fn line_to(&mut self, x: f64, y: f64) {
        let p = Point(x, y);
        if let Some(last_pos) = self.last_pos {
            self.push(PathItem::Line(Line(last_pos, p)));
        }
        self.set_pos(p);
    }

    /// Add an arc.
    pub fn arc(&mut self, x: f64, y: f64, radius: f64, angle1: f64, angle2: f64) {
        let center = Point(x, y);
        let arc = PathItem::Arc(Arc {
            center,
            radius,
            angle1,
            angle2,
        });
        if let Some(last_pos) = self.last_pos {
            let left_point = arc.left_point();
            if last_pos != left_point {
                self.push(PathItem::Line(Line(last_pos, left_point)));
            }
        }
        self.set_pos(arc.right_point());
        self.push(arc);
    }

    /// Add an ellipse.
    pub fn ellipse(
        &mut self,
        x: f64,
        y: f64,
        radius_x: f64,
        radius_y: f64,
        rotation: f64,
        angle1: f64,
        angle2: f64,
    ) {
        let radius_x = radius_x.abs();
        let radius_y = radius_y.abs();
        let center = Point(x, y);
        let ellipse = PathItem::Ellipse(Ellipse {
            center,
            radius_x,
            radius_y,
            rotation,
            angle1,
            angle2,
        });
        if let Some(last_pos) = self.last_pos {
            let left_point = ellipse.left_point();
            if last_pos != left_point {
                self.push(PathItem::Line(Line(last_pos, left_point)));
            }
        }
        self.set_pos(ellipse.right_point());
        self.push(ellipse);
    }

    /// Add an endpoint-parameterized ellipse.
    pub fn ellipse_from_endpoint(
        &mut self,
        radius_x: f64,
        radius_y: f64,
        rotation: f64,
        large: bool,
        clockwise: bool,
        x: f64,
        y: f64,
    ) {
        let start = self.last_pos.unwrap_or_else(|| panic!("PathBuilder::move_to() is required before ellipse_from_endpoint"));
        let end = Point(x, y);
        if radius_x == 0.0 || radius_y == 0.0 {
            self.set_pos(end);
            self.push(PathItem::Line(Line(start, end)));
            return;
        }
        let mut radius_x = radius_x.abs();
        let mut radius_y = radius_y.abs();
        let p = (start - end).rotate(-rotation) / 2.0;
        {
            let s = (p.0 / radius_x).powi(2) + (p.1 / radius_y).powi(2);
            if 1.0 < s {
                radius_x *= s.sqrt();
                radius_y *= s.sqrt();
            }
        }
        let (rx2, ry2) = (radius_x.powi(2), radius_y.powi(2));
        let mut a = ((rx2 * ry2 - rx2 * p.1.powi(2) - ry2 * p.0.powi(2)) / (rx2 * p.1.powi(2) + ry2 * p.0.powi(2))).sqrt();
        if large == clockwise {
            a = -a;
        }
        let q = Point(radius_x * p.1 / radius_y, -radius_y * p.0 / radius_x) * a;
        let center = q.rotate(rotation) + (start + end) / 2.0;
        let a1 = Point((p.0 - q.0) / radius_x, (p.1 - q.1) / radius_y);
        let mut angle1 = (a1.0 / a1.norm()).acos().copysign(a1.1);
        let a2 = Point(-(p.0 + q.0) / radius_x, -(p.1 + q.1) / radius_y);
        let mut angle2 = (a2.0 / a2.norm()).acos().copysign(a2.1);
        if clockwise && angle2 < angle1 {
            angle2 += PI * 2.0;
        }
        if !clockwise && angle1 < angle2 {
            angle1 += PI * 2.0;
        }
        let ellipse = PathItem::Ellipse(Ellipse {
            center,
            radius_x,
            radius_y,
            rotation,
            angle1,
            angle2,
        });
        self.set_pos(end);
        self.push(ellipse);
    }

    /// Add a quadratic bezier curve.
    pub fn quad(&mut self, control_x: f64, control_y: f64, x: f64, y: f64) {
        if let Some(last_pos) = self.last_pos {
            let quad = PathItem::Quad(Quad {
                start: last_pos,
                end: Point(x, y),
                control1: Point(control_x, control_y),
            });
            let left_point = quad.left_point();
            if last_pos != left_point {
                self.push(PathItem::Line(Line(last_pos, left_point)));
            }
            self.set_pos(quad.right_point());
            self.push(quad);
        } else {
            panic!("PathBuilder::move_to() is required before quad");
        }
    }

    /// Add a cubic bezier curve.
    pub fn cubic(
        &mut self,
        control_x1: f64,
        control_y1: f64,
        control_x2: f64,
        control_y2: f64,
        x: f64,
        y: f64,
    ) {
        if let Some(last_pos) = self.last_pos {
            let cubic = PathItem::Cubic(Cubic {
                start: last_pos,
                end: Point(x, y),
                control1: Point(control_x1, control_y1),
                control2: Point(control_x2, control_y2),
            });
            let left_point = cubic.left_point();
            if last_pos != left_point {
                self.push(PathItem::Line(Line(last_pos, left_point)));
            }
            self.set_pos(cubic.right_point());
            self.push(cubic);
        } else {
            panic!("PathBuilder::move_to() is required before cubic");
        }
    }

    /// Close the path.
    pub fn close(&mut self) {
        if let Some(p) = self.path_start {
            self.line_to(p.0, p.1);
            self.push(PathItem::CloseAndJump);
            self.path_start = None;
            self.last_pos = None;
        }
    }

    /// Return the built Path.
    pub fn end(&mut self) -> Path {
        let mut items = Vec::new();
        std::mem::swap(&mut items, &mut self.items);
        Path(items)
    }

    /// Return current position.
    pub fn current_pos(&self) -> Option<(f64, f64)> {
        self.last_pos.map(|p| p.into())
    }
}