Skip to main content

brep_blend/blending/fillet/
setback_g2.rs

1//! A set-back corner whose blends are curvature-continuous
2//! (`fillet_edges_setback_g2`): three straight convex edges between planes meet
3//! at one vertex; each is rounded by the order-2 section of
4//! `fillet_edge_g2` (contact of order 2 with both faces) as far as the plane
5//! `setback` from the corner along it, and the corner is closed by one patch
6//! that meets the three blends and the three faces with their tangent planes
7//! and their curvatures.
8//!
9//! Built in three steps.
10//!
11//! 1. The corner is cut back: the parallelepiped on the corner spanned by the
12//!    three edges, `setback` along each, is taken off, so that each edge ends
13//!    on a planar end face at a vertex with one edge along each of its faces,
14//!    and the strip of each is built directly (`g2_prism`): the section
15//!    extruded along the edge, exact, ending on the carried section.
16//! 2. The three end faces go. On each face the two strips' contact lines end
17//!    at their cuts, and the face is closed between them by the planar quartic
18//!    whose controls are the two cuts, the midpoints toward the lines'
19//!    crossing and the crossing itself: tangent to both contact lines and as
20//!    straight as they are at its ends (its second derivative vanishes there).
21//!    The corner's hole has six sides, three sections and three face curves,
22//!    and six right-angled corners.
23//! 3. The hole is filled by the side-ribbon transfinite patch over a regular
24//!    hexagon (Gregory; Várady): `P = Σ w_k R_k(s_k, d_k)`, `d_k` the distance
25//!    to side `k` (1 at the centre), `s_k = d_{k-1} / (d_{k-1} + d_{k+1})` and
26//!    `w_k ∝ 1 / d_k³`, so that on side `k` every other weight vanishes with its
27//!    first two derivatives and the patch agrees with the ribbon `R_k` to
28//!    second order. A strip's ribbon is the strip itself continued toward the
29//!    corner (`C(s) + λ(s) φ(d) e`, on its extrusion); a face's is a map into
30//!    its plane (`Q(s) + φ(d) M(s) + φ(d)² N(s)`), with `M` and `N` solved at
31//!    both its ends so that its second-order jet there is the neighbouring
32//!    strip's: the section is flat where it meets the face, so that jet lies in
33//!    the plane. `φ(d) = d / (1 + (d/δ)³)^⅓` (δ = `REACH`) keeps each ribbon's jet at its side
34//!    and bounds how far it reaches across the patch. The patch is fitted as
35//!    three bicubic patches over the hexagon's three rhombi, which share the
36//!    centre and the seams to alternate corners; its sides are the exact
37//!    sections and face curves, the fitted patch held to them within
38//!    `BOUNDARY_BAR` of the corner's size, and its tangent planes and
39//!    curvatures checked against the strips' and faces' along every side.
40//!    Anything outside this construction is refused by name.
41use super::*;
42use crate::topology::{CoedgeRecord, LoopRecord, VertexRecord};
43use crate::{NurbsSurface, Vec4};
44
45const ENTRY: &str = "fillet_edges_setback_g2";
46
47/// How far each ribbon reaches across the patch (in units of the hexagon's
48/// inradius): `φ` saturates at it.
49const REACH: f64 = 0.6;
50
51/// Samples each way over a rhombus for the fit, clustered toward both ends.
52const GRID: usize = 81;
53
54/// The largest distance between the fitted patch and the exact sides, and
55/// between the fit and the transfinite patch inside, as a fraction of the
56/// corner's size.
57const BOUNDARY_BAR: f64 = 1e-6;
58
59/// The largest angle (radians) between the patch's normal and its
60/// neighbour's along a side, or between two patches across a seam.
61const ANGLE_BAR: f64 = 1e-4;
62
63/// The largest difference in normal curvature across a side or a seam, as a
64/// fraction of the strips' largest curvature.
65const CURVATURE_BAR: f64 = 2e-2;
66
67fn refuse(what: &'static str, message: String) -> KernelRefusal {
68    KernelRefusal::unsupported(KernelStage::Refine, what, format!("{ENTRY}: {message}"))
69}
70
71fn input(what: &'static str, message: String) -> KernelRefusal {
72    KernelRefusal::input(KernelStage::Collect, what, format!("{ENTRY}: {message}"))
73}
74
75fn is_line(edge: &EdgeRecord) -> bool {
76    edge.curve.degree == 1 && edge.curve.control_points.len() == 2
77}
78
79fn ends(edge: &EdgeRecord) -> Result<(Vec3, Vec3), KernelRefusal> {
80    Ok((edge.curve.evaluate(edge.t0).or_refuse(KernelStage::Refine, "evaluate")?, edge.curve.evaluate(edge.t1).or_refuse(KernelStage::Refine, "evaluate")?))
81}
82
83fn next_id_after(body: &BrepSolid) -> u64 {
84    body.vertices
85        .iter()
86        .map(|v| v.id)
87        .chain(body.edges.iter().map(|x| x.id))
88        .chain(body.shells.iter().flat_map(|s| s.faces.iter()).flat_map(|f| std::iter::once(f.id).chain(f.loops.iter().flat_map(|l| std::iter::once(l.id).chain(l.coedges.iter().map(|c| c.id))))))
89        .max()
90        .unwrap_or(0)
91        + 1
92}
93
94/// A straight parameter line from `a` to `b` over the parameter range `[t0, t1]`.
95fn uv_line(a: [f64; 2], b: [f64; 2], t0: f64, t1: f64) -> Result<NurbsCurve, KernelRefusal> {
96    NurbsCurve::new(1, vec![t0, t0, t1, t1], vec![Vec4 { x: a[0], y: a[1], z: 0.0, w: 1.0 }, Vec4 { x: b[0], y: b[1], z: 0.0, w: 1.0 }]).or_refuse(KernelStage::Refine, "uv_line")
97}
98
99/// `fillet_edges_g2` of the three edges the points lie on, meeting at one
100/// convex vertex between three planes, whose strips stop `setback` from the
101/// vertex (measured along each edge) and whose corner is closed by one
102/// curvature-continuous patch: tangent to the strips and the faces and with
103/// their curvatures along every side (see the module notes). `offset` is the
104/// blends' tangent offset and `center` their centre radius (where not
105/// positive, the thumbweight that takes off what the ball's round does).
106pub fn fillet_edges_setback_g2(
107    solid: &BrepSolid,
108    edge_points: &[Vec3],
109    edge_names: Option<&[String]>,
110    offset: f64,
111    setback: f64,
112    center: f64,
113    name: Option<&str>,
114) -> Result<BrepSolid, KernelRefusal> {
115    let _operation = crate::blend::BlendOperation::enter();
116    if !(offset.is_finite() && offset > 0.0) || !center.is_finite() {
117        return Err(input("g2_size", "the offset must be positive and the centre radius finite".into()));
118    }
119    if !(setback.is_finite() && setback > offset) {
120        return Err(input("setback_size", format!("the setback {setback} must exceed the offset {offset}")));
121    }
122    if edge_points.len() != 3 {
123        return Err(KernelRefusal::unsupported(KernelStage::Collect, "setback_selection", format!("{ENTRY}: three edges meeting at one corner are set back")));
124    }
125    if solid.shells.len() != 1 {
126        return Err(refuse("setback_shells", "the body has more than one shell".into()));
127    }
128    let mut ids = [0u64; 3];
129    for (k, point) in edge_points.iter().enumerate() {
130        ids[k] = super::edges::resolve_edge_by_point(solid, *point)?;
131    }
132    if ids[0] == ids[1] || ids[1] == ids[2] || ids[0] == ids[2] {
133        return Err(input("setback_selection", "two of the points lie on one edge".into()));
134    }
135    let edge_of = |id: u64| solid.edges.iter().find(|e| e.id == id);
136    let mut counts: std::collections::HashMap<u64, usize> = std::collections::HashMap::new();
137    for &id in &ids {
138        let edge = edge_of(id).ok_or_else(|| input("setback_edge", "an edge is missing".into()))?;
139        for v in [edge.start_vertex_id, edge.end_vertex_id] {
140            *counts.entry(v).or_insert(0) += 1;
141        }
142    }
143    let corner_vertex = counts.iter().find(|(_, &c)| c == 3).map(|(&v, _)| v).ok_or_else(|| KernelRefusal::unsupported(KernelStage::Collect, "setback_selection", format!("{ENTRY}: the three edges do not meet at one vertex")))?;
144    let corner = solid.vertices.iter().find(|v| v.id == corner_vertex).map(|v| v.point).ok_or_else(|| input("setback_vertex", "the corner vertex is missing".into()))?;
145    let at_corner = solid.edges.iter().filter(|e| e.start_vertex_id == corner_vertex || e.end_vertex_id == corner_vertex).count();
146    if at_corner != 3 {
147        return Err(refuse("setback_g2_corner", format!("the corner has {at_corner} edges, not three")));
148    }
149    let mut t = [Vec3::new(0.0, 0.0, 0.0); 3];
150    let mut length = [0.0f64; 3];
151    for (k, &id) in ids.iter().enumerate() {
152        let edge = edge_of(id).expect("edge");
153        if !is_line(edge) {
154            return Err(refuse("setback_g2_edge", "a selected edge is not straight".into()));
155        }
156        let (a, b) = ends(edge)?;
157        let far = if edge.start_vertex_id == corner_vertex { b } else { a };
158        length[k] = far.sub(corner).length();
159        t[k] = far.sub(corner).normalized().or_refuse(KernelStage::Collect, "normalized")?;
160        if !(length[k] > setback * (1.0 + 1e-6)) {
161            return Err(input("setback_reach", format!("the setback {setback} reaches the far end of an edge {} long", length[k])));
162        }
163    }
164    let det = t[0].dot(t[1].cross(t[2]));
165    if det.abs() < 1e-6 {
166        return Err(refuse("setback_g2_corner", "the three edges are nearly coplanar".into()));
167    }
168    let shortest = length.iter().copied().fold(f64::INFINITY, f64::min);
169    let tolerance = 1e-9 * (1.0 + corner.length());
170    let inside = corner.add(t[0].add(t[1]).add(t[2]).scale(1e-3 * shortest));
171    if crate::classify_point(inside, solid, tolerance).or_refuse(KernelStage::Collect, "classify_point")?.class != crate::PointClass::In {
172        return Err(refuse("setback_concave", "the corner is not convex: only a convex corner is set back".into()));
173    }
174
175    // 1. Cut the corner back and build the three strips.
176    let (a, b, c) = if det > 0.0 { (t[0], t[1], t[2]) } else { (t[0], t[2], t[1]) };
177    let margin = setback;
178    let cube = crate::make_box_brep(Vec3::new(-margin, -margin, -margin), setback + margin, setback + margin, setback + margin).map_err(|e| refuse("setback_g2_notch", e))?;
179    let place = crate::AffineTransform { elements: [a.x, b.x, c.x, corner.x, a.y, b.y, c.y, corner.y, a.z, b.z, c.z, corner.z, 0.0, 0.0, 0.0, 1.0] };
180    let cutter = crate::transform_brep(&cube, place, false).map_err(|e| refuse("setback_g2_notch", e))?;
181    let mut body = boolean_operation(solid, &cutter, BooleanOperation::Subtract, &BooleanOptions::default())
182        .map_err(|r| refuse("setback_g2_notch", format!("the corner could not be cut back: {}", r.message)))?;
183    if body.shells.len() != 1 {
184        return Err(refuse("setback_g2_notch", "cutting the corner back left more than one shell".into()));
185    }
186    // The cutter reaches `setback` past each face as well: it must have taken
187    // the corner's parallelepiped and nothing else (no rib or wall nearby).
188    let taken = crate::solid_mass_properties(solid).or_refuse(KernelStage::Refine, "mass_properties")?.volume - crate::solid_mass_properties(&body).or_refuse(KernelStage::Refine, "mass_properties")?.volume;
189    let notch = setback * setback * setback * det.abs();
190    if (taken - notch).abs() > 1e-6 * notch {
191        return Err(refuse("setback_g2_notch", format!("cutting the corner back takes {taken:.6e}, not the corner's {notch:.6e}: other material lies within the setback of the corner")));
192    }
193    for k in 0..3 {
194        let probe = corner.add(t[k].scale(0.5 * (setback + length[k])));
195        let id = super::edges::resolve_edge_by_point(&body, probe)?;
196        let cross = analyze_edge(&body, id, offset).map_err(|r| refuse("setback_g2_strip", format!("edge {k}'s section could not be read ({})", r.message)))?;
197        if !matches!(cross.path, EdgePath::Straight { .. }) {
198            return Err(refuse("setback_g2_strip", "a strip is built only on a straight edge between planes".into()));
199        }
200        let profile = super::tool::g2_cross_section(&cross, offset, center)?;
201        let built = super::g2_prism::blend_prism_edge(&body, id, &cross, &profile[1], super::edges::per_edge_name(edge_names, name, k))
202            .ok_or_else(|| refuse("setback_g2_strip", format!("edge {k}'s strip could not be built on the cut-back corner")))?;
203        check_blend_interference(&body, &built, &[id], ENTRY)?;
204        body = built;
205    }
206
207    // 2. The end faces go; each face is closed between its two cuts.
208    let faces = body.shells[0].faces.clone();
209    let mut end_face = [usize::MAX; 3];
210    for (fi, face) in faces.iter().enumerate() {
211        let Some(n) = super::g2_prism::planar_normal(face) else { continue };
212        let Some(on) = face.surface.control_points.first().and_then(|row| row.first()).and_then(|c| c.point().ok()) else { continue };
213        for k in 0..3 {
214            let plane = t[(k + 1) % 3].cross(t[(k + 2) % 3]).normalized().or_refuse(KernelStage::Refine, "normalized")?;
215            let at = corner.add(t[k].scale(setback));
216            if n.cross(plane).length() <= 1e-9 && plane.dot(on.sub(at)).abs() <= 1e-9 * (1.0 + setback + at.length()) {
217                if end_face[k] != usize::MAX {
218                    return Err(refuse("setback_g2_notch", "two faces lie on one end plane".into()));
219                }
220                end_face[k] = fi;
221            }
222        }
223    }
224    if end_face.contains(&usize::MAX) {
225        return Err(refuse("setback_g2_notch", "an end face of the cut-back corner is missing".into()));
226    }
227    let holders = |edge_id: u64| -> Vec<usize> {
228        let mut out = Vec::new();
229        for (fi, f) in faces.iter().enumerate() {
230            if f.loops.iter().any(|l| l.coedges.iter().any(|c| c.edge_id == edge_id)) {
231                out.push(fi);
232            }
233        }
234        out
235    };
236    let mut sections = [(0u64, 0usize); 3]; // (edge, strip face)
237    let mut segments: Vec<(u64, usize)> = Vec::new(); // (edge, face)
238    let mut inner: Vec<u64> = Vec::new();
239    for k in 0..3 {
240        let face = &faces[end_face[k]];
241        if face.loops.len() != 1 {
242            return Err(refuse("setback_g2_notch", "an end face has a hole".into()));
243        }
244        let mut found = 0;
245        for c in &face.loops[0].coedges {
246            let others: Vec<usize> = holders(c.edge_id).into_iter().filter(|&f| f != end_face[k]).collect();
247            if others.len() != 1 {
248                return Err(refuse("setback_g2_notch", "an end face's edge is not shared with one other face".into()));
249            }
250            let other = others[0];
251            if end_face.contains(&other) {
252                if !inner.contains(&c.edge_id) {
253                    inner.push(c.edge_id);
254                }
255            } else if super::g2_prism::planar_normal(&faces[other]).is_some() {
256                segments.push((c.edge_id, other));
257            } else {
258                sections[k] = (c.edge_id, other);
259                found += 1;
260            }
261        }
262        if found != 1 {
263            return Err(refuse("setback_g2_notch", format!("an end face meets {found} strips, not one")));
264        }
265    }
266    if segments.len() != 6 || inner.len() != 3 {
267        return Err(refuse("setback_g2_notch", format!("the cut-back corner has {} edges on its faces and {} between its end faces, not 6 and 3", segments.len(), inner.len())));
268    }
269    let mut result = body.clone();
270    let mut next = next_id_after(&result);
271    let mut id = || {
272        next += 1;
273        next
274    };
275    let edge_now = |result: &BrepSolid, x: u64| result.edges.iter().find(|e| e.id == x).cloned();
276    let walked = |edge: &EdgeRecord, forward: bool| if forward { (edge.start_vertex_id, edge.end_vertex_id) } else { (edge.end_vertex_id, edge.start_vertex_id) };
277    let point_of = |result: &BrepSolid, v: u64| result.vertices.iter().find(|x| x.id == v).map(|x| x.point);
278    // (face index, curve edge, its plane's normal)
279    let mut face_curves: Vec<(usize, u64, Vec3)> = Vec::new();
280    let segment_ids: Vec<u64> = segments.iter().map(|s| s.0).collect();
281    let mut closed_faces: Vec<usize> = segments.iter().map(|s| s.1).collect();
282    closed_faces.sort_unstable();
283    closed_faces.dedup();
284    if closed_faces.len() != 3 {
285        return Err(refuse("setback_g2_faces", format!("{} faces meet the cut-back corner, not three", closed_faces.len())));
286    }
287    for &fi in &closed_faces {
288        let face = &faces[fi];
289        let normal = super::g2_prism::planar_normal(face).expect("planar");
290        let li = face.loops.iter().position(|l| l.coedges.iter().any(|c| segment_ids.contains(&c.edge_id))).expect("loop");
291        let ring = &face.loops[li].coedges;
292        let n = ring.len();
293        let at = (0..n)
294            .find(|&ci| segment_ids.contains(&ring[ci].edge_id) && segment_ids.contains(&ring[(ci + 1) % n].edge_id))
295            .ok_or_else(|| refuse("setback_g2_faces", "a face's two cut edges are not consecutive".into()))?;
296        let (first, second) = (&ring[at], &ring[(at + 1) % n]);
297        let (before, after) = (&ring[(at + n - 1) % n], &ring[(at + 2) % n]);
298        let (rail1, rail2) = (edge_now(&result, before.edge_id).expect("rail"), edge_now(&result, after.edge_id).expect("rail"));
299        if !is_line(&rail1) || !is_line(&rail2) {
300            return Err(refuse("setback_g2_faces", "a strip's contact line is not straight".into()));
301        }
302        let (far1, cut1) = walked(&rail1, before.forward);
303        let (cut2, far2) = walked(&rail2, after.forward);
304        let (v_first, _) = walked(&edge_now(&result, first.edge_id).expect("segment"), first.forward);
305        let (_, v_second) = walked(&edge_now(&result, second.edge_id).expect("segment"), second.forward);
306        if v_first != cut1 || v_second != cut2 {
307            return Err(refuse("setback_g2_faces", "a face's cut edges do not run between its contact lines".into()));
308        }
309        let (r1, r2) = (point_of(&result, cut1).expect("cut"), point_of(&result, cut2).expect("cut"));
310        let d1 = r1.sub(point_of(&result, far1).expect("far")).normalized().or_refuse(KernelStage::Refine, "normalized")?;
311        let d2 = r2.sub(point_of(&result, far2).expect("far")).normalized().or_refuse(KernelStage::Refine, "normalized")?;
312        // The contact lines' crossing: r1 + λ d1 = r2 + μ d2.
313        let gap = r2.sub(r1);
314        let (a11, a12, a22) = (d1.dot(d1), -d1.dot(d2), d2.dot(d2));
315        let (b1, b2) = (d1.dot(gap), -d2.dot(gap));
316        let det2 = a11 * a22 - a12 * a12;
317        if det2.abs() < 1e-12 {
318            return Err(refuse("setback_g2_faces", "a face's two contact lines are parallel".into()));
319        }
320        let lambda = (b1 * a22 - a12 * b2) / det2;
321        let mu = (a11 * b2 - a12 * b1) / det2;
322        let crossing = r1.add(d1.scale(lambda));
323        if !(lambda > 0.0 && mu > 0.0) || crossing.sub(r2.add(d2.scale(mu))).length() > 1e-7 * (1.0 + setback) {
324            return Err(refuse("setback_g2_faces", "a face's contact lines do not cross toward the corner".into()));
325        }
326        let controls = [r1, r1.add(crossing).scale(0.5), crossing, r2.add(crossing).scale(0.5), r2];
327        let quartic = NurbsCurve::new(4, vec![0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0], controls.iter().map(|&p| Vec4::from_point(p, 1.0)).collect()).or_refuse(KernelStage::Refine, "face_curve")?;
328        let pcurve = super::g2_prism::mapped_on_plane(face, &quartic).ok_or_else(|| refuse("setback_g2_faces", "a face curve could not be put on its plane".into()))?;
329        let e = id();
330        result.edges.push(EdgeRecord { id: e, curve: quartic, t0: 0.0, t1: 1.0, start_vertex_id: cut1, end_vertex_id: cut2, degenerate: false, name: None });
331        let coedge = CoedgeRecord { id: id(), edge_id: e, forward: true, pcurve };
332        let mut coedges = Vec::with_capacity(n - 1);
333        for (ci, c) in ring.iter().enumerate() {
334            if ci == at {
335                coedges.push(coedge.clone());
336            } else if ci != (at + 1) % n {
337                coedges.push(c.clone());
338            }
339        }
340        result.shells[0].faces[fi].loops[li].coedges = coedges;
341        face_curves.push((fi, e, normal));
342    }
343    let gone_faces: Vec<u64> = end_face.iter().map(|&fi| faces[fi].id).collect();
344    result.shells[0].faces.retain(|f| !gone_faces.contains(&f.id));
345    result.edges.retain(|e| !segment_ids.contains(&e.id) && !inner.contains(&e.id));
346    let used: Vec<u64> = result.edges.iter().flat_map(|e| [e.start_vertex_id, e.end_vertex_id]).collect();
347    result.vertices.retain(|v| used.contains(&v.id));
348
349    // 3. The hole's sides, walked against their neighbours, chained.
350    let mut pieces: Vec<Side> = Vec::with_capacity(6);
351    for k in 0..3 {
352        let (edge_id, strip) = sections[k];
353        let strip_face = &faces[strip];
354        let c = strip_face.loops.iter().flat_map(|l| l.coedges.iter()).find(|c| c.edge_id == edge_id).expect("section use");
355        let edge = edge_now(&result, edge_id).expect("section");
356        pieces.push(Side::new(edge, !c.forward, Kind::Strip { toward: t[k].scale(-1.0) })?);
357    }
358    for &(_, e, normal) in &face_curves {
359        let edge = edge_now(&result, e).expect("face curve");
360        pieces.push(Side::new(edge, false, Kind::Face { normal })?);
361    }
362    let mut chain = vec![pieces.remove(0)];
363    while !pieces.is_empty() {
364        let to = chain.last().expect("side").to;
365        let at = pieces.iter().position(|p| p.from == to).ok_or_else(|| refuse("setback_g2_hole", "the corner's six sides do not close".into()))?;
366        chain.push(pieces.remove(at));
367    }
368    if chain[5].to != chain[0].from || (0..6).any(|k| matches!(chain[k].kind, Kind::Strip { .. }) != (k % 2 == 0)) {
369        return Err(refuse("setback_g2_hole", "the corner's sides do not alternate between strips and faces round a closed loop".into()));
370    }
371    let sides: [Side; 6] = chain.try_into().map_err(|_| refuse("setback_g2_hole", "the corner does not have six sides".into()))?;
372    let patch = CornerPatch::new(sides)?;
373    let fitted = patch.fit(corner, &mut id, name)?;
374    let curvature_scale = patch.curvature_scale()?;
375    fitted.check(&patch, &result, curvature_scale)?;
376    fitted.contained(corner, t, setback)?;
377    result.vertices.push(fitted.centre);
378    result.edges.extend(fitted.seams.iter().cloned());
379    result.shells[0].faces.extend(fitted.faces.iter().cloned());
380    result.mass_properties_cache = Default::default();
381    super::edges::refuse_invalid_result(&result, ENTRY)?;
382    Ok(result)
383}
384
385#[derive(Clone, Copy, Debug)]
386enum Kind {
387    /// A strip's section; `toward`: the unit direction along its edge toward the corner.
388    Strip { toward: Vec3 },
389    /// A face curve; `normal`: its plane's unit normal.
390    Face { normal: Vec3 },
391}
392
393/// One side of the hole, as the patch walks it: `B(s) = curve(τ(s))`, `s` in
394/// `[0, 1]` from `from` to `to`.
395#[derive(Clone, Debug)]
396struct Side {
397    edge: EdgeRecord,
398    forward: bool,
399    from: u64,
400    to: u64,
401    kind: Kind,
402}
403
404impl Side {
405    fn new(edge: EdgeRecord, forward: bool, kind: Kind) -> Result<Side, KernelRefusal> {
406        let (from, to) = if forward { (edge.start_vertex_id, edge.end_vertex_id) } else { (edge.end_vertex_id, edge.start_vertex_id) };
407        Ok(Side { edge, forward, from, to, kind })
408    }
409
410    fn tau(&self, s: f64) -> f64 {
411        let (t0, t1) = (self.edge.t0, self.edge.t1);
412        if self.forward { t0 + s * (t1 - t0) } else { t1 - s * (t1 - t0) }
413    }
414
415    fn tau_rate(&self) -> f64 {
416        if self.forward { self.edge.t1 - self.edge.t0 } else { self.edge.t0 - self.edge.t1 }
417    }
418
419    /// `B`, `B'` and `B''` (with respect to `s`).
420    fn jet(&self, s: f64) -> Result<[Vec3; 3], KernelRefusal> {
421        let d = self.edge.curve.derivatives(self.tau(s), 2).or_refuse(KernelStage::Refine, "derivatives")?;
422        let r = self.tau_rate();
423        Ok([d[0], d[1].scale(r), d[2].scale(r * r)])
424    }
425
426    fn at(&self, s: f64) -> Result<Vec3, KernelRefusal> {
427        self.edge.curve.evaluate(self.tau(s.clamp(0.0, 1.0))).or_refuse(KernelStage::Refine, "evaluate")
428    }
429}
430
431/// `φ(d)`: `d` to second order at 0, saturating at [`REACH`].
432fn phi(d: f64) -> f64 {
433    let q = d / REACH;
434    d / (1.0 + q * q * q.abs()).cbrt()
435}
436
437/// The regular hexagon the patch is built over (circumradius 1, side 1,
438/// inradius √3/2), counter-clockwise.
439struct Hexagon {
440    corners: [[f64; 2]; 6],
441    normals: [[f64; 2]; 6],
442}
443
444const INRADIUS: f64 = 0.866_025_403_784_438_6;
445
446impl Hexagon {
447    fn new() -> Hexagon {
448        let mut corners = [[0.0; 2]; 6];
449        for (k, c) in corners.iter_mut().enumerate() {
450            let a = std::f64::consts::FRAC_PI_2 + k as f64 * std::f64::consts::FRAC_PI_3;
451            *c = [a.cos(), a.sin()];
452        }
453        let mut normals = [[0.0; 2]; 6];
454        for k in 0..6 {
455            let (p, q) = (corners[k], corners[(k + 1) % 6]);
456            let m = [0.5 * (p[0] + q[0]), 0.5 * (p[1] + q[1])];
457            let l = m[0].hypot(m[1]);
458            normals[k] = [-m[0] / l, -m[1] / l];
459        }
460        Hexagon { corners, normals }
461    }
462
463    /// `d_k(p)`: 0 on side `k`, 1 at the centre.
464    fn d(&self, k: usize, p: [f64; 2]) -> f64 {
465        let (v, n) = (self.corners[k], self.normals[k]);
466        ((p[0] - v[0]) * n[0] + (p[1] - v[1]) * n[1]) / INRADIUS
467    }
468
469    fn d_grad(&self, k: usize) -> [f64; 2] {
470        [self.normals[k][0] / INRADIUS, self.normals[k][1] / INRADIUS]
471    }
472
473    /// `s_k(p)`, its gradient and its Hessian.
474    fn s_jet(&self, k: usize, p: [f64; 2]) -> (f64, [f64; 2], [[f64; 2]; 2]) {
475        let (before, after) = ((k + 5) % 6, (k + 1) % 6);
476        let (a, b) = (self.d(before, p), self.d(after, p));
477        let (ga, gb) = (self.d_grad(before), self.d_grad(after));
478        let dd = a + b;
479        let gd = [ga[0] + gb[0], ga[1] + gb[1]];
480        let s = a / dd;
481        let g = [ga[0] / dd - a * gd[0] / (dd * dd), ga[1] / dd - a * gd[1] / (dd * dd)];
482        let mut h = [[0.0; 2]; 2];
483        for i in 0..2 {
484            for j in 0..2 {
485                h[i][j] = -(ga[i] * gd[j] + ga[j] * gd[i]) / (dd * dd) + 2.0 * a * gd[i] * gd[j] / (dd * dd * dd);
486            }
487        }
488        (s, g, h)
489    }
490
491    fn s(&self, k: usize, p: [f64; 2]) -> f64 {
492        let (a, b) = (self.d((k + 5) % 6, p), self.d((k + 1) % 6, p));
493        (a / (a + b)).clamp(0.0, 1.0)
494    }
495}
496
497fn dot2(a: [f64; 2], b: [f64; 2]) -> f64 {
498    a[0] * b[0] + a[1] * b[1]
499}
500
501fn quad2(h: [[f64; 2]; 2], a: [f64; 2], b: [f64; 2]) -> f64 {
502    a[0] * (h[0][0] * b[0] + h[0][1] * b[1]) + a[1] * (h[1][0] * b[0] + h[1][1] * b[1])
503}
504
505fn in_plane(v: Vec3, n: Vec3) -> Vec3 {
506    v.sub(n.scale(v.dot(n)))
507}
508
509/// The transfinite patch over the hexagon.
510struct CornerPatch {
511    hex: Hexagon,
512    sides: [Side; 6],
513    /// Per strip side: `λ` at `s = 0` and `s = 1`.
514    lambda: [[f64; 2]; 6],
515    /// Per face side: `M(0), M'(0), M(1), M'(1)` and `N(0), N(1)`.
516    m: [[Vec3; 4]; 6],
517    n: [[Vec3; 2]; 6],
518}
519
520impl CornerPatch {
521    fn new(sides: [Side; 6]) -> Result<CornerPatch, KernelRefusal> {
522        let hex = Hexagon::new();
523        let zero = Vec3::new(0.0, 0.0, 0.0);
524        let mut patch = CornerPatch { hex, sides, lambda: [[0.0; 2]; 6], m: [[zero; 4]; 6], n: [[zero; 2]; 6] };
525        // λ at each end of a strip: the neighbouring face curve's speed along
526        // the shared side's direction, so the two agree along it at the corner.
527        for f in (0..6).step_by(2) {
528            let Kind::Strip { toward } = patch.sides[f].kind else { unreachable!() };
529            for (slot, (l, s_l, corner)) in [((f + 5) % 6, 1.0, f), ((f + 1) % 6, 0.0, (f + 1) % 6)].into_iter().enumerate() {
530                let v = patch.hex.corners[corner];
531                let x = Self::along(&patch.hex, l);
532                let (_, gs, _) = patch.hex.s_jet(l, v);
533                let [_, b1, _] = patch.sides[l].jet(s_l)?;
534                let gd = patch.hex.d_grad(f);
535                let rate = dot2(gd, x);
536                if rate.abs() < 1e-12 {
537                    return Err(refuse("setback_g2_patch", "a strip side's distance does not change along its neighbour".into()));
538                }
539                let speed = b1.dot(toward) * dot2(gs, x) / rate;
540                if !(speed > 0.0) {
541                    return Err(refuse("setback_g2_patch", "a face curve does not leave its cut toward the corner".into()));
542                }
543                patch.lambda[f][slot] = speed;
544            }
545        }
546        // Each face ribbon's M, M' and N at both ends, from the strip's jet.
547        for l in (1..6).step_by(2) {
548            let Kind::Face { normal } = patch.sides[l].kind else { unreachable!() };
549            for (end, (f, corner, s_l)) in [((l + 5) % 6, l, 0.0), ((l + 1) % 6, (l + 1) % 6, 1.0)].into_iter().enumerate() {
550                let v = patch.hex.corners[corner];
551                let x = Self::along(&patch.hex, l);
552                let y = patch.hex.normals[l];
553                let kappa = dot2(patch.hex.d_grad(l), y);
554                let (_, gs, hs) = patch.hex.s_jet(l, v);
555                let [_, b1, b2] = patch.sides[l].jet(s_l)?;
556                let target = |u: [f64; 2], w: Option<[f64; 2]>| patch.strip_jet(f, v, u, w);
557                let (ty, txy, tyy) = (target(y, None)?, target(x, Some(y))?, target(y, Some(y))?);
558                let (sx, sy) = (dot2(gs, x), dot2(gs, y));
559                let m = ty.sub(b1.scale(sy)).scale(1.0 / kappa);
560                let m1 = txy.sub(b2.scale(sx * sy)).sub(b1.scale(quad2(hs, x, y))).scale(1.0 / (kappa * sx));
561                let nn = tyy.sub(b2.scale(sy * sy)).sub(b1.scale(quad2(hs, y, y))).sub(m1.scale(2.0 * kappa * sy)).scale(1.0 / (2.0 * kappa * kappa));
562                patch.m[l][2 * end] = in_plane(m, normal);
563                patch.m[l][2 * end + 1] = in_plane(m1, normal);
564                patch.n[l][end] = in_plane(nn, normal);
565            }
566        }
567        Ok(patch)
568    }
569
570    /// The unit direction of side `k` in the domain, from its start.
571    fn along(hex: &Hexagon, k: usize) -> [f64; 2] {
572        let (p, q) = (hex.corners[k], hex.corners[(k + 1) % 6]);
573        let l = (q[0] - p[0]).hypot(q[1] - p[1]);
574        [(q[0] - p[0]) / l, (q[1] - p[1]) / l]
575    }
576
577    /// The first (`w` = None) or second derivative of strip `f`'s ribbon,
578    /// composed with `s_f` and `d_f`, at the domain corner `v` (where `d_f` = 0).
579    fn strip_jet(&self, f: usize, v: [f64; 2], u: [f64; 2], w: Option<[f64; 2]>) -> Result<Vec3, KernelRefusal> {
580        let Kind::Strip { toward } = self.sides[f].kind else { unreachable!() };
581        let (s, gs, hs) = self.hex.s_jet(f, v);
582        let gd = self.hex.d_grad(f);
583        let [_, b1, b2] = self.sides[f].jet(s.clamp(0.0, 1.0))?;
584        let [l0, l1] = self.lambda[f];
585        let lambda = l0 + (l1 - l0) * s;
586        let dl = l1 - l0;
587        Ok(match w {
588            None => b1.scale(dot2(gs, u)).add(toward.scale(lambda * dot2(gd, u))),
589            Some(w) => b2
590                .scale(dot2(gs, u) * dot2(gs, w))
591                .add(b1.scale(quad2(hs, u, w)))
592                .add(toward.scale(dl * (dot2(gs, u) * dot2(gd, w) + dot2(gs, w) * dot2(gd, u)))),
593        })
594    }
595
596    /// Ribbon `k` at `(s, d)`.
597    fn ribbon(&self, k: usize, s: f64, d: f64) -> Result<Vec3, KernelRefusal> {
598        let s = s.clamp(0.0, 1.0);
599        let base = self.sides[k].at(s)?;
600        if d == 0.0 {
601            return Ok(base);
602        }
603        let p = phi(d);
604        Ok(match self.sides[k].kind {
605            Kind::Strip { toward } => {
606                let [l0, l1] = self.lambda[k];
607                base.add(toward.scale((l0 + (l1 - l0) * s) * p))
608            }
609            Kind::Face { .. } => {
610                let [m0, m0d, m1, m1d] = self.m[k];
611                let (h00, h10, h01, h11) = (2.0 * s * s * s - 3.0 * s * s + 1.0, s * s * s - 2.0 * s * s + s, -2.0 * s * s * s + 3.0 * s * s, s * s * s - s * s);
612                let m = m0.scale(h00).add(m0d.scale(h10)).add(m1.scale(h01)).add(m1d.scale(h11));
613                let n = self.n[k][0].scale(1.0 - s).add(self.n[k][1].scale(s));
614                base.add(m.scale(p)).add(n.scale(p * p))
615            }
616        })
617    }
618
619    /// The patch at the domain point `p`.
620    fn eval(&self, p: [f64; 2]) -> Result<Vec3, KernelRefusal> {
621        let d: [f64; 6] = std::array::from_fn(|k| self.hex.d(k, p).max(0.0));
622        let (low, least) = d.iter().copied().enumerate().fold((0, f64::INFINITY), |best, (k, x)| if x < best.1 { (k, x) } else { best });
623        if least <= 1e-13 {
624            return self.ribbon(low, self.hex.s(low, p), 0.0);
625        }
626        let inv: [f64; 6] = std::array::from_fn(|k| 1.0 / (d[k] * d[k] * d[k]));
627        let total: f64 = inv.iter().sum();
628        let mut out = Vec3::new(0.0, 0.0, 0.0);
629        for k in 0..6 {
630            out = out.add(self.ribbon(k, self.hex.s(k, p), d[k])?.scale(inv[k] / total));
631        }
632        Ok(out)
633    }
634
635    /// Rhombus `m`'s domain point at `(u, v)`: `(0,0)` = corner `2m+1`, `(1,0)` =
636    /// corner `2m+2`, `(1,1)` = the centre, `(0,1)` = corner `2m`.
637    fn rhombus(&self, m: usize, u: f64, v: f64) -> [f64; 2] {
638        let o = self.hex.corners[(2 * m + 1) % 6];
639        let a = self.hex.corners[(2 * m + 2) % 6];
640        let b = self.hex.corners[(2 * m) % 6];
641        [o[0] + u * (a[0] - o[0]) + v * (b[0] - o[0]), o[1] + u * (a[1] - o[1]) + v * (b[1] - o[1])]
642    }
643
644    /// The largest curvature of the strips along their sections, the scale the
645    /// curvature bar is read against.
646    fn curvature_scale(&self) -> Result<f64, KernelRefusal> {
647        let mut most = 0.0f64;
648        for k in (0..6).step_by(2) {
649            for i in 0..=16 {
650                let [_, b1, b2] = self.sides[k].jet(i as f64 / 16.0)?;
651                let speed = b1.length();
652                if speed > 0.0 {
653                    most = most.max(b1.cross(b2).length() / (speed * speed * speed));
654                }
655            }
656        }
657        Ok(most)
658    }
659
660    fn fit(&self, corner: Vec3, id: &mut dyn FnMut() -> u64, name: Option<&str>) -> Result<Fitted, KernelRefusal> {
661        // Clustered toward both ends (Chebyshev-Lobatto): the patch bends fastest at the hexagon's corners.
662        let n = GRID;
663        let params: Vec<f64> = (0..n)
664            .map(|i| 0.5 - 0.5 * (std::f64::consts::PI * i as f64 / (n - 1) as f64).cos())
665            .map(|t| if t < 1e-15 { 0.0 } else if t > 1.0 - 1e-15 { 1.0 } else { t })
666            .collect();
667        // The seam from corner 2m to the centre, shared by rhombus m (its top
668        // row) and rhombus m-1 (its right column), sampled once.
669        let mut seam_samples: Vec<Vec<Vec3>> = Vec::with_capacity(3);
670        let centre_point = self.eval([0.0, 0.0])?;
671        for m in 0..3 {
672            let v = self.hex.corners[2 * m];
673            let mut row = Vec::with_capacity(GRID);
674            for (i, &t) in params.iter().enumerate() {
675                row.push(if i + 1 == GRID { centre_point } else { self.eval([v[0] * (1.0 - t), v[1] * (1.0 - t)])? });
676            }
677            seam_samples.push(row);
678        }
679        let mut surfaces = Vec::with_capacity(3);
680        for m in 0..3 {
681            let g = GRID;
682            let mut samples = vec![vec![Vec3::new(0.0, 0.0, 0.0); g]; g]; // [u][v]
683            for i in 0..GRID {
684                for j in 0..GRID {
685                    samples[i][j] = if j + 1 == g {
686                        seam_samples[m][i]
687                    } else if i + 1 == g {
688                        seam_samples[(m + 1) % 3][j]
689                    } else {
690                        self.eval(self.rhombus(m, params[i], params[j]))?
691                    };
692                }
693            }
694            surfaces.push(interpolate_grid(&samples, &params)?);
695        }
696        // Stamp each shared seam with one set of controls: rhombus m's right
697        // column is rhombus m+1's top row.
698        for m in 0..3 {
699            let next = (m + 1) % 3;
700            let column: Vec<Vec4> = surfaces[m].control_points[GRID - 1].clone();
701            for (i, c) in column.into_iter().enumerate() {
702                let len = surfaces[next].control_points[i].len();
703                surfaces[next].control_points[i][len - 1] = c;
704            }
705        }
706        // Vertices and seams.
707        let centre = VertexRecord { id: id(), point: centre_point };
708        let mut seams = Vec::with_capacity(3);
709        let mut seam_ids = [0u64; 3];
710        for m in 0..3 {
711            // Seam at corner 2m: rhombus (m+2)%3's right column, corner 2m -> centre.
712            let owner = (m + 2) % 3;
713            let curve = surfaces[owner].iso_curve_u(1.0).or_refuse(KernelStage::Refine, "iso_curve_u")?;
714            let [a, b] = curve.domain().or_refuse(KernelStage::Refine, "domain")?;
715            let e = id();
716            seams.push(EdgeRecord { id: e, curve, t0: a, t1: b, start_vertex_id: self.sides[2 * m].from, end_vertex_id: centre.id, degenerate: false, name: None });
717            seam_ids[m] = e;
718        }
719        let mut faces = Vec::with_capacity(3);
720        for m in 0..3 {
721            let (bottom, left) = (&self.sides[2 * m + 1], &self.sides[2 * m]);
722            let side_pcurve = |side: &Side, a: [f64; 2], b: [f64; 2]| -> Result<NurbsCurve, KernelRefusal> {
723                // Walked from a to b as s runs 0 -> 1; over the edge's range.
724                let (t0, t1) = (side.edge.t0, side.edge.t1);
725                if side.forward { uv_line(a, b, t0, t1) } else { uv_line(b, a, t0, t1)?.reversed().or_refuse(KernelStage::Refine, "reversed") }
726            };
727            let right_seam = seam_ids[(m + 1) % 3];
728            let top_seam = seam_ids[m];
729            let coedges = vec![
730                CoedgeRecord { id: id(), edge_id: bottom.edge.id, forward: bottom.forward, pcurve: side_pcurve(bottom, [0.0, 0.0], [1.0, 0.0])? },
731                CoedgeRecord { id: id(), edge_id: right_seam, forward: true, pcurve: uv_line([1.0, 0.0], [1.0, 1.0], 0.0, 1.0)? },
732                CoedgeRecord { id: id(), edge_id: top_seam, forward: false, pcurve: uv_line([0.0, 1.0], [1.0, 1.0], 0.0, 1.0)?.reversed().or_refuse(KernelStage::Refine, "reversed")? },
733                CoedgeRecord { id: id(), edge_id: left.edge.id, forward: left.forward, pcurve: side_pcurve(left, [0.0, 1.0], [0.0, 0.0])? },
734            ];
735            let surface = surfaces[m].clone();
736            let middle = surface.evaluate(0.5, 0.5).or_refuse(KernelStage::Refine, "evaluate")?;
737            let normal = surface.normal(0.5, 0.5).or_refuse(KernelStage::Refine, "normal")?;
738            if normal.dot(corner.sub(middle)) <= 0.0 {
739                return Err(KernelRefusal::internal(KernelStage::Refine, "setback_g2_sense", format!("{ENTRY}: a corner patch faces into the body")));
740            }
741            let loop_id = id();
742            faces.push(FaceRecord { id: id(), surface, same_sense: true, loops: vec![LoopRecord { id: loop_id, coedges }], name: name.map(|value| format!("{value}[{m}]")) });
743        }
744        Ok(Fitted { centre, seams, faces, surfaces })
745    }
746}
747
748/// The tensor-product cubic interpolant of `grid[u][v]` at `params` both ways.
749fn interpolate_grid(grid: &[Vec<Vec3>], params: &[f64]) -> Result<NurbsSurface, KernelRefusal> {
750    let n = params.len();
751    // Along v for each u, then along u for each v-control.
752    let mut columns: Vec<NurbsCurve> = Vec::with_capacity(n);
753    for row in grid {
754        columns.push(crate::fit::interpolate_curve(row, 3, params).or_refuse(KernelStage::Refine, "patch_fit")?);
755    }
756    let knots_v = columns[0].knots.clone();
757    let count_v = columns[0].control_points.len();
758    if count_v != n || columns.iter().any(|c| c.knots != knots_v || c.control_points.len() != n) {
759        return Err(refuse("setback_g2_fit", "the corner patch's rows were not interpolated alike".into()));
760    }
761    let mut knots_u = Vec::new();
762    let mut by_v: Vec<Vec<Vec4>> = Vec::with_capacity(count_v);
763    for j in 0..count_v {
764        let points: Vec<Vec3> = columns.iter().map(|c| c.control_points[j].point()).collect::<Result<_, _>>().or_refuse(KernelStage::Refine, "point")?;
765        let across = crate::fit::interpolate_curve(&points, 3, params).or_refuse(KernelStage::Refine, "patch_fit")?;
766        if across.control_points.len() != n {
767            return Err(refuse("setback_g2_fit", "the corner patch's columns were not interpolated alike".into()));
768        }
769        knots_u = across.knots.clone();
770        by_v.push(across.control_points.clone());
771    }
772    let net: Vec<Vec<Vec4>> = (0..n).map(|i| (0..count_v).map(|j| by_v[j][i]).collect()).collect();
773    NurbsSurface::new(3, 3, knots_u, knots_v, net).or_refuse(KernelStage::Refine, "patch_surface")
774}
775
776struct Fitted {
777    centre: VertexRecord,
778    seams: Vec<EdgeRecord>,
779    faces: Vec<FaceRecord>,
780    surfaces: Vec<NurbsSurface>,
781}
782
783/// A surface's unit normal and its normal curvature along `direction` at `(u, v)`.
784fn normal_and_bend(surface: &NurbsSurface, u: f64, v: f64, direction: Vec3) -> Result<(Vec3, f64), KernelRefusal> {
785    let d = surface.derivatives(u, v, 2).or_refuse(KernelStage::Refine, "derivatives")?;
786    let (su, sv) = (d[1][0], d[0][1]);
787    let normal = su.cross(sv).normalized().or_refuse(KernelStage::Refine, "normalized")?;
788    // The direction in (u, v): solve su a + sv b = direction (least squares).
789    let (e, f, g) = (su.dot(su), su.dot(sv), sv.dot(sv));
790    let (p, q) = (su.dot(direction), sv.dot(direction));
791    let det = e * g - f * f;
792    let (a, b) = ((p * g - f * q) / det, (e * q - f * p) / det);
793    let tangent = su.scale(a).add(sv.scale(b));
794    let second = d[2][0].scale(a * a).add(d[1][1].scale(2.0 * a * b)).add(d[0][2].scale(b * b));
795    let bend = second.dot(normal) / tangent.dot(tangent);
796    Ok((normal, bend))
797}
798
799impl Fitted {
800    /// Every point of the patch within the corner's parallelepiped: at depths
801    /// 0 to `setback` along the three edges (within a millionth of it).
802    fn contained(&self, corner: Vec3, t: [Vec3; 3], setback: f64) -> Result<(), KernelRefusal> {
803        let det = t[0].dot(t[1].cross(t[2]));
804        let slack = 1e-6 * setback;
805        let samples = 32;
806        for surface in &self.surfaces {
807            for i in 0..=samples {
808                for j in 0..=samples {
809                    let p = surface.evaluate(i as f64 / samples as f64, j as f64 / samples as f64).or_refuse(KernelStage::Refine, "evaluate")?.sub(corner);
810                    // p = Σ a_k t_k (Cramer).
811                    let a = [p.dot(t[1].cross(t[2])) / det, t[0].dot(p.cross(t[2])) / det, t[0].dot(t[1].cross(p)) / det];
812                    if a.iter().any(|&x| x < -slack || x > setback + slack) {
813                        return Err(refuse("setback_g2_reach", format!("the corner patch leaves the corner's cut-back region (depths {a:?} against 0..{setback}): this construction does not close this corner")));
814                    }
815                }
816            }
817        }
818        Ok(())
819    }
820
821    /// The fit against the exact sides and the transfinite patch, and the
822    /// joins across the sides and the seams.
823    fn check(&self, patch: &CornerPatch, result: &BrepSolid, curvature_scale: f64) -> Result<(), KernelRefusal> {
824        let mut points = Vec::new();
825        for side in &patch.sides {
826            for i in 0..=4 {
827                points.push(side.at(i as f64 / 4.0)?);
828            }
829        }
830        let size = crate::model_scale(points);
831        let mut deviation = 0.0f64;
832        let mut angle = 0.0f64;
833        let mut bend_gap = 0.0f64;
834        let samples = 24;
835        for m in 0..3 {
836            let surface = &self.surfaces[m];
837            // Inside: between the fit's samples.
838            for i in 0..2 * (GRID - 1) {
839                for j in [GRID / 3, GRID / 2, 2 * GRID / 3] {
840                    let (u, v) = ((i as f64 + 0.5) / (2 * (GRID - 1)) as f64, (j as f64 + 0.5) / (GRID - 1) as f64);
841                    let exact = patch.eval(patch.rhombus(m, u, v))?;
842                    deviation = deviation.max(surface.evaluate(u, v).or_refuse(KernelStage::Refine, "evaluate")?.sub(exact).length());
843                    let exact = patch.eval(patch.rhombus(m, v, u))?;
844                    deviation = deviation.max(surface.evaluate(v, u).or_refuse(KernelStage::Refine, "evaluate")?.sub(exact).length());
845                }
846            }
847            // Along its two sides: position, normal and the curvature across.
848            for (k, on) in [(2 * m + 1, true), (2 * m, false)] {
849                let side = &patch.sides[k];
850                let neighbour = result
851                    .shells[0]
852                    .faces
853                    .iter()
854                    .find(|f| !self.faces.iter().any(|g| g.id == f.id) && f.loops.iter().any(|l| l.coedges.iter().any(|c| c.edge_id == side.edge.id)))
855                    .ok_or_else(|| refuse("setback_g2_patch", "a side's neighbour is missing".into()))?;
856                for i in 1..samples {
857                    let s = i as f64 / samples as f64;
858                    let (u, v) = if on { (s, 0.0) } else { (0.0, 1.0 - s) };
859                    let exact = side.at(s)?;
860                    let here = surface.evaluate(u, v).or_refuse(KernelStage::Refine, "evaluate")?;
861                    deviation = deviation.max(here.sub(exact).length());
862                    let [_, b1, _] = side.jet(s)?;
863                    let foot = crate::project_point_to_surface(&neighbour.surface, exact).or_refuse(KernelStage::Refine, "project")?;
864                    let dn = neighbour.surface.derivatives(foot.u, foot.v, 1).or_refuse(KernelStage::Refine, "derivatives")?;
865                    let theirs = dn[1][0].cross(dn[0][1]).normalized().or_refuse(KernelStage::Refine, "normalized")?;
866                    let (ours, _) = normal_and_bend(surface, u, v, b1)?;
867                    let across = ours.cross(b1).normalized().or_refuse(KernelStage::Refine, "normalized")?;
868                    let (ours, bend_ours) = normal_and_bend(surface, u, v, across)?;
869                    let sign = if ours.dot(theirs) < 0.0 { -1.0 } else { 1.0 };
870                    angle = angle.max(ours.cross(theirs).length().atan2(ours.dot(theirs).abs()));
871                    let bend_theirs = match side.kind {
872                        Kind::Face { .. } => 0.0,
873                        Kind::Strip { .. } => {
874                            let (_, b) = normal_and_bend(&neighbour.surface, foot.u, foot.v, across)?;
875                            sign * b
876                        }
877                    };
878                    bend_gap = bend_gap.max((bend_ours - bend_theirs).abs());
879                }
880            }
881            // Across its right seam, against the next rhombus's top row.
882            let next = &self.surfaces[(m + 1) % 3];
883            for i in 1..samples {
884                let s = i as f64 / samples as f64;
885                let (a, _) = normal_and_bend(surface, 1.0, s, Vec3::new(1.0, 0.0, 0.0))?;
886                let (b, _) = normal_and_bend(next, s, 1.0, Vec3::new(1.0, 0.0, 0.0))?;
887                angle = angle.max(a.cross(b).length().atan2(a.dot(b)));
888                let along = surface.derivatives(1.0, s, 1).or_refuse(KernelStage::Refine, "derivatives")?[0][1];
889                let across = a.cross(along).normalized().or_refuse(KernelStage::Refine, "normalized")?;
890                let (_, ka) = normal_and_bend(surface, 1.0, s, across)?;
891                let (_, kb) = normal_and_bend(next, s, 1.0, across)?;
892                bend_gap = bend_gap.max((ka - kb).abs());
893            }
894        }
895        if std::env::var("BREP_DEBUG_SETBACK_G2").is_ok() {
896            eprintln!("setback g2 corner: fit deviation {deviation:.3e} (size {size:.3e}), worst normal angle {angle:.3e}, worst curvature gap {bend_gap:.3e} (scale {curvature_scale:.3e})");
897        }
898        if !(deviation <= BOUNDARY_BAR * size) {
899            return Err(refuse("setback_g2_fit", format!("the corner patch's fit strays {deviation:.3e} from its sides and its construction (bar {:.3e})", BOUNDARY_BAR * size)));
900        }
901        if !(angle <= ANGLE_BAR) {
902            return Err(refuse("setback_g2_tangent", format!("the corner patch meets its neighbours {angle:.3e} rad out of their tangent planes (bar {ANGLE_BAR:.1e})")));
903        }
904        if !(bend_gap <= CURVATURE_BAR * curvature_scale) {
905            return Err(refuse("setback_g2_curvature", format!("the corner patch's curvature jumps by {bend_gap:.3e} across a side or seam (bar {:.3e})", CURVATURE_BAR * curvature_scale)));
906        }
907        let regular = self.surfaces.iter().all(|s| crate::certify_regular(s).is_ok());
908        if !regular {
909            return Err(refuse("setback_g2_fold", "the corner patch folds".into()));
910        }
911        Ok(())
912    }
913}