Skip to main content

brep_construction/construction/loft_topology/
closed.rs

1use super::*;
2
3/// §5.8 CLOSED loft: the sections form a RING (the last flows back into the
4/// first), producing a capless genus-1 solid. Every interpolation column runs
5/// through `interpolate_curve_closed`, so the ring is C² across the closure —
6/// not a welded seam. Topology per skin is the cylinder-wall rectangle turned
7/// on its side: u runs along the section curve (open), v through the sections
8/// (closed); the section-0 curves themselves serve as the doubled v-seam
9/// edges and the corner rings (one closed curve through every section at each
10/// section corner) are shared between adjacent skins.
11pub fn loft_profile_brep_closed(
12    input_sections: &[Vec<NurbsCurve>],
13) -> Result<BrepSolid, KernelRefusal> {
14    loft_profile_brep_closed_shifted(input_sections, 0)
15}
16
17/// The largest number of stations one interpolation column of a SHIFTED closed
18/// loft may carry, laps included — the loft's own station cap, because the
19/// column solve is dense and `O(stations³)`.
20const MAX_SHIFTED_COLUMN_STATIONS: usize = 1024;
21
22/// [`loft_profile_brep_closed`] for a ring whose sections come back SHIFTED:
23/// after the last section the cycle continues into section 0 with curve `j`
24/// flowing into curve `(j + shift) mod m`, not into curve `j`.
25///
26/// That is a twisted sweep's closure when the section is symmetric. A square
27/// rolled a quarter turn over one lap lands each side on the NEXT side's place,
28/// so the wall leaving side `j` must arrive on side `j + 1`. The faces stay ONE
29/// PER SECTION CURVE, each spanning one lap: face `j` runs from curve `j` of
30/// section 0 (its `v = 0` seam) to curve `j + shift` of section 0 (its `v = 1`
31/// seam). Its corner rings run from vertex `j` to vertex `j + shift`. The seam
32/// edges are still the section-0 curves, each used by one face at `v = 0` and one
33/// at `v = 1`, so `V − E + F = m − 2m + m = 0`.
34///
35/// C² ACROSS THE SEAM, not welded. The curve indices form cycles of
36/// `laps = m / gcd(m, shift)` under `j → j + shift`, and a control column's data
37/// runs through all of them before it repeats. So each column is interpolated
38/// PERIODICALLY over `laps × S` stations, at parameters `l + p_k` for lap `l`, and
39/// split at the whole laps into one piece per face. Each piece is the lap's own
40/// v-parameterization, `[0, 1]` on the same knots every face uses. At `shift = 0`
41/// every cycle is one lap and this is exactly [`loft_profile_brep_closed`].
42///
43/// Curves `j` and `j + shift` of section 0 must share a representation (degree,
44/// knots, weights). The seam edge at `v = 1` is the other curve, parameterized
45/// as this face's own `u`.
46pub fn loft_profile_brep_closed_shifted(
47    input_sections: &[Vec<NurbsCurve>],
48    shift: usize,
49) -> Result<BrepSolid, KernelRefusal> {
50    loft_profile_brep_closed_core(input_sections, shift, None)
51}
52
53/// [`loft_profile_brep_closed`] with every column BROKEN at the section
54/// indices `breaks` ([`super::broken::interpolate_column_broken`]) and at the
55/// seam: the ring is fitted as runs from break to break, unrolled through the
56/// wrap back to section 0, each face spanning `v ∈ [0, 1]` from section 0 to
57/// itself. `breaks` are interior (`0 < b < sections`); the seam is always one.
58/// Unshifted rings only — a shifted ring's columns run several laps.
59pub fn loft_profile_brep_closed_broken(
60    input_sections: &[Vec<NurbsCurve>],
61    breaks: &[usize],
62) -> Result<BrepSolid, KernelRefusal> {
63    loft_profile_brep_closed_core(input_sections, 0, Some(breaks))
64}
65
66fn loft_profile_brep_closed_core(
67    input_sections: &[Vec<NurbsCurve>],
68    shift: usize,
69    breaks: Option<&[usize]>,
70) -> Result<BrepSolid, KernelRefusal> {
71    let tolerance = 1e-6;
72    let section_count = input_sections.len();
73    if section_count < 4 {
74        return Err(KernelRefusal::input(
75            KernelStage::Collect,
76            "section_count",
77            "loftSolid: a closed loft needs at least 4 sections",
78        ));
79    }
80    let sections = input_sections.to_vec();
81    let curve_count = validate_sections(&sections, tolerance, "loftSolid", false)?;
82    if shift >= curve_count {
83        return Err(KernelRefusal::input(
84            KernelStage::Collect,
85            "seam_shift",
86            format!(
87                "loftSolid: a closed loft's seam shift {shift} must be below its {curve_count} curves"
88            ),
89        ));
90    }
91    // The curve each one flows into across the seam.
92    let landing = |curve_index: usize| (curve_index + shift) % curve_count;
93    for curve_index in 0..curve_count {
94        let (from, to) = (&sections[0][curve_index], &sections[0][landing(curve_index)]);
95        if from.degree != to.degree
96            || from.control_points.len() != to.control_points.len()
97            || from.knots.len() != to.knots.len()
98            || from.knots.iter().zip(&to.knots).any(|(a, b)| (a - b).abs() > 1e-9)
99            || from
100                .control_points
101                .iter()
102                .zip(&to.control_points)
103                .any(|(a, b)| (a.w - b.w).abs() > 1e-12 * a.w.abs().max(1.0))
104        {
105            return Err(KernelRefusal::input(
106                KernelStage::Collect,
107                "seam_compatibility",
108                format!(
109                    "loftSolid: curve {curve_index} flows across the seam into curve {}, and the two \
110                     are not representation-compatible",
111                    landing(curve_index)
112                ),
113            ));
114        }
115    }
116
117    // Cyclic chord parameters over S stations plus the wrap span back to
118    // station 0 — the closed analogue of the open loft's averaging.
119    let mut accumulated = vec![0.0; section_count + 1];
120    let mut columns = 0usize;
121    for curve_index in 0..curve_count {
122        for control_index in 0..sections[0][curve_index].control_points.len() {
123            let mut chords = vec![0.0; section_count + 1];
124            let mut total = 0.0;
125            for station in 1..=section_count {
126                let previous = sections[station - 1][curve_index].control_points[control_index]
127                    .point()
128                    .or_refuse(KernelStage::Refine, "control_point")?;
129                let across = if station == section_count {
130                    landing(curve_index)
131                } else {
132                    curve_index
133                };
134                let current = sections[station % section_count][across].control_points
135                    [control_index]
136                    .point()
137                    .or_refuse(KernelStage::Refine, "control_point")?;
138                total += current.sub(previous).length();
139                chords[station] = total;
140            }
141            if total <= tolerance {
142                continue;
143            }
144            for station in 0..=section_count {
145                accumulated[station] += chords[station] / total;
146            }
147            columns += 1;
148        }
149    }
150    if columns == 0 {
151        return Err(KernelRefusal::input(
152            KernelStage::Classify,
153            "coincident_sections",
154            "loftSolid: sections coincide",
155        ));
156    }
157    let mut parameters = vec![0.0; section_count + 1];
158    for station in 0..=section_count {
159        parameters[station] = accumulated[station] / columns as f64;
160    }
161    parameters[0] = 0.0;
162    parameters[section_count] = 1.0;
163    if parameters.windows(2).any(|pair| pair[1] <= pair[0] + 1e-9) {
164        return Err(KernelRefusal::input(
165            KernelStage::Classify,
166            "section_order",
167            "loftSolid: closed sections are not strictly ordered",
168        ));
169    }
170
171    if let Some(breaks) = breaks.filter(|breaks| shift != 0 || breaks.iter().any(|&b| b == 0 || b >= section_count)) {
172        return Err(KernelRefusal::internal(
173            KernelStage::Collect,
174            "loft_breaks",
175            format!("loftSolid: closed column breaks {breaks:?} must be interior to {section_count} sections on an unshifted ring"),
176        ));
177    }
178    let mut skins = Vec::with_capacity(curve_count);
179    if shift == 0 {
180        for curve_index in 0..curve_count {
181            let reference = &sections[0][curve_index];
182            let mut grid = Vec::with_capacity(reference.control_points.len());
183            let mut knots_v = Vec::new();
184            for control_index in 0..reference.control_points.len() {
185                let points = sections
186                    .iter()
187                    .map(|section| section[curve_index].control_points[control_index].point())
188                    .collect::<Result<Vec<_>, String>>()
189                    .or_refuse(KernelStage::Refine, "control_point")?;
190                let interpolated = if let Some(breaks) = breaks {
191                    // Unrolled: station 0 again at the wrap parameter.
192                    let mut unrolled = points.clone();
193                    unrolled.push(points[0]);
194                    super::broken::interpolate_column_broken(&unrolled, &parameters, breaks)
195                        .or_refuse(KernelStage::Refine, "interpolate_broken")?
196                } else {
197                    crate::interpolate_curve_closed(&points, &parameters)
198                        .or_refuse(KernelStage::Refine, "interpolate_closed")?
199                };
200                knots_v = interpolated.knots.clone();
201                let weight = reference.control_points[control_index].w;
202                grid.push(
203                    interpolated
204                        .control_points
205                        .iter()
206                        .map(|point| Vec4::from_point(point.point().unwrap(), weight))
207                        .collect(),
208                );
209            }
210            skins.push(NurbsSurface::new(
211                reference.degree,
212                3,
213                reference.knots.clone(),
214                knots_v,
215                grid,
216            )
217            .or_refuse(KernelStage::Fragment, "skin")?);
218        }
219    } else {
220        skins = shifted_skins(&sections, &parameters, curve_count, shift)?;
221    }
222
223    // Topology: c corner vertices (section-0 corners), c corner-ring edges
224    // (closed v-curves at each corner), c seam edges (the section-0 curves),
225    // c skin faces. V − E + F = c − 2c + c = 0 → genus 1.
226    let base_points = closed_points(&sections[0], tolerance)?;
227    let mut vertices = Vec::with_capacity(curve_count);
228    for (index, point) in base_points.iter().enumerate() {
229        vertices.push(VertexRecord {
230            id: index as u64 + 1,
231            point: *point,
232        });
233    }
234    let mut edges = Vec::with_capacity(2 * curve_count);
235    let mut ring_edge_ids = Vec::with_capacity(curve_count);
236    let mut seam_edge_ids = Vec::with_capacity(curve_count);
237    for index in 0..curve_count {
238        let [u_start, u_end] = sections[0][index]
239            .domain()
240            .or_refuse(KernelStage::Fragment, "domain")?;
241        let _ = u_end;
242        let ring = skins[index]
243            .iso_curve_u(u_start)
244            .or_refuse(KernelStage::Fragment, "iso_curve")?;
245        let [ring_start, ring_end] = ring
246            .domain()
247            .or_refuse(KernelStage::Fragment, "domain")?;
248        let ring_id = 100 + index as u64;
249        ring_edge_ids.push(ring_id);
250        edges.push(EdgeRecord {
251            id: ring_id,
252            curve: ring,
253            t0: ring_start,
254            t1: ring_end,
255            start_vertex_id: index as u64 + 1,
256            end_vertex_id: landing(index) as u64 + 1,
257            degenerate: false,
258            name: None,
259        });
260        let seam = sections[0][index].clone();
261        let [seam_start, seam_end] = seam
262            .domain()
263            .or_refuse(KernelStage::Fragment, "domain")?;
264        let seam_id = 100 + curve_count as u64 + index as u64;
265        seam_edge_ids.push(seam_id);
266        edges.push(EdgeRecord {
267            id: seam_id,
268            curve: seam,
269            t0: seam_start,
270            t1: seam_end,
271            start_vertex_id: index as u64 + 1,
272            end_vertex_id: ((index + 1) % curve_count) as u64 + 1,
273            degenerate: false,
274            name: None,
275        });
276    }
277
278    let mut next_id = 1000u64;
279    let mut faces = Vec::with_capacity(curve_count);
280    for index in 0..curve_count {
281        let [u_start, u_end] = sections[0][index]
282            .domain()
283            .or_refuse(KernelStage::Fragment, "domain")?;
284        // Cylinder-wall rectangle: seam at v=0 forward, next corner ring up,
285        // seam at v=1 backward, own corner ring down. On a SHIFTED ring the seam
286        // at v=1 is the curve this one lands on.
287        let coedges = vec![
288            CoedgeRecord {
289                id: next_id,
290                edge_id: seam_edge_ids[index],
291                forward: true,
292                pcurve: parameter_line(u_start, 0.0, u_end, 0.0)
293                    .or_refuse(KernelStage::Fragment, "pcurve")?,
294            },
295            CoedgeRecord {
296                id: next_id + 1,
297                edge_id: ring_edge_ids[(index + 1) % curve_count],
298                forward: true,
299                pcurve: parameter_line(u_end, 0.0, u_end, 1.0)
300                    .or_refuse(KernelStage::Fragment, "pcurve")?,
301            },
302            CoedgeRecord {
303                id: next_id + 2,
304                edge_id: seam_edge_ids[landing(index)],
305                forward: false,
306                pcurve: parameter_line(u_end, 1.0, u_start, 1.0)
307                    .or_refuse(KernelStage::Fragment, "pcurve")?,
308            },
309            CoedgeRecord {
310                id: next_id + 3,
311                edge_id: ring_edge_ids[index],
312                forward: false,
313                pcurve: parameter_line(u_start, 1.0, u_start, 0.0)
314                    .or_refuse(KernelStage::Fragment, "pcurve")?,
315            },
316        ];
317        next_id += 4;
318        let loop_id = next_id;
319        next_id += 1;
320        let face_id = next_id;
321        next_id += 1;
322        faces.push(FaceRecord {
323            id: face_id,
324            surface: skins[index].clone(),
325            same_sense: true,
326            loops: vec![LoopRecord {
327                id: loop_id,
328                coedges,
329            }],
330            name: None,
331        });
332    }
333
334    let mut solid = BrepSolid {
335        mass_properties_cache: Default::default(),
336        cells: Default::default(),
337        id: next_id,
338        vertices,
339        edges,
340        shells: vec![ShellRecord {
341            id: next_id + 1,
342            faces,
343        }],
344        genus: 1,
345        kind: crate::BodyKind::Solid,
346    };
347    let issues = solid.validate();
348    if !issues.is_empty() {
349        return Err(KernelRefusal::internal(
350            KernelStage::Validate,
351            "validate",
352            format!(
353                "loftSolid: closed loft failed validation: {issues:?}"
354            ),
355        ));
356    }
357    // The ring's outward side depends on the sections' winding; the signed
358    // volume is the arbiter.
359    if crate::solid_signed_volume(&solid).or_refuse(KernelStage::Validate, "signed_volume")? < 0.0
360    {
361        crate::orientation::flip_all_faces(&mut solid)
362            ?;
363    }
364    // A ring carried round a path too tight for its own profile closes through
365    // itself, and neither the validation above nor the signed volume can see
366    // it: the enclosed space still measures. Same acceptance as the open loft.
367    crate::accept_sound(solid, "loftSolid")
368}
369
370/// The skins of a SHIFTED closed loft ([`loft_profile_brep_closed_shifted`]): each
371/// control column interpolated periodically over every lap of its curve cycle,
372/// then split at the whole laps, one piece per face.
373fn shifted_skins(
374    sections: &[Vec<NurbsCurve>],
375    parameters: &[f64],
376    curve_count: usize,
377    shift: usize,
378) -> Result<Vec<NurbsSurface>, KernelRefusal> {
379    let section_count = sections.len();
380    let gcd = |mut a: usize, mut b: usize| {
381        while b != 0 {
382            (a, b) = (b, a % b);
383        }
384        a
385    };
386    let laps = curve_count / gcd(curve_count, shift);
387    if laps * section_count > MAX_SHIFTED_COLUMN_STATIONS {
388        // Refused before any solve runs — a size the lane declines by name, not
389        // a budget that ran out, so it is a deferral rather than a non-convergence.
390        return Err(KernelRefusal::unsupported(
391            KernelStage::Collect,
392            "station_cap",
393            format!(
394                "loftSolid: a ring whose curves land {shift} along after one lap runs each skin \
395                 through {laps} laps of {section_count} stations, {} in all, past the \
396                 {MAX_SHIFTED_COLUMN_STATIONS}-station cap the loft's dense column solve can carry",
397                laps * section_count
398            ),
399        ));
400    }
401    // The knots every face shares in v: one lap's periodic interpolation, clamped.
402    let mut lap_knots = vec![parameters[0]; 4];
403    lap_knots.extend_from_slice(&parameters[1..section_count]);
404    lap_knots.extend(std::iter::repeat_n(parameters[section_count], 4));
405    let mut lap_parameters = Vec::with_capacity(laps * section_count + 1);
406    for lap in 0..laps {
407        for station in 0..section_count {
408            lap_parameters.push(lap as f64 + parameters[station]);
409        }
410    }
411    lap_parameters.push(laps as f64);
412
413    let mut grids: Vec<Vec<Vec<Vec4>>> = sections[0]
414        .iter()
415        .map(|curve| vec![Vec::new(); curve.control_points.len()])
416        .collect();
417    let mut visited = vec![false; curve_count];
418    for start in 0..curve_count {
419        if visited[start] {
420            continue;
421        }
422        let cycle: Vec<usize> = (0..laps).map(|lap| (start + lap * shift) % curve_count).collect();
423        for &curve_index in &cycle {
424            visited[curve_index] = true;
425        }
426        for control_index in 0..sections[0][start].control_points.len() {
427            let mut points = Vec::with_capacity(laps * section_count);
428            for &curve_index in &cycle {
429                for section in sections {
430                    points.push(
431                        section[curve_index].control_points[control_index]
432                            .point()
433                            .or_refuse(KernelStage::Refine, "control_point")?,
434                    );
435                }
436            }
437            let mut rest = crate::interpolate_curve_closed(&points, &lap_parameters)
438                .or_refuse(KernelStage::Refine, "interpolate_closed")?;
439            for (lap, &curve_index) in cycle.iter().enumerate() {
440                let piece = if lap + 1 < laps {
441                    let (piece, remainder) = rest
442                        .split((lap + 1) as f64)
443                        .or_refuse(KernelStage::Refine, "split")?;
444                    rest = remainder;
445                    piece
446                } else {
447                    rest.clone()
448                };
449                if piece.knots.len() != lap_knots.len()
450                    || piece
451                        .knots
452                        .iter()
453                        .zip(&lap_knots)
454                        .any(|(knot, own)| (knot - lap as f64 - own).abs() > 1e-9)
455                {
456                    return Err(KernelRefusal::internal(
457                        KernelStage::Refine,
458                        "lap_split",
459                        format!(
460                            "loftSolid: lap {lap} of a shifted ring's column did not split onto the \
461                             lap's own knots"
462                        ),
463                    ));
464                }
465                let weight = sections[0][curve_index].control_points[control_index].w;
466                grids[curve_index][control_index] = piece
467                    .control_points
468                    .iter()
469                    .map(|point| Ok(Vec4::from_point(point.point()?, weight)))
470                    .collect::<Result<Vec<_>, String>>()
471                    .or_refuse(KernelStage::Refine, "control_point")?;
472            }
473        }
474    }
475    sections[0]
476        .iter()
477        .zip(grids)
478        .map(|(reference, grid)| {
479            NurbsSurface::new(reference.degree, 3, reference.knots.clone(), lap_knots.clone(), grid)
480        })
481        .collect::<Result<Vec<_>, String>>()
482        .or_refuse(KernelStage::Fragment, "skin")
483}