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, Tolerance};

impl Approx for Cycle {
    type Approximation = CycleApprox;
    type Params = ();

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

        for edge in self.edges() {
            let edge_points = edge.approx(tolerance, ());
            points.extend(edge_points);
        }

        if let Some(&point) = points.first() {
            points.push(point);
        }

        CycleApprox { points }
    }
}

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

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| {
                let (_, point_global) = point;
                point_global
            })));
        }

        segments
    }
}