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
use std::array;

use fj_interop::ext::{ArrayExt, SliceExt};
use fj_math::Scalar;
use iter_fixed::IntoIteratorFixed;

use crate::{
    algorithms::transform::TransformObject,
    builder::{FaceBuilder, HalfEdgeBuilder, SurfaceBuilder},
    insert::Insert,
    objects::{Cycle, Face, FaceSet, Objects, Shell},
    partial::{
        HasPartial, PartialCurve, PartialHalfEdge, PartialSurface,
        PartialSurfaceVertex, PartialVertex,
    },
    services::Service,
    storage::Handle,
};

/// API for building a [`Shell`]
///
/// Also see [`Shell::builder`].
pub struct ShellBuilder {
    /// The faces that make up the [`Shell`]
    pub faces: FaceSet,
}

impl ShellBuilder {
    /// Build the [`Shell`] with the provided faces
    pub fn with_faces(
        mut self,
        faces: impl IntoIterator<Item = Handle<Face>>,
    ) -> Self {
        self.faces.extend(faces);
        self
    }

    /// Create a cube from the length of its edges
    pub fn with_cube_from_edge_length(
        mut self,
        edge_length: impl Into<Scalar>,
        objects: &mut Service<Objects>,
    ) -> Self {
        let edge_length = edge_length.into();

        // Let's define some short-hands. We're going to need them a lot.
        const Z: Scalar = Scalar::ZERO;
        let h = edge_length / 2.;

        let bottom = {
            let surface =
                objects.surfaces.xy_plane().translate([Z, Z, -h], objects);

            Face::partial()
                .with_exterior_polygon_from_points(
                    surface,
                    [[-h, -h], [h, -h], [h, h], [-h, h]],
                )
                .build(objects)
                .insert(objects)
        };

        let (sides, top_edges) = {
            let surfaces = bottom
                .exterior()
                .half_edges()
                .map(|half_edge| {
                    let [a, b] = half_edge
                        .vertices()
                        .clone()
                        .map(|vertex| vertex.global_form().position());
                    let c = a + [Z, Z, edge_length];

                    PartialSurface::plane_from_points([a, b, c])
                        .build(objects)
                        .insert(objects)
                })
                .collect::<Vec<_>>();

            let bottoms = bottom
                .exterior()
                .half_edges()
                .zip(&surfaces)
                .map(|(half_edge, surface)| {
                    PartialHalfEdge {
                        global_form: half_edge.global_form().clone().into(),
                        ..Default::default()
                    }
                    .update_as_line_segment_from_points(
                        surface.clone(),
                        [[Z, Z], [edge_length, Z]],
                    )
                    .build(objects)
                    .insert(objects)
                })
                .collect::<Vec<_>>();

            let sides_up = bottoms
                .clone()
                .into_iter()
                .zip(&surfaces)
                .map(|(bottom, surface)| {
                    let [_, from] = bottom.vertices();

                    let from = from.surface_form().clone();
                    let to = PartialSurfaceVertex {
                        position: Some(from.position() + [Z, edge_length]),
                        surface: Some(surface.clone()),
                        ..Default::default()
                    };

                    PartialHalfEdge {
                        vertices: [
                            PartialVertex {
                                surface_form: from.into(),
                                ..Default::default()
                            },
                            PartialVertex {
                                surface_form: to.into(),
                                ..Default::default()
                            },
                        ]
                        .map(Into::into),
                        ..Default::default()
                    }
                    .update_as_line_segment()
                    .build(objects)
                    .insert(objects)
                })
                .collect::<Vec<_>>();

            let sides_down = {
                let mut sides_up_prev = sides_up.clone();
                sides_up_prev.rotate_right(1);

                bottoms
                    .clone()
                    .into_iter()
                    .zip(sides_up_prev)
                    .zip(&surfaces)
                    .map(|((bottom, side_up_prev), surface)| {
                        let [_, from] = side_up_prev.vertices();
                        let [to, _] = bottom.vertices();

                        let to = to.surface_form().clone();
                        let from = PartialSurfaceVertex {
                            position: Some(to.position() + [Z, edge_length]),
                            surface: Some(surface.clone()),
                            global_form: from.global_form().clone().into(),
                        };

                        let curve = PartialCurve {
                            global_form: side_up_prev
                                .curve()
                                .global_form()
                                .clone()
                                .into(),
                            ..Default::default()
                        };

                        PartialHalfEdge {
                            vertices: [
                                PartialVertex {
                                    curve: curve.clone().into(),
                                    surface_form: from.into(),
                                    ..Default::default()
                                },
                                PartialVertex {
                                    curve: curve.into(),
                                    surface_form: to.into(),
                                    ..Default::default()
                                },
                            ]
                            .map(Into::into),
                            ..Default::default()
                        }
                        .update_as_line_segment()
                        .build(objects)
                        .insert(objects)
                    })
                    .collect::<Vec<_>>()
            };

            let tops = sides_up
                .clone()
                .into_iter()
                .zip(sides_down.clone())
                .map(|(side_up, side_down)| {
                    let [_, from] = side_up.vertices();
                    let [to, _] = side_down.vertices();

                    let from = from.surface_form().clone();
                    let to = to.surface_form().clone();

                    let from = PartialVertex {
                        surface_form: from.into(),
                        ..Default::default()
                    };
                    let to = PartialVertex {
                        surface_form: to.into(),
                        ..Default::default()
                    };

                    PartialHalfEdge {
                        vertices: [from, to].map(Into::into),
                        ..Default::default()
                    }
                    .update_as_line_segment()
                    .build(objects)
                    .insert(objects)
                })
                .collect::<Vec<_>>();

            let sides = bottoms
                .into_iter()
                .zip(sides_up)
                .zip(tops.clone())
                .zip(sides_down)
                .map(|(((bottom, side_up), top), side_down)| {
                    let cycle = Cycle::partial()
                        .with_half_edges([bottom, side_up, top, side_down])
                        .build(objects)
                        .insert(objects);

                    Face::partial()
                        .with_exterior(cycle)
                        .build(objects)
                        .insert(objects)
                })
                .collect::<Vec<_>>();

            (sides, tops)
        };

        let top = {
            let surface =
                objects.surfaces.xy_plane().translate([Z, Z, h], objects);

            let mut top_edges = top_edges;
            top_edges.reverse();

            let surface_vertices = {
                let points = [[-h, -h], [-h, h], [h, h], [h, -h]];

                let mut edges = top_edges.iter();
                let half_edges = array::from_fn(|_| edges.next().unwrap());

                let [a, b, c, d] = points
                    .into_iter_fixed()
                    .zip(half_edges)
                    .collect::<[_; 4]>()
                    .map(|(point, edge)| {
                        let vertex = edge.back();

                        PartialSurfaceVertex {
                            position: Some(point.into()),
                            surface: Some(surface.clone()),
                            global_form: vertex.global_form().clone().into(),
                        }
                        .build(objects)
                        .insert(objects)
                    });

                [a.clone(), b, c, d, a]
            };

            let mut edges = Vec::new();
            for (surface_vertices, edge) in surface_vertices
                .as_slice()
                .array_windows_ext()
                .zip(top_edges)
            {
                let vertices = edge
                    .vertices()
                    .each_ref_ext()
                    .into_iter_fixed()
                    .zip(surface_vertices.clone())
                    .collect::<[_; 2]>()
                    .map(|(vertex, surface_form)| PartialVertex {
                        position: Some(vertex.position()),
                        surface_form: surface_form.into(),
                        ..Default::default()
                    });

                edges.push(
                    PartialHalfEdge {
                        vertices: vertices.map(Into::into),
                        global_form: edge.global_form().clone().into(),
                    }
                    .update_as_line_segment()
                    .build(objects)
                    .insert(objects),
                );
            }

            Face::partial()
                .with_exterior(Cycle::new(edges).insert(objects))
                .build(objects)
                .insert(objects)
        };

        self.faces.extend([bottom]);
        self.faces.extend(sides);
        self.faces.extend([top]);

        self
    }

    /// Build the [`Shell`]
    pub fn build(self, objects: &mut Service<Objects>) -> Handle<Shell> {
        Shell::new(self.faces).insert(objects)
    }
}