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

use crate::{
    insert::Insert,
    objects::{Curve, Objects, Surface, Vertex, VerticesInNormalizedOrder},
    partial::{
        MaybePartial, MergeWith, PartialGlobalEdge, PartialHalfEdge,
        PartialSurfaceVertex, PartialVertex,
    },
    storage::Handle,
    validate::ValidationError,
};

use super::CurveBuilder;

/// Builder API for [`PartialHalfEdge`]
pub trait HalfEdgeBuilder: Sized {
    /// Update the partial half-edge with the given back vertex
    fn with_back_vertex(self, back: impl Into<MaybePartial<Vertex>>) -> Self;

    /// Update the partial half-edge with the given front vertex
    fn with_front_vertex(self, front: impl Into<MaybePartial<Vertex>>) -> Self;

    /// Update partial half-edge as a circle, from the given radius
    ///
    /// # Implementation Note
    ///
    /// In principle, only the `build` method should take a reference to
    /// [`Objects`]. As of this writing, this method is the only one that
    /// deviates from that. I couldn't think of a way to do it better.
    fn update_as_circle_from_radius(
        self,
        radius: impl Into<Scalar>,
        objects: &Objects,
    ) -> Result<Self, ValidationError>;

    /// Update partial half-edge as a line segment, from the given points
    fn update_as_line_segment_from_points(
        self,
        surface: Handle<Surface>,
        points: [impl Into<Point<2>>; 2],
    ) -> Self;

    /// Update partial half-edge as a line segment, reusing existing vertices
    fn update_as_line_segment(self) -> Self;

    /// Infer the global form of the partial half-edge
    fn infer_global_form(self) -> Self;
}

impl HalfEdgeBuilder for PartialHalfEdge {
    fn with_back_vertex(self, back: impl Into<MaybePartial<Vertex>>) -> Self {
        let [_, front] = self.vertices.clone();
        self.with_vertices([back.into(), front])
    }

    fn with_front_vertex(self, front: impl Into<MaybePartial<Vertex>>) -> Self {
        let [back, _] = self.vertices.clone();
        self.with_vertices([back, front.into()])
    }

    fn update_as_circle_from_radius(
        self,
        radius: impl Into<Scalar>,
        objects: &Objects,
    ) -> Result<Self, ValidationError> {
        let mut curve = self.curve.clone().into_partial();
        curve.update_as_circle_from_radius(radius);

        let path = curve.path.expect("Expected path that was just created");

        let [a_curve, b_curve] =
            [Scalar::ZERO, Scalar::TAU].map(|coord| Point::from([coord]));

        let [global_vertex, _] = self.global_form.vertices();

        let surface_vertex = PartialSurfaceVertex {
            position: Some(path.point_from_path_coords(a_curve)),
            surface: curve.surface.clone(),
            global_form: global_vertex,
        }
        .build(objects)?
        .insert(objects)?;

        let [back, front] =
            [a_curve, b_curve].map(|point_curve| PartialVertex {
                position: Some(point_curve),
                curve: curve.clone().into(),
                surface_form: surface_vertex.clone().into(),
            });

        Ok(self.with_curve(curve).with_vertices([back, front]))
    }

    fn update_as_line_segment_from_points(
        self,
        surface: Handle<Surface>,
        points: [impl Into<Point<2>>; 2],
    ) -> Self {
        let vertices = points.map(|point| {
            let surface_form = PartialSurfaceVertex {
                position: Some(point.into()),
                surface: Some(surface.clone()),
                ..Default::default()
            };

            PartialVertex {
                surface_form: surface_form.into(),
                ..Default::default()
            }
        });

        self.with_surface(surface)
            .with_vertices(vertices)
            .update_as_line_segment()
    }

    fn update_as_line_segment(self) -> Self {
        let [from, to] = self.vertices.clone();
        let [from_surface, to_surface] =
            [&from, &to].map(|vertex| vertex.surface_form());

        let surface = self
            .curve
            .surface()
            .merge_with(from_surface.surface())
            .merge_with(to_surface.surface())
            .expect("Can't infer line segment without a surface");
        let points = [&from_surface, &to_surface].map(|vertex| {
            vertex
                .position()
                .expect("Can't infer line segment without surface position")
        });

        let mut curve = self.curve.clone().into_partial();
        curve.surface = Some(surface);
        curve.update_as_line_from_points(points);

        let [back, front] = {
            let vertices = [(from, 0.), (to, 1.)].map(|(vertex, position)| {
                vertex.update_partial(|mut vertex| {
                    vertex.position = Some([position].into());
                    vertex.curve = curve.clone().into();
                    vertex
                })
            });

            // The global vertices we extracted are in normalized order, which
            // means we might need to switch their order here. This is a bit of
            // a hack, but I can't think of something better.
            let global_forms = {
                let must_switch_order = {
                    let objects = Objects::new();
                    let vertices = vertices.clone().map(|vertex| {
                        vertex
                            .into_full(&objects)
                            .unwrap()
                            .global_form()
                            .clone()
                    });

                    let (_, must_switch_order) =
                        VerticesInNormalizedOrder::new(vertices);

                    must_switch_order
                };

                let [a, b] = self.global_form.vertices();
                if must_switch_order {
                    [b, a]
                } else {
                    [a, b]
                }
            };

            vertices
                .into_iter_fixed()
                .zip(global_forms)
                .collect::<[_; 2]>()
                .map(|(vertex, global_form)| {
                    vertex.update_partial(|mut vertex| {
                        vertex.surface_form = vertex.surface_form.merge_with(
                            PartialSurfaceVertex {
                                global_form,
                                ..Default::default()
                            },
                        );
                        vertex
                    })
                })
        };

        self.with_curve(curve).with_vertices([back, front])
    }

    fn infer_global_form(self) -> Self {
        self.with_global_form(PartialGlobalEdge::default())
    }
}

/// Builder API for [`PartialGlobalEdge`]
pub trait GlobalEdgeBuilder {
    /// Update partial global edge from the given curve and vertices
    fn update_from_curve_and_vertices(
        self,
        curve: &Curve,
        vertices: &[Handle<Vertex>; 2],
    ) -> Self;
}

impl GlobalEdgeBuilder for PartialGlobalEdge {
    fn update_from_curve_and_vertices(
        mut self,
        curve: &Curve,
        vertices: &[Handle<Vertex>; 2],
    ) -> Self {
        self.curve = curve.global_form().clone().into();
        self.vertices = vertices
            .clone()
            .map(|vertex| vertex.global_form().clone().into());
        self
    }
}