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
use fj_math::{Point, Segment};

use crate::objects::Cycle;

use super::{Approx, Local, Tolerance};

impl Approx for Cycle {
    type Approximation = CycleApprox;

    fn approx(&self, tolerance: Tolerance) -> Self::Approximation {
        let mut points = Vec::new();

        for edge in self.edges() {
            let edge_points = edge.approx(tolerance);

            points.extend(edge_points.into_iter().map(|point| {
                let local = edge
                    .curve()
                    .kind()
                    .point_from_curve_coords(*point.local_form());
                Local::new(local, *point.global_form())
            }));
        }

        // Can't just rely on `dedup`, as the conversion from curve coordinates
        // could lead to subtly different surface coordinates.
        points.dedup_by(|a, b| a.global_form() == b.global_form());

        CycleApprox { points }
    }
}

/// An approximation of a [`Cycle`]
#[derive(Debug, Eq, PartialEq, Hash)]
pub struct CycleApprox {
    /// The points that approximate the cycle
    pub points: Vec<Local<Point<2>>>,
}

impl CycleApprox {
    /// Construct the segments that approximate the cycle
    pub fn segments(&self) -> Vec<Segment<3>> {
        let mut segments = Vec::new();

        for segment in self.points.windows(2) {
            // This can't panic, as we passed `2` to `windows`. Can be cleaned
            // up, once `array_windows` is stable.
            let segment = [segment[0], segment[1]];

            segments
                .push(Segment::from(segment.map(|point| *point.global_form())));
        }

        segments
    }
}