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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
use rin_math::Swizzles2;
use rin_math::{
    Pnt2, scalar::SubsetOf, Deg, Angle, convert, Float, NumCast, cast, zero,
    RealField, FloatPnt, NumPnt, ToPnt
};
use crate::Polyline;

use super::{mesh, Mesh, bezier, quad_bezier, arc_vertices, star_vertices, catmull_rom_vertices};
use color::{ToRgba,Rgba};
use color::consts::WHITE;
use std::iter::FromIterator;
use std::ops::Neg;

#[derive(Copy, Clone)]
pub enum Command<Point>
where
    Point: NumPnt + Copy,
    <Point as NumPnt>::Field: Copy
{
    Move{ to: Point },
    Line{ to: Point },
    Bezier{ cp1: Point, cp2: Point, to: Point },
    QuadBezier{ cp1: Point, to: Point },
    CatmullRom{ to: Point },
    Arc{
        center: Point,
        init_angle: Deg<<Point as NumPnt>::Field>,
        angle: Deg<<Point as NumPnt>::Field>,
        w: <Point as NumPnt>::Field,
        h: <Point as NumPnt>::Field
    },
    Close
}

#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub enum LineCap{
    Square,
    Triangular,
}

/// Represents a 2D path using commands that can be later
/// decomposed into line segments if the renderer requires it
///
/// The path uses a cursor that can be moved or told to draw
/// a specific line, curve or other shape.IntoIterator
///
/// The starting point for the next primitive will be the last
/// point of the previous one
#[derive(Clone)]
pub struct Path2D<Point = Pnt2>
where
    Point: FloatPnt + Copy,
    <Point as NumPnt>::Field: RealField + Copy,
    <Point as NumPnt>::Coordinates: Neg<Output = <Point as NumPnt>::Coordinates>
{
    commands: Vec<Command<Point>>,
    line_width: f32,
    color_line: Rgba<f32>,
    color_fill: Rgba<f32>,
    line_cap: LineCap,
}

