Skip to main content

brep_construction/construction/loft_topology/
basic.rs

1use super::*;
2
3#[derive(Clone)]
4struct SectionFrame {
5    normal: Vec3,
6    centroid: Vec3,
7    samples: Vec<Vec3>,
8    planar: bool,
9}
10
11pub(super) fn closed_points(
12    curves: &[NurbsCurve],
13    tolerance: f64,
14) -> Result<Vec<Vec3>, KernelRefusal> {
15    if curves.len() < 2 {
16        return Err(KernelRefusal::input(
17            KernelStage::Collect,
18            "section_curve_count",
19            "loftSolid: a section needs at least 2 curves",
20        ));
21    }
22    let mut points = Vec::with_capacity(curves.len());
23    for (index, curve) in curves.iter().enumerate() {
24        let [start, end] = curve.domain().or_refuse(KernelStage::Collect, "domain")?;
25        let next = &curves[(index + 1) % curves.len()];
26        let next_start = next.domain().or_refuse(KernelStage::Collect, "domain")?[0];
27        if curve
28            .evaluate(end)
29            .or_refuse(KernelStage::Collect, "evaluate")?
30            .sub(
31                next.evaluate(next_start)
32                    .or_refuse(KernelStage::Collect, "evaluate")?,
33            )
34            .length()
35            > tolerance
36        {
37            return Err(KernelRefusal::input(
38                KernelStage::Collect,
39                "open_section",
40                format!("loftSolid: section is open at curve {index}"),
41            ));
42        }
43        points.push(
44            curve
45                .evaluate(start)
46                .or_refuse(KernelStage::Collect, "evaluate")?,
47        );
48    }
49    Ok(points)
50}
51
52fn section_frame(curves: &[NurbsCurve], tolerance: f64) -> Result<SectionFrame, KernelRefusal> {
53    let mut samples = Vec::new();
54    for curve in curves {
55        let [start, end] = curve.domain().or_refuse(KernelStage::Classify, "domain")?;
56        for index in 0..16 {
57            samples.push(
58                curve
59                    .evaluate(start + (end - start) * index as f64 / 16.0)
60                    .or_refuse(KernelStage::Classify, "evaluate")?,
61            );
62        }
63    }
64    let mut normal = crate::polygon::newell_normal(&samples);
65    let mut centroid = samples.iter().fold(Vec3::default(), |sum, &point| sum.add(point));
66    // A zero Newell normal is a section without area — the caller's loop, not a
67    // solve, so it is an input refusal carrying the vector helper's own text.
68    normal = normal
69        .normalized()
70        .or_input(KernelStage::Classify, "section_normal")?;
71    centroid = centroid.scale(1.0 / samples.len() as f64);
72    let planar = samples
73        .iter()
74        .all(|point| point.sub(samples[0]).dot(normal).abs() <= tolerance * 100.0);
75    Ok(SectionFrame {
76        normal,
77        centroid,
78        samples,
79        planar,
80    })
81}
82
83/// How far off an end section's plane a step has to lean before it may say which
84/// side of that section the loft's material is on. `0.1` — the same band
85/// `extrude_profile_brep` refuses a sliver at, and the same one the sweep's own
86/// per-station guard uses.
87const CAP_ADVANCE_MIN: f64 = 0.1;
88
89/// Find the inward advance direction at an end section, walking nearest first.
90/// Skip centroids in the end plane until `|step·normal| / |step|` reaches
91/// `CAP_ADVANCE_MIN`. This handles turning lofts and guides that initially
92/// travel sideways; an end-to-end chord alone can misorient their caps.
93/// Return `None` if the entire run stays in the end plane.
94fn advance_from(
95    sections: &[Vec<NurbsCurve>],
96    anchor: Vec3,
97    normal: Vec3,
98    order: impl Iterator<Item = usize>,
99    tolerance: f64,
100) -> Result<Option<Vec3>, KernelRefusal> {
101    for index in order {
102        let step = section_frame(&sections[index], tolerance)?
103            .centroid
104            .sub(anchor);
105        let length = step.length();
106        if length > tolerance && (step.dot(normal) / length).abs() >= CAP_ADVANCE_MIN {
107            return Ok(Some(step.scale(1.0 / length)));
108        }
109    }
110    Ok(None)
111}
112
113fn reverse_section(curves: &[NurbsCurve]) -> Result<Vec<NurbsCurve>, KernelRefusal> {
114    curves
115        .iter()
116        .rev()
117        .map(NurbsCurve::reversed)
118        .collect::<Result<Vec<_>, String>>()
119        .or_refuse(KernelStage::Classify, "reverse_section")
120}
121
122/// One end cap. `advance` is the direction the loft RUNS THROUGH this cap —
123/// measured at this end, not end to end (see `advance_from`) — and it orients
124/// the cap plane: `outward` then says whether the face's own normal follows it
125/// (the finish cap) or opposes it (the start cap).
126fn cap_face(
127    curves: &[NurbsCurve],
128    edge_ids: &[u64],
129    frame: &SectionFrame,
130    advance: Vec3,
131    outward: bool,
132    next_id: &mut u64,
133) -> Result<FaceRecord, KernelRefusal> {
134    let normal = if frame.normal.dot(advance) >= 0.0 {
135        frame.normal
136    } else {
137        frame.normal.scale(-1.0)
138    };
139    let x_axis = normal
140        .perpendicular()
141        .or_refuse(KernelStage::Fragment, "cap_frame")?;
142    let y_axis = normal
143        .cross(x_axis)
144        .normalized()
145        .or_refuse(KernelStage::Fragment, "cap_frame")?;
146    let (mut min_x, mut min_y) = (f64::INFINITY, f64::INFINITY);
147    let (mut max_x, mut max_y) = (f64::NEG_INFINITY, f64::NEG_INFINITY);
148    for point in &frame.samples {
149        let delta = point.sub(frame.centroid);
150        min_x = min_x.min(delta.dot(x_axis));
151        max_x = max_x.max(delta.dot(x_axis));
152        min_y = min_y.min(delta.dot(y_axis));
153        max_y = max_y.max(delta.dot(y_axis));
154    }
155    let padding = (max_x - min_x).max(max_y - min_y) * 0.05 + 1e-6;
156    let origin = frame
157        .centroid
158        .add(x_axis.scale(min_x - padding))
159        .add(y_axis.scale(min_y - padding));
160    let surface = make_plane(
161        origin,
162        x_axis,
163        y_axis,
164        max_x - min_x + 2.0 * padding,
165        max_y - min_y + 2.0 * padding,
166    )
167    .or_refuse(KernelStage::Fragment, "cap_plane")?;
168    let mut coedges = Vec::with_capacity(curves.len());
169    if outward {
170        for (index, curve) in curves.iter().enumerate() {
171            coedges.push(CoedgeRecord {
172                id: *next_id,
173                edge_id: edge_ids[index],
174                forward: true,
175                pcurve: curve_to_plane_parameters(curve, origin, x_axis, y_axis)
176                    .or_refuse(KernelStage::Fragment, "cap_pcurve")?,
177            });
178            *next_id += 1;
179        }
180    } else {
181        for index in (0..curves.len()).rev() {
182            coedges.push(CoedgeRecord {
183                id: *next_id,
184                edge_id: edge_ids[index],
185                forward: false,
186                pcurve: curve_to_plane_parameters(&curves[index], origin, x_axis, y_axis)
187                    .or_refuse(KernelStage::Fragment, "cap_pcurve")?
188                    .reversed()
189                    .or_refuse(KernelStage::Fragment, "cap_pcurve")?,
190            });
191            *next_id += 1;
192        }
193    }
194    let loop_id = *next_id;
195    *next_id += 1;
196    let face_id = *next_id;
197    *next_id += 1;
198    Ok(FaceRecord {
199        id: face_id,
200        surface,
201        same_sense: outward,
202        loops: vec![LoopRecord {
203            id: loop_id,
204            coedges,
205        }],
206        name: None,
207    })
208}
209
210/// Loft corresponding edges of closed sections. For two sections, exact
211/// degree elevation and knot insertion reconcile mixed line/arc representations
212/// and the ruled skins retain both boundaries' rational weights. Multi-section
213/// interpolation requires matching degrees, knots and weights.
214pub fn loft_profile_brep(input_sections: &[Vec<NurbsCurve>]) -> Result<BrepSolid, KernelRefusal> {
215    loft_profile_brep_core(input_sections, None, &[], true)
216}
217
218/// [`loft_profile_brep`] without the self-intersection scan at its exit, for a
219/// caller whose body is sound by construction (a planar region carried along a
220/// screw, every level a turned copy of it); the incidence checks still run.
221pub(crate) fn loft_profile_brep_unscanned(input_sections: &[Vec<NurbsCurve>]) -> Result<BrepSolid, KernelRefusal> {
222    loft_profile_brep_core(input_sections, None, &[], false)
223}
224
225/// [`loft_profile_brep`] with every column BROKEN at the section indices
226/// `breaks` ([`super::broken::interpolate_column_broken`]): each run between
227/// breaks is interpolated on its own and the runs meet C0 at a full-multiplicity
228/// knot, one face per section curve as before. The sweep passes the stations
229/// where its path's curvature jumps. Empty `breaks` is [`loft_profile_brep`].
230pub fn loft_profile_brep_broken(
231    input_sections: &[Vec<NurbsCurve>],
232    breaks: &[usize],
233) -> Result<BrepSolid, KernelRefusal> {
234    loft_profile_brep_core(input_sections, None, breaks, true)
235}
236
237/// §5.8 loft with END TANGENCY: the skin leaves the first section along
238/// `start_direction` and arrives at the last along `end_direction` (unit
239/// directions; each interpolation column scales them by its own chord length,
240/// the standard magnitude that keeps the v-parametrization well conditioned).
241/// Exact by construction — the column interpolant reproduces the prescribed
242/// end derivatives.
243pub fn loft_profile_brep_tangent(
244    input_sections: &[Vec<NurbsCurve>],
245    start_direction: Vec3,
246    end_direction: Vec3,
247) -> Result<BrepSolid, KernelRefusal> {
248    let start = start_direction.normalized().map_err(|_| {
249        KernelRefusal::input(
250            KernelStage::Collect,
251            "start_tangent",
252            "loftSolid: start tangent must be a nonzero direction",
253        )
254    })?;
255    let end = end_direction.normalized().map_err(|_| {
256        KernelRefusal::input(
257            KernelStage::Collect,
258            "end_tangent",
259            "loftSolid: end tangent must be a nonzero direction",
260        )
261    })?;
262    loft_profile_brep_core(input_sections, Some((start, end)), &[], true)
263}
264
265fn loft_profile_brep_core(
266    input_sections: &[Vec<NurbsCurve>],
267    end_tangents: Option<(Vec3, Vec3)>,
268    breaks: &[usize],
269    scan: bool,
270) -> Result<BrepSolid, KernelRefusal> {
271    let mut profile = super::ConstructionProfile::new("loft");
272    let tolerance = 1e-6;
273    let section_count = input_sections.len();
274    if section_count < 2 {
275        return Err(KernelRefusal::input(
276            KernelStage::Collect,
277            "section_count",
278            "loftSolid: need at least 2 sections",
279        ));
280    }
281    let mut sections = input_sections.to_vec();
282    // A two-section loft is a ruled rational patch: unlike the interpolated
283    // multi-station/tangent paths it can retain different boundary weights.
284    let ruled = section_count == 2 && end_tangents.is_none();
285    if !breaks.is_empty() && (end_tangents.is_some() || breaks.iter().any(|&b| b == 0 || b >= section_count - 1)) {
286        return Err(KernelRefusal::internal(
287            KernelStage::Collect,
288            "loft_breaks",
289            format!("loftSolid: column breaks {breaks:?} must be interior to {section_count} sections and need no end tangents"),
290        ));
291    }
292    let curve_count = if ruled {
293        super::validation::validate_section_loops(&sections, tolerance, "loftSolid")?
294    } else {
295        // Sections round the same outline that only start their loops elsewhere are turned to match.
296        super::validation::align_section_starts(&mut sections);
297        validate_sections(&sections, tolerance, "loftSolid", true)?
298    };
299
300    let first_frame = section_frame(&sections[0], tolerance)?;
301    let last_frame = section_frame(&sections[section_count - 1], tolerance)?;
302    if !first_frame.planar || !last_frame.planar {
303        return Err(KernelRefusal::unsupported(
304            KernelStage::Classify,
305            "planar_end_sections",
306            "loftSolid: end sections must be planar",
307        ));
308    }
309    // Ends in the same place put the two caps on top of each other whatever the
310    // run does in between; say that before blaming a section plane below.
311    last_frame
312        .centroid
313        .sub(first_frame.centroid)
314        .normalized()
315        .map_err(|_| {
316            KernelRefusal::input(
317                KernelStage::Classify,
318                "coincident_ends",
319                "loftSolid: end sections coincide",
320            )
321        })?;
322    // Each cap must face away from its own inward advance direction; a turning
323    // loft can leave one end edge-on even when the other end is valid.
324    let start_advance = advance_from(
325        &sections,
326        first_frame.centroid,
327        first_frame.normal,
328        1..section_count,
329        tolerance,
330    )?
331    .ok_or_else(|| {
332        KernelRefusal::input(
333            KernelStage::Classify,
334            "start_in_plane",
335            "loftSolid: the loft runs inside its START section's plane — every later section \
336             lies in it, so the start cap would be a sliver rather than a face",
337        )
338    })?;
339    // Walking inward from the FAR end measures backwards, so negate it: both
340    // directions point the way the loft runs, start to finish.
341    let finish_advance = advance_from(
342        &sections,
343        last_frame.centroid,
344        last_frame.normal,
345        (0..section_count - 1).rev(),
346        tolerance,
347    )?
348    .map(|step| step.scale(-1.0))
349    .ok_or_else(|| {
350        KernelRefusal::input(
351            KernelStage::Classify,
352            "end_in_plane",
353            "loftSolid: the loft runs inside its END section's plane — every earlier section \
354             lies in it, so the end cap would be a sliver rather than a face",
355        )
356    })?;
357    // Sections all planar on parallel planes must advance along the normal one
358    // way. Where the stations' offsets turn back, the skin rises to the turning
359    // station and comes down again: every point inside that section's outline
360    // lies, near it, in the outline of the stations on both sides, which stand
361    // on the same side of its plane, so the material there is swept twice and
362    // the skin passes through itself. A step of no advance is the same turn
363    // inside a smooth run (its interpolant leaves the plane and comes back); it
364    // is allowed only on a ruled span, both ends a column break or an end of
365    // the loft, which is then a flat shoulder between the two outlines.
366    let frames = sections
367        .iter()
368        .map(|section| section_frame(section, tolerance))
369        .collect::<Result<Vec<_>, _>>()?;
370    let parallel = frames
371        .iter()
372        .all(|frame| frame.planar && frame.normal.cross(first_frame.normal).length() <= 1e-9);
373    if parallel {
374        let offsets: Vec<f64> = frames
375            .iter()
376            .map(|frame| frame.centroid.sub(first_frame.centroid).dot(first_frame.normal))
377            .collect();
378        // No advance is an offset difference at rounding of the sections'
379        // coordinates (coplanar sections read their offsets from different
380        // samples); any advance past that is an advance, however short.
381        let scale = frames.iter().fold(1.0f64, |m, frame| {
382            m.max(frame.centroid.x.abs()).max(frame.centroid.y.abs()).max(frame.centroid.z.abs())
383        });
384        let noise = 1e-12 * scale;
385        let rise = (offsets[section_count - 1] - offsets[0]).signum();
386        let ruled_end = |k: usize| k == 0 || k == section_count - 1 || breaks.contains(&k);
387        if let Some(k) = (1..section_count).find(|&k| {
388            let step = (offsets[k] - offsets[k - 1]) * rise;
389            if step.abs() <= noise {
390                !(ruled_end(k - 1) && ruled_end(k))
391            } else {
392                step < 0.0
393            }
394        }) {
395            return Err(KernelRefusal::input(
396                KernelStage::Classify,
397                "section_order",
398                format!(
399                    "loftSolid: section {k} does not advance past section {} along their common normal \
400                     (offsets {:.6} then {:.6}); the loft would turn back through itself",
401                    k - 1,
402                    offsets[k - 1],
403                    offsets[k],
404                ),
405            ));
406        }
407    }
408    let first_normal = if first_frame.normal.dot(start_advance) >= 0.0 {
409        first_frame.normal
410    } else {
411        first_frame.normal.scale(-1.0)
412    };
413    let x_axis = first_normal
414        .perpendicular()
415        .or_refuse(KernelStage::Classify, "section_frame")?;
416    let y_axis = first_normal
417        .cross(x_axis)
418        .normalized()
419        .or_refuse(KernelStage::Classify, "section_frame")?;
420    // Winding is normalized PER SECTION against this one frame, not decided once
421    // from section 0 and applied to every section.
422    //
423    // The skin rails control point `k` of curve `i` of one section to the same
424    // `(i, k)` of the next, so two sections traversed OPPOSITE ways rail corner
425    // to opposite corner and the skin twists into a bow-tie. Deciding one flip
426    // from section 0 and applying it to all of them cannot see that: it reverses
427    // them together, which preserves the disagreement exactly.
428    //
429    // Measured before this changed (`examples/feature_refusal_census_probe.rs`,
430    // `GATE loft_profile_brep.opposed_winding`): two 2x2 squares 5 apart, wound
431    // opposite ways, lofted to a solid of **volume 0 that passes `validate()`**
432    // — a silently-wrong result, not a refusal. The shipping LOFT feature
433    // reached it with two ordinary sketches on opposed planes.
434    //
435    // The comparison is CHAIN-RELATIVE — each section against its PREDECESSOR,
436    // not against section 0.
437    //
438    // Measuring every section against section 0's frame looks equivalent and is
439    // not: a frame-guided loft rotates each station's plane with the guide, so
440    // on a bend past 90 degrees a station's projected area goes negative purely
441    // because its plane has turned (cos > 90 deg < 0), and reversing it un-does
442    // the guide's own rotation. Measured on a 150-degree arc: volume 17.5685
443    // against a Pappus-exact 104.7198, a 83 % error, where the predecessor rule
444    // is exact.
445    //
446    // Consecutive stations of any sane loft turn far less than 90 degrees, so
447    // the predecessor comparison leaves a bend alone, while a genuinely opposed
448    // pair still flips. It also removes the knife edge at exactly 90 degrees,
449    // where a fixed-frame projection is float noise.
450    //
451    // `section_frame(..).normal` is the Newell normal, whose ORIENTATION already
452    // encodes the traversal direction; only its sign is read. Section 0 keeps
453    // the original rule verbatim, so its behaviour — and the side-face
454    // permutation below, which keys off section 0 alone — is byte-identical.
455    let mut section_reversed = Vec::with_capacity(section_count);
456    section_reversed.push(
457        profile_area(&sections[0], first_frame.centroid, x_axis, y_axis)
458            .or_refuse(KernelStage::Classify, "profile_area")?
459            < 0.0,
460    );
461    let mut previous_normal = if section_reversed[0] {
462        first_frame.normal.scale(-1.0)
463    } else {
464        first_frame.normal
465    };
466    for section in sections.iter().skip(1) {
467        let normal = section_frame(section, tolerance)?.normal;
468        let flip = normal.dot(previous_normal) < 0.0;
469        section_reversed.push(flip);
470        previous_normal = if flip { normal.scale(-1.0) } else { normal };
471    }
472    // Side faces are named by the FIRST section's input-curve order, so the
473    // face permutation below still keys off section 0 alone.
474    let reversed_winding = section_reversed[0];
475    for (index, flip) in section_reversed.into_iter().enumerate() {
476        if flip {
477            sections[index] = reverse_section(&sections[index])?;
478        }
479    }
480
481    if ruled {
482        // Match AFTER winding normalization: reversing a loop changes which
483        // curves correspond. Degree elevation and knot insertion preserve the
484        // exact line/arc geometry; no sampling or refitting is involved.
485        for curve_index in 0..curve_count {
486            let family = [
487                sections[0][curve_index].clone(),
488                sections[1][curve_index].clone(),
489            ];
490            // Preserve existing parameter domains when no conversion is needed.
491            if family[0].degree == family[1].degree
492                && family[0].knots == family[1].knots
493                && family[0].control_points.len() == family[1].control_points.len()
494            {
495                continue;
496            }
497            let (compatible, _) = crate::coons::compat::make_family_compatible(&family, 1)
498                .or_refuse(KernelStage::Refine, "section_compatibility")?;
499            for (section, curve) in sections.iter_mut().zip(compatible) {
500                section[curve_index] = curve;
501            }
502        }
503    }
504
505    profile.lap("profile");
506    let mut parameters = vec![0.0; section_count];
507    let mut accumulated = vec![0.0; section_count];
508    let mut columns = 0usize;
509    for curve_index in 0..curve_count {
510        for control_index in 0..sections[0][curve_index].control_points.len() {
511            let mut total = 0.0;
512            let mut chords = vec![0.0; section_count];
513            for section_index in 1..section_count {
514                let previous = sections[section_index - 1][curve_index].control_points
515                    [control_index]
516                    .point()
517                    .or_refuse(KernelStage::Refine, "control_point")?;
518                let current = sections[section_index][curve_index].control_points[control_index]
519                    .point()
520                    .or_refuse(KernelStage::Refine, "control_point")?;
521                total += current.sub(previous).length();
522                chords[section_index] = total;
523            }
524            if total <= tolerance {
525                continue;
526            }
527            for section_index in 0..section_count {
528                accumulated[section_index] += chords[section_index] / total;
529            }
530            columns += 1;
531        }
532    }
533    if columns == 0 {
534        return Err(KernelRefusal::input(
535            KernelStage::Classify,
536            "coincident_sections",
537            "loftSolid: sections coincide",
538        ));
539    }
540    for index in 0..section_count {
541        parameters[index] = accumulated[index] / columns as f64;
542    }
543    parameters[0] = 0.0;
544    parameters[section_count - 1] = 1.0;
545    if parameters.windows(2).any(|pair| pair[1] <= pair[0] + 1e-9) {
546        return Err(KernelRefusal::input(
547            KernelStage::Classify,
548            "section_order",
549            "loftSolid: sections are not strictly ordered",
550        ));
551    }
552    // Tangent lofts always interpolate cubically — the end-derivative rows
553    // need the two extra control points even for a 2-section Hermite loft.
554    let degree_v = if end_tangents.is_some() || !breaks.is_empty() {
555        3
556    } else {
557        3usize.min(section_count - 1)
558    };
559    let mut skins = Vec::with_capacity(curve_count);
560    for curve_index in 0..curve_count {
561        let reference = &sections[0][curve_index];
562        if ruled {
563            // Interpolate HOMOGENEOUS controls, including each end's own
564            // weights. Copying the first end's weights onto the second would
565            // turn an exact circular arc into a different boundary curve.
566            let grid = reference
567                .control_points
568                .iter()
569                .zip(&sections[1][curve_index].control_points)
570                .map(|(&start, &end)| vec![start, end])
571                .collect();
572            skins.push(
573                NurbsSurface::new(
574                    reference.degree,
575                    1,
576                    reference.knots.clone(),
577                    vec![0.0, 0.0, 1.0, 1.0],
578                    grid,
579                )
580                .or_refuse(KernelStage::Fragment, "skin")?,
581            );
582            continue;
583        }
584        let mut grid = Vec::with_capacity(reference.control_points.len());
585        let mut knots_v = Vec::new();
586        for control_index in 0..reference.control_points.len() {
587            let points = sections
588                .iter()
589                .map(|section| section[curve_index].control_points[control_index].point())
590                .collect::<Result<Vec<_>, String>>()
591                .or_refuse(KernelStage::Refine, "control_point")?;
592            let interpolated = match end_tangents {
593                None if !breaks.is_empty() => super::broken::interpolate_column_broken(&points, &parameters, breaks)
594                    .or_refuse(KernelStage::Refine, "interpolate_broken")?,
595                None => interpolate_curve(&points, degree_v, &parameters)
596                    .or_refuse(KernelStage::Refine, "interpolate")?,
597                Some((start_direction, end_direction)) => {
598                    let chord: f64 = points
599                        .windows(2)
600                        .map(|pair| pair[1].sub(pair[0]).length())
601                        .sum();
602                    // A column whose stations coincide still needs a usable
603                    // tangent magnitude; fall back to the section spacing.
604                    let magnitude = if chord > tolerance { chord } else { 1.0 };
605                    crate::interpolate_curve_with_end_tangents(
606                        &points,
607                        &parameters,
608                        start_direction.scale(magnitude),
609                        end_direction.scale(magnitude),
610                    )
611                    .or_refuse(KernelStage::Refine, "interpolate_tangent")?
612                }
613            };
614            knots_v = interpolated.knots.clone();
615            let weight = reference.control_points[control_index].w;
616            grid.push(
617                interpolated
618                    .control_points
619                    .iter()
620                    .map(|point| Vec4::from_point(point.point().unwrap(), weight))
621                    .collect(),
622            );
623        }
624        skins.push(NurbsSurface::new(
625            reference.degree,
626            degree_v,
627            reference.knots.clone(),
628            knots_v,
629            grid,
630        )
631        .or_refuse(KernelStage::Fragment, "skin")?);
632    }
633
634    profile.lap("surface");
635    let bottom = &sections[0];
636    let top = &sections[section_count - 1];
637    let bottom_points = closed_points(bottom, tolerance)?;
638    let top_points = closed_points(top, tolerance)?;
639    let mut vertices = Vec::with_capacity(2 * curve_count);
640    for (index, point) in bottom_points.iter().chain(&top_points).enumerate() {
641        vertices.push(VertexRecord {
642            id: index as u64 + 1,
643            point: *point,
644        });
645    }
646    let mut edges = Vec::with_capacity(3 * curve_count);
647    let mut bottom_edge_ids = Vec::new();
648    let mut top_edge_ids = Vec::new();
649    let mut vertical_edge_ids = Vec::new();
650    for index in 0..curve_count {
651        let [start, end] = bottom[index]
652            .domain()
653            .or_refuse(KernelStage::Fragment, "domain")?;
654        // The TOP curve's own range, which is NOT the bottom's once the winding
655        // normalization has reversed one section's curve ORDER: `reverse_section`
656        // reverses the order and `reversed()` preserves each curve's domain, so
657        // `top[i]` becomes a curve that lived on a different parameter span.
658        // Stamping the bottom's span on it made `coedge_sample` evaluate the top
659        // curve outside its own domain — pinned at an end while the skin swept
660        // the real arc — which on a circular section split into two half-arcs is
661        // a deviation of exactly the diameter.
662        let [top_start, top_end] = top[index]
663            .domain()
664            .or_refuse(KernelStage::Fragment, "domain")?;
665        let bottom_id = 10 + index as u64;
666        let top_id = 10 + curve_count as u64 + index as u64;
667        let vertical_id = 10 + 2 * curve_count as u64 + index as u64;
668        bottom_edge_ids.push(bottom_id);
669        top_edge_ids.push(top_id);
670        vertical_edge_ids.push(vertical_id);
671        edges.push(EdgeRecord {
672            id: bottom_id,
673            curve: bottom[index].clone(),
674            t0: start,
675            t1: end,
676            start_vertex_id: index as u64 + 1,
677            end_vertex_id: ((index + 1) % curve_count) as u64 + 1,
678            degenerate: false,
679            name: None,
680        });
681        edges.push(EdgeRecord {
682            id: top_id,
683            curve: top[index].clone(),
684            t0: top_start,
685            t1: top_end,
686            start_vertex_id: (curve_count + index) as u64 + 1,
687            end_vertex_id: (curve_count + (index + 1) % curve_count) as u64 + 1,
688            degenerate: false,
689            name: None,
690        });
691        let vertical = skins[index]
692            .iso_curve_u(start)
693            .or_refuse(KernelStage::Fragment, "iso_curve")?;
694        let [v_start, v_end] = vertical
695            .domain()
696            .or_refuse(KernelStage::Fragment, "domain")?;
697        edges.push(EdgeRecord {
698            id: vertical_id,
699            curve: vertical,
700            t0: v_start,
701            t1: v_end,
702            start_vertex_id: index as u64 + 1,
703            end_vertex_id: (curve_count + index) as u64 + 1,
704            degenerate: false,
705            name: None,
706        });
707    }
708
709    profile.lap("edges");
710    let mut next_id = 1000u64;
711    let mut faces = Vec::with_capacity(curve_count + 2);
712    for index in 0..curve_count {
713        let [start, end] = bottom[index]
714            .domain()
715            .or_refuse(KernelStage::Fragment, "domain")?;
716        let coedges = vec![
717            CoedgeRecord {
718                id: next_id,
719                edge_id: bottom_edge_ids[index],
720                forward: true,
721                pcurve: parameter_line(start, 0.0, end, 0.0)
722                    .or_refuse(KernelStage::Fragment, "pcurve")?,
723            },
724            CoedgeRecord {
725                id: next_id + 1,
726                edge_id: vertical_edge_ids[(index + 1) % curve_count],
727                forward: true,
728                pcurve: parameter_line(end, 0.0, end, 1.0)
729                    .or_refuse(KernelStage::Fragment, "pcurve")?,
730            },
731            CoedgeRecord {
732                id: next_id + 2,
733                edge_id: top_edge_ids[index],
734                forward: false,
735                pcurve: parameter_line(end, 1.0, start, 1.0)
736                    .or_refuse(KernelStage::Fragment, "pcurve")?,
737            },
738            CoedgeRecord {
739                id: next_id + 3,
740                edge_id: vertical_edge_ids[index],
741                forward: false,
742                pcurve: parameter_line(start, 1.0, start, 0.0)
743                    .or_refuse(KernelStage::Fragment, "pcurve")?,
744            },
745        ];
746        next_id += 4;
747        let loop_id = next_id;
748        next_id += 1;
749        let face_id = next_id;
750        next_id += 1;
751        faces.push(FaceRecord {
752            id: face_id,
753            surface: skins[index].clone(),
754            same_sense: true,
755            loops: vec![LoopRecord {
756                id: loop_id,
757                coedges,
758            }],
759            name: None,
760        });
761    }
762    if reversed_winding {
763        // The winding normalization reversed the section curve order above.
764        // Callers stamp side-face names by INPUT-curve order (the extrude
765        // and revolve wall-naming permutation, loft edition) — emit side
766        // faces in input order.
767        faces.reverse();
768    }
769    faces.push(cap_face(
770        bottom,
771        &bottom_edge_ids,
772        &first_frame,
773        start_advance,
774        false,
775        &mut next_id,
776    )?);
777    faces.push(cap_face(
778        top,
779        &top_edge_ids,
780        &last_frame,
781        finish_advance,
782        true,
783        &mut next_id,
784    )?);
785    let solid = BrepSolid {
786        mass_properties_cache: Default::default(),
787        cells: Default::default(),
788        id: next_id + 1,
789        vertices,
790        edges,
791        shells: vec![ShellRecord { id: next_id, faces }],
792        genus: 0,
793        kind: crate::BodyKind::Solid,
794    };
795    profile.lap("topology_pcurves");
796    let issues = solid.validate();
797    profile.lap("validation");
798    if !issues.is_empty() {
799        return Err(KernelRefusal::internal(
800            KernelStage::Validate,
801            "validate",
802            format!(
803                "Rust loft builder produced invalid topology: {issues:?}"
804            ),
805        ));
806    }
807    // `validate()` is an INCIDENCE test: a loft whose walls pass through each
808    // other — sections that cross, a run tighter than the profile's own
809    // half-width — satisfies every one of its checks. This is the soundness
810    // question asked at the lane's single exit, repaired where it can be and
811    // refused by name where it cannot. Every path sweep ends here too.
812    if !scan {
813        return Ok(solid);
814    }
815    let accepted = crate::accept_sound(solid, "loftSolid");
816    profile.lap("acceptance");
817    accepted
818}