Skip to main content

brep_construction/construction/
surface_faces.rs

1//! Faces on given surfaces, and the solid a set of such faces bounds.
2//!
3//! [`face_from_surface`] makes a sheet of one face on a surface over its whole
4//! parameter domain. The face's four sides are the surface's boundary
5//! iso-curves, read for what they are:
6//!
7//! - a side that is one point (every pole of the row coincides) is a POLE, a
8//!   degenerate edge at a vertex;
9//! - two opposite sides that coincide are a SEAM, one edge the face uses once
10//!   each way (a cylinder's side has one seam, a ball's one seam and two
11//!   poles, a ring's two seams);
12//! - any other side is an open edge of the sheet.
13//!
14//! [`face_from_surface_trimmed`] makes a sheet of one face on a surface
15//! bounded by closed loops of curves lying on it (a disc on a plane inside a
16//! circle, a wall on a plane under a spline).
17//!
18//! [`solid_from_sheets`] joins sheets along their coinciding edges (the
19//! kernel's sewing, [`crate::sew_solid`]) and returns the solid they bound,
20//! outward. Sheets that leave an edge open are refused by name; nothing is
21//! closed by guessing.
22use crate::topology::{CoedgeRecord, EdgeRecord, FaceRecord, LoopRecord, ShellRecord, VertexRecord};
23use crate::{
24    build_pcurve_on_surface, make_line, sew_solid, BodyKind, BrepSolid, KernelRefusal, KernelStage, NurbsCurve,
25    NurbsSurface, OrRefuse, Vec3,
26};
27
28/// The prefix of every refusal of this module.
29pub const SURFACE_FACE_REFUSAL: &str = "surfaceFace";
30
31fn input(what: &'static str, message: String) -> KernelRefusal {
32    KernelRefusal::input(KernelStage::Collect, what, format!("{SURFACE_FACE_REFUSAL}: {message}"))
33}
34
35fn refuse(stage: KernelStage, what: &'static str, message: String) -> KernelRefusal {
36    KernelRefusal::unsupported(stage, what, format!("{SURFACE_FACE_REFUSAL}: {message}"))
37}
38
39/// The records of a sheet under construction, ids counted from 1.
40struct Records {
41    vertices: Vec<VertexRecord>,
42    edges: Vec<EdgeRecord>,
43    next: u64,
44    tolerance: f64,
45}
46
47impl Records {
48    fn new(tolerance: f64) -> Self {
49        Self { vertices: Vec::new(), edges: Vec::new(), next: 0, tolerance }
50    }
51
52    fn id(&mut self) -> u64 {
53        self.next += 1;
54        self.next
55    }
56
57    /// The vertex at `point`: an earlier one within the tolerance, or a new one.
58    fn vertex(&mut self, point: Vec3) -> u64 {
59        if let Some(found) = self.vertices.iter().find(|vertex| vertex.point.sub(point).length() <= self.tolerance) {
60            return found.id;
61        }
62        let id = self.id();
63        self.vertices.push(VertexRecord { id, point });
64        id
65    }
66
67    fn edge(&mut self, curve: NurbsCurve, start: u64, end: u64, degenerate: bool) -> Result<u64, KernelRefusal> {
68        let [t0, t1] = curve.domain().or_refuse(KernelStage::Collect, "surfaceFace.edge_domain")?;
69        let id = self.id();
70        self.edges.push(EdgeRecord { id, curve, t0, t1, start_vertex_id: start, end_vertex_id: end, degenerate, name: None });
71        Ok(id)
72    }
73
74    fn sheet(mut self, surface: &NurbsSurface, loops: Vec<Vec<(u64, bool, NurbsCurve)>>) -> BrepSolid {
75        let mut records = Vec::with_capacity(loops.len());
76        for coedges in loops {
77            let coedges = coedges
78                .into_iter()
79                .map(|(edge_id, forward, pcurve)| CoedgeRecord { id: self.id(), edge_id, forward, pcurve })
80                .collect();
81            records.push(LoopRecord { id: self.id(), coedges });
82        }
83        let face = FaceRecord { id: self.id(), surface: surface.clone(), same_sense: true, loops: records, name: None };
84        let shell = ShellRecord { id: self.id(), faces: vec![face] };
85        BrepSolid {
86            mass_properties_cache: Default::default(),
87            id: self.id(),
88            vertices: self.vertices,
89            edges: self.edges,
90            shells: vec![shell],
91            genus: 0,
92            kind: BodyKind::Sheet,
93            cells: Default::default(),
94        }
95    }
96}
97
98/// A length the surface's extent sets: the diagonal of its poles' box.
99fn extent(surface: &NurbsSurface) -> f64 {
100    let (mut low, mut high) = ([f64::INFINITY; 3], [f64::NEG_INFINITY; 3]);
101    for pole in surface.control_points.iter().flatten() {
102        let point = [pole.x / pole.w, pole.y / pole.w, pole.z / pole.w];
103        for axis in 0..3 {
104            low[axis] = low[axis].min(point[axis]);
105            high[axis] = high[axis].max(point[axis]);
106        }
107    }
108    Vec3::new(high[0] - low[0], high[1] - low[1], high[2] - low[2]).length()
109}
110
111/// The point every pole of `curve` sits at, when they all do within `tolerance`.
112fn collapsed(curve: &NurbsCurve, tolerance: f64) -> Option<Vec3> {
113    let point = |index: usize| {
114        let pole = curve.control_points[index];
115        Vec3::new(pole.x / pole.w, pole.y / pole.w, pole.z / pole.w)
116    };
117    let first = point(0);
118    (1..curve.control_points.len()).all(|index| point(index).sub(first).length() <= tolerance).then_some(first)
119}
120
121/// Whether `a` and `b`, two opposite sides of one patch, are the same curve
122/// point for point (they share knots and degree, so sample at equal parameters).
123fn coincide(a: &NurbsCurve, b: &NurbsCurve, tolerance: f64) -> Result<bool, KernelRefusal> {
124    const SAMPLES: usize = 33;
125    let [t0, t1] = a.domain().or_refuse(KernelStage::Collect, "surfaceFace.side_domain")?;
126    for index in 0..=SAMPLES {
127        let t = t0 + (t1 - t0) * index as f64 / SAMPLES as f64;
128        let gap = a.evaluate(t).or_refuse(KernelStage::Collect, "surfaceFace.side")?
129            .sub(b.evaluate(t).or_refuse(KernelStage::Collect, "surfaceFace.side")?);
130        if gap.length() > tolerance {
131            return Ok(false);
132        }
133    }
134    Ok(true)
135}
136
137fn uv_line(from: [f64; 2], to: [f64; 2]) -> Result<NurbsCurve, KernelRefusal> {
138    make_line(Vec3::new(from[0], from[1], 0.0), Vec3::new(to[0], to[1], 0.0)).or_refuse(KernelStage::Collect, "surfaceFace.pcurve")
139}
140
141fn accept(sheet: BrepSolid, what: &'static str) -> Result<BrepSolid, KernelRefusal> {
142    let issues = sheet.validate();
143    if let Some(issue) = issues.first() {
144        return Err(refuse(KernelStage::Validate, what, format!("the face is not valid: {issue:?}")));
145    }
146    Ok(sheet)
147}
148
149/// A sheet of one face on `surface` over its whole domain, its normal the
150/// surface's own (`∂S/∂u × ∂S/∂v`).
151///
152/// Each side of the domain is read from the surface: a side collapsed to a
153/// point is a pole (a degenerate edge), two opposite sides that coincide are
154/// one seam edge, and every other side is an open edge. So a clamped patch
155/// gives a face with four open edges, a tube's side a face with a seam and two
156/// open rims, and a ball or a ring a closed face, which [`solid_from_sheets`]
157/// takes alone.
158///
159/// Refuses a surface that is a point or a curve (two adjacent sides
160/// collapsed, or a side collapsed whose neighbours coincide all along).
161pub fn face_from_surface(surface: &NurbsSurface) -> Result<BrepSolid, KernelRefusal> {
162    let [u0, u1] = surface.domain_u().or_refuse(KernelStage::Collect, "surfaceFace.domain")?;
163    let [v0, v1] = surface.domain_v().or_refuse(KernelStage::Collect, "surfaceFace.domain")?;
164    let size = extent(surface);
165    if !(size.is_finite() && size > 0.0) {
166        return Err(input("surface_extent", "the surface has no extent".into()));
167    }
168    let tolerance = 1e-9 * size;
169    let side = |along_u: bool, at: f64| -> Result<NurbsCurve, KernelRefusal> {
170        if along_u { surface.iso_curve_v(at) } else { surface.iso_curve_u(at) }.or_refuse(KernelStage::Collect, "surfaceFace.side")
171    };
172    // the four sides, each along its own rising parameter
173    let (bottom, top) = (side(true, v0)?, side(true, v1)?);
174    let (left, right) = (side(false, u0)?, side(false, u1)?);
175    let poles = [collapsed(&bottom, tolerance), collapsed(&right, tolerance), collapsed(&top, tolerance), collapsed(&left, tolerance)];
176    if (0..4).any(|index| poles[index].is_some() && poles[(index + 1) % 4].is_some()) {
177        return Err(input("surface_collapsed", "two adjacent sides of the surface are single points".into()));
178    }
179    let seam_u = poles[1].is_none() && poles[3].is_none() && coincide(&left, &right, tolerance)?;
180    let seam_v = poles[0].is_none() && poles[2].is_none() && coincide(&bottom, &top, tolerance)?;
181
182    let mut records = Records::new(tolerance);
183    let corner = |u: f64, v: f64| surface.evaluate(u, v).or_refuse(KernelStage::Collect, "surfaceFace.corner");
184    let c00 = records.vertex(corner(u0, v0)?);
185    let c10 = records.vertex(corner(u1, v0)?);
186    let c11 = records.vertex(corner(u1, v1)?);
187    let c01 = records.vertex(corner(u0, v1)?);
188    let edge = |records: &mut Records, curve: NurbsCurve, pole: Option<Vec3>, start: u64, end: u64| -> Result<u64, KernelRefusal> {
189        match pole {
190            Some(point) => {
191                let line = make_line(point, point).or_refuse(KernelStage::Collect, "surfaceFace.pole")?;
192                records.edge(line, start, start, true)
193            }
194            None => records.edge(curve, start, end, false),
195        }
196    };
197    let bottom_edge = edge(&mut records, bottom, poles[0], c00, c10)?;
198    let left_edge = edge(&mut records, left, poles[3], c00, c01)?;
199    let top_edge = if seam_v { bottom_edge } else { edge(&mut records, top, poles[2], c01, c11)? };
200    let right_edge = if seam_u { left_edge } else { edge(&mut records, right, poles[1], c10, c11)? };
201    // counter-clockwise in (u, v), so the face lies on the left of each coedge
202    // as seen along the surface's normal
203    let coedges = vec![
204        (bottom_edge, true, uv_line([u0, v0], [u1, v0])?),
205        (right_edge, true, uv_line([u1, v0], [u1, v1])?),
206        (top_edge, false, uv_line([u1, v1], [u0, v1])?),
207        (left_edge, false, uv_line([u0, v1], [u0, v0])?),
208    ];
209    accept(records.sheet(surface, vec![coedges]), "face")
210}
211
212/// The area a closed chain of pcurves encloses in the parameter plane, signed
213/// (positive counter-clockwise), from a sampled polygon.
214pub fn signed_area(pcurves: &[NurbsCurve]) -> Result<f64, KernelRefusal> {
215    const SAMPLES: usize = 48;
216    let mut points = Vec::with_capacity(pcurves.len() * SAMPLES);
217    for pcurve in pcurves {
218        let [t0, t1] = pcurve.domain().or_refuse(KernelStage::Collect, "surfaceFace.pcurve_domain")?;
219        for index in 0..SAMPLES {
220            let at = pcurve.evaluate(t0 + (t1 - t0) * index as f64 / SAMPLES as f64).or_refuse(KernelStage::Collect, "surfaceFace.pcurve")?;
221            points.push([at.x, at.y]);
222        }
223    }
224    let mut twice = 0.0;
225    for index in 0..points.len() {
226        let (a, b) = (points[index], points[(index + 1) % points.len()]);
227        twice += a[0] * b[1] - b[0] * a[1];
228    }
229    Ok(0.5 * twice)
230}
231
232/// A sheet of one face on `surface` bounded by `loops`: the first its outer
233/// boundary, the rest holes. Each loop is a closed chain of curves lying on
234/// the surface, head to tail in either sense (a single closed curve is a loop
235/// of one); each curve becomes an edge and each joint a vertex. The face's
236/// normal is the surface's own.
237///
238/// The curves' images in the surface's parameters are the kernel's
239/// ([`crate::build_pcurve_on_surface`]: exact on a plane, fitted elsewhere).
240/// The loops are turned the way a face needs them, the outer one
241/// counter-clockwise about the normal and the holes clockwise.
242///
243/// Refuses an empty loop, a chain that does not close, and a curve that does
244/// not lie on the surface.
245pub fn face_from_surface_trimmed(surface: &NurbsSurface, loops: &[Vec<NurbsCurve>]) -> Result<BrepSolid, KernelRefusal> {
246    let today = trimmed_sheet(surface, loops, false);
247    let (on, check) = (trim_layer_on(), trim_layer_check());
248    // only a face the validation refuses is retried: an open loop or a curve off the surface is refused as before
249    let invalid = matches!(&today, Err(refusal) if refusal.stage == KernelStage::Validate);
250    if !(on || check) || !invalid {
251        if check {
252            eprintln!("TRIM_LAYER check: the global images {}; the layered route is not asked", if today.is_ok() { "build the face" } else { "are refused before validation" });
253        }
254        return today;
255    }
256    let layered = trimmed_sheet(surface, loops, true);
257    if check {
258        match (&today, &layered) {
259            (Err(refusal), Ok(_)) => eprintln!("TRIM_LAYER check: the global images are refused ({refusal}); the layered route builds the face"),
260            (Err(refusal), Err(other)) => eprintln!("TRIM_LAYER check: both routes refuse: global {refusal}; layered {other}"),
261            _ => {}
262        }
263    }
264    match layered {
265        Ok(sheet) if on => Ok(sheet),
266        _ => today,
267    }
268}
269
270/// `BREP_TRIM_LAYER` (default on; `=0` restores the global images alone): [`face_from_surface_trimmed`] retries a
271/// face its trims' global images do not make with each loop's images on ONE
272/// layer of the surface ([`layered_images`]): a patch that folds back over the
273/// face, or runs on to a second layer close beside it, gives a trim point two
274/// nearby preimages, and the global nearest point may take the wrong one for
275/// some samples. A face the global images make is theirs unchanged; where the
276/// layered route also fails, the global refusal stands word for word.
277fn trim_layer_on() -> bool {
278    crate::switch!("BREP_TRIM_LAYER", true)
279}
280
281/// `BREP_TRIM_LAYER_CHECK`: say, for every trimmed face, which route makes it
282/// (stderr), without changing the outcome.
283fn trim_layer_check() -> bool {
284    crate::debug_flag!("BREP_TRIM_LAYER_CHECK")
285}
286
287/// The sheet of [`face_from_surface_trimmed`], each loop's images either the
288/// kernel's global fits (`layered` false, the route before the switch) or
289/// [`layered_images`].
290fn trimmed_sheet(surface: &NurbsSurface, loops: &[Vec<NurbsCurve>], layered: bool) -> Result<BrepSolid, KernelRefusal> {
291    if loops.is_empty() || loops.iter().any(Vec::is_empty) {
292        return Err(input("trim_no_loop", "at least one loop, each of at least one curve, is required".into()));
293    }
294    let size = extent(surface);
295    if !(size.is_finite() && size > 0.0) {
296        return Err(input("surface_extent", "the surface has no extent".into()));
297    }
298    let tolerance = 1e-9 * size;
299    let ends = |curve: &NurbsCurve| -> Result<[Vec3; 2], KernelRefusal> {
300        let [t0, t1] = curve.domain().or_refuse(KernelStage::Collect, "surfaceFace.curve_domain")?;
301        Ok([curve.evaluate(t0).or_refuse(KernelStage::Collect, "surfaceFace.curve")?, curve.evaluate(t1).or_refuse(KernelStage::Collect, "surfaceFace.curve")?])
302    };
303    let mut records = Records::new(tolerance);
304    let mut face_loops = Vec::with_capacity(loops.len());
305    let mut outer: Option<Vec<NurbsCurve>> = None;
306    for (loop_index, curves) in loops.iter().enumerate() {
307        let images = if layered { Some(layered_images(surface, curves, size, outer.as_deref())?) } else { None };
308        let mut coedges = Vec::with_capacity(curves.len());
309        for (index, curve) in curves.iter().enumerate() {
310            let [start, end] = ends(curve)?;
311            let [next, _] = ends(&curves[(index + 1) % curves.len()])?;
312            if end.sub(next).length() > tolerance {
313                return Err(input("trim_open_loop", format!("loop {loop_index} does not close after curve {index} (gap {:.3e})", end.sub(next).length())));
314            }
315            let (from, to) = (records.vertex(start), records.vertex(end));
316            let pcurve = match &images {
317                Some(images) => images[index].clone(),
318                None => build_pcurve_on_surface(surface, curve).map_err(|error| {
319                    refuse(KernelStage::Fragment, "trim_off_surface", format!("curve {index} of loop {loop_index} has no image on the surface: {error}"))
320                })?,
321            };
322            coedges.push((records.edge(curve.clone(), from, to, false)?, true, pcurve));
323        }
324        let pcurves: Vec<NurbsCurve> = coedges.iter().map(|(_, _, pcurve)| pcurve.clone()).collect();
325        if loop_index == 0 {
326            outer = Some(pcurves.clone());
327        }
328        let area = signed_area(&pcurves)?;
329        if area == 0.0 {
330            return Err(input("trim_no_area", format!("loop {loop_index} encloses no area on the surface")));
331        }
332        // the outer loop runs counter-clockwise, a hole clockwise
333        if (area > 0.0) != (loop_index == 0) {
334            let mut turned = Vec::with_capacity(coedges.len());
335            for (edge, _, pcurve) in coedges.into_iter().rev() {
336                turned.push((edge, false, pcurve.reversed().or_refuse(KernelStage::Collect, "surfaceFace.pcurve_reverse")?));
337            }
338            coedges = turned;
339        }
340        face_loops.push(coedges);
341    }
342    accept(records.sheet(surface, face_loops), "trimmed_face")
343}
344
345/// The stations each trim is walked at, and the matched reads of its image.
346const LAYER_STATIONS: usize = 64;
347
348/// Each curve of the closed chain `curves` imaged on ONE layer of `surface`:
349/// the chain's first point is placed at each of its preimages in turn (the
350/// global nearest point first, then the feet a grid of seeds reaches), and
351/// from there every curve is walked station by station, each foot seeded by
352/// the one before, so no station can leave the layer the chain started on;
353/// the next curve starts where the last one ended. A trim the walk finds at
354/// one u (or one v) all along is an iso-curve and its image is that line in
355/// the parameters, exactly; any other trim keeps the kernel's fit, taken only
356/// when its ends are the walk's. A placement is taken when its chain closes in
357/// the parameters, every image reads within `1e-7 · size` of its curve at
358/// matched parameters, and, for a hole (`outer` given), it starts and stays
359/// inside the outer loop's images without crossing them. A walk that would cross a seam jumps in the
360/// parameters and is not taken. Where several placements are taken (a patch
361/// covering the face twice exactly carries the loop on both layers), the one
362/// on which the loop already runs the way the face needs it (the outer loop
363/// counter-clockwise, a hole clockwise) is chosen, then the one starting at
364/// the least (u, v): the caller's loop sense names the layer, and the choice
365/// never rests on which foot the nearest-point search meets first.
366fn layered_images(surface: &NurbsSurface, curves: &[NurbsCurve], size: f64, outer: Option<&[NurbsCurve]>) -> Result<Vec<NurbsCurve>, KernelRefusal> {
367    let refused = |message: String| refuse(KernelStage::Fragment, "trim_layer", message);
368    let [u0, u1] = surface.domain_u().or_refuse(KernelStage::Collect, "surfaceFace.domain")?;
369    let [v0, v1] = surface.domain_v().or_refuse(KernelStage::Collect, "surfaceFace.domain")?;
370    let (u_span, v_span) = (u1 - u0, v1 - v0);
371    let bar = 1e-7 * size;
372    let at = |curve: &NurbsCurve, fraction: f64| -> Result<Vec3, KernelRefusal> {
373        let [t0, t1] = curve.domain().or_refuse(KernelStage::Collect, "surfaceFace.curve_domain")?;
374        curve.evaluate(t0 + (t1 - t0) * fraction).or_refuse(KernelStage::Collect, "surfaceFace.curve")
375    };
376    let first = at(&curves[0], 0.0)?;
377    // the first point's preimages: the global nearest point, then the feet a grid of seeds reaches
378    let mut starts: Vec<[f64; 2]> = Vec::new();
379    let mut admit = |foot: Result<crate::SurfaceProjection, String>, starts: &mut Vec<[f64; 2]>| {
380        if let Ok(foot) = foot {
381            let fresh = starts.iter().all(|seen| ((seen[0] - foot.u) / u_span).abs().max(((seen[1] - foot.v) / v_span).abs()) > 1e-6);
382            if foot.distance <= bar && fresh {
383                starts.push([foot.u, foot.v]);
384            }
385        }
386    };
387    admit(crate::project_point_to_surface(surface, first), &mut starts);
388    const GRID: usize = 8;
389    for i in 0..=GRID {
390        for j in 0..=GRID {
391            let seed = [u0 + u_span * i as f64 / GRID as f64, v0 + v_span * j as f64 / GRID as f64];
392            admit(crate::project_point_to_surface_seeded(surface, first, seed[0], seed[1]), &mut starts);
393        }
394    }
395    starts.sort_by(|a, b| a[0].total_cmp(&b[0]).then(a[1].total_cmp(&b[1])));
396    let mut reasons = Vec::new();
397    let mut taken: Option<Vec<NurbsCurve>> = None;
398    for start in &starts {
399        if let Some(outer) = outer {
400            if !inside(outer, *start)? {
401                reasons.push(format!("start ({:.6}, {:.6}) is outside the outer loop", start[0], start[1]));
402                continue;
403            }
404        }
405        match walk_layer(surface, curves, *start, [[u0, u1], [v0, v1]], bar, &at) {
406            Ok(images) if outer.is_some_and(|outer| !within(outer, &images).unwrap_or(false)) => {
407                reasons.push(format!("start ({:.6}, {:.6}): the hole leaves or crosses the outer loop", start[0], start[1]));
408            }
409            Ok(images) => {
410                if (signed_area(&images)? > 0.0) == outer.is_none() {
411                    return Ok(images);
412                }
413                taken.get_or_insert(images);
414            }
415            Err(reason) => reasons.push(format!("start ({:.6}, {:.6}): {reason}", start[0], start[1])),
416        }
417    }
418    if let Some(images) = taken {
419        return Ok(images);
420    }
421    Err(refused(format!("no layer of the surface carries the loop: {}", if reasons.is_empty() { "the first point has no preimage".into() } else { reasons.join("; ") })))
422}
423
424/// One placement of [`layered_images`]: the chain walked from `start`.
425fn walk_layer(
426    surface: &NurbsSurface,
427    curves: &[NurbsCurve],
428    start: [f64; 2],
429    [[u0, u1], [v0, v1]]: [[f64; 2]; 2],
430    bar: f64,
431    at: &dyn Fn(&NurbsCurve, f64) -> Result<Vec3, KernelRefusal>,
432) -> Result<Vec<NurbsCurve>, String> {
433    let (u_span, v_span) = (u1 - u0, v1 - v0);
434    let step = |a: [f64; 2], b: [f64; 2]| ((a[0] - b[0]) / u_span).abs().max(((a[1] - b[1]) / v_span).abs());
435    let mut seed = start;
436    let mut images = Vec::with_capacity(curves.len());
437    for (index, curve) in curves.iter().enumerate() {
438        let mut feet = Vec::with_capacity(LAYER_STATIONS + 1);
439        for station in 0..=LAYER_STATIONS {
440            let point = at(curve, station as f64 / LAYER_STATIONS as f64).map_err(|error| error.to_string())?;
441            let foot = crate::project_point_to_surface_seeded(surface, point, seed[0], seed[1])?;
442            if foot.distance > bar {
443                return Err(format!("curve {index} leaves the layer at station {station} ({:.3e} off)", foot.distance));
444            }
445            // a foot on the domain's edge has a twin across a seam: the one beside the walk is taken, read on the surface
446            let mut uv = [foot.u, foot.v];
447            for (axis, [low, high]) in [[u0, u1], [v0, v1]].into_iter().enumerate() {
448                let span = high - low;
449                let twin = if (uv[axis] - low).abs() <= 1e-12 * span { high } else if (uv[axis] - high).abs() <= 1e-12 * span { low } else { continue };
450                let mut other = uv;
451                other[axis] = twin;
452                if (other[axis] - seed[axis]).abs() < (uv[axis] - seed[axis]).abs() && surface.evaluate(other[0], other[1])?.sub(point).length() <= bar {
453                    uv = other;
454                }
455            }
456            if station > 0 && step(seed, uv) > 0.25 {
457                return Err(format!("curve {index} jumps in the parameters at station {station}"));
458            }
459            seed = uv;
460            feet.push(seed);
461        }
462        let (head, tail) = (feet[0], feet[LAYER_STATIONS]);
463        let flat = |axis: usize, span: f64| feet.iter().all(|foot| ((foot[axis] - head[axis]) / span).abs() <= 1e-9);
464        let image = if flat(0, u_span) {
465            uv_line(head, [head[0], tail[1]]).map_err(|error| error.to_string())?
466        } else if flat(1, v_span) {
467            uv_line(head, [tail[0], head[1]]).map_err(|error| error.to_string())?
468        } else {
469            let fit = build_pcurve_on_surface(surface, curve)?;
470            let [q0, q1] = fit.domain()?;
471            let (a, b) = (fit.evaluate(q0)?, fit.evaluate(q1)?);
472            if step([a.x, a.y], head) > 1e-6 || step([b.x, b.y], tail) > 1e-6 {
473                return Err(format!("curve {index}'s fitted image is on another layer"));
474            }
475            fit
476        };
477        // the image against its curve at matched parameters
478        let [q0, q1] = image.domain()?;
479        for station in 0..=2 * LAYER_STATIONS {
480            let fraction = station as f64 / (2 * LAYER_STATIONS) as f64;
481            let uv = image.evaluate(q0 + (q1 - q0) * fraction)?;
482            let gap = surface.evaluate(uv.x, uv.y)?.sub(at(curve, fraction).map_err(|error| error.to_string())?).length();
483            if gap > bar {
484                return Err(format!("curve {index}'s image reads {gap:.3e} off it at fraction {fraction:.4}"));
485            }
486        }
487        images.push(image);
488    }
489    if step(seed, start) > 1e-9 {
490        return Err("the chain does not close in the parameters".into());
491    }
492    Ok(images)
493}
494
495/// The closed chain of parameter curves `chain` as a polygon of 48 samples a curve.
496fn polygon(chain: &[NurbsCurve]) -> Result<Vec<[f64; 2]>, KernelRefusal> {
497    const SAMPLES: usize = 48;
498    let mut polygon = Vec::with_capacity(chain.len() * SAMPLES);
499    for pcurve in chain {
500        let [t0, t1] = pcurve.domain().or_refuse(KernelStage::Collect, "surfaceFace.pcurve_domain")?;
501        for index in 0..SAMPLES {
502            let at = pcurve.evaluate(t0 + (t1 - t0) * index as f64 / SAMPLES as f64).or_refuse(KernelStage::Collect, "surfaceFace.pcurve")?;
503            polygon.push([at.x, at.y]);
504        }
505    }
506    Ok(polygon)
507}
508
509/// Whether the hole `hole` lies wholly inside the outer loop `outer` in the
510/// parameters: every sample of it inside, and no side of its polygon crossing
511/// a side of the outer one.
512fn within(outer: &[NurbsCurve], hole: &[NurbsCurve]) -> Result<bool, KernelRefusal> {
513    let (rim, ring) = (polygon(outer)?, polygon(hole)?);
514    for point in &ring {
515        if !inside(outer, *point)? {
516            return Ok(false);
517        }
518    }
519    let cross = |a: [f64; 2], b: [f64; 2], c: [f64; 2]| (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
520    for i in 0..ring.len() {
521        let (a, b) = (ring[i], ring[(i + 1) % ring.len()]);
522        for j in 0..rim.len() {
523            let (c, d) = (rim[j], rim[(j + 1) % rim.len()]);
524            if cross(a, b, c) * cross(a, b, d) < 0.0 && cross(c, d, a) * cross(c, d, b) < 0.0 {
525                return Ok(false);
526            }
527        }
528    }
529    Ok(true)
530}
531
532/// Whether `point` lies inside the closed chain of parameter curves `chain`
533/// (even-odd, on a sampled polygon).
534fn inside(chain: &[NurbsCurve], point: [f64; 2]) -> Result<bool, KernelRefusal> {
535    let polygon = polygon(chain)?;
536    let mut within = false;
537    for index in 0..polygon.len() {
538        let (a, b) = (polygon[index], polygon[(index + 1) % polygon.len()]);
539        if (a[1] > point[1]) != (b[1] > point[1]) && point[0] < a[0] + (point[1] - a[1]) * (b[0] - a[0]) / (b[1] - a[1]) {
540            within = !within;
541        }
542    }
543    Ok(within)
544}
545
546/// `sheets` as one body of all their faces, every id made new, unsewn.
547fn joined_sheets(sheets: &[BrepSolid], tolerance: f64) -> Result<BrepSolid, KernelRefusal> {
548    if sheets.is_empty() || sheets.iter().any(|sheet| sheet.shells.iter().all(|shell| shell.faces.is_empty())) {
549        return Err(input("sheets_empty", "at least one sheet, each of at least one face, is required".into()));
550    }
551    if !(tolerance.is_finite() && tolerance > 0.0) {
552        return Err(input("sheets_tolerance", "the sewing tolerance must be positive".into()));
553    }
554    // one body of all the faces, every id made new
555    let mut next = 0u64;
556    let mut id = || {
557        next += 1;
558        next
559    };
560    let (mut vertices, mut edges, mut shells) = (Vec::new(), Vec::new(), Vec::new());
561    for sheet in sheets {
562        let vertex_ids: std::collections::HashMap<u64, u64> = sheet.vertices.iter().map(|vertex| (vertex.id, id())).collect();
563        let edge_ids: std::collections::HashMap<u64, u64> = sheet.edges.iter().map(|edge| (edge.id, id())).collect();
564        let renamed = |ids: &std::collections::HashMap<u64, u64>, old: u64| {
565            ids.get(&old).copied().ok_or_else(|| input("sheets_reference", format!("a sheet refers to the missing id {old}")))
566        };
567        for vertex in &sheet.vertices {
568            vertices.push(VertexRecord { id: vertex_ids[&vertex.id], point: vertex.point });
569        }
570        for edge in &sheet.edges {
571            let mut record = edge.clone();
572            record.id = edge_ids[&edge.id];
573            record.start_vertex_id = renamed(&vertex_ids, edge.start_vertex_id)?;
574            record.end_vertex_id = renamed(&vertex_ids, edge.end_vertex_id)?;
575            edges.push(record);
576        }
577        for shell in &sheet.shells {
578            let mut faces = Vec::with_capacity(shell.faces.len());
579            for face in &shell.faces {
580                let mut record = face.clone();
581                record.id = id();
582                for loop_record in &mut record.loops {
583                    loop_record.id = id();
584                    for coedge in &mut loop_record.coedges {
585                        coedge.id = id();
586                        coedge.edge_id = renamed(&edge_ids, coedge.edge_id)?;
587                    }
588                }
589                faces.push(record);
590            }
591            shells.push(ShellRecord { id: id(), faces });
592        }
593    }
594    let joined = BrepSolid {
595        mass_properties_cache: Default::default(),
596        id: id(),
597        vertices,
598        edges,
599        shells,
600        genus: 0,
601        kind: BodyKind::Sheet,
602        cells: Default::default(),
603    };
604    Ok(joined)
605}
606
607/// One sheet of all the faces of `sheets`, joined along the edges that
608/// coincide within `tolerance` (the kernel's sewing, as [`solid_from_sheets`]
609/// joins them), its boundary left open: the patches of a filled N-sided hole
610/// as one body. Refuses a joined body the kernel's validation rejects.
611pub fn sheet_from_sheets(sheets: &[BrepSolid], tolerance: f64) -> Result<BrepSolid, KernelRefusal> {
612    let joined = joined_sheets(sheets, tolerance)?;
613    let (mut sheet, _) = sew_solid(&joined, tolerance)?;
614    sheet.kind = BodyKind::Sheet;
615    accept(sheet, "joined_sheet")
616}
617
618/// The solid `sheets` bound: their faces joined along the edges that coincide
619/// within `tolerance` (the kernel's sewing, [`crate::sew_solid`], which pairs
620/// edges by where they lie and needs no agreement between the sheets'
621/// normals), then turned outward.
622///
623/// One closed face is a solid by itself (a ball's or a ring's face from
624/// [`face_from_surface`]). Refuses sheets that leave an edge open after
625/// sewing, saying how many, and a joined body the kernel's validation rejects.
626/// `BREP_SHEETS_SIGN_ONLY` (default on; `=0` restores): [`solid_from_sheets`]
627/// orients the sewn shell by its volume's SIGN, read by
628/// `solid_signed_volume_for_sign` against 0, whose verdict is the exact
629/// integral's (a certified bound, a reading far from 0, or the exact value
630/// itself), instead of integrating the whole volume. offset/elliptic-cylinder-
631/// grown's five sheets: a 37 ms sign certificate, then a 127 ms integral the
632/// flip never needed (host).
633fn sheets_sign_only_on() -> bool {
634    crate::switch!("BREP_SHEETS_SIGN_ONLY", true)
635}
636
637pub fn solid_from_sheets(sheets: &[BrepSolid], tolerance: f64) -> Result<BrepSolid, KernelRefusal> {
638    let joined = joined_sheets(sheets, tolerance)?;
639    let (mut solid, report) = sew_solid(&joined, tolerance)?;
640    // a pole's degenerate edge bounds its one face by nature; every other edge must bound two
641    let mut uses = std::collections::HashMap::<u64, usize>::new();
642    for coedge in solid.shells.iter().flat_map(|shell| &shell.faces).flat_map(|face| &face.loops).flat_map(|record| &record.coedges) {
643        *uses.entry(coedge.edge_id).or_default() += 1;
644    }
645    let open = solid.edges.iter().filter(|edge| !edge.degenerate && uses.get(&edge.id).copied().unwrap_or(0) < 2).count();
646    if open > 0 {
647        return Err(refuse(
648            KernelStage::Sew,
649            "sheets_open",
650            format!("the sheets do not close: {open} edge(s) bound one face only after sewing ({} sewn)", report.edges_sewn),
651        ));
652    }
653    solid.kind = BodyKind::Solid;
654    // V − E + F − H = 2·(shells) − 2g, poles' degenerate edges not counted
655    let live = solid.edges.iter().filter(|edge| !edge.degenerate).count() as i64;
656    let faces = solid.shells.iter().map(|shell| shell.faces.len()).sum::<usize>() as i64;
657    let rings = solid.shells.iter().flat_map(|shell| &shell.faces).map(|face| face.loops.len().saturating_sub(1)).sum::<usize>() as i64;
658    let twice = 2 * solid.shells.len() as i64 - (solid.vertices.len() as i64 - live + faces - rings);
659    if twice < 0 || twice % 2 != 0 {
660        return Err(refuse(KernelStage::Validate, "sheets_euler", format!("the joined faces' counts describe no closed surface (2g = {twice})")));
661    }
662    solid.genus = twice / 2;
663    // Only the sign is read (`BREP_SHEETS_SIGN_ONLY`).
664    let volume = if sheets_sign_only_on() { crate::solid_signed_volume_for_sign(&solid, 0.0) } else { crate::solid_signed_volume(&solid) }
665        .or_refuse(KernelStage::Validate, "surfaceFace.volume")?;
666    if volume < 0.0 {
667        crate::orientation::flip_all_faces(&mut solid)?;
668    }
669    let issues = solid.validate();
670    if let Some(issue) = issues.first() {
671        return Err(refuse(KernelStage::Validate, "sheets_invalid", format!("the joined faces are not a valid solid: {issue:?}")));
672    }
673    Ok(solid)
674}
675