impl<Point> Path2D<Point>
where
    Point: FloatPnt + Copy,
    <Point as NumPnt>::Field: RealField + Copy,
    <Point as NumPnt>::Coordinates: Neg<Output = <Point as NumPnt>::Coordinates>
{
    pub fn new() -> Path2D<Point>{
        Path2D {
            commands: Vec::new(),
            line_width: 1.0,
            color_line: WHITE.to_rgba(),
            color_fill: WHITE.to_rgba(),
            line_cap: LineCap::Square,
        }
    }

    /// Line width (some renderers might not support line widths different than 1)
    pub fn set_line_width(&mut self, w: f32){
        self.line_width = w;
    }

    pub fn line_width(&self) -> f32{
        self.line_width
    }

    /// Line caps
    pub fn set_line_cap(&mut self, cap: LineCap){
        self.line_cap = cap;
    }

    pub fn line_cap(&self) -> LineCap{
        self.line_cap
    }

    /// Sets the color of the contours and lines or curves
    pub fn set_line_color<C: ToRgba>(&mut self, c: &C){
        self.color_line = c.to_rgba().to_standard();
    }

    pub fn line_color(&self) -> Rgba<f32>{
        self.color_line
    }

    /// Sets the color of the shapes fill
    pub fn set_fill_color<C: ToRgba>(&mut self, c: &C){
        self.color_fill = c.to_rgba().to_standard();
    }

    pub fn fill_color(&self) -> Rgba<f32>{
        self.color_fill
    }

    /// Moves the cursor
    pub fn move_to(&mut self, to: Point){
        self.commands.push(Command::Move{to: to});
    }

    /// Draws a line segment from the last postion to `to`
    pub fn line_to(&mut self, to: Point){
        self.commands.push(Command::Line{to: to});
    }

    /// Draws a cubic bezier curve from the last position to `to` using
    /// the control points `cp1` and `cp2`
    pub fn bezier_to(&mut self, cp1: Point, cp2: Point, to: Point){
        self.commands.push(Command::Bezier{cp1: cp1, cp2: cp2, to:to});
    }

    /// Draws a quadratic bezier curve from the last position to `to` using
    /// the control point `cp1`
    pub fn quad_bezier_to(&mut self, cp1: Point, to: Point){
        self.commands.push(Command::QuadBezier{cp1: cp1, to:to});
    }

    /// Draws a hermite spine from the last point to `to
    ///
    /// For this to show anything there needs to be at least 4 curve_to
    /// points
    pub fn catmull_rom_to(&mut self, to: Point){
        self.commands.push(Command::CatmullRom{to: to});
    }

    /// Draws an arc segment from the center
    ///
    /// As an exception to other primitives this
    /// doesn't start from the last point but from the center
    /// passed as an argument
    pub fn arc(&mut self,
        center: Point,
        w: <Point as NumPnt>::Field,
        h: <Point as NumPnt>::Field,
        init_angle: Deg<<Point as NumPnt>::Field>,
        angle: Deg<<Point as NumPnt>::Field>)
    {
        self.commands.push(Command::Arc{center: center, init_angle: init_angle, angle: angle, w: w, h: h});
    }

    /// Join the last and first points in the path
    pub fn close(&mut self){
		self.commands.push(Command::Close);
	}

    /// Add a path to this one
    pub fn append(&mut self, path: Path2D<Point>){
        self.commands.extend(path.commands.into_iter());
    }

    /// Clear the path
    pub fn clear(&mut self){
		self.commands.truncate(0);
	}

    /// Returns true if the path doesn't contain any commands
    pub fn is_empty(&self) -> bool {
        self.commands.is_empty()
    }

    pub fn push_command(&mut self, command: Command<Point>) {
        self.commands.push(command)
    }

    /// Converts the path contour into line segments using
    /// the passed resolution when converting curves or arcs
    ///
    /// This function will call the passed callback for every point in
    /// the decomposition passing the previous point, the current point
    /// and a boolean indicating if the shape should be closed or not
    pub fn to_lines<F>(&self, resolution: u32, mut f: F)
		where F: FnMut(Point, Point, bool),
          Point: Copy,
          <Point as NumPnt>::Coordinates: Neg<Output = <Point as NumPnt>::Coordinates> + Copy + ToPnt<Point>,
          <Point as NumPnt>::Field: RealField + Float + NumCast
    {
        let mut prev: Point = Point::origin();
        let mut first: Point = Point::origin();
        let mut just_closed: bool = true;
        let mut curve_points: Vec<Point> = Vec::new();
        for c in self.commands.iter(){
            match *c{
                Command::Move{to} => {
                    curve_points.clear();
                    prev = to;
                    first = to;
                    just_closed = false;
                },

                Command::Line{to} => {
                    curve_points.truncate(0);
                    f(prev,to,false);
                    prev = to;
                    if just_closed { first = to; just_closed = false}
                },

                Command::Bezier{cp1, cp2, to} => {
                    curve_points.clear();
                    bezier(prev, cp1, cp2, to, resolution, |p|{
                        f(prev,p,false);
                        prev = p;
                    });
                },

                Command::QuadBezier{cp1, to} => {
                    curve_points.clear();
                    quad_bezier(prev, cp1, to, resolution, |p|{
                        f(prev,p,false);
                        prev=p;
                    })
                },

                Command::CatmullRom{to} => {
                    curve_points.push(to);
                    if curve_points.len() == 4{
                        catmull_rom_vertices(&curve_points[0],&curve_points[1],&curve_points[2],&curve_points[3], cast(0.5).unwrap(), resolution, |p|{
                            f(prev,p,false);
                            prev = p;
                        });
                        curve_points.remove(0);
                    }
                },

                Command::Arc{center, w, h, init_angle, angle} => {
                    curve_points.clear();
                    let mut first_p = true;
                    arc_vertices(center, w*cast(0.5).unwrap(), h*cast(0.5).unwrap(), init_angle, angle, resolution, |p|{
                        if !first_p {
							f(prev,p,false);
						}else{
							first_p = false;
							if just_closed { first = p; just_closed = false}
						}
                        prev = p;
                    });
                },

                Command::Close => {
                    curve_points.clear();
                    f(prev,first,true);
                    just_closed = true;
                },

                //_ => {}
            }
        }
    }

    /// Similar tp to_lines but using a line_strip kind of primitive type
    ///
    /// The passed callback receives the next point and if it should close
    /// the shape as a boolean
    pub fn to_line_strips<F>(&self, resolution: u32, mut f: F)
		where F: FnMut(Point, bool),
          Point: Copy,
          <Point as NumPnt>::Coordinates: Neg<Output = <Point as NumPnt>::Coordinates> + Copy + ToPnt<Point>,
          <Point as NumPnt>::Field: Float + NumCast
    {
        let mut prev: Point = Point::origin();
        let mut first: Point = Point::origin();
        let mut just_closed: bool = true;
        let mut curve_points: Vec<Point> = Vec::new();
        for c in self.commands.iter(){
            match *c{
                Command::Move{to} => {
                    curve_points.clear();
                    f(to,true);
                    prev = to;
                    first = to;
                    just_closed = false;
                },

                Command::Line{to} => {
                    curve_points.clear();
                    f(to,false);
                    prev = to;
                    if just_closed { first = to; just_closed = false;}
                },

                Command::Bezier{cp1, cp2, to} => {
                    curve_points.clear();
                    bezier(prev, cp1, cp2, to, resolution, |p|{
                        f(p,false);
                    });
                    prev = to;
                },

                Command::QuadBezier{cp1, to} => {
                    curve_points.clear();
                    quad_bezier(prev, cp1, to, resolution, |p|{
                        f(p,false);
                    });
                    prev = to;
                },

                Command::CatmullRom{to} => {
                    curve_points.push(to);
                    if curve_points.len() == 4{
                        catmull_rom_vertices(&curve_points[0],&curve_points[1],&curve_points[2],&curve_points[3], cast(0.5).unwrap(), resolution, |p|{
                            f(p,false);
                            prev = p;
                        });
                        curve_points.remove(0);
                    }
                },

                Command::Arc{center, init_angle, angle, w, h} => {
                    curve_points.clear();
                    f(center,true);
                    let mut first_p = true;
                    arc_vertices(center, w*cast(0.5).unwrap(), h*cast(0.5).unwrap(), init_angle, angle, resolution, |p|{
						if first_p{
							if just_closed { first = p; just_closed = false;}
							first_p = false;
						}
                        f(p, false);
                        prev = p;
                    });
                    f(center,false);
                },

                Command::Close => {
                    curve_points.clear();
                    f(first,false);
                    just_closed = true;
                },

                //_ => {}
            }
        }
    }

    pub fn to_polylines(&self, resolution: u32) -> Vec<Polyline<<Point as NumPnt>::Field>>
    where
        Point: Swizzles2<<Point as NumPnt>::Field, Swizzle2 = Pnt2<<Point as NumPnt>::Field>> + Copy,
        <Point as NumPnt>::Coordinates: Copy + ToPnt<Point>,
        <Point as NumPnt>::Field: NumCast + RealField + Float,
    {
        let mut polylines = vec![Polyline::new()];
        let mut prev: Point = Point::origin();
        let mut first: Point = Point::origin();
        let mut just_closed: bool = true;
        let mut curve_points: Vec<Point> = Vec::new();
        for c in self.commands.iter(){
            match *c{
                Command::Move{to} => {
                    curve_points.clear();
                    let polyline = if polylines.last().unwrap().is_empty(){
                        polylines.last_mut().unwrap()
                    }else{
                        polylines.push(Polyline::new());
                        polylines.last_mut().unwrap()
                    };
                    polyline.push(to.xy());
                    prev = to;
                    first = to;
                    just_closed = false;
                },

                Command::Line{to} => {
                    curve_points.clear();
                    polylines.last_mut().unwrap().push(to.xy());
                    prev = to;
                    if just_closed { first = to; just_closed = false;}
                },

                Command::Bezier{cp1, cp2, to} => {
                    curve_points.clear();
                    bezier(prev, cp1, cp2, to, resolution, |p|{
                        polylines.last_mut().unwrap().push(p.xy());
                    });
                    prev = to;
                },

                Command::QuadBezier{cp1, to} => {
                    curve_points.clear();
                    quad_bezier(prev, cp1, to, resolution, |p|{
                        polylines.last_mut().unwrap().push(p.xy());
                    });
                    prev = to;
                },

                Command::CatmullRom{to} => {
                    curve_points.push(to);
                    if curve_points.len() == 4{
                        catmull_rom_vertices(&curve_points[0],&curve_points[1],&curve_points[2],&curve_points[3], cast(0.5).unwrap(), resolution, |p|{
                            polylines.last_mut().unwrap().push(p.xy());
                            prev = p;
                        });
                        curve_points.remove(0);
                    }
                },

                Command::Arc{center, init_angle, angle, w, h} => {
                    curve_points.clear();
                    let mut first_p = true;
                    arc_vertices(center, w*cast(0.5).unwrap(), h*cast(0.5).unwrap(), init_angle, angle, resolution, |p|{
						if first_p{
							if just_closed { first = p; just_closed = false;}
							first_p = false;
						}
                        polylines.last_mut().unwrap().push(p.xy());
                        prev = p;
                    });
                },

                Command::Close => {
                    curve_points.clear();
                    polylines.last_mut().unwrap().close();
                    just_closed = true;
                },

                //_ => {}
            }
        }
        polylines
    }

    /// Returns a mesh with the full outline of the path
    pub fn to_outline_mesh(&self, curve_resolution: u32) -> Mesh<<Point as NumPnt>::Coordinates>
        where <Point as NumPnt>::Field: Float + NumCast,
          <Point as NumPnt>::Coordinates: Neg<Output = <Point as NumPnt>::Coordinates> + Copy + ToPnt<Point>,
          Point: Copy,
    {
        let mut mesh = Mesh::default();
        mesh.set_primitive_type(mesh::PrimitiveType::Lines);
        self.to_lines(curve_resolution, |from, to, _close|{
            mesh.push(from.coordinates());
            mesh.push(to.coordinates());
        });
        mesh
    }

    /// Returns a mesh with the fill of the mesh
    ///
    /// This fill is not tesselated and should be
    /// drawn using a stencil buffer
    pub fn to_fill_mesh(&self, curve_resolution: u32) -> Mesh<<Point as NumPnt>::Coordinates>
        where <Point as NumPnt>::Field: Float + NumCast,
          <Point as NumPnt>::Coordinates: Neg<Output = <Point as NumPnt>::Coordinates> + Copy + ToPnt<Point>,
          Point: Copy,
    {
        let mut mesh = Mesh::default();
        mesh.set_primitive_type(mesh::PrimitiveType::TriangleFan);
        self.to_line_strips(curve_resolution, |to, _new_shape|{
            mesh.push(to.coordinates());
        });
        mesh
    }
}

