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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
#![allow(non_snake_case)]
use std::fmt;
use crate::draw_commands::DrawCommand;
use crate::color::Color;
use crate::point::{Point, Vec2DWorld, Vec2DScreen};
use crate::transform::Transform;
use crate::geom::{
segment_intersects_circle, bezier_intersects_circle, bbox_from_points,
};
use super::{ShapeBuilder, ShapeStored, ShapeFinished, ShapeType};
fn thirds(a: Vec2DWorld, b: Vec2DWorld) -> (Vec2DWorld, Vec2DWorld) {
let v = b - a;
(v*1.0/3.0 + a, v*2.0/3.0 + a)
}
fn bisector(A: Vec2DWorld, B: Vec2DWorld, C: Vec2DWorld) -> Vec2DWorld {
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()
}
fn add_smooth(sec: Option<PathCommand>, last: PathCommand, pos: Vec2DWorld) -> (PathCommand, Option<PathCommand>) {
match last {
PathCommand::MoveTo(p) | PathCommand::LineTo(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 {
let prev = sec.unwrap().to();
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: Vec2DWorld) {
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 {
pub pt1: Vec2DWorld,
pub pt2: Vec2DWorld,
pub to: Vec2DWorld,
}
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 PathCommand {
MoveTo(Vec2DWorld),
LineTo(Vec2DWorld),
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(),
}
}
pub fn to(&self) -> Vec2DWorld {
match *self {
PathCommand::MoveTo(p) => p,
PathCommand::LineTo(p) => p,
PathCommand::CurveTo(c) => c.to,
}
}
pub fn intersects_circle(&self, center: Vec2DWorld, radius: f64, prev: Option<Vec2DWorld>) -> bool {
match *self {
PathCommand::MoveTo(p) => p.distance(center) < radius,
PathCommand::LineTo(p) => {
p.distance(center) < radius || segment_intersects_circle(prev, p, center, radius)
}
PathCommand::CurveTo(p) => {
p.to.distance(center) < radius || bezier_intersects_circle(prev, p.pt1, p.pt2, p.to, center, radius)
}
}
}
fn points(&self) -> Box<dyn Iterator<Item=Vec2DWorld>> {
match *self {
PathCommand::MoveTo(p) => Box::new(IntoIterator::into_iter([p])),
PathCommand::LineTo(p) => Box::new(IntoIterator::into_iter([p])),
PathCommand::CurveTo(CubicBezierCurve { pt1, pt2, to }) => Box::new(IntoIterator::into_iter([pt1, pt2, to])),
}
}
}
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 PathBuilder {
commands: Vec<PathCommand>,
thickness: f64,
color: Color,
}
impl PathBuilder {
pub fn start(color: Color, initial: Vec2DWorld, thickness: f64) -> PathBuilder {
let mut commands = Vec::with_capacity(1000);
commands.push(PathCommand::MoveTo(initial));
PathBuilder {
commands,
thickness,
color,
}
}
pub fn with_params(color: Color, commands: Vec<PathCommand>, thickness: f64) -> PathBuilder {
PathBuilder {
commands, color, thickness,
}
}
}
impl ShapeBuilder for PathBuilder {
fn handle_mouse_moved(&mut self, pos: Vec2DScreen, t: Transform, _snap: f64) {
add_point(&mut self.commands, t.to_world_coordinates(pos));
}
fn handle_button_pressed(&mut self, _pos: Vec2DScreen, _t: Transform, _snap: f64) { }
fn handle_button_released(&mut self, _pos: Vec2DScreen, _t: Transform, _snap: f64) -> ShapeFinished {
ShapeFinished::Yes(Box::new(Path::from_parts(
self.commands.clone(), self.color, self.thickness,
)))
}
fn draw_commands(&self) -> Vec<DrawCommand> {
vec![DrawCommand::Path {
commands: self.commands.clone(),
thickness: self.thickness,
color: self.color,
}]
}
}
#[derive(Debug)]
pub struct Path {
commands: Vec<PathCommand>,
color: Color,
thickness: f64,
}
impl Path {
pub fn from_parts(commands: Vec<PathCommand>, color: Color, thickness: f64) -> Path {
Path {
commands, color, thickness,
}
}
}
impl ShapeStored for Path {
fn draw_commands(&self) -> DrawCommand {
DrawCommand::Path {
commands: self.commands.clone(),
thickness: self.thickness,
color: self.color,
}
}
fn bbox(&self) -> [Vec2DWorld; 2] {
let points = self.commands.iter().map(|c| c.points()).flatten();
bbox_from_points(points)
}
fn shape_type(&self) -> ShapeType {
ShapeType::Path
}
fn intersects_circle(&self, center: Vec2DWorld, radius: f64) -> bool {
let mut last_point = None;
for c in self.commands.iter() {
if c.intersects_circle(center, radius, last_point) {
return true;
}
last_point = Some(c.to());
}
false
}
fn color(&self) -> Color {
self.color
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::color::Color;
use crate::point::Vec2DWorld;
#[test]
fn test_thirds() {
assert_eq!(thirds(Vec2DWorld::new(3.0, 0.0), Vec2DWorld::new(6.0, 0.0)), (Vec2DWorld::new(4.0, 0.0), Vec2DWorld::new(5.0, 0.0)));
assert_eq!(thirds(Vec2DWorld::new(0.0, 0.0), Vec2DWorld::new(6.0, 6.0)), (Vec2DWorld::new(2.0, 2.0), Vec2DWorld::new(4.0, 4.0)));
assert_eq!(thirds(Vec2DWorld::new(-15.0, 30.0), Vec2DWorld::new(-18.0, 27.0)), (Vec2DWorld::new(-16.0, 29.0), Vec2DWorld::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 = Vec2DWorld::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 line = Path::from_parts(vec![
PathCommand::MoveTo(Vec2DWorld::new(1.0, 0.0)),
PathCommand::LineTo(Vec2DWorld::new(0.0, 1.0)),
], Color::green(), 4.0);
assert_eq!(line.bbox(), [Vec2DWorld::new(0.0, 0.0), Vec2DWorld::new(1.0, 1.0)]);
}
#[test]
fn test_bbox_twisted_line() {
let line = Path::from_parts(vec![
PathCommand::MoveTo(Vec2DWorld::new(-12.0, -1.0)),
PathCommand::LineTo(Vec2DWorld::new(-5.0, 0.0)),
PathCommand::LineTo(Vec2DWorld::new(-2.0, 7.0)),
PathCommand::LineTo(Vec2DWorld::new(2.0, -8.0)),
], Color::green(), 1.0);
assert_eq!(line.bbox(), [Vec2DWorld::new(-12.0, -8.0), Vec2DWorld::new(2.0, 7.0)]);
}
#[test]
fn can_delete_single_point_paths() {
let poly = Path::from_parts(vec![
PathCommand::MoveTo(Vec2DWorld::new(0.0, 0.0)),
], Color::green(), 1.0);
assert!(poly.intersects_circle(Vec2DWorld::new(0.0, 0.0), 10.0));
}
#[test]
fn can_delete_beizer_curves() {
let path = Path::from_parts(vec![
PathCommand::MoveTo(Vec2DWorld::new(33.0, 135.0)),
PathCommand::CurveTo(CubicBezierCurve {
pt1: Vec2DWorld::new(50.0, 200.0),
pt2: Vec2DWorld::new(171.0, 70.0),
to: Vec2DWorld::new(196.0, 113.0),
}),
], Default::default(), 1.0);
let cases = [
(Vec2DWorld::new(37.0, 129.0), true),
(Vec2DWorld::new(81.0, 154.0), true),
(Vec2DWorld::new(127.0, 109.0), true),
(Vec2DWorld::new(74.0, 90.0), false),
(Vec2DWorld::new(147.0, 165.0), false),
(Vec2DWorld::new(177.0, 121.0), false),
];
for (center, result) in cases {
assert_eq!(path.intersects_circle(center, 15.0), result);
}
}
#[test]
fn can_delete_straight_segments() {
let path = Path::from_parts(vec![
PathCommand::MoveTo(Vec2DWorld::new(33.0, 135.0)),
PathCommand::LineTo(Vec2DWorld::new(196.0, 113.0)),
], Default::default(), 1.0);
let cases = [
(Vec2DWorld::new(37.0, 129.0), true),
(Vec2DWorld::new(81.0, 154.0), false),
(Vec2DWorld::new(127.0, 109.0), true),
(Vec2DWorld::new(74.0, 90.0), false),
(Vec2DWorld::new(147.0, 165.0), false),
(Vec2DWorld::new(177.0, 121.0), true),
];
for (center, result) in cases {
assert_eq!(path.intersects_circle(center, 15.0), result);
}
}
}