impl<Point> FromIterator<Command<Point>> for Path2D<Point>
where
    Point: FloatPnt + Copy,
    <Point as NumPnt>::Field: RealField + Copy,
    <Point as NumPnt>::Coordinates: Neg<Output = <Point as NumPnt>::Coordinates>
{
    fn from_iter<T>(commands: T) -> Self where T: IntoIterator<Item = Command<Point>> {
        Path2D {
            commands: commands.into_iter().collect(),
            line_width: 1.0,
            color_line: WHITE.to_rgba(),
            color_fill: WHITE.to_rgba(),
            line_cap: LineCap::Square,
        }
    }
}

/// Returns a path containing a star
pub fn star<Point>(
    center: Point,
    r: <Point as NumPnt>::Field,
    ri: <Point as NumPnt>::Field,
    points: u32) -> Path2D<Point>
where
    u32: SubsetOf<<Point as NumPnt>::Field>,
    Point: FloatPnt + Copy,
    <Point as NumPnt>::Field: RealField + Float + NumCast + Neg,
    <Point as NumPnt>::Coordinates: Neg<Output = <Point as NumPnt>::Coordinates>
{
    let mut path = Path2D::new();
    let mut first = true;
    star_vertices(center,r,ri,points,|p|{
        if first {path.move_to(p);}
        else {path.line_to(p);}
        first = false;
    });
    path.close();
    path
}

/// Returns a path containing a circle
pub fn circle<Point>(center: Point, r: <Point as NumPnt>::Field) -> Path2D<Point>
	where Point: FloatPnt + Copy,
          <Point as NumPnt>::Field: RealField + Float + NumCast + Neg + Copy,
          <Point as NumPnt>::Coordinates: Neg<Output = <Point as NumPnt>::Coordinates>
{
    let mut path = Path2D::new();
    let two = cast(2.0).unwrap();
    path.arc(center, r*two, r*two, zero(), Deg::two_pi());
    path
}

/// Returns a path containing a regular polygon
pub fn regular_poly<Point>(
    center: Point,
    r: <Point as NumPnt>::Field,
    sides: u32) -> Path2D<Point>

where
    u32: SubsetOf<<Point as NumPnt>::Field>,
    Point: FloatPnt + Copy,
    <Point as NumPnt>::Field: RealField + Float + NumCast + Neg,
    <Point as NumPnt>::Coordinates: Neg<Output = <Point as NumPnt>::Coordinates>
{
    let mut path = Path2D::new();
    let mut first = true;
    let from = -Deg::half_pi();
    let two_pi: Deg<<Point as NumPnt>::Field> = Deg::two_pi();
    let fsides: <Point as NumPnt>::Field = convert(sides);
    let fsides_1: <Point as NumPnt>::Field = convert(sides - 1);
    let to = two_pi * fsides_1 / fsides;
    arc_vertices(center, r, r, from, to, sides, |p|{
        if first {path.move_to(p); }
        else {path.line_to(p); }
        first = false;
    });
    path.close();
    path
}

/// Returns a path containing an ellipse
pub fn ellipse<Point>(
    center: Point,
    w: <Point as NumPnt>::Field,
    h: <Point as NumPnt>::Field) -> Path2D<Point>

where
    Point: FloatPnt + Copy,
    <Point as NumPnt>::Field: RealField + Float + NumCast + Neg + Copy,
    <Point as NumPnt>::Coordinates: Neg<Output = <Point as NumPnt>::Coordinates>
{
    let mut path = Path2D::new();
    path.arc(center,w,h,zero(),Deg::two_pi());
    path
}

/// Returns a path containing a rectangle
pub fn rect<Point>(
    pos: Point,
    w: <Point as NumPnt>::Field,
    h: <Point as NumPnt>::Field) -> Path2D<Point>
where
    Point: FloatPnt + Copy,
    <Point as NumPnt>::Field: RealField + Float + NumCast + Neg,
    <Point as NumPnt>::Coordinates: Neg<Output = <Point as NumPnt>::Coordinates>
{
    let mut path = Path2D::new();
    path.move_to(pos);
    let mut t = Point::origin().coordinates();
    t[0] = w;
    path.line_to(pos + t);
    let mut t = Point::origin().coordinates();
    t[0] = w;
    t[1] = h;
    path.line_to(pos + t);
    let mut t = Point::origin().coordinates();
    t[1] = h;
    path.line_to(pos + t);
    path.close();
    path
}

/// Returns a path containing a triangle
pub fn triangle<Point>(p0: Point, p1: Point, p2: Point) -> Path2D<Point>
where
    Point: FloatPnt + Copy,
    <Point as NumPnt>::Field: RealField + Float + NumCast + Neg,
    <Point as NumPnt>::Coordinates: Neg<Output = <Point as NumPnt>::Coordinates>
{
    let mut path = Path2D::new();
    path.move_to(p0);
    path.line_to(p1);
    path.line_to(p2);
    path.close();
    path
}