Skip to main content

brep_boolean/healing/
face_merge.rs

1use crate::analytic_surface::circumcenter;
2pub use crate::mass_properties::{face_area, face_volume_contribution, parameter_space_area};
3pub use crate::topology::{BrepSolid, CoedgeRecord, EdgeRecord, FaceRecord, LoopRecord};
4pub use crate::{
5    build_pcurve_on_surface, make_line, make_plane, make_revolution, KnotVector, NurbsCurve,
6    NurbsSurface, Vec3, Vec4,
7};
8use crate::{KernelRefusal, KernelStage, OrRefuse, RefusalClass};
9pub use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
10
11fn controls_match(first: Vec4, second: Vec4, tolerance: f64) -> bool {
12    (first.x - second.x).abs() <= tolerance
13        && (first.y - second.y).abs() <= tolerance
14        && (first.z - second.z).abs() <= tolerance
15        && (first.w - second.w).abs() <= tolerance
16}
17
18/// Whether two faces ride the SAME carrier patch — identical degrees, knots
19/// and control points inside `tolerance`. `pub` because the direct-edit
20/// cap lane asks the same question for the same reason this module does: when
21/// two faces share one carrier their coedges' pcurves are interchangeable, so
22/// loops can move between them with nothing refit.
23pub fn same_surface(first: &NurbsSurface, second: &NurbsSurface, tolerance: f64) -> bool {
24    first.degree_u == second.degree_u
25        && first.degree_v == second.degree_v
26        && first.knots_u.len() == second.knots_u.len()
27        && first.knots_v.len() == second.knots_v.len()
28        && first.control_points.len() == second.control_points.len()
29        && first
30            .control_points
31            .iter()
32            .zip(&second.control_points)
33            .all(|(a, b)| {
34                a.len() == b.len()
35                    && a.iter()
36                        .zip(b)
37                        .all(|(a, b)| controls_match(*a, *b, tolerance))
38            })
39        && first
40            .knots_u
41            .iter()
42            .zip(&second.knots_u)
43            .all(|(a, b)| (a - b).abs() <= tolerance)
44        && first
45            .knots_v
46            .iter()
47            .zip(&second.knots_v)
48            .all(|(a, b)| (a - b).abs() <= tolerance)
49}
50
51fn surface_domains(surface: &NurbsSurface) -> Result<([f64; 2], [f64; 2]), KernelRefusal> {
52    Ok((
53        KnotVector::new(surface.knots_u.clone(), surface.degree_u)
54            .or_refuse(KernelStage::Sew, "new")?
55            .domain(),
56        KnotVector::new(surface.knots_v.clone(), surface.degree_v)
57            .or_refuse(KernelStage::Sew, "new")?
58            .domain(),
59    ))
60}
61
62pub fn outward_normal(face: &FaceRecord) -> Result<Vec3, KernelRefusal> {
63    let (u, v) = surface_domains(&face.surface)?;
64    let normal = face
65        .surface
66        .normal((u[0] + u[1]) / 2.0, (v[0] + v[1]) / 2.0)
67        .or_refuse(KernelStage::Sew, "healing.face_merge")?;
68    Ok(if face.same_sense {
69        normal
70    } else {
71        normal.scale(-1.0)
72    })
73}
74
75fn planar_support(
76    face: &FaceRecord,
77    tolerance: f64,
78) -> Result<Option<(Vec3, Vec3)>, KernelRefusal> {
79    let (u, v) = surface_domains(&face.surface)?;
80    let midpoint_u = (u[0] + u[1]) / 2.0;
81    let midpoint_v = (v[0] + v[1]) / 2.0;
82    let origin = face
83        .surface
84        .evaluate(midpoint_u, midpoint_v)
85        .or_refuse(KernelStage::Sew, "evaluate")?;
86    // No normal at the domain centre (a cusp, pinch or fold line through the
87    // carrier): no plane (`BREP_SINGULAR_CENTRE_NOT_PLANAR`, default off).
88    let normal = match face.surface.normal(midpoint_u, midpoint_v) {
89        Ok(normal) => normal,
90        Err(error) => {
91            if crate::imprint::support::singular_centre_not_planar(|| format!("face_merge: face {}", face.id), &error) {
92                return Ok(None);
93            }
94            return Err(error).or_refuse(KernelStage::Sew, "normal");
95        }
96    };
97    let controls = face
98        .surface
99        .control_points
100        .iter()
101        .flatten()
102        .map(|control| control.point())
103        .collect::<Result<Vec<_>, _>>()
104        .or_refuse(KernelStage::Sew, "healing.face_merge")?;
105    let scale = controls
106        .iter()
107        .map(|point| point.sub(origin).length())
108        .fold(1.0f64, f64::max);
109    let plane_tolerance = (tolerance * 100.0).max(1e-7) * scale;
110    if controls
111        .iter()
112        .all(|point| point.sub(origin).dot(normal).abs() <= plane_tolerance)
113    {
114        Ok(Some((origin, normal)))
115    } else {
116        Ok(None)
117    }
118}
119
120fn coplanar_with_same_outward_normal(
121    first: &FaceRecord,
122    second: &FaceRecord,
123    tolerance: f64,
124) -> Result<bool, KernelRefusal> {
125    let Some((first_origin, first_geometric_normal)) = planar_support(first, tolerance)? else {
126        return Ok(false);
127    };
128    let Some((_, second_geometric_normal)) = planar_support(second, tolerance)? else {
129        return Ok(false);
130    };
131    if first_geometric_normal.dot(second_geometric_normal).abs() < 1.0 - 1e-7 {
132        return Ok(false);
133    }
134    let first_normal = outward_normal(first)?;
135    let second_normal = outward_normal(second)?;
136    if first_normal.dot(second_normal) < 1.0 - 1e-7 {
137        return Ok(false);
138    }
139    let (second_u, second_v) = surface_domains(&second.surface)?;
140    // The merged face is emitted carrying `first`'s plane, so every point of
141    // `second` has to lie ON that plane, not merely near it.  The band is the
142    // caller's coplanarity tolerance, floored where a caller asks for less
143    // than its own fitting noise and CAPPED at the assembler weld: past that
144    // the assembler holds a point and this plane apart, so the merged face is
145    // one nothing exact downstream can consume — the STEP importer's phase
146    // 1.75 ear-clips precisely such a face back into planar triangles.
147    //
148    // The cap replaces a `* (1.0 + first_origin.length())` factor that
149    // charged the band by how far the plane's origin sits from the WORLD
150    // origin — where the part happens to have been modelled, not a property
151    // of its geometry.  On a 190-unit part 50 units out it opened a 1.9e-7
152    // request to a 9.7e-4 band, wide enough to merge adjacent facets of a
153    // tessellated curve into one "plane" whose own corners sat 5.4e-4 off it.
154    let plane_tolerance = (tolerance * 100.0)
155        .max(1e-6)
156        .min(crate::tolerance::assembler_weld(tolerance));
157    for u in second_u {
158        for v in second_v {
159            if second
160                .surface
161                .evaluate(u, v)
162                .or_refuse(KernelStage::Sew, "evaluate")?
163                .sub(first_origin)
164                .dot(first_normal)
165                .abs()
166                > plane_tolerance
167            {
168                return Ok(false);
169            }
170        }
171    }
172    Ok(true)
173}
174
175/// Circular-arc support of a curve, detected by sampling: circumcenter of
176/// three spread samples, validated against all samples for constant radius
177/// and planarity. Returns (center, unit plane normal, radius).
178fn arc_circle_support(
179    curve: &NurbsCurve,
180    tolerance: f64,
181) -> Result<Option<(Vec3, Vec3, f64)>, KernelRefusal> {
182    let [t0, t1] = curve.domain().or_refuse(KernelStage::Sew, "domain")?;
183    let samples = (0..=8)
184        .map(|index| curve.evaluate(t0 + (t1 - t0) * index as f64 / 8.0))
185        .collect::<Result<Vec<_>, _>>()
186        .or_refuse(KernelStage::Sew, "healing.face_merge")?;
187    // A full-circle carrier evaluates identical endpoints, so the sample
188    // triple must avoid (start, end); fall back across spreads until one is
189    // non-degenerate.
190    let Some(center) = circumcenter(samples[0], samples[2], samples[5])
191        .or_else(|| circumcenter(samples[0], samples[4], samples[8]))
192        .or_else(|| circumcenter(samples[1], samples[4], samples[7]))
193    else {
194        return Ok(None);
195    };
196    let radius = samples[0].sub(center).length();
197    if radius <= tolerance {
198        return Ok(None);
199    }
200    let normal = match samples[2]
201        .sub(samples[0])
202        .cross(samples[5].sub(samples[0]))
203        .normalized()
204        .or_else(|_| {
205            samples[4]
206                .sub(samples[0])
207                .cross(samples[8].sub(samples[0]))
208                .normalized()
209        }) {
210        Ok(normal) => normal,
211        Err(_) => return Ok(None),
212    };
213    let band = tolerance.max(1e-9 * radius);
214    for sample in &samples {
215        let delta = sample.sub(center);
216        if (delta.length() - radius).abs() > band || delta.dot(normal).abs() > band {
217            if std::env::var("BREP_DEBUG_MERGE").is_ok() {
218                eprintln!(
219                    "    arc reject: radius={radius} dr={} dplane={} band={band}",
220                    (delta.length() - radius).abs(),
221                    delta.dot(normal).abs()
222                );
223            }
224            return Ok(None);
225        }
226    }
227    Ok(Some((center, normal, radius)))
228}
229
230/// Merge lanes a caller opts into beyond what the solid-wide merge does.
231///
232/// The solid-wide merge runs after every boolean and keeps every face it does
233/// not have to join: the default (all off) is exactly its behaviour. A caller
234/// joining faces the USER selected together (Push Face on the halves of an
235/// imported bore) asks for more: those faces are one region of one carrier by
236/// the user's own reading, and a face the merge leaves split is a face the
237/// edit cannot move.
238#[derive(Clone, Copy, Debug, Default)]
239pub struct MergeLanes<'a> {
240    /// Admit a CONE (a ruled revolution whose two boundary circles differ in
241    /// radius) wherever the cylinder lanes run. Only the full-turn lane builds
242    /// its carrier from the radius at each end; the partial-turn lane stays
243    /// cylinder-only.
244    pub cones: bool,
245    /// Let the full-turn lane seam a ring closed by two half-turn patches on
246    /// a SHARED axial edge (the halves of a bore written as two faces). The
247    /// solid-wide merge keeps such pairs apart (see `merge_cylinder_full_turn`).
248    pub shared_seam_ring: bool,
249    /// Among equally ranked seam candidates, prefer an axial edge ending at one
250    /// of these vertices: the seam a coaxial neighbour of the same selection
251    /// already kept, so the rim the two faces share meets both seams at ONE
252    /// vertex and closes into one circle.
253    pub seam_vertices: Option<&'a HashSet<u64>>,
254    /// The re-seam lane ([`rejoin_seam_split_pairs`]): join only two pieces
255    /// of ONE cylinder or frustum carrier whose only shared edges are the
256    /// carrier's own seam, on a carrier seamed in their union's angular gap,
257    /// and decline every other pair.
258    pub reseam: bool,
259}
260
261pub struct CylinderSupport {
262    origin: Vec3,
263    axis: Vec3,
264    /// The radius at `origin`.
265    radius: f64,
266    /// dρ per unit of axial travel along `axis`: zero for a cylinder, the
267    /// cone's slope for a cone (admitted only under `MergeLanes::cones`).
268    slope: f64,
269    /// +1 when the face's outward normal points radially away from the
270    /// axis, -1 when it points inward.
271    outward_radial_sign: f64,
272}
273
274impl CylinderSupport {
275    /// The carrier's radius `axial` along `axis` from `origin`.
276    fn radius_at(&self, axial: f64) -> f64 {
277        self.radius + self.slope * axial
278    }
279}
280
281/// Detect a ruled cylinder patch: quadratic circular arc in one parameter
282/// direction, linear in the other, both boundary arcs sharing an axis and
283/// radius. Covers extruded arcs, revolved axis-parallel lines, and
284/// primitive cylinder walls regardless of parameterization. With
285/// `allow_cone`, two coaxial boundary arcs of DIFFERENT radii are a cone
286/// patch, admitted when the patch's midpoint lies on the cone they span.
287pub fn ruled_cylinder_support(
288    face: &FaceRecord,
289    tolerance: f64,
290    allow_cone: bool,
291    allow_apex: bool,
292) -> Result<Option<CylinderSupport>, KernelRefusal> {
293    let surface = &face.surface;
294    let debug = std::env::var("BREP_DEBUG_MERGE").is_ok();
295    let (arc_first, columns) = match (surface.degree_u, surface.degree_v) {
296        (2, 1) => (true, surface.control_points[0].len()),
297        (1, 2) => (false, surface.control_points.len()),
298        _ => {
299            if debug {
300                eprintln!(
301                    "  support face {}: degrees ({},{}) not ruled-arc",
302                    face.id, surface.degree_u, surface.degree_v
303                );
304            }
305            return Ok(None);
306        }
307    };
308    // Boolean splits can insert linear-direction knots, so a ruled carrier
309    // may hold more than two columns; the outermost columns still bound the
310    // patch and interior straightness is enforced by the final area check.
311    let last = columns - 1;
312    let iso_curve = |side: usize| -> Result<NurbsCurve, KernelRefusal> {
313        let controls = if arc_first {
314            surface
315                .control_points
316                .iter()
317                .map(|row| row[side])
318                .collect::<Vec<_>>()
319        } else {
320            surface.control_points[side].clone()
321        };
322        let knots = if arc_first {
323            surface.knots_u.clone()
324        } else {
325            surface.knots_v.clone()
326        };
327        NurbsCurve::new(2, knots, controls).or_refuse(KernelStage::Sew, "NurbsCurve::new")
328    };
329    let scale = surface
330        .control_points
331        .iter()
332        .flatten()
333        .map(|point| point.point().map(|p| p.length()).unwrap_or(0.0))
334        .fold(1.0f64, f64::max);
335    let circle_tolerance = (tolerance * 100.0).max(1e-7 * scale);
336    // An apex iso is one point: a circle of radius zero about it. Its plane is
337    // the far circle's, so the checks below read that normal against the axis.
338    let apex_of = |curve: &NurbsCurve| -> Result<Option<Vec3>, KernelRefusal> {
339        if !allow_apex {
340            return Ok(None);
341        }
342        let [t0, t1] = curve.domain().or_refuse(KernelStage::Sew, "domain")?;
343        let first = curve.evaluate(t0).or_refuse(KernelStage::Sew, "evaluate")?;
344        for index in 1..=8 {
345            let point = curve.evaluate(t0 + (t1 - t0) * index as f64 / 8.0).or_refuse(KernelStage::Sew, "evaluate")?;
346            if point.sub(first).length() > circle_tolerance {
347                return Ok(None);
348            }
349        }
350        Ok(Some(first))
351    };
352    let (iso0, iso1) = (iso_curve(0)?, iso_curve(last)?);
353    let (apex0, apex1) = (apex_of(&iso0)?, apex_of(&iso1)?);
354    let far_circle = match (apex0, apex1) {
355        (Some(_), None) => arc_circle_support(&iso1, circle_tolerance)?,
356        (None, Some(_)) => arc_circle_support(&iso0, circle_tolerance)?,
357        _ => None,
358    };
359    let apex_circle = |apex: Vec3| far_circle.map(|(_, normal, _)| (apex, normal, 0.0));
360    let circle0 = match apex0 {
361        Some(apex) => apex_circle(apex),
362        None => arc_circle_support(&iso0, circle_tolerance)?,
363    };
364    let circle1 = match apex1 {
365        Some(apex) => apex_circle(apex),
366        None => arc_circle_support(&iso1, circle_tolerance)?,
367    };
368    let Some((center0, normal0, radius0)) = circle0
369    else {
370        if debug {
371            eprintln!("  support face {}: first iso not circular", face.id);
372        }
373        return Ok(None);
374    };
375    let Some((center1, normal1, radius1)) = circle1
376    else {
377        if debug {
378            eprintln!("  support face {}: last iso not circular", face.id);
379        }
380        return Ok(None);
381    };
382    let is_cone = (radius0 - radius1).abs() > circle_tolerance;
383    if is_cone && !allow_cone {
384        if debug {
385            eprintln!(
386                "  support face {}: radii differ {} vs {}",
387                face.id, radius0, radius1
388            );
389        }
390        return Ok(None);
391    }
392    let axial = center1.sub(center0);
393    if axial.length() <= circle_tolerance {
394        if debug {
395            eprintln!("  support face {}: zero axial extent", face.id);
396        }
397        return Ok(None);
398    }
399    let axis = axial
400        .normalized()
401        .or_refuse(KernelStage::Sew, "normalized")?;
402    if axis.dot(normal0).abs() < 1.0 - 1e-7 || axis.dot(normal1).abs() < 1.0 - 1e-7 {
403        if debug {
404            eprintln!(
405                "  support face {}: arc planes not perpendicular to axis",
406                face.id
407            );
408        }
409        return Ok(None);
410    }
411    let outward = outward_normal(face)?;
412    let (u, v) = surface_domains(surface)?;
413    let midpoint = surface
414        .evaluate((u[0] + u[1]) / 2.0, (v[0] + v[1]) / 2.0)
415        .or_refuse(KernelStage::Sew, "healing.face_merge")?;
416    let foot = center0.add(axis.scale(midpoint.sub(center0).dot(axis)));
417    let radial = match midpoint.sub(foot).normalized() {
418        Ok(radial) => radial,
419        Err(_) => return Ok(None),
420    };
421    let slope = if is_cone {
422        (radius1 - radius0) / axial.length()
423    } else {
424        0.0
425    };
426    if is_cone {
427        // A twisted ruling between the two circles is a hyperboloid, not a
428        // cone: the patch's own midpoint must sit on the cone they span.
429        let axial_mid = midpoint.sub(center0).dot(axis);
430        let off = (midpoint.sub(foot).length() - (radius0 + slope * axial_mid)).abs();
431        if off > circle_tolerance {
432            if debug {
433                eprintln!("  support face {}: midpoint {off:.3e} off the spanned cone", face.id);
434            }
435            return Ok(None);
436        }
437    }
438    let alignment = outward.dot(radial);
439    // A cone's normal leans off the radial by its half-angle.
440    if alignment.abs() < 0.9 / (1.0 + slope * slope).sqrt() {
441        if debug {
442            eprintln!(
443                "  support face {}: outward not radial ({alignment})",
444                face.id
445            );
446        }
447        return Ok(None);
448    }
449    Ok(Some(CylinderSupport {
450        origin: center0,
451        axis,
452        radius: radius0,
453        slope,
454        outward_radial_sign: alignment.signum(),
455    }))
456}
457
458fn cosurface_cylinder_pair(
459    first: &FaceRecord,
460    second: &FaceRecord,
461    tolerance: f64,
462    lanes: MergeLanes<'_>,
463) -> Result<Option<CylinderSupport>, KernelRefusal> {
464    let debug = std::env::var("BREP_DEBUG_MERGE").is_ok();
465    let Some(support_a) = ruled_cylinder_support(first, tolerance, lanes.cones, false)? else {
466        if debug {
467            eprintln!(
468                "merge {}x{}: first not a ruled cylinder",
469                first.id, second.id
470            );
471        }
472        return Ok(None);
473    };
474    let Some(support_b) = ruled_cylinder_support(second, tolerance, lanes.cones, false)? else {
475        if debug {
476            eprintln!(
477                "merge {}x{}: second not a ruled cylinder",
478                first.id, second.id
479            );
480        }
481        return Ok(None);
482    };
483    let scale = 1.0f64
484        .max(support_a.origin.length())
485        .max(support_b.origin.length())
486        .max(support_a.radius);
487    let band = (tolerance * 100.0).max(1e-7 * scale);
488    // Both radii read at A's origin and one radius-length further along A's
489    // axis: equal for two cylinders of one radius, and for two patches of
490    // one cone (whose slopes agree once B's axis is turned to A's).
491    let radius_mismatch = {
492        let station = support_a.radius.max(1.0);
493        let b_axial = |axial_on_a: f64| {
494            support_a
495                .origin
496                .add(support_a.axis.scale(axial_on_a))
497                .sub(support_b.origin)
498                .dot(support_b.axis)
499        };
500        (support_a.radius - support_b.radius_at(b_axial(0.0)))
501            .abs()
502            .max((support_a.radius_at(station) - support_b.radius_at(b_axial(station))).abs())
503    };
504    if support_a.axis.dot(support_b.axis).abs() < 1.0 - 1e-7
505        || radius_mismatch > band
506        || support_a.outward_radial_sign != support_b.outward_radial_sign
507    {
508        if debug {
509            eprintln!(
510                "merge {}x{}: axis/radius/sign mismatch dot={} dr={} signs=({},{})",
511                first.id,
512                second.id,
513                support_a.axis.dot(support_b.axis),
514                radius_mismatch,
515                support_a.outward_radial_sign,
516                support_b.outward_radial_sign
517            );
518        }
519        return Ok(None);
520    }
521    let offset = support_b.origin.sub(support_a.origin);
522    let perpendicular = offset.sub(support_a.axis.scale(offset.dot(support_a.axis)));
523    if perpendicular.length() > band {
524        if debug {
525            eprintln!(
526                "merge {}x{}: axes offset {}",
527                first.id,
528                second.id,
529                perpendicular.length()
530            );
531        }
532        return Ok(None);
533    }
534    if debug {
535        eprintln!(
536            "merge {}x{}: MATCH r={} axis=({:.4},{:.4},{:.4})",
537            first.id,
538            second.id,
539            support_a.radius,
540            support_a.axis.x,
541            support_a.axis.y,
542            support_a.axis.z
543        );
544    }
545    Ok(Some(support_a))
546}
547
548struct ExtrusionSupport {
549    /// Profile iso curve at the sweep start, in its actual 3D position.
550    base: NurbsCurve,
551    /// Unit sweep direction (from column 0 toward the last column).
552    direction: Vec3,
553    /// Axial interval the patch occupies along `direction`.
554    interval: [f64; 2],
555}
556
557/// Detect a linear sweep of an arbitrary profile curve: one parameter
558/// direction is degree 1 with every profile control translated by the SAME
559/// vector (weights unchanged), and the profile lies in a plane perpendicular
560/// to the sweep. This is exact at the control-point level, so it also merges
561/// swept faces whose profile is only approximately circular.
562fn ruled_extrusion_support(
563    face: &FaceRecord,
564    tolerance: f64,
565) -> Result<Option<ExtrusionSupport>, KernelRefusal> {
566    let surface = &face.surface;
567    // Planar faces are the coplanar path's business; a plane recognized as
568    // an "extrusion of a line" here could merge across a knife edge.
569    if planar_support(face, tolerance)?.is_some() {
570        return Ok(None);
571    }
572    let profile_first = if surface.degree_v == 1 && surface.degree_u >= 1 {
573        true
574    } else if surface.degree_u == 1 && surface.degree_v >= 1 {
575        false
576    } else {
577        return Ok(None);
578    };
579    let (profile_count, linear_count) = if profile_first {
580        (
581            surface.control_points.len(),
582            surface.control_points[0].len(),
583        )
584    } else {
585        (
586            surface.control_points[0].len(),
587            surface.control_points.len(),
588        )
589    };
590    if linear_count < 2 {
591        return Ok(None);
592    }
593    let control = |profile_index: usize, linear_index: usize| -> Vec4 {
594        if profile_first {
595            surface.control_points[profile_index][linear_index]
596        } else {
597            surface.control_points[linear_index][profile_index]
598        }
599    };
600    let scale = surface
601        .control_points
602        .iter()
603        .flatten()
604        .map(|point| point.point().map(|p| p.length()).unwrap_or(0.0))
605        .fold(1.0f64, f64::max);
606    let band = (tolerance * 100.0).max(1e-7 * scale);
607    let mut translation: Option<Vec3> = None;
608    for profile_index in 0..profile_count {
609        let first = control(profile_index, 0);
610        let last = control(profile_index, linear_count - 1);
611        if (first.w - last.w).abs() > 1e-9 * first.w.abs().max(1.0) {
612            return Ok(None);
613        }
614        let step = last
615            .point()
616            .or_refuse(KernelStage::Sew, "point")?
617            .sub(first.point().or_refuse(KernelStage::Sew, "point")?);
618        if let Some(reference) = translation {
619            if step.sub(reference).length() > band {
620                return Ok(None);
621            }
622        } else {
623            translation = Some(step);
624        }
625        let start = first.point().or_refuse(KernelStage::Sew, "point")?;
626        for linear_index in 1..linear_count - 1 {
627            let middle = control(profile_index, linear_index);
628            if (middle.w - first.w).abs() > 1e-9 * first.w.abs().max(1.0) {
629                return Ok(None);
630            }
631            let offset = middle
632                .point()
633                .or_refuse(KernelStage::Sew, "point")?
634                .sub(start);
635            let along = offset.dot(step) / step.dot(step).max(1e-30);
636            if offset.sub(step.scale(along)).length() > band
637                || !(-1e-9..=1.0 + 1e-9).contains(&along)
638            {
639                return Ok(None);
640            }
641        }
642    }
643    let translation = translation.ok_or_else(|| {
644        KernelRefusal::internal(
645            KernelStage::Sew,
646            "face_merge",
647            "extrusion support: empty net",
648        )
649    })?;
650    if translation.length() <= band {
651        return Ok(None);
652    }
653    let direction = translation
654        .normalized()
655        .or_refuse(KernelStage::Sew, "normalized")?;
656    let base_controls = (0..profile_count).map(|index| control(index, 0)).collect();
657    let base_knots = if profile_first {
658        surface.knots_u.clone()
659    } else {
660        surface.knots_v.clone()
661    };
662    let base_degree = if profile_first {
663        surface.degree_u
664    } else {
665        surface.degree_v
666    };
667    let base = NurbsCurve::new(base_degree, base_knots, base_controls)
668        .or_refuse(KernelStage::Sew, "new")?;
669    let [t0, t1] = base.domain().or_refuse(KernelStage::Sew, "domain")?;
670    let mut axial = [f64::INFINITY, f64::NEG_INFINITY];
671    for index in 0..=8 {
672        let z = base
673            .evaluate(t0 + (t1 - t0) * index as f64 / 8.0)
674            .or_refuse(KernelStage::Sew, "evaluate")?
675            .dot(direction);
676        axial[0] = axial[0].min(z);
677        axial[1] = axial[1].max(z);
678    }
679    if axial[1] - axial[0] > band {
680        // Slanted profiles sweep skewed slabs whose axial union is not an
681        // interval; keep the merge to perpendicular profiles.
682        return Ok(None);
683    }
684    let start = (axial[0] + axial[1]) / 2.0;
685    Ok(Some(ExtrusionSupport {
686        base,
687        direction,
688        interval: [start, start + translation.length()],
689    }))
690}
691
692fn perpendicular_profile(curve: &NurbsCurve, direction: Vec3) -> Result<NurbsCurve, KernelRefusal> {
693    let controls = curve
694        .control_points
695        .iter()
696        .map(|control| {
697            let point = control.point().or_refuse(KernelStage::Sew, "point")?;
698            Ok(Vec4::from_point(
699                point.sub(direction.scale(point.dot(direction))),
700                control.w,
701            ))
702        })
703        .collect::<Result<Vec<_>, KernelRefusal>>()?;
704    NurbsCurve::new(curve.degree, curve.knots.clone(), controls)
705        .or_refuse(KernelStage::Sew, "NurbsCurve::new")
706}
707
708fn curves_coincide(
709    first: &NurbsCurve,
710    second: &NurbsCurve,
711    band: f64,
712) -> Result<bool, KernelRefusal> {
713    for (from, to) in [(first, second), (second, first)] {
714        let [t0, t1] = from.domain().or_refuse(KernelStage::Sew, "domain")?;
715        for index in 0..=8 {
716            let point = from
717                .evaluate(t0 + (t1 - t0) * index as f64 / 8.0)
718                .or_refuse(KernelStage::Sew, "evaluate")?;
719            let projection = match crate::project_point_to_curve(to, point) {
720                Ok(projection) => projection,
721                Err(_) => return Ok(false),
722            };
723            if projection.distance > band {
724                return Ok(false);
725            }
726        }
727    }
728    Ok(true)
729}
730
731/// Matching linear sweeps: parallel directions, identical perpendicular
732/// profile, adjacent (or touching) axial intervals.
733fn coextrusion_pair(
734    older: &FaceRecord,
735    newer: &FaceRecord,
736    tolerance: f64,
737) -> Result<Option<(ExtrusionSupport, [f64; 2])>, KernelRefusal> {
738    let debug = std::env::var("BREP_DEBUG_MERGE").is_ok();
739    let Some(support_a) = ruled_extrusion_support(older, tolerance)? else {
740        return Ok(None);
741    };
742    let Some(support_b) = ruled_extrusion_support(newer, tolerance)? else {
743        return Ok(None);
744    };
745    let alignment = support_a.direction.dot(support_b.direction);
746    if alignment.abs() < 1.0 - 1e-9 {
747        if debug {
748            eprintln!(
749                "coextrusion {}x{}: directions differ (dot {alignment})",
750                older.id, newer.id
751            );
752        }
753        return Ok(None);
754    }
755    let scale = 1.0f64
756        .max(support_a.interval[1].abs())
757        .max(support_b.interval[1].abs());
758    let band = (tolerance * 100.0).max(1e-7 * scale);
759    let profile_a = perpendicular_profile(&support_a.base, support_a.direction)?;
760    let profile_b = perpendicular_profile(&support_b.base, support_a.direction)?;
761    if !curves_coincide(&profile_a, &profile_b, band)? {
762        if debug {
763            eprintln!("coextrusion {}x{}: profiles differ", older.id, newer.id);
764        }
765        return Ok(None);
766    }
767    // Express B's interval along A's direction regardless of B's own sweep
768    // orientation: anti-parallel sweeps negate the axial coordinate.
769    let interval_b = if alignment < 0.0 {
770        [-support_b.interval[1], -support_b.interval[0]]
771    } else {
772        support_b.interval
773    };
774    if interval_b[0] > support_a.interval[1] + band || support_a.interval[0] > interval_b[1] + band
775    {
776        if debug {
777            eprintln!(
778                "coextrusion {}x{}: axial gap {:?} vs {:?}",
779                older.id, newer.id, support_a.interval, interval_b
780            );
781        }
782        return Ok(None);
783    }
784    let certified_on = crate::switch!("BREP_COEXTRUSION_CERTIFIED_APART", true);
785    let certified_check = crate::switch!("BREP_COEXTRUSION_CERTIFIED_APART_CHECK", false);
786    if (certified_on || certified_check) && profile_a.degree > 1 && profile_b.degree > 1 {
787        // A finite complete profile-crossing cover excludes a shared arc.
788        // The sampling band can call two shallowly crossing profiles equal;
789        // merging them would replace distinct wall patches by one carrier.
790        let crossings = match (older.surface.linear_extrusion(), newer.surface.linear_extrusion()) {
791            (Some(a), Some(b)) => crate::analytic_surface::certified_parallel_extrusion_sections(a, b, tolerance),
792            _ => None,
793        };
794        if let Some(crossings) = crossings {
795            if certified_check {
796                eprintln!("COEXTRUSION_CERTIFIED_APART faces={}x{} crossings={} applied={certified_on}",
797                    older.id, newer.id, crossings.len());
798            }
799            if certified_on { return Ok(None); }
800        }
801    }
802    let union = [
803        support_a.interval[0].min(interval_b[0]),
804        support_a.interval[1].max(interval_b[1]),
805    ];
806    Ok(Some((support_a, union)))
807}
808
809fn trimmed_curve(curve: &NurbsCurve, t0: f64, t1: f64) -> Result<NurbsCurve, KernelRefusal> {
810    crate::curve_helpers::trimmed_curve(curve, t0, t1, "face_merge trimmed")
811}
812
813/// The axial extent of `curve` about `support`'s axis, read off its control
814/// polygon: the axial coordinate is an affine functional of position and
815/// the weights are positive, so the curve's own extent lies inside its
816/// control points'. Nine samples per edge missed a sphere-cut rim's peak by
817/// 0.14 (BadBoolean, master's gate of 2026-10-13); the carrier built that
818/// short had the projector fold the rim onto its top boundary, and the body
819/// read 0.14 low in volume with the validator none the wiser.
820fn axial_hull(curve: &NurbsCurve, support: &CylinderSupport) -> [f64; 2] {
821    let origin_axial = support.origin.dot(support.axis);
822    let mut range = [f64::INFINITY, f64::NEG_INFINITY];
823    for point in &curve.control_points {
824        let axial = Vec3::new(point.x / point.w, point.y / point.w, point.z / point.w)
825            .dot(support.axis)
826            - origin_axial;
827        range[0] = range[0].min(axial);
828        range[1] = range[1].max(axial);
829    }
830    range
831}
832
833/// An affine plane chart, proven from its complete bilinear control net.
834/// Rational or warped charts need the general projection path instead.
835struct AffinePlaneChart {
836    origin: Vec3,
837    du: Vec3,
838    dv: Vec3,
839    u0: f64,
840    v0: f64,
841}
842
843fn affine_plane_chart(surface: &NurbsSurface) -> Option<AffinePlaneChart> {
844    if surface.degree_u != 1 || surface.degree_v != 1
845        || surface.control_points.len() != 2
846        || surface.control_points.iter().any(|row| row.len() != 2)
847        || surface.knots_u.len() != 4 || surface.knots_v.len() != 4
848    { return None; }
849    let ku = &surface.knots_u;
850    let kv = &surface.knots_v;
851    if ku[0] != ku[1] || ku[2] != ku[3] || kv[0] != kv[1] || kv[2] != kv[3]
852        || ku[2] <= ku[1] || kv[2] <= kv[1]
853    { return None; }
854    let weight = surface.control_points[0][0].w;
855    if !weight.is_finite() || weight.abs() <= 1e-300
856        || surface.control_points.iter().flatten().any(|point| point.w != weight)
857    { return None; }
858    let p00 = surface.control_points[0][0].point().ok()?;
859    let p10 = surface.control_points[1][0].point().ok()?;
860    let p01 = surface.control_points[0][1].point().ok()?;
861    let p11 = surface.control_points[1][1].point().ok()?;
862    let u = p10.sub(p00);
863    let v = p01.sub(p00);
864    let scale = u.length().max(v.length()).max(1.0);
865    if p11.sub(p10).sub(v).length() > 1e-12 * scale { return None; }
866    let du = u.scale(1.0 / (ku[2] - ku[1]));
867    let dv = v.scale(1.0 / (kv[2] - kv[1]));
868    let determinant = du.dot(du) * dv.dot(dv) - du.dot(dv).powi(2);
869    if !determinant.is_finite() || determinant <= 1e-12 * du.dot(du) * dv.dot(dv) {
870        return None;
871    }
872    Some(AffinePlaneChart { origin: p00, du, dv, u0: ku[1], v0: kv[1] })
873}
874
875/// Transfer the existing trimmed locus, rather than replacing it with the
876/// shared edge's potentially displaced fitted curve. Affine reparameterization
877/// preserves every rational weight, knot and degree, including controls outside
878/// the surface's finite patch.
879pub fn transfer_affine_planar_pcurve(
880    source: &NurbsSurface,
881    target: &NurbsSurface,
882    curve: &NurbsCurve,
883    tolerance: f64,
884) -> Option<NurbsCurve> {
885    let source = affine_plane_chart(source)?;
886    let target = affine_plane_chart(target)?;
887    let uu = target.du.dot(target.du);
888    let uv = target.du.dot(target.dv);
889    let vv = target.dv.dot(target.dv);
890    let determinant = uu * vv - uv * uv;
891    let mut transferred = curve.clone();
892    for control in &mut transferred.control_points {
893        if !control.w.is_finite() || control.w.abs() <= 1e-300 { return None; }
894        let point = source.origin
895            .add(source.du.scale(control.x / control.w - source.u0))
896            .add(source.dv.scale(control.y / control.w - source.v0));
897        let relative = point.sub(target.origin);
898        let a = relative.dot(target.du);
899        let b = relative.dot(target.dv);
900        let u = (a * vv - b * uv) / determinant;
901        let v = (b * uu - a * uv) / determinant;
902        let reconstructed = target.origin.add(target.du.scale(u)).add(target.dv.scale(v));
903        if !u.is_finite() || !v.is_finite()
904            || reconstructed.sub(point).length() > tolerance.max(1e-12)
905        { return None; }
906        control.x = (target.u0 + u) * control.w;
907        control.y = (target.v0 + v) * control.w;
908        control.z = 0.0;
909    }
910    Some(transferred)
911}
912
913fn transfer_planar_loops(
914    target: &NurbsSurface,
915    loops: &[LoopRecord],
916    older: &FaceRecord,
917    newer: &FaceRecord,
918    tolerance: f64,
919) -> Option<Vec<LoopRecord>> {
920    let mut transferred = loops.to_vec();
921    for loop_record in &mut transferred {
922        for coedge in &mut loop_record.coedges {
923            let source = [older, newer].into_iter().find(|face| {
924                face.loops.iter().flat_map(|lp| &lp.coedges)
925                    .any(|original| original.id == coedge.id && original.edge_id == coedge.edge_id)
926            })?;
927            coedge.pcurve = transfer_affine_planar_pcurve(
928                &source.surface, target, &coedge.pcurve, tolerance,
929            )?;
930        }
931    }
932    Some(transferred)
933}
934
935fn reproject_loops(
936    surface: &NurbsSurface,
937    loops: Vec<LoopRecord>,
938    edges: &HashMap<u64, &EdgeRecord>,
939) -> Result<Vec<LoopRecord>, KernelRefusal> {
940    let mut projected_loops = Vec::new();
941    for loop_record in loops {
942        // The loop keeps its id: the body's ids are already unique, and a
943        // fresh `index + 1` repeats another face's loop (a recarried cone
944        // apex face took loop id 1, which the topology arena refuses).
945        let id = loop_record.id;
946        let mut projected = Vec::new();
947        for mut coedge in loop_record.coedges {
948            let edge = edges[&coedge.edge_id];
949            let mut curve = trimmed_curve(&edge.curve, edge.t0, edge.t1)?;
950            if !coedge.forward {
951                curve = curve.reversed().or_refuse(KernelStage::Sew, "reversed")?;
952            }
953            coedge.pcurve = build_pcurve_on_surface(surface, &curve)
954                .or_refuse(KernelStage::Sew, "build_pcurve_on_surface")?;
955            projected.push(coedge);
956        }
957        projected_loops.push(LoopRecord { id, coedges: projected });
958    }
959    Ok(projected_loops)
960}
961
962/// Put the one degenerate `apex` coedge back into the loop that passes through
963/// its vertex: a parameter line at the pole from the arriving trim's longitude
964/// to the leaving trim's. Each trim's pole end takes the longitude of its next
965/// control point, since projection cannot read a longitude at the pole. False
966/// when no single loop passes through the apex.
967fn stitch_cone_apex(
968    surface: &NurbsSurface,
969    loops: &mut [LoopRecord],
970    apex: &CoedgeRecord,
971    edges: &HashMap<u64, &EdgeRecord>,
972) -> Result<bool, KernelRefusal> {
973    let vertex = edges[&apex.edge_id].start_vertex_id;
974    let mut sites = Vec::new();
975    for (loop_index, loop_record) in loops.iter().enumerate() {
976        for (index, coedge) in loop_record.coedges.iter().enumerate() {
977            let next = &loop_record.coedges[(index + 1) % loop_record.coedges.len()];
978            if traversal_vertices(edges[&coedge.edge_id], coedge).1 == vertex
979                && traversal_vertices(edges[&next.edge_id], next).0 == vertex
980            {
981                sites.push((loop_index, index));
982            }
983        }
984    }
985    let [(loop_index, index)] = sites[..] else {
986        return Ok(false);
987    };
988    let coedges = &mut loops[loop_index].coedges;
989    let next_index = (index + 1) % coedges.len();
990    let (u_domain, _) = surface_domains(surface)?;
991    let [_, t1] = coedges[index].pcurve.domain().or_refuse(KernelStage::Sew, "domain")?;
992    let pole = coedges[index].pcurve.evaluate(t1).or_refuse(KernelStage::Sew, "evaluate")?;
993    let apex_point = surface.evaluate(pole.x, pole.y).or_refuse(KernelStage::Sew, "evaluate")?;
994    let across = surface
995        .evaluate((u_domain[0] + u_domain[1]) / 2.0, pole.y)
996        .or_refuse(KernelStage::Sew, "evaluate")?;
997    let angle_is_u = across.sub(apex_point).length() <= 1e-7 * (1.0 + apex_point.length());
998    let snapped = |pcurve: &mut NurbsCurve, at_end: bool| -> Result<Vec3, KernelRefusal> {
999        let count = pcurve.control_points.len();
1000        if count < 2 {
1001            return Err(KernelRefusal::internal(KernelStage::Sew, "face_merge", "cone apex: trim has one control point"));
1002        }
1003        let (slot, inner) = if at_end { (count - 1, count - 2) } else { (0, 1) };
1004        let from = pcurve.control_points[inner].point().or_refuse(KernelStage::Sew, "point")?;
1005        let weight = pcurve.control_points[slot].w;
1006        let mut point = pcurve.control_points[slot].point().or_refuse(KernelStage::Sew, "point")?;
1007        if angle_is_u {
1008            point.x = from.x;
1009        } else {
1010            point.y = from.y;
1011        }
1012        pcurve.control_points[slot] = Vec4::from_point(point, weight);
1013        Ok(point)
1014    };
1015    let arriving = snapped(&mut coedges[index].pcurve, true)?;
1016    let leaving = snapped(&mut coedges[next_index].pcurve, false)?;
1017    let mut bridge = apex.clone();
1018    bridge.pcurve = make_line(arriving, leaving).or_refuse(KernelStage::Sew, "healing.face_merge")?;
1019    coedges.insert(index + 1, bridge);
1020    Ok(true)
1021}
1022
1023fn traversal_vertices(edge: &EdgeRecord, coedge: &CoedgeRecord) -> (u64, u64) {
1024    if coedge.forward {
1025        (edge.start_vertex_id, edge.end_vertex_id)
1026    } else {
1027        (edge.end_vertex_id, edge.start_vertex_id)
1028    }
1029}
1030
1031/// The parameter space every leftover coedge's pcurve lives in, when the merged
1032/// faces share ONE carrier. Only then can a merge read a loop's parameter-space
1033/// continuity; a reprojecting lane walks before its pcurves share a space.
1034pub struct SharedParameterSpace<'a> {
1035    pub surface: &'a NurbsSurface,
1036    /// The radius that made two fitted endpoints one vertex.
1037    pub weld: f64,
1038}
1039
1040impl SharedParameterSpace<'_> {
1041    fn coincide(&self, first: Vec3, second: Vec3) -> bool {
1042        let band = crate::classification::surface_uv_band(self.surface, first.x, first.y, self.weld);
1043        (first.x - second.x).abs() <= band && (first.y - second.y).abs() <= band
1044    }
1045}
1046
1047pub fn shared_trim_certificate_enabled() -> bool {
1048    switch!(live "BREP_FACE_MERGE_TRIM_CERT", true)
1049}
1050
1051/// `BREP_FACE_MERGE_RESEAM` (default on, `0` off): after a feature's boolean,
1052/// two pieces of ONE cylinder or frustum carrier whose only shared edge is
1053/// the carrier's own seam (their union is a partial turn that straddles the
1054/// seam, so in the carrier's chart it is two regions a period apart) are
1055/// joined on a revolution carrier seamed in the union's angular gap
1056/// ([`rejoin_seam_split_pairs`]). The boolean keeps its body as it was when a
1057/// later feature names something the join would change (see the boolean's
1058/// `seam_rejoin_later_references`). A cone with an apex, a sphere and a
1059/// torus are not read here. Off by default: a later offset shell of a joined
1060/// wall under a rim fillet closes on fewer turns of the cylinder than it
1061/// does on the split wall (the offset shell's own sensitivity to where the
1062/// rim blend's carrier starts; it already fails some turns of the split one).
1063pub fn seam_reseam_enabled() -> bool {
1064    switch!(live "BREP_FACE_MERGE_RESEAM", true)
1065}
1066
1067/// Prove closure of the complete boundary isocurves. Clamping makes these
1068/// the first/last control rows; their common positive rational basis bounds
1069/// the entire difference by the largest paired control-point displacement.
1070fn closed_control_boundary(surface: &NurbsSurface, along_u: bool, weld: f64) -> bool {
1071    let (degree, knots, lo, hi) = if along_u {
1072        let Ok([lo,hi]) = surface.domain_u() else { return false; };
1073        (surface.degree_u, &surface.knots_u, lo, hi)
1074    } else {
1075        let Ok([lo,hi]) = surface.domain_v() else { return false; };
1076        (surface.degree_v, &surface.knots_v, lo, hi)
1077    };
1078    if knots.len() < 2*(degree+1)
1079        || !knots[..=degree].iter().all(|k| *k == lo)
1080        || !knots[knots.len()-degree-1..].iter().all(|k| *k == hi)
1081    { return false; }
1082    let agree = |a: Vec4, b: Vec4| {
1083        if a.w <= 0.0 || !a.w.is_finite() || a.w != b.w { return false; }
1084        let (Ok(a), Ok(b)) = (a.point(), b.point()) else { return false; };
1085        a.sub(b).length() <= weld
1086    };
1087    if along_u {
1088        let (Some(first), Some(last)) = (surface.control_points.first(), surface.control_points.last()) else { return false; };
1089        first.len() == last.len() && first.iter().zip(last).all(|(a,b)| agree(*a,*b))
1090    } else {
1091        surface.control_points.iter().all(|row| match (row.first(), row.last()) {
1092            (Some(a), Some(b)) => agree(*a,*b),
1093            _ => false,
1094        })
1095    }
1096}
1097
1098/// Linear pcurves on affine boundary isocurves compose to polylines.
1099/// Matched positive-weight polygon controls therefore bound the COMPLETE
1100/// paired images by their largest 3D displacement, even when the other UV
1101/// coordinate differs by roundoff. No UV band or station sample is used.
1102fn affine_boundary_trim_pair(
1103    surface: &NurbsSurface,
1104    along_u: bool,
1105    first_at_low: bool,
1106    first: &NurbsCurve,
1107    reverse: &NurbsCurve,
1108    weld: f64,
1109) -> bool {
1110    let (degree, knots, bounds) = if along_u {
1111        (surface.degree_v, &surface.knots_v, surface.domain_v())
1112    } else {
1113        (surface.degree_u, &surface.knots_u, surface.domain_u())
1114    };
1115    let Ok([lo,hi]) = bounds else { return false; };
1116    if degree != 1 || knots.as_slice() != [lo,lo,hi,hi] || hi <= lo { return false; }
1117    let ends = if along_u {
1118        let (Some(a),Some(b)) = (surface.control_points.first(),surface.control_points.last()) else { return false; };
1119        if a.len()!=2 || b.len()!=2 { return false; }
1120        [a[0],a[1],b[0],b[1]]
1121    } else {
1122        if surface.control_points.len()!=2 { return false; }
1123        let (a,b) = (&surface.control_points[0],&surface.control_points[1]);
1124        let (Some(a0),Some(a1),Some(b0),Some(b1)) = (a.first(),a.last(),b.first(),b.last()) else { return false; };
1125        [*a0,*b0,*a1,*b1]
1126    };
1127    if ends[0].w<=0.0 || ends[0].w!=ends[1].w || ends[2].w<=0.0 || ends[2].w!=ends[3].w {
1128        return false;
1129    }
1130    let (Ok(a0),Ok(a1),Ok(b0),Ok(b1)) = (ends[0].point(),ends[1].point(),ends[2].point(),ends[3].point()) else { return false; };
1131    let (a0,a1,b0,b1) = if first_at_low { (a0,a1,b0,b1) } else { (b0,b1,a0,a1) };
1132    let image = |p: &Vec4, a: Vec3, b: Vec3| {
1133        let t = if along_u { p.y/p.w } else { p.x/p.w };
1134        a.add(b.sub(a).scale((t-lo)/(hi-lo)))
1135    };
1136    first.control_points.iter().zip(&reverse.control_points).all(|(a,b)| {
1137        let distance = image(a,a0,a1).sub(image(b,b0,b1)).length();
1138        distance.is_finite() && distance <= weld
1139    })
1140}
1141
1142/// Prove that a retained shared pair is a periodic seam over its whole
1143/// trim. Positive common rational bases match the other parameter, or
1144/// affine boundary images bound matched linear polygons. Every periodic
1145/// coordinate control lies on opposite closed domain sides.
1146/// This qualifies retention after the existing coincidence check fails. It
1147/// does not change cancellation policy or widen a UV band. Work is linear
1148/// in the existing control arrays, with no sampling or refinement search.
1149pub fn periodic_shared_trim(
1150    space: &SharedParameterSpace,
1151    first: &CoedgeRecord,
1152    second: &CoedgeRecord,
1153) -> bool {
1154    if first.forward == second.forward { return false; }
1155    let Ok(reverse) = second.pcurve.reversed() else { return false; };
1156    let curve = &first.pcurve;
1157    if curve.degree != reverse.degree || curve.control_points.len() != reverse.control_points.len()
1158        || curve.control_points.is_empty()
1159    { return false; }
1160    let polygon = |c: &NurbsCurve| {
1161        c.degree == 1 && c.knots.len() == c.control_points.len()+2
1162            && c.knots[0] == c.knots[1]
1163            && c.knots[c.knots.len()-1] == c.knots[c.knots.len()-2]
1164            && c.knots[1..c.knots.len()-1].windows(2).all(|k| k[1] > k[0])
1165    };
1166    let polygon = polygon(curve) && polygon(&reverse);
1167    if (!polygon && curve.knots != reverse.knots)
1168        || !curve.control_points.iter().zip(&reverse.control_points).all(|(a,b)| {
1169            [a,b].iter().all(|p| p.w > 0.0 && p.w.is_finite()
1170                && (p.x/p.w).is_finite() && (p.y/p.w).is_finite())
1171                && (polygon || a.w == b.w)
1172        })
1173    { return false; }
1174    let coordinate = |p: &Vec4, u: bool| if u { p.x/p.w } else { p.y/p.w };
1175    let same_coordinate = |u: bool| curve.control_points.iter().zip(&reverse.control_points)
1176        .all(|(a,b)| if polygon { coordinate(a,u) == coordinate(b,u) }
1177            else if u { a.x == b.x } else { a.y == b.y });
1178    for u in [true,false] {
1179        let bounds = if u { space.surface.domain_u() } else { space.surface.domain_v() };
1180        let Ok([lo,hi]) = bounds else { continue; };
1181        let other_bounds = if u { space.surface.domain_v() } else { space.surface.domain_u() };
1182        let Ok([other_lo,other_hi]) = other_bounds else { continue; };
1183        // The closed-boundary control bound applies on its active domain.
1184        // Positive pcurve hulls must stay inside it; extrapolated traces
1185        // need a different proof and keep their existing face partition.
1186        if !curve.control_points.iter().chain(&reverse.control_points)
1187            .all(|p| coordinate(p,!u) >= other_lo && coordinate(p,!u) <= other_hi)
1188        { continue; }
1189        let opposite = [(lo,hi),(hi,lo)].iter().any(|(a,b)|
1190            curve.control_points.iter().all(|p| coordinate(p,u) == *a)
1191                && reverse.control_points.iter().all(|p| coordinate(p,u) == *b));
1192        if opposite && closed_control_boundary(space.surface, u, space.weld)
1193            && (same_coordinate(!u) || (polygon && affine_boundary_trim_pair(
1194                space.surface, u, coordinate(&curve.control_points[0],u)==lo,
1195                curve, &reverse, space.weld)))
1196        {
1197            return true;
1198        }
1199    }
1200    false
1201}
1202
1203/// A coedge's pcurve at its start, middle and end. The pcurve runs in the
1204/// coedge's own direction, so its domain start is where the traversal starts.
1205fn pcurve_stations(coedge: &CoedgeRecord) -> Option<[Vec3; 3]> {
1206    let [t0, t1] = coedge.pcurve.domain().ok()?;
1207    Some([
1208        coedge.pcurve.evaluate(t0).ok()?,
1209        coedge.pcurve.evaluate((t0 + t1) / 2.0).ok()?,
1210        coedge.pcurve.evaluate(t1).ok()?,
1211    ])
1212}
1213
1214/// SLIT DISSOLUTION. An edge whose two leftover uses run along the SAME
1215/// parameter-space segment, one each way, separates nothing: its ring on the
1216/// other side was the shared edge the merge just cancelled (a flanged hole's
1217/// annulus, slit to the ring it bridged to). Kept, the walk can only return
1218/// along it and close a loop of zero area. Two uses a PERIOD apart are a seam
1219/// the region wraps across, and stay.
1220fn dissolve_slits(
1221    remaining: &mut Vec<CoedgeRecord>,
1222    edges: &HashMap<u64, &EdgeRecord>,
1223    space: &SharedParameterSpace,
1224) {
1225    let mut uses = HashMap::<u64, Vec<usize>>::default();
1226    for (index, coedge) in remaining.iter().enumerate() {
1227        uses.entry(coedge.edge_id).or_default().push(index);
1228    }
1229    let slits = uses
1230        .iter()
1231        .filter(|(edge_id, indices)| {
1232            if indices.len() != 2 || edges[*edge_id].degenerate {
1233                return false;
1234            }
1235            let (first, second) = (&remaining[indices[0]], &remaining[indices[1]]);
1236            if first.forward == second.forward {
1237                return false;
1238            }
1239            let (Some(first), Some(second)) = (pcurve_stations(first), pcurve_stations(second)) else {
1240                return false;
1241            };
1242            space.coincide(first[0], second[2])
1243                && space.coincide(first[1], second[1])
1244                && space.coincide(first[2], second[0])
1245        })
1246        .map(|(edge_id, _)| *edge_id)
1247        .collect::<HashSet<_>>();
1248    remaining.retain(|coedge| !slits.contains(&coedge.edge_id));
1249}
1250
1251/// Stitch a merged face's leftover coedges into loops, or `None` when the
1252/// stitching is not determined.
1253///
1254/// A loop can pass one VERTEX twice — a bridge's foot on the ring it joins —
1255/// so reaching the start vertex does not by itself close the loop, and a vertex
1256/// with several unused coedges leaving it does not name the next one. There the
1257/// walk follows the loop's PARAMETER-SPACE continuity when the coedges share a
1258/// carrier (`space`): the successor starts where the current pcurve ends, and a
1259/// seam's two images of one vertex a period apart are two different places.
1260/// Without a shared space, or with no single successor, the merge is refused
1261/// and the faces stay as they were assembled.
1262fn walk_cycles(
1263    mut remaining: Vec<CoedgeRecord>,
1264    edges: &HashMap<u64, &EdgeRecord>,
1265    space: Option<&SharedParameterSpace>,
1266) -> Option<Vec<LoopRecord>> {
1267    let maximum_cycle_length = remaining.len();
1268    let mut loops = Vec::new();
1269    while !remaining.is_empty() {
1270        let first = remaining.remove(0);
1271        let (start, mut end) = traversal_vertices(edges[&first.edge_id], &first);
1272        let mut cycle = vec![first];
1273        loop {
1274            let leaving = remaining
1275                .iter()
1276                .enumerate()
1277                .filter_map(|(index, coedge)| {
1278                    (traversal_vertices(edges[&coedge.edge_id], coedge).0 == end).then_some(index)
1279                })
1280                .collect::<Vec<_>>();
1281            let closes = end == start;
1282            let successor = match (leaving.as_slice(), closes) {
1283                ([], true) => None,
1284                ([only], false) => Some(*only),
1285                ([], false) => return None,
1286                _ => {
1287                    let space = space?;
1288                    let here = pcurve_stations(cycle.last()?)?[2];
1289                    let closing = closes && space.coincide(here, pcurve_stations(&cycle[0])?[0]);
1290                    let mut continuing = Vec::new();
1291                    for index in leaving {
1292                        if space.coincide(here, pcurve_stations(&remaining[index])?[0]) {
1293                            continuing.push(index);
1294                        }
1295                    }
1296                    match (continuing.as_slice(), closing) {
1297                        ([], true) => None,
1298                        ([only], false) => Some(*only),
1299                        _ => return None,
1300                    }
1301                }
1302            };
1303            let Some(index) = successor else {
1304                break;
1305            };
1306            let next = remaining.remove(index);
1307            end = traversal_vertices(edges[&next.edge_id], &next).1;
1308            cycle.push(next);
1309            if cycle.len() > maximum_cycle_length {
1310                return None;
1311            }
1312        }
1313        // A cycle that traverses every one of its edges both ways encloses
1314        // nothing, however its parameter-space image reads.
1315        let mut counts = HashMap::<u64, usize>::default();
1316        for coedge in &cycle {
1317            *counts.entry(coedge.edge_id).or_default() += 1;
1318        }
1319        if counts.values().all(|count| *count == 2) {
1320            return None;
1321        }
1322        loops.push(LoopRecord {
1323            id: loops.len() as u64 + 1,
1324            coedges: cycle,
1325        });
1326    }
1327    Some(loops)
1328}
1329
1330/// Whether two faces ride ONE carrier — the same geometric surface, oriented
1331/// the same way out of the material — by any of the four readings this module
1332/// merges on: bit-identical patches, coplanar planes with the same outward
1333/// normal, cosurface cylinder patches, and coextruded profiles.
1334///
1335/// `pub` because the direct-edit rejoin asks the same question for the
1336/// same reason: a survivor face on the far side of a deleted band can only
1337/// take the near side's loops when the two are one carrier. It asks GEOMETRIC
1338/// cosurface rather than [`same_surface`] alone, because a mirrored twin is
1339/// the same surface reparametrized — reflected control points, flipped
1340/// `same_sense` — and bit-identity reads that as two.
1341pub fn faces_are_cosurface(
1342    first: &FaceRecord,
1343    second: &FaceRecord,
1344    tolerance: f64,
1345) -> Result<bool, KernelRefusal> {
1346    if first.same_sense == second.same_sense
1347        && same_surface(&first.surface, &second.surface, tolerance)
1348    {
1349        return Ok(true);
1350    }
1351    if coplanar_with_same_outward_normal(first, second, tolerance)? {
1352        return Ok(true);
1353    }
1354    if cosurface_cylinder_pair(first, second, tolerance, MergeLanes::default())?.is_some() {
1355        return Ok(true);
1356    }
1357    Ok(coextrusion_pair(first, second, tolerance)?.is_some())
1358}
1359
1360/// Degree-one clamped trims follow their control polygon regardless of knot
1361/// spacing. For higher degrees, equal positive rational bases make the
1362/// difference of the two affine images a convex combination of control-point
1363/// differences. Bound the whole
1364/// shared trim, rather than relying on cancellation of its area integral.
1365fn opposed_planar_trims_agree(
1366    older: &FaceRecord,
1367    first: &CoedgeRecord,
1368    newer: &FaceRecord,
1369    second: &CoedgeRecord,
1370    tolerance: f64,
1371) -> bool {
1372    let Ok(reverse) = second.pcurve.reversed() else {
1373        return false;
1374    };
1375    let curve = &first.pcurve;
1376    if curve.degree != reverse.degree || curve.control_points.len() != reverse.control_points.len()
1377    {
1378        return false;
1379    }
1380    let linear_polygon = |c: &NurbsCurve| {
1381        c.degree == 1
1382            && c.knots.len() == c.control_points.len() + 2
1383            && c.knots[0] == c.knots[1]
1384            && c.knots[c.knots.len() - 1] == c.knots[c.knots.len() - 2]
1385            && c.knots[1..c.knots.len() - 1]
1386                .windows(2)
1387                .all(|k| k[1] > k[0])
1388    };
1389    let polygon = linear_polygon(curve) && linear_polygon(&reverse);
1390    if !polygon && curve.knots != reverse.knots {
1391        return false;
1392    }
1393    curve
1394        .control_points
1395        .iter()
1396        .zip(&reverse.control_points)
1397        .all(|(a, b)| {
1398            if !a.w.is_finite()
1399                || !b.w.is_finite()
1400                || a.w <= 0.0
1401                || b.w <= 0.0
1402                || (!polygon && a.w != b.w)
1403            {
1404                return false;
1405            }
1406            let (Ok(a), Ok(b)) = (a.point(), b.point()) else {
1407                return false;
1408            };
1409            let (Ok(a), Ok(b)) = (
1410                older.surface.evaluate_extended(a.x, a.y),
1411                newer.surface.evaluate_extended(b.x, b.y),
1412            ) else {
1413                return false;
1414            };
1415            a.sub(b).length() <= tolerance
1416        })
1417}
1418
1419/// Like [`decline!`], but leaves a labelled lane instead of the whole pair
1420/// merge, so a later lane can read the same pair again.
1421macro_rules! fall_through {
1422    ($older:expr, $newer:expr, $label:lifetime) => {{
1423        if std::env::var("BREP_DEBUG_MERGE").is_ok() {
1424            eprintln!(
1425                "merge {}x{}: lane left at face_merge.rs:{}",
1426                $older.id,
1427                $newer.id,
1428                line!()
1429            );
1430        }
1431        break $label;
1432    }};
1433}
1434
1435/// Trace a declined pair merge under `BREP_DEBUG_MERGE` with the source line
1436/// that declined it, then return `Ok(None)`. A pair whose carriers MATCH can
1437/// still be declined a dozen lines later (shared-edge census, cycle walk,
1438/// area check); without the line the trace reads "MATCH" and then nothing,
1439/// which is how the E13 cosurface report (2026-10-13) hid its cause.
1440macro_rules! decline {
1441    ($older:expr, $newer:expr) => {{
1442        if std::env::var("BREP_DEBUG_MERGE").is_ok() {
1443            eprintln!(
1444                "merge {}x{}: declined at face_merge.rs:{}",
1445                $older.id,
1446                $newer.id,
1447                line!()
1448            );
1449        }
1450        return Ok(None);
1451    }};
1452}
1453
1454pub fn try_merge_pair(
1455    older: &FaceRecord,
1456    newer: &FaceRecord,
1457    edges: &HashMap<u64, &EdgeRecord>,
1458    tolerance: f64,
1459    same_carrier_area_tolerance_ratio: f64,
1460) -> Result<Option<FaceRecord>, KernelRefusal> {
1461    try_merge_pair_lanes(
1462        older,
1463        newer,
1464        edges,
1465        tolerance,
1466        same_carrier_area_tolerance_ratio,
1467        MergeLanes::default(),
1468    )
1469}
1470
1471/// [`try_merge_pair`] with the opt-in [`MergeLanes`].
1472pub fn try_merge_pair_lanes(
1473    older: &FaceRecord,
1474    newer: &FaceRecord,
1475    edges: &HashMap<u64, &EdgeRecord>,
1476    tolerance: f64,
1477    same_carrier_area_tolerance_ratio: f64,
1478    lanes: MergeLanes<'_>,
1479) -> Result<Option<FaceRecord>, KernelRefusal> {
1480    let mut same_carrier = older.same_sense == newer.same_sense
1481        && same_surface(&older.surface, &newer.surface, tolerance);
1482    // Oppositely oriented planar patches can form a folded, zero-thickness
1483    // overlap along a multi-edge seam. Cancelling that seam preserves the
1484    // signed region, not the sum of the two unsigned face areas.
1485    let cancel_planar_fold = older.same_sense != newer.same_sense
1486        && older.loops.len() == 1
1487        && newer.loops.len() == 1
1488        && same_surface(&older.surface, &newer.surface, tolerance)
1489        && older
1490            .surface
1491            .is_affine()
1492            .or_refuse(KernelStage::Sew, "is_affine")?
1493        && newer
1494            .surface
1495            .is_affine()
1496            .or_refuse(KernelStage::Sew, "is_affine")?;
1497    let coplanar_planar =
1498        !same_carrier && coplanar_with_same_outward_normal(older, newer, tolerance)?;
1499    let mut cosurface_cylinder = if !same_carrier && !coplanar_planar {
1500        cosurface_cylinder_pair(older, newer, tolerance, lanes)?
1501    } else {
1502        None
1503    };
1504    let cosurface_extrusion = if !same_carrier && !coplanar_planar && cosurface_cylinder.is_none() {
1505        coextrusion_pair(older, newer, tolerance)?
1506    } else {
1507        None
1508    };
1509    let older_coedges = older
1510        .loops
1511        .iter()
1512        .flat_map(|loop_record| &loop_record.coedges)
1513        .collect::<Vec<_>>();
1514    let newer_coedges = newer
1515        .loops
1516        .iter()
1517        .flat_map(|loop_record| &loop_record.coedges)
1518        .collect::<Vec<_>>();
1519    let mut space = (same_carrier || cancel_planar_fold).then(|| SharedParameterSpace {
1520        surface: &older.surface,
1521        weld: crate::tolerance::assembler_weld(tolerance),
1522    });
1523    let mut shared_older = HashSet::default();
1524    let mut shared_newer = HashSet::default();
1525    let mut shared_edges = HashSet::default();
1526    // Same-carrier pairs a period apart that `periodic_shared_trim` proves
1527    // are the carrier's seam (older coedge, newer coedge, edge), and whether
1528    // any noncoincident pair went unproved: the re-seam route reads them.
1529    let mut seam_pairs: Vec<(u64, u64, u64)> = Vec::new();
1530    let mut unproved_seam = false;
1531    // Shared edges the merged face keeps, both ways: on ONE carrier, a pair
1532    // whose two images lie a period apart is the carrier's seam (the
1533    // dissolve_slits doctrine), and the union wraps across it. Cancelling it
1534    // tore the seam out of a shelled cylinder's wall against its own strip
1535    // (the E13 report, 2026-10-13) and the area check declined the pair. A
1536    // pair that touches ONLY across the seam still declines below: its union
1537    // is two regions a period apart in this carrier's chart, one face record
1538    // holding two discs (the slab-corner mirror union read V−E+F = 1 so).
1539    for first in &older_coedges {
1540        if edges[&first.edge_id].degenerate {
1541            continue;
1542        }
1543        for second in &newer_coedges {
1544            if first.edge_id != second.edge_id {
1545                continue;
1546            }
1547            if first.forward == second.forward {
1548                decline!(older, newer);
1549            }
1550            if cancel_planar_fold
1551                && !opposed_planar_trims_agree(older, first, newer, second, tolerance)
1552            {
1553                decline!(older, newer);
1554            }
1555            if same_carrier && !cancel_planar_fold {
1556                if let (Some(space), Some(here), Some(there)) =
1557                    (&space, pcurve_stations(first), pcurve_stations(second))
1558                {
1559                    let retraced = space.coincide(here[0], there[2])
1560                        && space.coincide(here[1], there[1])
1561                        && space.coincide(here[2], there[0]);
1562                    if !retraced {
1563                        // A noncoincident pair may be retained only as a
1564                        // proved periodic seam. An interior partition stays
1565                        // between faces; retaining it here creates a slit.
1566                        let proved = periodic_shared_trim(space, first, second);
1567                        if shared_trim_certificate_enabled() && !proved
1568                        { decline!(older, newer); }
1569                        if proved {
1570                            seam_pairs.push((first.id, second.id, first.edge_id));
1571                        } else {
1572                            unproved_seam = true;
1573                        }
1574                        continue;
1575                    }
1576                } else if shared_trim_certificate_enabled() {
1577                    decline!(older, newer);
1578                }
1579            }
1580            shared_older.insert(first.id);
1581            shared_newer.insert(second.id);
1582            shared_edges.insert(first.edge_id);
1583        }
1584    }
1585    // The pieces touch ONLY across the carrier's seam: their union is one
1586    // region of the cylinder (or cone) that this chart cuts in two. Read the
1587    // pair as a cosurface cylinder pair instead, the seam uses cancelled as
1588    // shared edges, so the partial-turn lane seams a new carrier in the
1589    // union's angular gap. A union that wraps the whole turn finds no gap
1590    // there and declines as before.
1591    let mut reseamed = false;
1592    if shared_older.is_empty()
1593        && !seam_pairs.is_empty()
1594        && !unproved_seam
1595        && same_carrier
1596        && !cancel_planar_fold
1597        && lanes.reseam
1598    {
1599        let reseam_lanes = MergeLanes { cones: true, ..lanes };
1600        if let Some(support) = cosurface_cylinder_pair(older, newer, tolerance, reseam_lanes)? {
1601            for (first, second, edge) in &seam_pairs {
1602                shared_older.insert(*first);
1603                shared_newer.insert(*second);
1604                shared_edges.insert(*edge);
1605            }
1606            same_carrier = false;
1607            space = None;
1608            cosurface_cylinder = Some(support);
1609            reseamed = true;
1610        }
1611    }
1612    if lanes.reseam && !reseamed {
1613        decline!(older, newer);
1614    }
1615    if shared_older.is_empty() || shared_older.len() != shared_newer.len() {
1616        decline!(older, newer);
1617    }
1618    if cancel_planar_fold && shared_older.len() < 2 {
1619        decline!(older, newer);
1620    }
1621    if !same_carrier
1622        && !cancel_planar_fold
1623        && !coplanar_planar
1624        && cosurface_cylinder.is_none()
1625        && cosurface_extrusion.is_none()
1626    {
1627        decline!(older, newer);
1628    }
1629    let mut remaining = older_coedges
1630        .into_iter()
1631        .filter(|coedge| {
1632            !shared_older.contains(&coedge.id)
1633                && !(coplanar_planar && edges[&coedge.edge_id].degenerate)
1634        })
1635        .chain(newer_coedges.into_iter().filter(|coedge| {
1636            !shared_newer.contains(&coedge.id)
1637                && !(coplanar_planar && edges[&coedge.edge_id].degenerate)
1638        }))
1639        .cloned()
1640        .collect::<Vec<_>>();
1641    if cancel_planar_fold {
1642        // The opposite fold shares this affine chart too. A retraced slit
1643        // contributes no signed boundary, but three coincident samples do
1644        // not prove that: opposite bows can match there and enclose slivers.
1645        // Use the whole-curve control bound before discarding either use.
1646        let mut uses = HashMap::<u64, Vec<&CoedgeRecord>>::default();
1647        for coedge in &remaining {
1648            uses.entry(coedge.edge_id).or_default().push(coedge);
1649        }
1650        let mut slits = HashSet::default();
1651        for (id, uses) in uses {
1652            if uses.len() == 2
1653                && !edges[&id].degenerate
1654                && uses[0].forward != uses[1].forward
1655                && opposed_planar_trims_agree(older, uses[0], older, uses[1], tolerance)
1656            {
1657                slits.insert(id);
1658            }
1659        }
1660        remaining.retain(|coedge| !slits.contains(&coedge.edge_id));
1661    } else if let Some(space) = &space {
1662        dissolve_slits(&mut remaining, edges, space);
1663    }
1664    let Some(mut loops) = walk_cycles(remaining, edges, space.as_ref()) else {
1665        // Cancelling the shared edges of a cosurface cylinder pair whose
1666        // union wraps the full turn can strand one face's seam strip at a
1667        // fork the 3D walk cannot resolve (the E13 report, 2026-10-13); the
1668        // full-turn lane walks in the merged carrier's own parameter space.
1669        if let Some(support) = &cosurface_cylinder {
1670            if let Some(merged) =
1671                merge_cylinder_full_turn(older, newer, edges, tolerance, support, &shared_edges, lanes)?
1672            {
1673                return Ok(Some(merged));
1674            }
1675        }
1676        decline!(older, newer);
1677    };
1678    if loops.iter().any(|loop_record| {
1679        loop_record
1680            .coedges
1681            .iter()
1682            .all(|coedge| edges[&coedge.edge_id].degenerate)
1683    }) {
1684        decline!(older, newer);
1685    }
1686    if loops.is_empty() {
1687        decline!(older, newer);
1688    }
1689    loops.sort_by(|first, second| {
1690        let area = |loop_record: &LoopRecord| {
1691            parameter_space_area(&FaceRecord {
1692                id: older.id,
1693                surface: older.surface.clone(),
1694                same_sense: older.same_sense,
1695                loops: vec![loop_record.clone()],
1696                name: None,
1697            })
1698            .map(f64::abs)
1699        };
1700        match (area(first), area(second)) {
1701            (Ok(a), Ok(b)) => b.total_cmp(&a),
1702            _ => std::cmp::Ordering::Equal,
1703        }
1704    });
1705    if same_carrier || cancel_planar_fold {
1706        if cancel_planar_fold && loops.len() != 1 {
1707            decline!(older, newer);
1708        }
1709        let expected = parameter_space_area(older)
1710            .or_refuse(KernelStage::Sew, "parameter_space_area")?
1711            + parameter_space_area(newer).or_refuse(KernelStage::Sew, "parameter_space_area")?;
1712        if cancel_planar_fold && expected.abs() <= tolerance * tolerance {
1713            decline!(older, newer);
1714        }
1715        let merged = FaceRecord {
1716            id: older.id,
1717            surface: older.surface.clone(),
1718            same_sense: if cancel_planar_fold {
1719                expected > 0.0
1720            } else {
1721                older.same_sense
1722            },
1723            loops,
1724            name: older.name.clone(),
1725        };
1726
1727        let actual =
1728            parameter_space_area(&merged).or_refuse(KernelStage::Sew, "parameter_space_area")?;
1729        let area_ratio = if cancel_planar_fold {
1730            same_carrier_area_tolerance_ratio.min(1e-7)
1731        } else {
1732            same_carrier_area_tolerance_ratio
1733        };
1734        let area_tolerance = 1e-9f64.max(expected.abs() * area_ratio);
1735        if (actual - expected).abs() > area_tolerance
1736            || (actual.abs() > 1e-12 && actual.is_sign_positive() != merged.same_sense)
1737        {
1738            decline!(older, newer);
1739        }
1740        return Ok(Some(merged));
1741    }
1742
1743    if reseamed {
1744        // The re-seam route keeps the pieces' own carrier, turned whole spans
1745        // to start inside their union's gap, and every trim's own pcurve
1746        // shifted with it: the joined face is exactly the face a primitive
1747        // whose seam lay in that gap would have given, which every later
1748        // feature reads as it reads the primitive's. It reads the full-turn
1749        // lane's bars, never the partial-turn lane's 5e-3 area share (one
1750        // piece of a seam-split pair can be a sliver that share would lose).
1751        let support = cosurface_cylinder.as_ref().expect("the re-seam route reads a cylinder support");
1752        let weld = crate::tolerance::assembler_weld(tolerance);
1753        let Some((surface, loops)) = turn_carrier_into_gap(&older.surface, loops, weld) else {
1754            decline!(older, newer);
1755        };
1756        let merged = FaceRecord { id: older.id, surface, same_sense: older.same_sense, loops, name: older.name.clone() };
1757        if reseam_accepts(older, newer, &merged, edges, tolerance, support)? {
1758            return Ok(Some(merged));
1759        }
1760        decline!(older, newer);
1761    }
1762
1763    if let Some(support) = &cosurface_cylinder {
1764        // The partial-turn lane first: a union that leaves an angular gap
1765        // takes a carrier seamed in that gap and never crosses the seam.
1766        // Whatever it declines (a sampled gap that is not one, a region that
1767        // wraps the full turn) the full-turn lane reads again on a closed
1768        // carrier seamed along an existing axial edge.
1769        'partial_turn: {
1770            // The partial-turn carrier is built at one radius: a cone goes
1771            // straight to the full-turn lane, which reads it per end.
1772            if support.slope != 0.0 {
1773                fall_through!(older, newer, 'partial_turn);
1774            }
1775            // Build one revolution carrier covering both patches: seam at the
1776            // largest angular gap so the merged region never crosses it, then
1777            // reproject every loop onto the shared cylinder.
1778            let x_reference = {
1779                let seed = loops
1780                    .iter()
1781                    .flat_map(|loop_record| &loop_record.coedges)
1782                    .find_map(|coedge| {
1783                        let edge = edges[&coedge.edge_id];
1784                        edge.curve.evaluate(edge.t0).ok()
1785                    })
1786                    .ok_or_else(|| {
1787                        KernelRefusal::internal(
1788                            KernelStage::Sew,
1789                            "face_merge",
1790                            "cylinder merge: no boundary sample",
1791                        )
1792                    })?;
1793                let delta = seed.sub(support.origin);
1794                let radial = delta.sub(support.axis.scale(delta.dot(support.axis)));
1795                match radial.normalized() {
1796                    Ok(radial) => radial,
1797                    Err(_) => fall_through!(older, newer, 'partial_turn),
1798                }
1799            };
1800            let y_reference = support.axis.cross(x_reference);
1801            let mut angles = Vec::new();
1802            // The angular sweep between consecutive samples of ONE edge: the
1803            // edge itself covers it, so no gap can open inside it.
1804            let mut swept: Vec<(f64, f64)> = Vec::new();
1805            let mut axial_range = [f64::INFINITY, f64::NEG_INFINITY];
1806            for coedge in loops.iter().flat_map(|loop_record| &loop_record.coedges) {
1807                let edge = edges[&coedge.edge_id];
1808                let curve = trimmed_curve(&edge.curve, edge.t0, edge.t1)?;
1809                let [c0, c1] = curve.domain().or_refuse(KernelStage::Sew, "domain")?;
1810                let hull = axial_hull(&curve, support);
1811                axial_range[0] = axial_range[0].min(hull[0]);
1812                axial_range[1] = axial_range[1].max(hull[1]);
1813                let mut previous: Option<f64> = None;
1814                for index in 0..=8 {
1815                    let point = curve
1816                        .evaluate(c0 + (c1 - c0) * index as f64 / 8.0)
1817                        .or_refuse(KernelStage::Sew, "evaluate")?;
1818                    let delta = point.sub(support.origin);
1819                    let axial = delta.dot(support.axis);
1820                    let radial = delta.sub(support.axis.scale(axial));
1821                    if radial.length() <= support.radius * 1e-6 {
1822                        continue;
1823                    }
1824                    let mut angle = radial.dot(y_reference).atan2(radial.dot(x_reference));
1825                    if angle < 0.0 {
1826                        angle += std::f64::consts::TAU;
1827                    }
1828                    if let Some(previous) = previous {
1829                        swept.push((previous, angle_difference(previous, angle)));
1830                    }
1831                    previous = Some(angle);
1832                    angles.push(angle);
1833                }
1834            }
1835            if angles.len() < 3 || axial_range[1] - axial_range[0] <= tolerance {
1836                fall_through!(older, newer, 'partial_turn);
1837            }
1838            // The boundary sweeps the whole turn (two half-turn walls closing a
1839            // ring between them): the largest gap between SAMPLES below would
1840            // be one sample step inside an arc, not a gap in the region, and
1841            // the carrier seamed there only fails the area check after a full
1842            // reprojection. Leave for the full-turn lane at once.
1843            if largest_uncovered_turn(&swept) <= 1e-6 {
1844                fall_through!(older, newer, 'partial_turn);
1845            }
1846            angles.sort_by(f64::total_cmp);
1847            let mut gap_start = angles.len() - 1;
1848            let mut largest_gap = angles[0] + std::f64::consts::TAU - angles[angles.len() - 1];
1849            for index in 0..angles.len() - 1 {
1850                let gap = angles[index + 1] - angles[index];
1851                if gap > largest_gap {
1852                    largest_gap = gap;
1853                    gap_start = index;
1854                }
1855            }
1856            let span = std::f64::consts::TAU - largest_gap;
1857            if span <= tolerance || span >= std::f64::consts::TAU - 1e-6 {
1858                fall_through!(older, newer, 'partial_turn);
1859            }
1860            let start_angle = angles[(gap_start + 1) % angles.len()];
1861            let start_direction = x_reference
1862                .scale(start_angle.cos())
1863                .add(y_reference.scale(start_angle.sin()));
1864            let generatrix = make_line(
1865                support
1866                    .origin
1867                    .add(support.axis.scale(axial_range[0]))
1868                    .add(start_direction.scale(support.radius)),
1869                support
1870                    .origin
1871                    .add(support.axis.scale(axial_range[1]))
1872                    .add(start_direction.scale(support.radius)),
1873            )
1874            .or_refuse(KernelStage::Sew, "healing.face_merge")?;
1875            let surface = make_revolution(support.origin, support.axis, &generatrix, span)
1876                .or_refuse(KernelStage::Sew, "make_revolution")?;
1877            let (u_domain, v_domain) = surface_domains(&surface)?;
1878            let sample = surface
1879                .evaluate(
1880                    (u_domain[0] + u_domain[1]) / 2.0,
1881                    (v_domain[0] + v_domain[1]) / 2.0,
1882                )
1883                .or_refuse(KernelStage::Sew, "healing.face_merge")?;
1884            let geometric_normal = surface
1885                .normal(
1886                    (u_domain[0] + u_domain[1]) / 2.0,
1887                    (v_domain[0] + v_domain[1]) / 2.0,
1888                )
1889                .or_refuse(KernelStage::Sew, "healing.face_merge")?;
1890            let delta = sample.sub(support.origin);
1891            let radial = delta.sub(support.axis.scale(delta.dot(support.axis)));
1892            let radial = match radial.normalized() {
1893                Ok(radial) => radial,
1894                Err(_) => fall_through!(older, newer, 'partial_turn),
1895            };
1896            let same_sense = geometric_normal.dot(radial).signum() == support.outward_radial_sign;
1897            let mut projected_loops = reproject_loops(&surface, loops, edges)?;
1898            projected_loops.sort_by(|first, second| {
1899                let area = |loop_record: &LoopRecord| {
1900                    parameter_space_area(&FaceRecord {
1901                        id: older.id,
1902                        surface: surface.clone(),
1903                        same_sense,
1904                        loops: vec![loop_record.clone()],
1905                        name: None,
1906                    })
1907                    .map(f64::abs)
1908                };
1909                match (area(first), area(second)) {
1910                    (Ok(a), Ok(b)) => b.total_cmp(&a),
1911                    _ => std::cmp::Ordering::Equal,
1912                }
1913            });
1914            let merged = FaceRecord {
1915                id: older.id,
1916                surface,
1917                same_sense,
1918                loops: projected_loops,
1919                name: older.name.clone(),
1920            };
1921            let area =
1922                parameter_space_area(&merged).or_refuse(KernelStage::Sew, "parameter_space_area")?;
1923            if area.abs() <= tolerance * tolerance || area.is_sign_positive() != merged.same_sense {
1924                fall_through!(older, newer, 'partial_turn);
1925            }
1926            // The reprojected trims must reproduce the pieces' combined 3D
1927            // area; a projection or seam mistake shows up here immediately.
1928            if boundary_areas_agree(older, newer, &merged) {
1929                return Ok(Some(merged));
1930            }
1931            let expected = face_area(older).or_refuse(KernelStage::Sew, "face_area")?
1932                + face_area(newer).or_refuse(KernelStage::Sew, "face_area")?;
1933            let actual = face_area(&merged).or_refuse(KernelStage::Sew, "face_area")?;
1934            if (actual - expected).abs() > expected.abs().max(1e-9) * 5e-3 {
1935                fall_through!(older, newer, 'partial_turn);
1936            }
1937            return Ok(Some(merged));
1938        }
1939        if let Some(merged) =
1940            merge_cylinder_full_turn(older, newer, edges, tolerance, support, &shared_edges, lanes)?
1941        {
1942            return Ok(Some(merged));
1943        }
1944        decline!(older, newer);
1945    }
1946
1947    if let Some((support, union)) = cosurface_extrusion {
1948        // Shared linear-sweep carrier: the older profile translated to the
1949        // union's start plane, extruded across the union interval.
1950        let shift = support.direction.scale(union[0] - support.interval[0]);
1951        let step = support.direction.scale(union[1] - union[0]);
1952        let rows = support
1953            .base
1954            .control_points
1955            .iter()
1956            .map(|control| -> Result<Vec<Vec4>, KernelRefusal> {
1957                let point = control
1958                    .point()
1959                    .or_refuse(KernelStage::Sew, "point")?
1960                    .add(shift);
1961                Ok(vec![
1962                    Vec4::from_point(point, control.w),
1963                    Vec4::from_point(point.add(step), control.w),
1964                ])
1965            })
1966            .collect::<Result<Vec<_>, _>>()?;
1967        let surface = NurbsSurface::new(
1968            support.base.degree,
1969            1,
1970            support.base.knots.clone(),
1971            vec![0.0, 0.0, 1.0, 1.0],
1972            rows,
1973        )
1974        .or_refuse(KernelStage::Sew, "healing.face_merge")?;
1975        let (older_u, older_v) = surface_domains(&older.surface)?;
1976        let older_mid = older
1977            .surface
1978            .evaluate(
1979                (older_u[0] + older_u[1]) / 2.0,
1980                (older_v[0] + older_v[1]) / 2.0,
1981            )
1982            .or_refuse(KernelStage::Sew, "healing.face_merge")?;
1983        let projection = crate::project_point_to_surface(&surface, older_mid)
1984            .or_refuse(KernelStage::Sew, "project_point_to_surface")?;
1985        let carrier_normal = surface
1986            .normal(projection.u, projection.v)
1987            .or_refuse(KernelStage::Sew, "normal")?;
1988        let same_sense = carrier_normal.dot(outward_normal(older)?) > 0.0;
1989        let mut projected_loops = reproject_loops(&surface, loops, edges)?;
1990        projected_loops.sort_by(|first, second| {
1991            let area = |loop_record: &LoopRecord| {
1992                parameter_space_area(&FaceRecord {
1993                    id: older.id,
1994                    surface: surface.clone(),
1995                    same_sense,
1996                    loops: vec![loop_record.clone()],
1997                    name: None,
1998                })
1999                .map(f64::abs)
2000            };
2001            match (area(first), area(second)) {
2002                (Ok(a), Ok(b)) => b.total_cmp(&a),
2003                _ => std::cmp::Ordering::Equal,
2004            }
2005        });
2006        let merged = FaceRecord {
2007            id: older.id,
2008            surface,
2009            same_sense,
2010            loops: projected_loops,
2011            name: older.name.clone(),
2012        };
2013        let area =
2014            parameter_space_area(&merged).or_refuse(KernelStage::Sew, "parameter_space_area")?;
2015        if area.abs() <= tolerance * tolerance || area.is_sign_positive() != merged.same_sense {
2016            decline!(older, newer);
2017        }
2018        let expected = face_area(older).or_refuse(KernelStage::Sew, "face_area")?
2019            + face_area(newer).or_refuse(KernelStage::Sew, "face_area")?;
2020        let actual = face_area(&merged).or_refuse(KernelStage::Sew, "face_area")?;
2021        if (actual - expected).abs() > expected.abs().max(1e-9) * 5e-3 {
2022            if std::env::var("BREP_DEBUG_MERGE").is_ok() {
2023                eprintln!(
2024                    "coextrusion {}x{}: area mismatch {actual} vs {expected}",
2025                    older.id, newer.id
2026                );
2027            }
2028            decline!(older, newer);
2029        }
2030        return Ok(Some(merged));
2031    }
2032
2033    let (u_domain, v_domain) = surface_domains(&older.surface)?;
2034    let origin = older
2035        .surface
2036        .evaluate(u_domain[0], v_domain[0])
2037        .or_refuse(KernelStage::Sew, "evaluate")?;
2038    let derivatives = older
2039        .surface
2040        .derivatives(
2041            (u_domain[0] + u_domain[1]) / 2.0,
2042            (v_domain[0] + v_domain[1]) / 2.0,
2043            1,
2044        )
2045        .or_refuse(KernelStage::Sew, "healing.face_merge")?;
2046    let u_axis = derivatives[1][0]
2047        .normalized()
2048        .or_refuse(KernelStage::Sew, "normalized")?;
2049    let geometric_normal = derivatives[1][0]
2050        .cross(derivatives[0][1])
2051        .normalized()
2052        .or_refuse(KernelStage::Sew, "normalized")?;
2053    let v_axis = geometric_normal
2054        .cross(u_axis)
2055        .normalized()
2056        .or_refuse(KernelStage::Sew, "normalized")?;
2057    let mut bounds_u = [f64::INFINITY, f64::NEG_INFINITY];
2058    let mut bounds_v = [f64::INFINITY, f64::NEG_INFINITY];
2059    for coedge in loops.iter().flat_map(|loop_record| &loop_record.coedges) {
2060        let edge = edges[&coedge.edge_id];
2061        let curve = trimmed_curve(&edge.curve, edge.t0, edge.t1)?;
2062        for control in &curve.control_points {
2063            let relative = control
2064                .point()
2065                .or_refuse(KernelStage::Sew, "point")?
2066                .sub(origin);
2067            let u = relative.dot(u_axis);
2068            let v = relative.dot(v_axis);
2069            bounds_u[0] = bounds_u[0].min(u);
2070            bounds_u[1] = bounds_u[1].max(u);
2071            bounds_v[0] = bounds_v[0].min(v);
2072            bounds_v[1] = bounds_v[1].max(v);
2073        }
2074    }
2075    let extent_u = bounds_u[1] - bounds_u[0];
2076    let extent_v = bounds_v[1] - bounds_v[0];
2077    if extent_u <= tolerance || extent_v <= tolerance {
2078        decline!(older, newer);
2079    }
2080    let surface_origin = origin
2081        .add(u_axis.scale(bounds_u[0]))
2082        .add(v_axis.scale(bounds_v[0]));
2083    let surface = make_plane(surface_origin, u_axis, v_axis, extent_u, extent_v)
2084        .or_refuse(KernelStage::Sew, "make_plane")?;
2085    let mut projected_loops = match transfer_planar_loops(&surface, &loops, older, newer, tolerance)
2086    {
2087        Some(transferred) => transferred,
2088        None => reproject_loops(&surface, loops, edges)?,
2089    };
2090    projected_loops.sort_by(|first, second| {
2091        let area = |loop_record: &LoopRecord| {
2092            parameter_space_area(&FaceRecord {
2093                id: older.id,
2094                surface: surface.clone(),
2095                same_sense: older.same_sense,
2096                loops: vec![loop_record.clone()],
2097                name: None,
2098            })
2099            .map(f64::abs)
2100        };
2101        match (area(first), area(second)) {
2102            (Ok(a), Ok(b)) => b.total_cmp(&a),
2103            _ => std::cmp::Ordering::Equal,
2104        }
2105    });
2106    let merged = FaceRecord {
2107        id: older.id,
2108        surface,
2109        same_sense: older.same_sense,
2110        loops: projected_loops,
2111        name: older.name.clone(),
2112    };
2113    let area = parameter_space_area(&merged).or_refuse(KernelStage::Sew, "parameter_space_area")?;
2114    if area.abs() <= tolerance * tolerance || area.is_sign_positive() != merged.same_sense {
2115        decline!(older, newer);
2116    }
2117    Ok(Some(merged))
2118}
2119
2120/// Angle of `point` about `support`'s axis in the (`x_reference`,
2121/// `y_reference`) frame, in `[0, TAU)`; `None` on the axis.
2122fn cylinder_angle(
2123    support: &CylinderSupport,
2124    x_reference: Vec3,
2125    y_reference: Vec3,
2126    point: Vec3,
2127) -> Option<f64> {
2128    let delta = point.sub(support.origin);
2129    let radial = delta.sub(support.axis.scale(delta.dot(support.axis)));
2130    if radial.length() <= support.radius * 1e-6 {
2131        return None;
2132    }
2133    let mut angle = radial.dot(y_reference).atan2(radial.dot(x_reference));
2134    if angle < 0.0 {
2135        angle += std::f64::consts::TAU;
2136    }
2137    // An atan2 a few ulp below zero rounds to TAU itself after the shift; the
2138    // range is half-open, so that reading is the seam angle 0.
2139    if angle >= std::f64::consts::TAU {
2140        angle = 0.0;
2141    }
2142    Some(angle)
2143}
2144
2145
2146/// The widest angle, in radians, that no `(start, signed sweep)` arc of
2147/// `swept` covers; `TAU` for no arcs. Arcs are read the short way round, as
2148/// [`angle_difference`] reports a sweep between two nearby samples.
2149pub fn largest_uncovered_turn(swept: &[(f64, f64)]) -> f64 {
2150    let tau = std::f64::consts::TAU;
2151    let mut arcs: Vec<(f64, f64)> = Vec::with_capacity(swept.len() + 1);
2152    for &(start, sweep) in swept {
2153        let (low, length) = if sweep < 0.0 { (start + sweep, -sweep) } else { (start, sweep) };
2154        let low = low.rem_euclid(tau);
2155        if low + length > tau {
2156            arcs.push((low, tau));
2157            arcs.push((0.0, low + length - tau));
2158        } else {
2159            arcs.push((low, low + length));
2160        }
2161    }
2162    if arcs.is_empty() {
2163        return tau;
2164    }
2165    arcs.sort_by(|a, b| a.0.total_cmp(&b.0));
2166    let mut largest = 0.0f64;
2167    let mut reach = arcs[0].1;
2168    for arc in &arcs[1..] {
2169        largest = largest.max(arc.0 - reach);
2170        reach = reach.max(arc.1);
2171    }
2172    // The wrap from the last reach round to the first arc's start.
2173    largest.max(arcs[0].0 + tau - reach)
2174}
2175
2176/// Signed angular distance from `from` to `to`, in `(-PI, PI]`.
2177fn angle_difference(from: f64, to: f64) -> f64 {
2178    let turn = (to - from).rem_euclid(std::f64::consts::TAU);
2179    if turn > std::f64::consts::PI {
2180        turn - std::f64::consts::TAU
2181    } else {
2182        turn
2183    }
2184}
2185
2186/// `carrier` (closed in u) turned whole spans to start at a full-multiplicity
2187/// knot inside the widest u interval no trim of `loops` sweeps across (the
2188/// knot inserted at the interval's middle when it holds none), with every
2189/// trim's pcurve shifted in u to the turned chart: exact, since turning a
2190/// closed net at a knot of multiplicity `degree` moves no basis function and
2191/// each trim lies on one side of the new seam. `None` when the carrier is not
2192/// closed in u or no such interval exists (the trims sweep the whole turn).
2193fn turn_carrier_into_gap(
2194    carrier: &NurbsSurface,
2195    loops: Vec<LoopRecord>,
2196    weld: f64,
2197) -> Option<(NurbsSurface, Vec<LoopRecord>)> {
2198    let degree = carrier.degree_u;
2199    if degree == 0 || !closed_control_boundary(carrier, true, weld) {
2200        return None;
2201    }
2202    let (u_domain, _) = surface_domains(carrier).ok()?;
2203    // Each trim's u samples and the u intervals it sweeps between them.
2204    let mut samples: Vec<f64> = Vec::new();
2205    let mut swept: Vec<(f64, f64)> = Vec::new();
2206    for coedge in loops.iter().flat_map(|loop_record| &loop_record.coedges) {
2207        let [t0, t1] = coedge.pcurve.domain().ok()?;
2208        let mut previous: Option<f64> = None;
2209        for index in 0..=16 {
2210            let u = coedge.pcurve.evaluate(t0 + (t1 - t0) * index as f64 / 16.0).ok()?.x;
2211            if !u.is_finite() {
2212                return None;
2213            }
2214            samples.push(u);
2215            if let Some(previous) = previous {
2216                swept.push((previous.min(u), previous.max(u)));
2217            }
2218            previous = Some(u);
2219        }
2220    }
2221    samples.sort_by(f64::total_cmp);
2222    let (first, last) = (*samples.first()?, *samples.last()?);
2223    if first < u_domain[0] - weld || last > u_domain[1] + weld {
2224        return None;
2225    }
2226    // The widest interval between consecutive samples that no sweep covers
2227    // (the trims meet across the old seam, so the wrap-around interval is
2228    // covered by construction and never read).
2229    let mut gap: Option<(f64, f64)> = None;
2230    for pair in samples.windows(2) {
2231        let (low, high) = (pair[0], pair[1]);
2232        let middle = (low + high) / 2.0;
2233        if high - low <= weld || swept.iter().any(|&(a, b)| a < middle && middle < b) {
2234            continue;
2235        }
2236        if gap.is_none_or(|(a, b)| high - low > b - a) {
2237            gap = Some((low, high));
2238        }
2239    }
2240    let (low, high) = gap?;
2241    let middle = (low + high) / 2.0;
2242    let existing = crate::boolean::reseat::full_knots(&carrier.knots_u, degree)
2243        .into_iter()
2244        .map(|(knot, _)| knot)
2245        .filter(|&knot| knot > low && knot < high)
2246        .min_by(|a, b| (a - middle).abs().total_cmp(&(b - middle).abs()));
2247    let (refined, seam) = match existing {
2248        Some(knot) => (carrier.clone(), knot),
2249        None => {
2250            let present = carrier.knots_u.iter().filter(|&&knot| knot == middle).count();
2251            let refined = carrier
2252                .insert_knot(crate::KnotDirection::U, middle, degree.saturating_sub(present))
2253                .ok()?;
2254            (refined, middle)
2255        }
2256    };
2257    let (knots_u, rows) =
2258        crate::boolean::reseat::rotate_closed(&refined.knots_u, degree, &refined.control_points, seam)?;
2259    let surface = NurbsSurface::new(refined.degree_u, refined.degree_v, knots_u, refined.knots_v.clone(), rows).ok()?;
2260    // u at or past the seam moves down by (seam - u0); u before it moves up
2261    // by (u1 - seam), the rest of the turn.
2262    let mut turned = Vec::with_capacity(loops.len());
2263    for mut loop_record in loops {
2264        for coedge in &mut loop_record.coedges {
2265            let [t0, t1] = coedge.pcurve.domain().ok()?;
2266            let mid = coedge.pcurve.evaluate((t0 + t1) / 2.0).ok()?.x;
2267            let shift = if mid >= seam { u_domain[0] - seam } else { u_domain[1] - seam };
2268            for point in &mut coedge.pcurve.control_points {
2269                point.x += shift * point.w;
2270            }
2271        }
2272        turned.push(loop_record);
2273    }
2274    Some((surface, turned))
2275}
2276
2277/// The re-seamed face built from a seam-split pair (`seam_reseam_enabled`)
2278/// stands in for both pieces: every trim on its edge within the validator's
2279/// own pcurve acceptance on the pair's extent, and the pieces' combined 3D
2280/// area and volume term about the origin reproduced within what trims
2281/// admitted `band` off their edges can move along the whole boundary (the
2282/// full-turn lane's bars).
2283fn reseam_accepts(
2284    older: &FaceRecord,
2285    newer: &FaceRecord,
2286    merged: &FaceRecord,
2287    edges: &HashMap<u64, &EdgeRecord>,
2288    tolerance: f64,
2289    support: &CylinderSupport,
2290) -> Result<bool, KernelRefusal> {
2291    let debug = std::env::var("BREP_DEBUG_MERGE").is_ok();
2292    let mut perimeter = 0.0f64;
2293    let mut bbox_lo = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
2294    let mut bbox_hi = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
2295    for coedge in [older, newer]
2296        .iter()
2297        .flat_map(|face| face.loops.iter().flat_map(|loop_record| &loop_record.coedges))
2298    {
2299        let edge = edges[&coedge.edge_id];
2300        if edge.degenerate {
2301            continue;
2302        }
2303        perimeter += crate::mass_properties::edge_arc_length(edge).unwrap_or(0.0);
2304        let curve = trimmed_curve(&edge.curve, edge.t0, edge.t1)?;
2305        let [c0, c1] = curve.domain().or_refuse(KernelStage::Sew, "domain")?;
2306        for index in 0..=8 {
2307            let point = curve
2308                .evaluate(c0 + (c1 - c0) * index as f64 / 8.0)
2309                .or_refuse(KernelStage::Sew, "evaluate")?;
2310            bbox_lo = Vec3::new(bbox_lo.x.min(point.x), bbox_lo.y.min(point.y), bbox_lo.z.min(point.z));
2311            bbox_hi = Vec3::new(bbox_hi.x.max(point.x), bbox_hi.y.max(point.y), bbox_hi.z.max(point.z));
2312        }
2313    }
2314    // The bars read the pair's own size, never its distance from the world
2315    // origin: far from the origin an origin-scaled band would admit a
2316    // carrier a visible distance off the pieces' own.
2317    let diagonal = bbox_hi.sub(bbox_lo).length();
2318    let scale = 1.0f64.max(diagonal).max(support.radius);
2319    let band = (tolerance * 100.0).max(1e-7 * scale);
2320    // The support stands for the pieces' carrier itself: every station of
2321    // that carrier lies on it within `band`. The support's detection admits
2322    // a slight taper as a cylinder; a carrier rebuilt from such a support
2323    // would move the wall, so the pair stays split.
2324    let carrier = &older.surface;
2325    let (u_domain, v_domain) = surface_domains(carrier)?;
2326    let mut worst_off = 0.0f64;
2327    for i in 0..=8 {
2328        for j in 0..=4 {
2329            let point = carrier
2330                .evaluate(
2331                    u_domain[0] + (u_domain[1] - u_domain[0]) * i as f64 / 8.0,
2332                    v_domain[0] + (v_domain[1] - v_domain[0]) * j as f64 / 4.0,
2333                )
2334                .or_refuse(KernelStage::Sew, "evaluate")?;
2335            let delta = point.sub(support.origin);
2336            let axial = delta.dot(support.axis);
2337            let radial = delta.sub(support.axis.scale(axial)).length();
2338            worst_off = worst_off.max((radial - support.radius_at(axial)).abs());
2339        }
2340    }
2341    let pcurve_limit = crate::KernelTolerances::for_scale(scale, 1e-7).pcurve_acceptance(diagonal);
2342    let mut worst_trim = 0.0f64;
2343    for coedge in merged.loops.iter().flat_map(|loop_record| &loop_record.coedges) {
2344        let edge = edges[&coedge.edge_id];
2345        let error = crate::topology::coedge_error_floored(
2346            &merged.surface,
2347            &coedge.pcurve,
2348            &edge.curve,
2349            edge,
2350            coedge.forward,
2351            pcurve_limit,
2352        )
2353        .unwrap_or(f64::INFINITY);
2354        worst_trim = worst_trim.max(error);
2355    }
2356    let expected_area = face_area(older).or_refuse(KernelStage::Sew, "face_area")?
2357        + face_area(newer).or_refuse(KernelStage::Sew, "face_area")?;
2358    let expected_term = face_volume_contribution(older)
2359        .or_refuse(KernelStage::Sew, "face_volume_contribution")?
2360        + face_volume_contribution(newer).or_refuse(KernelStage::Sew, "face_volume_contribution")?;
2361    let actual = face_area(merged).or_refuse(KernelStage::Sew, "face_area")?;
2362    let actual_term =
2363        face_volume_contribution(merged).or_refuse(KernelStage::Sew, "face_volume_contribution")?;
2364    let area_bar = band * perimeter + 1e-9 * expected_area.abs();
2365    let reach = bbox_lo.length().max(bbox_hi.length());
2366    let term_bar = band * perimeter * reach / 3.0 + 1e-9 * expected_term.abs().max(expected_area.abs());
2367    let accepted = worst_off <= band
2368        && worst_trim <= pcurve_limit
2369        && (actual - expected_area).abs() <= area_bar
2370        && (actual_term - expected_term).abs() <= term_bar;
2371    if debug {
2372        eprintln!(
2373            "merge {}x{}: re-seam {}: carrier off its support {worst_off:.3e} (band {band:.3e}), trim {worst_trim:.3e} (limit {pcurve_limit:.3e}), area {actual:.9} vs {expected_area:.9} (bar {area_bar:.3e}), volume term {actual_term:.9} vs {expected_term:.9} (bar {term_bar:.3e})",
2374            older.id,
2375            newer.id,
2376            if accepted { "MERGE" } else { "declined" }
2377        );
2378    }
2379    Ok(accepted)
2380}
2381
2382/// Merge two cosurface cylinder patches whose union wraps the FULL turn.
2383///
2384/// The partial-turn lane seams its carrier in the union's largest angular
2385/// gap; a union with no gap (the shelled cylinder's full outer wall against
2386/// the half-walls of a coaxial extrude, the E13 report of 2026-10-13) has no
2387/// such seam, and cancelling every shared edge there strands the full face's
2388/// seam strip at a fork the 3D walk cannot resolve. This lane builds a closed
2389/// revolution carrier seamed along an existing AXIAL edge that both faces
2390/// already traverse twice — one face's own seam pair, or a shared pair — keeps
2391/// the shared edges on that line as seam pairs instead of cancelling them,
2392/// places every seam-line trim on the side of the seam its traversal puts the
2393/// material on, and walks the leftover uses in the carrier's own parameter
2394/// space. Only a seam one of the faces ALREADY has is a candidate: a face
2395/// that wraps the turn by itself carries its own seam pair, and the merged
2396/// face keeps that seam. Two half-turn patches closing a ring between them
2397/// have no such seam; they were two faces before any boolean touched them
2398/// (a sketch circle's two arcs, a tube piece's two halves, a plate hole's
2399/// two bore segments whose names a flange picks) and they stay two faces
2400/// here — master's battery of 2026-10-13 read four regressions from merging
2401/// them. Each candidate is tried in turn, and the merged face must close
2402/// every loop in parameter space, keep every trim on its edge within the
2403/// validator's own pcurve acceptance, and reproduce the pieces'
2404/// parameter-space sign and their combined 3D area, or the candidate is
2405/// dropped; with no candidate left the pair stays as assembled.
2406///
2407/// What this lane does NOT do: two full rings seamed at different angles
2408/// (a shelled cylinder's bore wall and a coaxial extrude's hole wall whose
2409/// profile circle happened to start opposite) have no axial edge spanning
2410/// both, and merging them means re-seaming one through its far rim and the
2411/// cap on it — a solid-wide edit the face merge does not make. Such a pair
2412/// declines here with its loops open in parameter space and keeps its
2413/// circular joint.
2414fn merge_cylinder_full_turn(
2415    older: &FaceRecord,
2416    newer: &FaceRecord,
2417    edges: &HashMap<u64, &EdgeRecord>,
2418    tolerance: f64,
2419    support: &CylinderSupport,
2420    shared_edges: &HashSet<u64>,
2421    lanes: MergeLanes<'_>,
2422) -> Result<Option<FaceRecord>, KernelRefusal> {
2423    let debug = std::env::var("BREP_DEBUG_MERGE").is_ok();
2424    // `BREP_FULL_TURN_MERGE=0` hatches the lane off, for attribution only.
2425    if std::env::var("BREP_FULL_TURN_MERGE").as_deref() == Ok("0") {
2426        return Ok(None);
2427    }
2428    // Every non-degenerate use of either face, tagged with which face it came
2429    // from (0 older, 1 newer) so an edge used twice by ONE face reads as its
2430    // own seam.
2431    let uses = [older, newer]
2432        .iter()
2433        .enumerate()
2434        .flat_map(|(side, face)| {
2435            face.loops
2436                .iter()
2437                .flat_map(|loop_record| &loop_record.coedges)
2438                .filter(|coedge| !edges[&coedge.edge_id].degenerate)
2439                .map(move |coedge| (side, coedge.clone()))
2440        })
2441        .collect::<Vec<_>>();
2442    let Some(x_reference) = uses.iter().find_map(|(_, coedge)| {
2443        let edge = edges[&coedge.edge_id];
2444        let seed = edge.curve.evaluate(edge.t0).ok()?;
2445        let delta = seed.sub(support.origin);
2446        let radial = delta.sub(support.axis.scale(delta.dot(support.axis)));
2447        radial.normalized().ok()
2448    }) else {
2449        return Ok(None);
2450    };
2451    let y_reference = support.axis.cross(x_reference);
2452    let scale = 1.0f64.max(support.origin.length()).max(support.radius);
2453    let band = (tolerance * 100.0).max(1e-7 * scale);
2454    // The smallest radius the patches reach bounds the angle `band` subtends
2455    // (a cylinder's one radius; a cone's radius at its narrow end, read once
2456    // the axial range is known below and checked positive there).
2457    let mut angular_band = band / support.radius;
2458
2459    // Each use's stations: axial coordinate and angle at nine samples, plus
2460    // the station of its start and end in traversal order.
2461    struct Station {
2462        angle: Option<f64>,
2463    }
2464    let station = |point: Vec3| Station {
2465        angle: cylinder_angle(support, x_reference, y_reference, point),
2466    };
2467    let mut axial_range = [f64::INFINITY, f64::NEG_INFINITY];
2468    let mut samples = Vec::with_capacity(uses.len());
2469    let mut bbox_lo = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
2470    let mut bbox_hi = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
2471    // The boundary length of both faces together: the most area a set of
2472    // trims admitted `band` off their edges can move, per unit of `band`.
2473    let mut perimeter = 0.0f64;
2474    for (_, coedge) in &uses {
2475        let edge = edges[&coedge.edge_id];
2476        let curve = trimmed_curve(&edge.curve, edge.t0, edge.t1)?;
2477        let [c0, c1] = curve.domain().or_refuse(KernelStage::Sew, "domain")?;
2478        let hull = axial_hull(&curve, support);
2479        axial_range[0] = axial_range[0].min(hull[0]);
2480        axial_range[1] = axial_range[1].max(hull[1]);
2481        perimeter += crate::mass_properties::edge_arc_length(edge).unwrap_or(0.0);
2482        let mut stations = Vec::with_capacity(9);
2483        for index in 0..=8 {
2484            let point = curve
2485                .evaluate(c0 + (c1 - c0) * index as f64 / 8.0)
2486                .or_refuse(KernelStage::Sew, "evaluate")?;
2487            bbox_lo = Vec3::new(bbox_lo.x.min(point.x), bbox_lo.y.min(point.y), bbox_lo.z.min(point.z));
2488            bbox_hi = Vec3::new(bbox_hi.x.max(point.x), bbox_hi.y.max(point.y), bbox_hi.z.max(point.z));
2489            stations.push(station(point));
2490        }
2491        samples.push(stations);
2492    }
2493    if axial_range[1] - axial_range[0] <= tolerance {
2494        return Ok(None);
2495    }
2496    if support.slope != 0.0 {
2497        let narrow = support
2498            .radius_at(axial_range[0])
2499            .min(support.radius_at(axial_range[1]));
2500        if narrow <= band {
2501            return Ok(None);
2502        }
2503        angular_band = band / narrow;
2504    }
2505    // An edge is an axial line at angle `theta` when every sample reads that
2506    // angle: a straight generatrix of the shared cylinder.
2507    let axial_angle = |stations: &[Station]| -> Option<f64> {
2508        let first = stations.first()?.angle?;
2509        stations
2510            .iter()
2511            .all(|station| {
2512                station
2513                    .angle
2514                    .is_some_and(|angle| angle_difference(first, angle).abs() <= angular_band)
2515            })
2516            .then_some(first)
2517    };
2518    let mut use_count = HashMap::<u64, usize>::default();
2519    for (_, coedge) in &uses {
2520        *use_count.entry(coedge.edge_id).or_default() += 1;
2521    }
2522    // Candidate seam angles, ranked: a face's own seam pair (both uses from
2523    // one face) before a shared pair; a line used once bounds the region on
2524    // one side only and cannot seam a wrap by itself.
2525    let mut candidates: Vec<(u8, f64)> = Vec::new();
2526    // Candidate angles whose edge ends at a vertex `lanes.seam_vertices` names.
2527    let mut preferred: Vec<f64> = Vec::new();
2528    for (index, (side, coedge)) in uses.iter().enumerate() {
2529        if use_count.get(&coedge.edge_id).copied() != Some(2) {
2530            continue;
2531        }
2532        let Some(theta) = axial_angle(&samples[index]) else {
2533            continue;
2534        };
2535        let own_seam = uses
2536            .iter()
2537            .any(|(other_side, other)| {
2538                other.edge_id == coedge.edge_id
2539                    && other.id != coedge.id
2540                    && other_side == side
2541                    && other.forward != coedge.forward
2542            });
2543        let rank = if own_seam { 0 } else { 1 };
2544        if let Some(vertices) = lanes.seam_vertices {
2545            let edge = edges[&coedge.edge_id];
2546            if vertices.contains(&edge.start_vertex_id) || vertices.contains(&edge.end_vertex_id) {
2547                preferred.push(theta);
2548            }
2549        }
2550        if !candidates
2551            .iter()
2552            .any(|(_, known)| angle_difference(*known, theta).abs() <= angular_band)
2553        {
2554            candidates.push((rank, theta));
2555        } else if let Some(known) = candidates
2556            .iter_mut()
2557            .find(|(_, known)| angle_difference(*known, theta).abs() <= angular_band)
2558        {
2559            known.0 = known.0.min(rank);
2560        }
2561    }
2562    let is_preferred = |theta: f64| {
2563        preferred
2564            .iter()
2565            .any(|known| angle_difference(*known, theta).abs() <= angular_band)
2566    };
2567    // `false` sorts first: a preferred seam leads its rank. With no
2568    // preference every key is `true` and the order is the plain one.
2569    candidates.sort_by(|a, b| {
2570        a.0.cmp(&b.0)
2571            .then(is_preferred(b.1).cmp(&is_preferred(a.1)))
2572            .then(a.1.total_cmp(&b.1))
2573    });
2574    if debug {
2575        eprintln!(
2576            "merge {}x{}: full-turn lane, {} seam candidate(s) {:?}",
2577            older.id,
2578            newer.id,
2579            candidates.len(),
2580            candidates
2581        );
2582    }
2583    // A shared pair alone (rank 1) is two half patches closing a ring between
2584    // them: neither face wraps, and the merged face would carry a seam no
2585    // input face had. Those pairs stay as assembled (see the doc comment).
2586    // A caller that opted into `shared_seam_ring` is joining faces the user
2587    // named as one region; there the shared pair seams the ring.
2588    if !lanes.shared_seam_ring {
2589        candidates.retain(|(rank, _)| *rank == 0);
2590    }
2591    if candidates.is_empty() {
2592        if debug {
2593            eprintln!(
2594                "merge {}x{}: full-turn lane: no face wraps the turn by itself, the halves stay apart",
2595                older.id, newer.id
2596            );
2597        }
2598        return Ok(None);
2599    }
2600    let weld = crate::tolerance::assembler_weld(tolerance);
2601    // The validator's own edge/pcurve acceptance on this pair's extent (its
2602    // size-coupled ceiling floors at `pcurve_consistency`); the pair's
2603    // diagonal is at most the solid's, so nothing admitted here is refused
2604    // by the closing validation on that count.
2605    let pcurve_limit = crate::KernelTolerances::for_scale(scale, 1e-7)
2606        .pcurve_acceptance(bbox_hi.sub(bbox_lo).length());
2607    let expected_area = face_area(older).or_refuse(KernelStage::Sew, "face_area")?
2608        + face_area(newer).or_refuse(KernelStage::Sew, "face_area")?;
2609    let expected_term = face_volume_contribution(older)
2610        .or_refuse(KernelStage::Sew, "face_volume_contribution")?
2611        + face_volume_contribution(newer).or_refuse(KernelStage::Sew, "face_volume_contribution")?;
2612
2613    'candidate: for (_, theta) in candidates {
2614        let on_seam = |index: usize| {
2615            axial_angle(&samples[index])
2616                .is_some_and(|angle| angle_difference(theta, angle).abs() <= angular_band)
2617        };
2618        // Closed carrier seamed at `theta`, spanning both patches axially.
2619        let start_direction = x_reference
2620            .scale(theta.cos())
2621            .add(y_reference.scale(theta.sin()));
2622        let generatrix = make_line(
2623            support
2624                .origin
2625                .add(support.axis.scale(axial_range[0]))
2626                .add(start_direction.scale(support.radius_at(axial_range[0]))),
2627            support
2628                .origin
2629                .add(support.axis.scale(axial_range[1]))
2630                .add(start_direction.scale(support.radius_at(axial_range[1]))),
2631        )
2632        .or_refuse(KernelStage::Sew, "healing.face_merge")?;
2633        let surface = make_revolution(
2634            support.origin,
2635            support.axis,
2636            &generatrix,
2637            std::f64::consts::TAU,
2638        )
2639        .or_refuse(KernelStage::Sew, "make_revolution")?;
2640        let (u_domain, v_domain) = surface_domains(&surface)?;
2641        let (u_mid, v_mid) = (
2642            (u_domain[0] + u_domain[1]) / 2.0,
2643            (v_domain[0] + v_domain[1]) / 2.0,
2644        );
2645        let sample = surface
2646            .evaluate(u_mid, v_mid)
2647            .or_refuse(KernelStage::Sew, "healing.face_merge")?;
2648        let geometric_normal = surface
2649            .normal(u_mid, v_mid)
2650            .or_refuse(KernelStage::Sew, "healing.face_merge")?;
2651        let delta = sample.sub(support.origin);
2652        let radial = delta.sub(support.axis.scale(delta.dot(support.axis)));
2653        let Ok(radial) = radial.normalized() else {
2654            continue;
2655        };
2656        let same_sense = geometric_normal.dot(radial).signum() == support.outward_radial_sign;
2657        let v_of = |axial: f64| {
2658            v_domain[0]
2659                + (axial - axial_range[0]) / (axial_range[1] - axial_range[0])
2660                    * (v_domain[1] - v_domain[0])
2661        };
2662
2663        // Leftover uses: a shared edge off the seam line is cancelled; one on
2664        // it stays, both ways, as the merged face's seam.
2665        let mut remaining = Vec::new();
2666        for (index, (_, coedge)) in uses.iter().enumerate() {
2667            let seam_line = on_seam(index);
2668            if shared_edges.contains(&coedge.edge_id) && !seam_line {
2669                continue;
2670            }
2671            let edge = edges[&coedge.edge_id];
2672            let mut coedge = coedge.clone();
2673            let mut curve = trimmed_curve(&edge.curve, edge.t0, edge.t1)?;
2674            if !coedge.forward {
2675                curve = curve.reversed().or_refuse(KernelStage::Sew, "reversed")?;
2676            }
2677            if seam_line {
2678                // The material lies to the LEFT of a same-sense loop's
2679                // traversal in uv (parameter-space area positive) and to the
2680                // right of an opposite-sense one. A seam-line trim running
2681                // +v with material on its left is the domain's far side
2682                // (u = u1); running -v, its near side (u = u0).
2683                let [c0, c1] = curve.domain().or_refuse(KernelStage::Sew, "domain")?;
2684                let start = curve.evaluate(c0).or_refuse(KernelStage::Sew, "evaluate")?;
2685                let end = curve.evaluate(c1).or_refuse(KernelStage::Sew, "evaluate")?;
2686                let rising = end.sub(start).dot(support.axis) > 0.0;
2687                let far_side = rising == same_sense;
2688                let u = if far_side { u_domain[1] } else { u_domain[0] };
2689                // The trim carries the edge's OWN parameterisation: the
2690                // axial coordinate is an affine functional of position, so
2691                // mapping each control point (dehomogenised) and keeping the
2692                // degree, knots and weights reproduces v(t) exactly. A
2693                // two-point line assumed the edge ran its axis at constant
2694                // speed, which a spline tube's straight Hermite piece does
2695                // not (max deviation 0.5 at the validator, 2026-10-13).
2696                let origin_axial = support.origin.dot(support.axis);
2697                let control_points = curve
2698                    .control_points
2699                    .iter()
2700                    .map(|point| {
2701                        let w = point.w;
2702                        let axial = Vec3::new(point.x / w, point.y / w, point.z / w)
2703                            .dot(support.axis)
2704                            - origin_axial;
2705                        Vec4 { x: u * w, y: v_of(axial) * w, z: 0.0, w }
2706                    })
2707                    .collect();
2708                coedge.pcurve = NurbsCurve::new(curve.degree, curve.knots.clone(), control_points)
2709                    .or_refuse(KernelStage::Sew, "NurbsCurve::new")?;
2710            } else {
2711                // The kernel's fit, with its report read: a station standing
2712                // off the carrier (`off_surface`) is an edge this carrier
2713                // does not hold — the projector folds such a station onto
2714                // the carrier's boundary and the face becomes the wrong
2715                // region on a body `validate()` passes — and a residual over
2716                // the band is a trim that misses its edge between stations.
2717                let fit = match crate::fit_pcurve_on_surface(&surface, &curve) {
2718                    Ok(fit) => fit,
2719                    Err(_) => continue 'candidate,
2720                };
2721                if fit.report.off_surface > band || fit.report.residual > band {
2722                    if debug {
2723                        eprintln!(
2724                            "merge {}x{}: full-turn seam {theta:.4}: edge {} stands {:.3e} off the carrier, fit residual {:.3e} (band {band:.3e})",
2725                            older.id, newer.id, coedge.edge_id, fit.report.off_surface, fit.report.residual
2726                        );
2727                    }
2728                    continue 'candidate;
2729                }
2730                coedge.pcurve = fit.curve;
2731            }
2732            remaining.push(coedge);
2733        }
2734        let space = SharedParameterSpace { surface: &surface, weld };
2735        dissolve_slits(&mut remaining, edges, &space);
2736        if debug {
2737            for coedge in &remaining {
2738                let stations = pcurve_stations(coedge)
2739                    .map(|[a, m, b]| format!("({:.4},{:.4})->({:.4},{:.4})->({:.4},{:.4})", a.x, a.y, m.x, m.y, b.x, b.y))
2740                    .unwrap_or_default();
2741                eprintln!(
2742                    "  seam {theta:.4} use coedge {} edge {} fwd={} shared={} same_sense={same_sense} uv {stations}",
2743                    coedge.id,
2744                    coedge.edge_id,
2745                    coedge.forward,
2746                    shared_edges.contains(&coedge.edge_id)
2747                );
2748            }
2749        }
2750        let Some(mut loops) = walk_cycles(remaining, edges, Some(&space)) else {
2751            if debug {
2752                eprintln!(
2753                    "merge {}x{}: full-turn seam {theta:.4}: walk undetermined",
2754                    older.id, newer.id
2755                );
2756            }
2757            continue;
2758        };
2759        if loops.is_empty() {
2760            continue;
2761        }
2762        // Every loop must CLOSE in the carrier's parameter space: the walk
2763        // closes a cycle on vertex identity when nothing else leaves its
2764        // end, which on a seamed carrier accepts a full circle running one
2765        // period from its own vertex, or a ring whose own seam pair (off the
2766        // chosen seam) just dissolved as a slit. The area oracles below
2767        // integrate per pcurve and cannot see the grouping.
2768        let closed = loops.iter().all(|loop_record| {
2769            let count = loop_record.coedges.len();
2770            (0..count).all(|index| {
2771                let next = &loop_record.coedges[(index + 1) % count];
2772                match (
2773                    pcurve_stations(&loop_record.coedges[index]),
2774                    pcurve_stations(next),
2775                ) {
2776                    (Some(here), Some(there)) => space.coincide(here[2], there[0]),
2777                    _ => false,
2778                }
2779            })
2780        });
2781        if !closed {
2782            if debug {
2783                eprintln!(
2784                    "merge {}x{}: full-turn seam {theta:.4}: a loop is open in parameter space",
2785                    older.id, newer.id
2786                );
2787            }
2788            continue;
2789        }
2790        if debug {
2791            for loop_record in &loops {
2792                eprintln!(
2793                    "  seam {theta:.4} loop {:?}",
2794                    loop_record.coedges.iter().map(|c| (c.edge_id, c.forward)).collect::<Vec<_>>()
2795                );
2796            }
2797        }
2798        loops.sort_by(|first, second| {
2799            let area = |loop_record: &LoopRecord| {
2800                parameter_space_area(&FaceRecord {
2801                    id: older.id,
2802                    surface: surface.clone(),
2803                    same_sense,
2804                    loops: vec![loop_record.clone()],
2805                    name: None,
2806                })
2807                .map(f64::abs)
2808            };
2809            match (area(first), area(second)) {
2810                (Ok(a), Ok(b)) => b.total_cmp(&a),
2811                _ => std::cmp::Ordering::Equal,
2812            }
2813        });
2814        let merged = FaceRecord {
2815            id: older.id,
2816            surface,
2817            same_sense,
2818            loops,
2819            name: older.name.clone(),
2820        };
2821        // Every trim must lie on its edge by the validator's own reading;
2822        // a candidate that fails here falls through and the pair stays,
2823        // instead of the refusal surfacing from the closing validation as a
2824        // feature failure (the spline tube, 2026-10-13).
2825        let mut worst_trim = 0.0f64;
2826        for coedge in merged.loops.iter().flat_map(|loop_record| &loop_record.coedges) {
2827            let edge = edges[&coedge.edge_id];
2828            let error = crate::topology::coedge_error_floored(
2829                &merged.surface,
2830                &coedge.pcurve,
2831                &edge.curve,
2832                edge,
2833                coedge.forward,
2834                pcurve_limit,
2835            )
2836            .unwrap_or(f64::INFINITY);
2837            worst_trim = worst_trim.max(error);
2838        }
2839        if worst_trim > pcurve_limit {
2840            if debug {
2841                eprintln!(
2842                    "merge {}x{}: full-turn seam {theta:.4}: a trim is {worst_trim:.6} off its edge (limit {pcurve_limit:.6})",
2843                    older.id, newer.id
2844                );
2845            }
2846            continue;
2847        }
2848        let area =
2849            parameter_space_area(&merged).or_refuse(KernelStage::Sew, "parameter_space_area")?;
2850        if area.abs() <= tolerance * tolerance || area.is_sign_positive() != merged.same_sense {
2851            if debug {
2852                eprintln!(
2853                    "merge {}x{}: full-turn seam {theta:.4}: parameter area {area:.3e} vs same_sense {same_sense}",
2854                    older.id, newer.id
2855                );
2856            }
2857            continue;
2858        }
2859        // The merged face must reproduce the pieces' combined 3D area and
2860        // their combined volume term about the origin. The bar is what the
2861        // admitted trims can move: `band` off their edges along the whole
2862        // boundary (and that much times the farthest point for the volume
2863        // term), plus the quadrature's drift. A 5e-3 share of the area let
2864        // a 0.24 sliver through (BadBoolean, 2026-10-13); the volume term
2865        // sees a region of the right area in the wrong place, which the
2866        // area cannot.
2867        let actual = face_area(&merged).or_refuse(KernelStage::Sew, "face_area")?;
2868        let area_bar = band * perimeter + 1e-9 * expected_area.abs();
2869        if (actual - expected_area).abs() > area_bar {
2870            if debug {
2871                eprintln!(
2872                    "merge {}x{}: full-turn seam {theta:.4}: area {actual:.9} vs expected {expected_area:.9} (bar {area_bar:.3e})",
2873                    older.id, newer.id
2874                );
2875            }
2876            continue;
2877        }
2878        let actual_term =
2879            face_volume_contribution(&merged).or_refuse(KernelStage::Sew, "face_volume_contribution")?;
2880        let reach = bbox_lo.length().max(bbox_hi.length());
2881        let term_bar = band * perimeter * reach / 3.0 + 1e-9 * expected_term.abs().max(expected_area.abs());
2882        if (actual_term - expected_term).abs() > term_bar {
2883            if debug {
2884                eprintln!(
2885                    "merge {}x{}: full-turn seam {theta:.4}: volume term {actual_term:.9} vs expected {expected_term:.9} (bar {term_bar:.3e})",
2886                    older.id, newer.id
2887                );
2888            }
2889            continue;
2890        }
2891        if debug {
2892            eprintln!(
2893                "merge {}x{}: full-turn MERGE at seam {theta:.4}, {} loop(s); area {actual:.9} vs {expected_area:.9} (bar {area_bar:.3e}), volume term {actual_term:.9} vs {expected_term:.9} (bar {term_bar:.3e})",
2894                older.id,
2895                newer.id,
2896                merged.loops.len()
2897            );
2898        }
2899        return Ok(Some(merged));
2900    }
2901    Ok(None)
2902}
2903
2904
2905pub fn try_merge_connected_group(
2906    faces: &[FaceRecord],
2907    edges: &HashMap<u64, &EdgeRecord>,
2908    tolerance: f64,
2909    same_carrier_area_tolerance_ratio: f64,
2910    keep_unmerged: &[String],
2911) -> Result<Option<(Vec<usize>, FaceRecord)>, KernelRefusal> {
2912    for seed in 0..faces.len() {
2913        // A pinned face never seeds or joins a merge group.
2914        if face_is_pinned(&faces[seed], keep_unmerged) {
2915            continue;
2916        }
2917        let mut component = [seed].into_iter().collect::<HashSet<_>>();
2918        loop {
2919            let mut changed = false;
2920            for candidate in 0..faces.len() {
2921                if component.contains(&candidate)
2922                    || face_is_pinned(&faces[candidate], keep_unmerged)
2923                    || faces[candidate].same_sense != faces[seed].same_sense
2924                    || !same_surface(&faces[candidate].surface, &faces[seed].surface, 1e-7)
2925                {
2926                    continue;
2927                }
2928                let candidate_uses = faces[candidate]
2929                    .loops
2930                    .iter()
2931                    .flat_map(|loop_record| &loop_record.coedges);
2932                let adjacent = candidate_uses.into_iter().any(|candidate_use| {
2933                    !edges[&candidate_use.edge_id].degenerate
2934                        && component.iter().any(|member| {
2935                            faces[*member]
2936                                .loops
2937                                .iter()
2938                                .flat_map(|loop_record| &loop_record.coedges)
2939                                .any(|member_use| {
2940                                    member_use.edge_id == candidate_use.edge_id
2941                                        && member_use.forward != candidate_use.forward
2942                                })
2943                        })
2944                });
2945                if adjacent {
2946                    component.insert(candidate);
2947                    changed = true;
2948                }
2949            }
2950            if !changed {
2951                break;
2952            }
2953        }
2954        if component.len() < 2 {
2955            continue;
2956        }
2957
2958        let mut uses_by_edge = HashMap::<u64, Vec<CoedgeRecord>>::default();
2959        for index in &component {
2960            for coedge in faces[*index]
2961                .loops
2962                .iter()
2963                .flat_map(|loop_record| &loop_record.coedges)
2964            {
2965                uses_by_edge
2966                    .entry(coedge.edge_id)
2967                    .or_default()
2968                    .push(coedge.clone());
2969            }
2970        }
2971        if uses_by_edge.values().any(|uses| uses.len() > 2) {
2972            continue;
2973        }
2974        let internal = uses_by_edge
2975            .iter()
2976            .filter_map(|(edge_id, uses)| {
2977                (uses.len() == 2
2978                    && !edges[edge_id].degenerate
2979                    && uses[0].forward != uses[1].forward)
2980                    .then_some(*edge_id)
2981            })
2982            .collect::<HashSet<_>>();
2983        let remaining = uses_by_edge
2984            .into_iter()
2985            .filter(|(edge_id, _)| !internal.contains(edge_id))
2986            .flat_map(|(_, uses)| uses)
2987            .collect::<Vec<_>>();
2988        let space = SharedParameterSpace {
2989            surface: &faces[seed].surface,
2990            weld: crate::tolerance::assembler_weld(tolerance),
2991        };
2992        let Some(mut loops) = walk_cycles(remaining, edges, Some(&space)) else {
2993            continue;
2994        };
2995        if loops.is_empty() {
2996            continue;
2997        }
2998        loops.sort_by(|first, second| {
2999            let area = |loop_record: &LoopRecord| {
3000                parameter_space_area(&FaceRecord {
3001                    id: faces[seed].id,
3002                    surface: faces[seed].surface.clone(),
3003                    same_sense: faces[seed].same_sense,
3004                    loops: vec![loop_record.clone()],
3005                    name: None,
3006                })
3007                .map(f64::abs)
3008            };
3009            match (area(first), area(second)) {
3010                (Ok(a), Ok(b)) => b.total_cmp(&a),
3011                _ => std::cmp::Ordering::Equal,
3012            }
3013        });
3014        let merged = FaceRecord {
3015            id: faces[seed].id,
3016            surface: faces[seed].surface.clone(),
3017            same_sense: faces[seed].same_sense,
3018            loops,
3019            name: faces[seed].name.clone(),
3020        };
3021        let expected = component
3022            .iter()
3023            .map(|index| parameter_space_area(&faces[*index]))
3024            .collect::<Result<Vec<_>, _>>()
3025            .or_refuse(KernelStage::Sew, "healing.face_merge")?
3026            .into_iter()
3027            .sum::<f64>();
3028        let actual =
3029            parameter_space_area(&merged).or_refuse(KernelStage::Sew, "parameter_space_area")?;
3030        let area_tolerance = 1e-9f64.max(expected.abs() * same_carrier_area_tolerance_ratio);
3031        if (actual - expected).abs() > area_tolerance
3032            || (actual.abs() > 1e-12 && actual.is_sign_positive() != merged.same_sense)
3033        {
3034            continue;
3035        }
3036        let mut indices = component.into_iter().collect::<Vec<_>>();
3037        indices.sort_unstable();
3038        return Ok(Some((indices, merged)));
3039    }
3040    Ok(None)
3041}
3042
3043/// A face is PINNED out of the merge when its `name` contains any substring in
3044/// `keep_unmerged`: it never coalesces with a neighbour (in any merge lane) and
3045/// is emitted unchanged. An empty `keep_unmerged` pins nothing — the historical
3046/// behavior.
3047fn face_is_pinned(face: &FaceRecord, keep_unmerged: &[String]) -> bool {
3048    match &face.name {
3049        Some(name) => keep_unmerged
3050            .iter()
3051            .any(|needle| name.contains(needle.as_str())),
3052        None => false,
3053    }
3054}
3055
3056// Pairwise merge driver for one shell.
3057//
3058// `try_merge_pair` returns `None` for any two faces that share no
3059// non-degenerate edge, so the only candidates are edge-adjacent pairs; they
3060// are kept in a set ordered by the faces' original positions and evaluated
3061// smallest first. Faces stay in their original slots (a merged face keeps
3062// the lower slot, the absorbed face's slot is emptied), so that order never
3063// shifts. A rejected pair is dropped for good: `try_merge_pair` is a pure
3064// function of the two face records and the constant edge map, and a pair is
3065// re-queued only when one of its faces changes. Hence each accepted merge is
3066// the lexicographically first accepting pair over all faces — the same pair
3067// the former full rescan found — and the result is the same face set, in
3068// the same order, reached without re-examining every pair per merge.
3069thread_local! {
3070    /// Pairs [`try_merge_pair`] declined, by [`pair_identity`]: everything the
3071    /// pair test reads. A boolean hands the face merge every edge-adjacent
3072    /// pair of its result, and all but the pairs it touched are the pairs the
3073    /// boolean before it declined (a bore's two half-turn walls reach the
3074    /// full-turn lane and stay apart, each time).
3075    static DECLINED_PAIRS: std::cell::RefCell<HashSet<[u64; 2]>> = std::cell::RefCell::new(HashSet::default());
3076    static DECLINES_SERVED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3077}
3078
3079thread_local! {
3080    /// Partial-turn area checks the boundary reading decided, and those it
3081    /// handed to the surface integration, since the thread started.
3082    static BOUNDARY_AREA_CHECKS: std::cell::Cell<(usize, usize)> = const { std::cell::Cell::new((0, 0)) };
3083}
3084
3085/// `(decided, handed on)` by [`boundary_areas_agree`] since the thread started.
3086pub fn boundary_area_checks() -> (usize, usize) {
3087    BOUNDARY_AREA_CHECKS.with(|counts| counts.get())
3088}
3089
3090/// `BREP_MERGE_AREA_BOUNDARY` (default on; `=0` restores the surface integration): the partial-turn lane's area
3091/// check reads the three areas as boundary integrals first
3092/// ([`translational_boundary_area`]) and integrates over the surfaces only
3093/// when that reading cannot admit the merge.
3094fn boundary_area_check_on() -> bool {
3095    switch!("BREP_MERGE_AREA_BOUNDARY", true)
3096}
3097
3098/// How far below the area check's 5e-3 the boundary reading must find the
3099/// merged face's area from the two parts' before it admits the merge unread
3100/// by the surface integration: a tenth of the bar. The boundary reading is
3101/// itself held to [`BOUNDARY_AREA_SETTLED`], four orders tighter.
3102const BOUNDARY_AREA_ADMIT: f64 = 5e-4;
3103
3104/// The relative agreement between the boundary reading's two resolutions
3105/// below which it is taken as settled.
3106const BOUNDARY_AREA_SETTLED: f64 = 1e-7;
3107
3108/// Whether the boundary reading admits `merged` as the two parts' combined
3109/// area: all three faces read, and the merged area within
3110/// [`BOUNDARY_AREA_ADMIT`] of the sum. `false` decides nothing; the caller
3111/// then integrates as it always did, so a merge is never declined here.
3112fn boundary_areas_agree(older: &FaceRecord, newer: &FaceRecord, merged: &FaceRecord) -> bool {
3113    if !boundary_area_check_on() {
3114        return false;
3115    }
3116    let agreed = (|| {
3117        let expected = translational_boundary_area(older)? + translational_boundary_area(newer)?;
3118        let actual = translational_boundary_area(merged)?;
3119        Some((actual - expected).abs() <= expected.abs().max(1e-9) * BOUNDARY_AREA_ADMIT)
3120    })()
3121    .unwrap_or(false);
3122    BOUNDARY_AREA_CHECKS.with(|counts| {
3123        let (decided, handed_on) = counts.get();
3124        counts.set(if agreed { (decided + 1, handed_on) } else { (decided, handed_on + 1) });
3125    });
3126    agreed
3127}
3128
3129/// The widest ratio between a carrier's u weights the boundary reading
3130/// accepts.
3131const BOUNDARY_CARRIER_WEIGHT_RATIO: f64 = 4.0;
3132
3133const BOUNDARY_GAUSS_X: [f64; 4] = [0.1834346424956498, 0.5255324099163290, 0.7966664774136267, 0.9602898564975363];
3134const BOUNDARY_GAUSS_W: [f64; 4] = [0.3626837833783620, 0.3137066458778873, 0.2223810344533745, 0.1012285362903763];
3135
3136/// The area of a face on a TRANSLATIONAL carrier, `S(u, v) = C(u) + s(v) D`
3137/// with `s` linear (a cylinder patch, a linear sweep), read on its trim
3138/// boundary alone. The area element there is `g(u) du dv` with
3139/// `g(u) = |C'(u) x D| s'`, a function of `u` only, so by Green's theorem
3140/// the area inside the loops is `-∮ v g(u) du`: one carrier derivative per
3141/// boundary station and no cell of the surface. `v` is read from the
3142/// domain's start, so the sum does not cancel against an offset of the
3143/// parameterization. Each joint that misses is closed by its straight
3144/// chord, as the trim polygons close it.
3145///
3146/// `None` (the caller integrates over the surface) unless every condition
3147/// the identity needs holds: the carrier is degree 1 across two control
3148/// columns that differ by one vector with equal weights, its u weights
3149/// within [`BOUNDARY_CARRIER_WEIGHT_RATIO`] of one another; it is closed in
3150/// neither direction, so no loop steps a seam; every pcurve is polynomial
3151/// (equal weights); every boundary station lies inside the carrier's domain; and the reading at eight stations per
3152/// pcurve span (cut where it crosses a knot line of the carrier, across
3153/// which `g` has a kink) agrees with the reading at sixteen to
3154/// [`BOUNDARY_AREA_SETTLED`].
3155fn translational_boundary_area(face: &FaceRecord) -> Option<f64> {
3156    let surface = &face.surface;
3157    if surface.degree_v != 1 || surface.control_points.len() < 2 || surface.knots_v.len() != 4 {
3158        return None;
3159    }
3160    let closed = surface.closed_directions().ok()?;
3161    if closed != (false, false) && !(boundary_area_closed_on() && loops_close_in_the_chart(face)?) {
3162        return None;
3163    }
3164    // One sweep vector, equal weights across each row, and along u weights
3165    // no further apart than a circular arc's (a span of 120 degrees weighs
3166    // its middle control 1/2): a carrier re-weighted beyond that can gather
3167    // g next to a knot, where no fixed rule finds it.
3168    let mut sweep: Option<Vec3> = None;
3169    let mut scale = 0.0f64;
3170    let (mut lightest, mut heaviest) = (f64::INFINITY, 0.0f64);
3171    for row in &surface.control_points {
3172        let [low, high] = row.as_slice() else { return None };
3173        if !(low.w > 0.0) || low.w != high.w {
3174            return None;
3175        }
3176        lightest = lightest.min(low.w);
3177        heaviest = heaviest.max(low.w);
3178        let (low, high) = (low.point().ok()?, high.point().ok()?);
3179        scale = scale.max(low.length()).max(high.length());
3180        let step = high.sub(low);
3181        match sweep {
3182            None => sweep = Some(step),
3183            Some(first) if step.sub(first).length() <= 1e-12 * scale.max(first.length()) => {}
3184            Some(_) => return None,
3185        }
3186    }
3187    let sweep = sweep?;
3188    if !(sweep.length() > 0.0) || heaviest > lightest * BOUNDARY_CARRIER_WEIGHT_RATIO {
3189        return None;
3190    }
3191    let [u0, u1] = surface.domain_u().ok()?;
3192    let [v0, v1] = surface.domain_v().ok()?;
3193    let (slack_u, slack_v) = ((u1 - u0) * 1e-9, (v1 - v0) * 1e-9);
3194    // The carrier's u knot lines: g has a kink across each, so a pcurve span
3195    // is cut where it crosses one.
3196    let mut levels = vec![u0];
3197    levels.extend(crate::curve::interior_knots(&surface.knots_u, surface.degree_u));
3198    levels.push(u1);
3199    // g(u): the carrier's u derivative on the first column crossed with the
3200    // sweep, per unit v.
3201    let density = |u: f64| -> Option<f64> {
3202        let (_, along, _) = surface.deriv1(u, v0).ok()?;
3203        Some(along.cross(sweep).length() / (v1 - v0))
3204    };
3205    // -∫ v g(u) du along one parameter-plane path, at `panels` eight-point
3206    // panels; `path(t)` returns `(u, v, du/dt)` on [a, b].
3207    let path_integral = |path: &dyn Fn(f64) -> Option<(f64, f64, f64)>, a: f64, b: f64, panels: usize| -> Option<f64> {
3208        let mut total = 0.0;
3209        let width = (b - a) / panels as f64;
3210        for panel in 0..panels {
3211            let middle = a + width * (panel as f64 + 0.5);
3212            let half = width * 0.5;
3213            for (x, w) in BOUNDARY_GAUSS_X.iter().zip(&BOUNDARY_GAUSS_W) {
3214                for side in [-1.0, 1.0] {
3215                    let (u, v, du) = path(middle + side * half * x)?;
3216                    if u < u0 - slack_u || u > u1 + slack_u || v < v0 - slack_v || v > v1 + slack_v {
3217                        return None;
3218                    }
3219                    total -= w * half * (v - v0) * density(u.clamp(u0, u1))? * du;
3220                }
3221            }
3222        }
3223        Some(total)
3224    };
3225    let read = |panels: usize| -> Option<f64> {
3226        let mut area = 0.0;
3227        for loop_record in &face.loops {
3228            let count = loop_record.coedges.len();
3229            for (index, coedge) in loop_record.coedges.iter().enumerate() {
3230                let pcurve = &coedge.pcurve;
3231                // A rational pcurve can gather its whole sweep next to one
3232                // end, where no fixed rule finds it: only polynomial trims
3233                // are read.
3234                let weight = pcurve.control_points.first()?.w;
3235                if pcurve.control_points.iter().any(|control| control.w != weight) {
3236                    return None;
3237                }
3238                let [start, end] = pcurve.domain().ok()?;
3239                let mut breaks = vec![start];
3240                breaks.extend(crate::curve::interior_knots(&pcurve.knots, pcurve.degree));
3241                breaks.push(end);
3242                let breaks = crate::mass_properties::split_at_surface_breaks(pcurve, breaks, &levels, u1 - u0, true, false).ok()?;
3243                let along = |t: f64| -> Option<(f64, f64, f64)> {
3244                    let (point, tangent) = pcurve.deriv1(t).ok()?;
3245                    Some((point.x, point.y, tangent.x))
3246                };
3247                for pair in breaks.windows(2) {
3248                    area += path_integral(&along, pair[0], pair[1], panels)?;
3249                }
3250                // The joint to the next coedge, closed by its chord.
3251                let next = &loop_record.coedges[(index + 1) % count].pcurve;
3252                let here = pcurve.evaluate(end).ok()?;
3253                let there = next.evaluate(next.domain().ok()?[0]).ok()?;
3254                if here.x != there.x || here.y != there.y {
3255                    let chord = |t: f64| -> Option<(f64, f64, f64)> {
3256                        Some((here.x + (there.x - here.x) * t, here.y + (there.y - here.y) * t, there.x - here.x))
3257                    };
3258                    let mut cuts = vec![0.0];
3259                    if there.x != here.x {
3260                        let mut crossings: Vec<f64> = levels.iter().map(|level| (level - here.x) / (there.x - here.x)).filter(|t| *t > 0.0 && *t < 1.0).collect();
3261                        crossings.sort_by(f64::total_cmp);
3262                        cuts.extend(crossings);
3263                    }
3264                    cuts.push(1.0);
3265                    for pair in cuts.windows(2) {
3266                        area += path_integral(&chord, pair[0], pair[1], panels)?;
3267                    }
3268                }
3269            }
3270        }
3271        Some(area.abs())
3272    };
3273    let (coarse, fine) = (read(1)?, read(2)?);
3274    ((fine - coarse).abs() <= fine.abs() * BOUNDARY_AREA_SETTLED && fine.is_finite()).then_some(fine)
3275}
3276
3277/// `BREP_MERGE_AREA_BOUNDARY_CLOSED` (default on since 2026-11-19; `=0` leaves
3278/// every closed carrier to the surface integration): [`translational_boundary_area`]
3279/// also reads a face on a carrier closed in u (a full cylinder) when every
3280/// one of its loops closes in the carrier's own chart
3281/// ([`loops_close_in_the_chart`]).
3282fn boundary_area_closed_on() -> bool {
3283    switch!("BREP_MERGE_AREA_BOUNDARY_CLOSED", true)
3284}
3285
3286/// Whether every loop of `face` closes in its carrier's parameter chart:
3287/// each coedge's pcurve ends within a billionth of the chart's width of
3288/// where the next one starts, in both parameters.
3289///
3290/// On a closed carrier that is what lets Green's theorem read the face on
3291/// its boundary as on an open one. A loop that winds around the closed
3292/// direction (a full-turn rim, whose end lies a period from its start) or
3293/// hops the carrier's implicit seam (one pcurve ends on one side of the
3294/// chart, the next starts on the other) has a joint a period wide; the chord
3295/// that closes a joint would cross the whole chart, and the surface
3296/// integral reads such faces on routes of their own (winding bands, caps,
3297/// walls, the unwrapped covering plane). Those are left to it: `Some(false)`.
3298/// A loop of plain joints bounds the region it encloses in the chart, which
3299/// the integral reads on its in-domain path.
3300fn loops_close_in_the_chart(face: &FaceRecord) -> Option<bool> {
3301    let [u0, u1] = face.surface.domain_u().ok()?;
3302    let [v0, v1] = face.surface.domain_v().ok()?;
3303    let (gap_u, gap_v) = ((u1 - u0) * 1e-9, (v1 - v0) * 1e-9);
3304    for loop_record in &face.loops {
3305        let count = loop_record.coedges.len();
3306        if count == 0 {
3307            return Some(false);
3308        }
3309        for (index, coedge) in loop_record.coedges.iter().enumerate() {
3310            let next = &loop_record.coedges[(index + 1) % count].pcurve;
3311            let here = coedge.pcurve.evaluate(coedge.pcurve.domain().ok()?[1]).ok()?;
3312            let there = next.evaluate(next.domain().ok()?[0]).ok()?;
3313            if !((here.x - there.x).abs() <= gap_u && (here.y - there.y).abs() <= gap_v) {
3314                return Some(false);
3315            }
3316        }
3317    }
3318    Some(true)
3319}
3320
3321/// `BREP_MERGE_DECLINE_MEMO` (default on, `0` off): a pair whose content was declined
3322/// before is declined unread. Off under the reading memo's hatch
3323/// (`BREP_READING_MEMO=0`) and the merge's own trace (`BREP_DEBUG_MERGE`).
3324/// The most coedges a pair may hold, both faces together, for the decline
3325/// memo to read its identity.
3326const DECLINE_MEMO_COEDGES: usize = 32;
3327
3328fn decline_memo_on() -> bool {
3329    switch!("BREP_MERGE_DECLINE_MEMO", true)
3330        && crate::reading_memo::memo_on()
3331        && std::env::var_os("BREP_DEBUG_MERGE").is_none()
3332}
3333
3334/// Drop every memoised decline (`reading_memo::clear`).
3335pub fn clear_decline_memo() {
3336    DECLINED_PAIRS.with(|memo| memo.borrow_mut().clear());
3337}
3338
3339/// Declines served from the memo since the thread started.
3340pub fn declines_served() -> usize {
3341    DECLINES_SERVED.with(|served| served.get())
3342}
3343
3344/// One face's content as the pair test reads it, ids apart: the carrier and
3345/// sense, and per loop each coedge's sense, pcurve and edge (curve, domain,
3346/// degenerate flag) in order.
3347fn face_merge_content(face: &FaceRecord, edges: &HashMap<u64, &EdgeRecord>) -> [u64; 2] {
3348    let mut lane = crate::mass_properties::TwoLane::new();
3349    crate::mass_properties::hash_surface(&mut lane, &face.surface);
3350    lane.bool(face.same_sense);
3351    lane.usize(face.loops.len());
3352    for loop_record in &face.loops {
3353        lane.usize(loop_record.coedges.len());
3354        for coedge in &loop_record.coedges {
3355            let edge = edges[&coedge.edge_id];
3356            lane.bool(coedge.forward);
3357            crate::mass_properties::hash_curve(&mut lane, &coedge.pcurve);
3358            crate::mass_properties::hash_curve(&mut lane, &edge.curve);
3359            lane.f64(edge.t0);
3360            lane.f64(edge.t1);
3361            lane.bool(edge.degenerate);
3362        }
3363    }
3364    lane.finish()
3365}
3366
3367/// The identity of one ordered pair for the pair test: the two contents, the
3368/// two tolerances, and every coedge, edge and vertex id of the pair replaced
3369/// by its rank among the pair's ids of that kind (which uses share an edge or
3370/// a vertex, and every order between ids, without the ids themselves, which
3371/// an assembly mints anew).
3372fn pair_identity(
3373    contents: [[u64; 2]; 2],
3374    faces: [&FaceRecord; 2],
3375    edges: &HashMap<u64, &EdgeRecord>,
3376    tolerance: f64,
3377    same_carrier_area_tolerance_ratio: f64,
3378) -> [u64; 2] {
3379    let uses = || faces.into_iter().flat_map(|face| face.loops.iter().flat_map(|loop_record| &loop_record.coedges));
3380    let ranked = |mut ids: Vec<u64>| {
3381        ids.sort_unstable();
3382        ids.dedup();
3383        ids
3384    };
3385    let coedge_ids = ranked(uses().map(|coedge| coedge.id).collect());
3386    let edge_ids = ranked(uses().map(|coedge| coedge.edge_id).collect());
3387    let vertex_ids = ranked(
3388        uses()
3389            .flat_map(|coedge| {
3390                let edge = edges[&coedge.edge_id];
3391                [edge.start_vertex_id, edge.end_vertex_id]
3392            })
3393            .collect(),
3394    );
3395    let rank = |ids: &[u64], id: u64| ids.binary_search(&id).unwrap_or(usize::MAX);
3396    let mut lane = crate::mass_properties::TwoLane::new();
3397    for content in contents {
3398        lane.u64(content[0]);
3399        lane.u64(content[1]);
3400    }
3401    lane.f64(tolerance);
3402    lane.f64(same_carrier_area_tolerance_ratio);
3403    // The two process switches the pair test reads: a decline stored under
3404    // one setting is not the reading under the other.
3405    lane.bool(shared_trim_certificate_enabled());
3406    lane.bool(std::env::var("BREP_FULL_TURN_MERGE").as_deref() == Ok("0"));
3407    lane.bool(boundary_area_check_on());
3408    for coedge in uses() {
3409        let edge = edges[&coedge.edge_id];
3410        lane.usize(rank(&coedge_ids, coedge.id));
3411        lane.usize(rank(&edge_ids, coedge.edge_id));
3412        lane.usize(rank(&vertex_ids, edge.start_vertex_id));
3413        lane.usize(rank(&vertex_ids, edge.end_vertex_id));
3414    }
3415    lane.finish()
3416}
3417
3418struct PairMerger<'a> {
3419    /// Each slot's [`face_merge_content`], read on first use and dropped when
3420    /// a merge rebuilds the slot.
3421    contents: Vec<Option<[u64; 2]>>,
3422    slots: Vec<Option<FaceRecord>>,
3423    pinned: Vec<bool>,
3424    edges: &'a HashMap<u64, &'a EdgeRecord>,
3425    /// Non-degenerate edge id → slots of the faces using it.
3426    uses: HashMap<u64, Vec<usize>>,
3427    /// Edge-adjacent pairs `(lower slot, higher slot)` not yet rejected.
3428    candidates: std::collections::BTreeSet<(usize, usize)>,
3429    /// Ids of the faces this merger built (the surviving id of each pair).
3430    merged_ids: Vec<u64>,
3431}
3432
3433impl<'a> PairMerger<'a> {
3434    fn new(
3435        faces: Vec<FaceRecord>,
3436        edges: &'a HashMap<u64, &'a EdgeRecord>,
3437        keep_unmerged: &[String],
3438    ) -> Self {
3439        let pinned = faces
3440            .iter()
3441            .map(|face| face_is_pinned(face, keep_unmerged))
3442            .collect::<Vec<_>>();
3443        let mut merger = Self {
3444            contents: vec![None; faces.len()],
3445            slots: faces.into_iter().map(Some).collect(),
3446            pinned,
3447            edges,
3448            uses: HashMap::default(),
3449            candidates: std::collections::BTreeSet::new(),
3450            merged_ids: Vec::new(),
3451        };
3452        for slot in 0..merger.slots.len() {
3453            merger.index_slot(slot);
3454        }
3455        merger
3456    }
3457
3458    fn slot_edge_ids(&self, slot: usize) -> Vec<u64> {
3459        let Some(face) = &self.slots[slot] else {
3460            return Vec::new();
3461        };
3462        let mut ids = face
3463            .loops
3464            .iter()
3465            .flat_map(|loop_record| &loop_record.coedges)
3466            .map(|coedge| coedge.edge_id)
3467            .filter(|edge_id| !self.edges[edge_id].degenerate)
3468            .collect::<Vec<_>>();
3469        ids.sort_unstable();
3470        ids.dedup();
3471        ids
3472    }
3473
3474    /// Register `slot`'s edges and queue it against every face already
3475    /// using one of them.
3476    fn index_slot(&mut self, slot: usize) {
3477        for edge_id in self.slot_edge_ids(slot) {
3478            let users = self.uses.entry(edge_id).or_default();
3479            for &other in users.iter() {
3480                if other != slot && !self.pinned[other] && !self.pinned[slot] {
3481                    self.candidates.insert((other.min(slot), other.max(slot)));
3482                }
3483            }
3484            users.push(slot);
3485        }
3486    }
3487
3488    fn unindex_slot(&mut self, slot: usize) {
3489        for edge_id in self.slot_edge_ids(slot) {
3490            if let Some(users) = self.uses.get_mut(&edge_id) {
3491                users.retain(|user| *user != slot);
3492            }
3493        }
3494        self.candidates
3495            .retain(|(lower, higher)| *lower != slot && *higher != slot);
3496    }
3497
3498    /// Perform up to `budget` merges; returns how many were made.
3499    fn run(
3500        &mut self,
3501        budget: usize,
3502        tolerance: f64,
3503        same_carrier_area_tolerance_ratio: f64,
3504    ) -> Result<usize, KernelRefusal> {
3505        let mut merged_count = 0;
3506        while merged_count < budget {
3507            let Some(&(lower, higher)) = self.candidates.iter().next() else {
3508                break;
3509            };
3510            self.candidates.remove(&(lower, higher));
3511            let (Some(older), Some(newer)) = (&self.slots[lower], &self.slots[higher]) else {
3512                continue;
3513            };
3514            // The identity walks every coedge of both faces, so it is read
3515            // only for a small pair: a face with a long boundary (a plate
3516            // around many holes) meets each neighbour in a pair the test
3517            // declines at once, more cheaply than the identity is hashed.
3518            let small = [older, newer].iter().map(|face| face.loops.iter().map(|loop_record| loop_record.coedges.len()).sum::<usize>()).sum::<usize>()
3519                <= DECLINE_MEMO_COEDGES;
3520            let identity = (small && decline_memo_on()).then(|| {
3521                let contents = [(lower, older), (higher, newer)]
3522                    .map(|(slot, face)| *self.contents[slot].get_or_insert_with(|| face_merge_content(face, self.edges)));
3523                pair_identity(contents, [older, newer], self.edges, tolerance, same_carrier_area_tolerance_ratio)
3524            });
3525            if identity.is_some_and(|identity| DECLINED_PAIRS.with(|memo| memo.borrow().contains(&identity))) {
3526                DECLINES_SERVED.with(|served| served.set(served.get() + 1));
3527                crate::reading_memo::note(true);
3528                continue;
3529            }
3530            let Some(merged) = try_merge_pair(
3531                older,
3532                newer,
3533                self.edges,
3534                tolerance,
3535                same_carrier_area_tolerance_ratio,
3536            )?
3537            else {
3538                if let Some(identity) = identity {
3539                    crate::reading_memo::note(false);
3540                    DECLINED_PAIRS.with(|memo| {
3541                        let mut memo = memo.borrow_mut();
3542                        if memo.len() >= crate::reading_memo::capacity() {
3543                            memo.clear();
3544                        }
3545                        memo.insert(identity);
3546                    });
3547                }
3548                continue;
3549            };
3550            self.contents[lower] = None;
3551            self.contents[higher] = None;
3552            self.unindex_slot(higher);
3553            self.unindex_slot(lower);
3554            self.slots[higher] = None;
3555            self.merged_ids.push(merged.id);
3556            self.slots[lower] = Some(merged);
3557            self.index_slot(lower);
3558            merged_count += 1;
3559        }
3560        Ok(merged_count)
3561    }
3562
3563    fn into_faces(self) -> Vec<FaceRecord> {
3564        self.slots.into_iter().flatten().collect()
3565    }
3566}
3567
3568/// Merge adjacent fragments that retain the exact same carrier surface.
3569///
3570/// Every shared edge is cancelled in opposite directions and the remaining
3571/// coedges are stitched into outer/hole cycles without refitting geometry.
3572fn merge_same_surface_faces_impl(
3573    solid: &BrepSolid,
3574    tolerance: f64,
3575    validate: bool,
3576    same_carrier_area_tolerance_ratio: f64,
3577    keep_unmerged: &[String],
3578    validation_scope: Option<&HashSet<u64>>,
3579) -> Result<BrepSolid, KernelRefusal> {
3580    let mut result = solid.clone();
3581    let mut merged_ids: Vec<u64> = Vec::new();
3582    // `result.edges` is not touched until the retain below, so the id map is
3583    // built once; every candidate pair sees the same edge records.
3584    let edges = result
3585        .edges
3586        .iter()
3587        .map(|edge| (edge.id, edge))
3588        .collect::<HashMap<_, _>>();
3589    for shell in &mut result.shells {
3590        loop {
3591            if !validate {
3592                if let Some((indices, merged)) = try_merge_connected_group(
3593                    &shell.faces,
3594                    &edges,
3595                    tolerance,
3596                    same_carrier_area_tolerance_ratio,
3597                    keep_unmerged,
3598                )? {
3599                    let first = indices[0];
3600                    shell.faces[first] = merged;
3601                    for index in indices.into_iter().skip(1).rev() {
3602                        shell.faces.remove(index);
3603                    }
3604                    continue;
3605                }
3606            }
3607            // The validating lane has no group phase, so it drains every pair
3608            // merge in one pass; the open lane merges one pair, then offers
3609            // the changed shell to the group phase again, exactly as before.
3610            let budget = if validate { usize::MAX } else { 1 };
3611            let mut merger = PairMerger::new(
3612                std::mem::take(&mut shell.faces),
3613                &edges,
3614                keep_unmerged,
3615            );
3616            let merged = merger.run(budget, tolerance, same_carrier_area_tolerance_ratio);
3617            merged_ids.extend(merger.merged_ids.iter().copied());
3618            shell.faces = merger.into_faces();
3619            if merged? == 0 || validate {
3620                break;
3621            }
3622        }
3623    }
3624    // The validation reads the geometry of the caller's scope and of every
3625    // face this merge built; a face outside both left this pass as it came.
3626    let validation_scope = validation_scope.map(|scope| {
3627        let mut scope = scope.clone();
3628        scope.extend(merged_ids);
3629        scope
3630    });
3631    finish_merge(solid, result, validate, validation_scope.as_ref())
3632}
3633
3634/// Merge each face in `absorbed` into an edge-adjacent face outside `absorbed`
3635/// that rides the same carrier — the pair [`merge_same_surface_faces`] would
3636/// merge, at the same `tolerance` — and nothing else.
3637///
3638/// The absorbing face keeps its id, its name and its slot in the shell, and
3639/// its carrier is the frame the merged face is built on; a face in `absorbed`
3640/// that shares a carrier with no such neighbour is left as it was. Two faces
3641/// outside `absorbed` are never merged with each other, however cosurface: the
3642/// caller is naming whose material a face is, not normalizing the solid, so a
3643/// coplanar pair the document kept apart stays apart. The result passes the
3644/// validating merge's Euler and `validate()` checks or the call refuses.
3645pub fn absorb_faces_into_carriers(
3646    solid: &BrepSolid,
3647    tolerance: f64,
3648    absorbed: &HashSet<u64>,
3649) -> Result<BrepSolid, KernelRefusal> {
3650    let mut result = solid.clone();
3651    let edges = result
3652        .edges
3653        .iter()
3654        .map(|edge| (edge.id, edge))
3655        .collect::<HashMap<_, _>>();
3656    let edge_ids = |face: &FaceRecord| -> HashSet<u64> {
3657        face.loops
3658            .iter()
3659            .flat_map(|loop_record| &loop_record.coedges)
3660            .map(|coedge| coedge.edge_id)
3661            .filter(|edge_id| !edges[edge_id].degenerate)
3662            .collect()
3663    };
3664    for shell in &mut result.shells {
3665        'merge: loop {
3666            for inner in 0..shell.faces.len() {
3667                if !absorbed.contains(&shell.faces[inner].id) {
3668                    continue;
3669                }
3670                let inner_edges = edge_ids(&shell.faces[inner]);
3671                for outer in 0..shell.faces.len() {
3672                    if outer == inner
3673                        || absorbed.contains(&shell.faces[outer].id)
3674                        || edge_ids(&shell.faces[outer]).is_disjoint(&inner_edges)
3675                    {
3676                        continue;
3677                    }
3678                    let Some(merged) =
3679                        try_merge_pair(&shell.faces[outer], &shell.faces[inner], &edges, tolerance, 1e-7)?
3680                    else {
3681                        continue;
3682                    };
3683                    shell.faces[outer] = merged;
3684                    shell.faces.remove(inner);
3685                    continue 'merge;
3686                }
3687            }
3688            break;
3689        }
3690    }
3691    finish_merge(solid, result, true, None)
3692}
3693
3694/// Rebuild the cone face `id` on one carrier holding all its trims, every trim
3695/// re-read from its 3D edge, with its apex pole stitched back. A blend end grows
3696/// such a face past its old chart. False when it is not a ruled cone patch or the
3697/// rebuilt face does not close.
3698pub fn recarry_cone_apex_face(solid: &mut BrepSolid, id: u64, tolerance: f64) -> Result<bool, KernelRefusal> {
3699    let Some(face) = solid.shells.iter().flat_map(|shell| &shell.faces).find(|face| face.id == id).cloned() else {
3700        return Ok(false);
3701    };
3702    let Some(support) = ruled_cylinder_support(&face, tolerance, true, true)? else {
3703        return Ok(false);
3704    };
3705    let edges = solid.edges.iter().map(|edge| (edge.id, edge)).collect::<HashMap<_, _>>();
3706    let mut apex = None;
3707    let mut loops = face.loops.clone();
3708    for loop_record in &mut loops {
3709        loop_record.coedges.retain(|coedge| {
3710            let pole = edges[&coedge.edge_id].degenerate;
3711            if pole && apex.is_none() {
3712                apex = Some(coedge.clone());
3713            }
3714            !pole
3715        });
3716    }
3717    let seed = {
3718        let Some(point) = loops.iter().flat_map(|l| &l.coedges).find_map(|coedge| {
3719            let edge = edges[&coedge.edge_id];
3720            let [a, b] = [edge.curve.evaluate(edge.t0).ok()?, edge.curve.evaluate(edge.t1).ok()?];
3721            let radial = |p: Vec3| { let d = p.sub(support.origin); d.sub(support.axis.scale(d.dot(support.axis))) };
3722            if radial(a).length() > radial(b).length() { Some(radial(a)) } else { Some(radial(b)) }
3723        }) else {
3724            return Ok(false);
3725        };
3726        point.normalized().or_refuse(KernelStage::Sew, "normalized")?
3727    };
3728    let y_reference = support.axis.cross(seed);
3729    let mut angles = Vec::new();
3730    let mut axial_range = [f64::INFINITY, f64::NEG_INFINITY];
3731    for coedge in loops.iter().flat_map(|l| &l.coedges) {
3732        let edge = edges[&coedge.edge_id];
3733        let curve = trimmed_curve(&edge.curve, edge.t0, edge.t1)?;
3734        let [c0, c1] = curve.domain().or_refuse(KernelStage::Sew, "domain")?;
3735        let hull = axial_hull(&curve, &support);
3736        axial_range[0] = axial_range[0].min(hull[0]);
3737        axial_range[1] = axial_range[1].max(hull[1]);
3738        for index in 0..=32 {
3739            let delta = curve.evaluate(c0 + (c1 - c0) * index as f64 / 32.0).or_refuse(KernelStage::Sew, "evaluate")?.sub(support.origin);
3740            let radial = delta.sub(support.axis.scale(delta.dot(support.axis)));
3741            if radial.length() > (support.radius * 1e-6).max(tolerance) {
3742                angles.push(radial.dot(y_reference).atan2(radial.dot(seed)).rem_euclid(std::f64::consts::TAU));
3743            }
3744        }
3745    }
3746    if angles.len() < 3 {
3747        return Ok(false);
3748    }
3749    angles.sort_by(f64::total_cmp);
3750    let (mut gap_start, mut largest) = (angles.len() - 1, angles[0] + std::f64::consts::TAU - angles[angles.len() - 1]);
3751    for index in 0..angles.len() - 1 {
3752        if angles[index + 1] - angles[index] > largest {
3753            largest = angles[index + 1] - angles[index];
3754            gap_start = index;
3755        }
3756    }
3757    let span = std::f64::consts::TAU - largest;
3758    if span <= tolerance || span >= std::f64::consts::TAU - 1e-6 {
3759        return Ok(false);
3760    }
3761    let start = angles[(gap_start + 1) % angles.len()];
3762    let direction = seed.scale(start.cos()).add(y_reference.scale(start.sin()));
3763    let end_radius = |axial: f64| { let radius = support.radius_at(axial); if radius.abs() <= tolerance { 0.0 } else { radius } };
3764    let at = |axial: f64| support.origin.add(support.axis.scale(axial)).add(direction.scale(end_radius(axial)));
3765    let generatrix = make_line(at(axial_range[0]), at(axial_range[1])).or_refuse(KernelStage::Sew, "healing.face_merge")?;
3766    let surface = make_revolution(support.origin, support.axis, &generatrix, span).or_refuse(KernelStage::Sew, "make_revolution")?;
3767    let (u_domain, v_domain) = surface_domains(&surface)?;
3768    let (mid_u, mid_v) = ((u_domain[0] + u_domain[1]) / 2.0, (v_domain[0] + v_domain[1]) / 2.0);
3769    let delta = surface.evaluate(mid_u, mid_v).or_refuse(KernelStage::Sew, "evaluate")?.sub(support.origin);
3770    let radial = delta.sub(support.axis.scale(delta.dot(support.axis))).normalized().or_refuse(KernelStage::Sew, "normalized")?;
3771    let same_sense = surface.normal(mid_u, mid_v).or_refuse(KernelStage::Sew, "normal")?.dot(radial).signum() == support.outward_radial_sign;
3772    let mut projected = reproject_loops(&surface, loops, &edges)?;
3773    if let Some(apex) = &apex {
3774        if !stitch_cone_apex(&surface, &mut projected, apex, &edges)? {
3775            return Ok(false);
3776        }
3777    }
3778    let rebuilt = FaceRecord { id, surface, same_sense, loops: projected, name: face.name.clone() };
3779    let area = parameter_space_area(&rebuilt).or_refuse(KernelStage::Sew, "parameter_space_area")?;
3780    if area.abs() <= tolerance * tolerance || area.is_sign_positive() != rebuilt.same_sense {
3781        return Ok(false);
3782    }
3783    drop(edges);
3784    for shell in &mut solid.shells {
3785        if let Some(slot) = shell.faces.iter_mut().find(|face| face.id == id) {
3786            *slot = rebuilt;
3787            return Ok(true);
3788        }
3789    }
3790    Ok(false)
3791}
3792
3793/// Merge edge-adjacent faces of `group` that ride the same carrier — the
3794/// pairs [`merge_same_surface_faces`] would merge, at the same `tolerance`,
3795/// plus two lanes only a user's selection opts into: cone patches, and two
3796/// half-turn patches closing a ring on a shared axial edge (see
3797/// `MergeLanes`) — and nothing else: a face outside `group` is never touched,
3798/// however cosurface with a neighbour.
3799///
3800/// Cancelling a shared edge leaves its end vertices between two pieces of one
3801/// rim (the two half circles a split bore's halves each bounded); those
3802/// pieces are joined into one edge where they continue each other exactly
3803/// (`merge_curve_continuation_edges_at`, at those vertices only), so the merged
3804/// face carries the closed rims a face built whole carries.
3805///
3806/// The surviving face of each merged pair is the one in the lower shell slot;
3807/// it keeps its id and name. Returns the merged solid and, for every face id
3808/// of `group` (sorted, deduplicated), the pair `(face, carrier)` naming the
3809/// face that now carries it (itself when it did not merge). The result passes
3810/// the validating merge's Euler and `validate()` checks, scoped to the merged
3811/// faces, or the call refuses.
3812///
3813/// Push Face uses it to treat the halves of a split carrier the user selected
3814/// together (an imported bore written as two half cylinders) as the one face
3815/// the push moves: a half pushed alone can never meet its unmoved sibling.
3816pub fn merge_faces_within(
3817    solid: &BrepSolid,
3818    tolerance: f64,
3819    group: &[u64],
3820) -> Result<(BrepSolid, Vec<(u64, u64)>), KernelRefusal> {
3821    let group: HashSet<u64> = group.iter().copied().collect();
3822    let mut carried_by: Vec<(u64, u64)> = group.iter().map(|id| (*id, *id)).collect();
3823    carried_by.sort_unstable();
3824    let mut result = solid.clone();
3825    let edges = result
3826        .edges
3827        .iter()
3828        .map(|edge| (edge.id, edge))
3829        .collect::<HashMap<_, _>>();
3830    let edge_ids = |face: &FaceRecord| -> HashSet<u64> {
3831        face.loops
3832            .iter()
3833            .flat_map(|loop_record| &loop_record.coedges)
3834            .map(|coedge| coedge.edge_id)
3835            .filter(|edge_id| !edges[edge_id].degenerate)
3836            .collect()
3837    };
3838    let mut merged_ids: HashSet<u64> = HashSet::default();
3839    let mut cancelled_edges: HashSet<u64> = HashSet::default();
3840    // End vertices of the shared edges merged faces kept as their seams.
3841    let mut seam_vertices: HashSet<u64> = HashSet::default();
3842    for shell in &mut result.shells {
3843        'merge: loop {
3844            // Only the group's own slots are read: a 1 200-face import pays
3845            // for its four selected faces, not for every pair of the shell.
3846            let slots: Vec<usize> = (0..shell.faces.len())
3847                .filter(|slot| group.contains(&shell.faces[*slot].id))
3848                .collect();
3849            for (index, &lower) in slots.iter().enumerate() {
3850                let lower_edges = edge_ids(&shell.faces[lower]);
3851                for &higher in &slots[index + 1..] {
3852                    let higher_edges = edge_ids(&shell.faces[higher]);
3853                    if higher_edges.is_disjoint(&lower_edges) {
3854                        continue;
3855                    }
3856                    let lanes = MergeLanes {
3857                        cones: true,
3858                        shared_seam_ring: true,
3859                        seam_vertices: Some(&seam_vertices),
3860                        reseam: false,
3861                    };
3862                    let Some(mut merged) = try_merge_pair_lanes(
3863                        &shell.faces[lower],
3864                        &shell.faces[higher],
3865                        &edges,
3866                        tolerance,
3867                        1e-7,
3868                        lanes,
3869                    )?
3870                    else {
3871                        continue;
3872                    };
3873                    let survivor = shell.faces[lower].id;
3874                    let absorbed = shell.faces[higher].id;
3875                    merged.id = survivor;
3876                    merged.name = shell.faces[lower].name.clone();
3877                    let kept = edge_ids(&merged);
3878                    for edge_id in lower_edges.intersection(&higher_edges) {
3879                        if kept.contains(edge_id) {
3880                            let edge = edges[edge_id];
3881                            seam_vertices.insert(edge.start_vertex_id);
3882                            seam_vertices.insert(edge.end_vertex_id);
3883                        } else {
3884                            cancelled_edges.insert(*edge_id);
3885                        }
3886                    }
3887                    for (_, carrier) in carried_by.iter_mut() {
3888                        if *carrier == absorbed {
3889                            *carrier = survivor;
3890                        }
3891                    }
3892                    merged_ids.insert(survivor);
3893                    shell.faces[lower] = merged;
3894                    shell.faces.remove(higher);
3895                    continue 'merge;
3896                }
3897            }
3898            break;
3899        }
3900    }
3901    if merged_ids.is_empty() {
3902        return Ok((result, carried_by));
3903    }
3904    let joints: HashSet<u64> = cancelled_edges
3905        .iter()
3906        .flat_map(|edge_id| {
3907            let edge = edges[edge_id];
3908            [edge.start_vertex_id, edge.end_vertex_id]
3909        })
3910        .collect();
3911    let result = finish_merge(solid, result, true, Some(&merged_ids))?;
3912    if joints.is_empty() {
3913        return Ok((result, carried_by));
3914    }
3915    let result = crate::coalesce::merge_curve_continuation_edges_at(&result, tolerance, &joints)?;
3916    Ok((result, carried_by))
3917}
3918
3919/// The tail every merge shares: drop the edges and vertices no face uses any
3920/// more and, on the validating lane, recount the genus and validate.
3921fn finish_merge(
3922    solid: &BrepSolid,
3923    mut result: BrepSolid,
3924    validate: bool,
3925    validation_scope: Option<&HashSet<u64>>,
3926) -> Result<BrepSolid, KernelRefusal> {
3927    // A merged face numbers its loops from 1 (`reproject_loops`,
3928    // `walk_cycles`), so two merged faces can share a loop id, which the
3929    // topology arena refuses ("duplicate loop wire id"): give repeats fresh ids.
3930    result.renumber_repeated_wire_ids();
3931    let used_edges = result
3932        .shells
3933        .iter()
3934        .flat_map(|shell| &shell.faces)
3935        .flat_map(|face| &face.loops)
3936        .flat_map(|loop_record| &loop_record.coedges)
3937        .map(|coedge| coedge.edge_id)
3938        .collect::<HashSet<_>>();
3939    result.edges.retain(|edge| used_edges.contains(&edge.id));
3940    let used_vertices = result
3941        .edges
3942        .iter()
3943        .flat_map(|edge| [edge.start_vertex_id, edge.end_vertex_id])
3944        .collect::<HashSet<_>>();
3945    result
3946        .vertices
3947        .retain(|vertex| used_vertices.contains(&vertex.id));
3948    if !validate {
3949        return Ok(result);
3950    }
3951    if std::env::var("BREP_DEBUG_MERGE").is_ok() {
3952        let entry_faces: i64 = solid.shells.iter().map(|s| s.faces.len() as i64).sum();
3953        let entry_holes: i64 = solid
3954            .shells
3955            .iter()
3956            .flat_map(|s| &s.faces)
3957            .map(|f| f.loops.len().saturating_sub(1) as i64)
3958            .sum();
3959        let entry_edges = solid.edges.iter().filter(|e| !e.degenerate).count() as i64;
3960        let entry_used: std::collections::HashSet<u64> = solid
3961            .shells
3962            .iter()
3963            .flat_map(|s| &s.faces)
3964            .flat_map(|f| &f.loops)
3965            .flat_map(|l| &l.coedges)
3966            .map(|c| c.edge_id)
3967            .collect();
3968        eprintln!(
3969            "merge entry census: V={} E={entry_edges} (coedge-referenced {}) F={entry_faces} H={entry_holes} S={} stored_genus={}",
3970            solid.vertices.len(),
3971            entry_used.len(),
3972            solid.shells.len(),
3973            solid.genus
3974        );
3975    }
3976    let face_count = result
3977        .shells
3978        .iter()
3979        .map(|shell| shell.faces.len() as i64)
3980        .sum::<i64>();
3981    let hole_count = result.bounding_hole_count();
3982    let edge_count = result.edges.iter().filter(|edge| !edge.degenerate).count() as i64;
3983    // Count only LIVE vertices (referenced by a non-degenerate edge): the
3984    // merge removes edges and faces, orphaning vertices that then must not
3985    // participate in the Euler census — mirroring refresh_derived_genus
3986    // (boolean.rs). Counting stale vertices inflated V and rejected valid
3987    // merges as "non-integral genus" (the helmet report's final layer).
3988    let live_vertices: std::collections::HashSet<u64> = result
3989        .edges
3990        .iter()
3991        .filter(|edge| !edge.degenerate)
3992        .flat_map(|edge| [edge.start_vertex_id, edge.end_vertex_id])
3993        .collect();
3994    let vertex_count = result
3995        .vertices
3996        .iter()
3997        .filter(|vertex| live_vertices.contains(&vertex.id))
3998        .count() as i64;
3999    let euler = vertex_count - edge_count + face_count - hole_count;
4000    let numerator = result.shells.len() as i64 * 2 - euler;
4001    // Mirror validate()'s convention (topology.rs): the reduced V−E+F−H
4002    // formula does not model parameter-space POLE COLLAPSES reliably, so on a
4003    // complex carrying degenerate edges the parity check must not reject —
4004    // the helmet result holds 17 legitimate degenerate (pole) edges and its
4005    // odd numerator here is a formula artifact, not a defect; validate()
4006    // below performs the real integrity checks either way. With no
4007    // degenerate edges the strict behavior is unchanged.
4008    let has_degenerate = result.edges.iter().any(|edge| edge.degenerate);
4009    if numerator < 0 || numerator % 2 != 0 {
4010        if std::env::var("BREP_DEBUG_MERGE").is_ok() {
4011            eprintln!(
4012                "merge euler reject: V={vertex_count} E={edge_count} F={face_count} H={hole_count} S={} euler={euler} numerator={numerator} degenerate={has_degenerate}",
4013                result.shells.len()
4014            );
4015        }
4016        if !has_degenerate
4017            || std::env::var("BREP_MERGE_DEGENERATE_EULER_STRICT").as_deref() == Ok("1")
4018        {
4019            return Err(KernelRefusal::new(
4020                RefusalClass::NonIntegralGenus {
4021                    shells: result.shells.len() as u32,
4022                    euler: euler as i64,
4023                },
4024                KernelStage::Validate,
4025                "merge_same_surface_faces produced non-integral genus",
4026            ));
4027        }
4028    } else {
4029        result.genus = numerator / 2;
4030    }
4031    let issues = match validation_scope {
4032        Some(scope) => result.validate_scoped(scope),
4033        None => result.validate(),
4034    };
4035    if !issues.is_empty() {
4036        return Err(KernelRefusal::new(
4037            RefusalClass::DegenerateArrangement {
4038                open_edges: 0,
4039                issues: issues.len() as u32,
4040            },
4041            KernelStage::Validate,
4042            format!("merge_same_surface_faces produced invalid topology: {issues:?}"),
4043        ));
4044    }
4045    Ok(result)
4046}
4047
4048/// Join every pair of faces the re-seam lane admits ([`MergeLanes::reseam`])
4049/// and nothing else, pair by pair: `(the body, (surviving face id, absorbed
4050/// face id) per join)`, or `None` when no pair joins or the joined body fails
4051/// the merge's closing Euler and `validate()` checks.
4052pub fn rejoin_seam_split_pairs(
4053    solid: &BrepSolid,
4054    tolerance: f64,
4055    keep_unmerged: &[String],
4056) -> Result<Option<(BrepSolid, Vec<(u64, u64)>)>, KernelRefusal> {
4057    let mut result = solid.clone();
4058    let edges = solid.edges.iter().map(|edge| (edge.id, edge)).collect::<HashMap<_, _>>();
4059    let lanes = MergeLanes { reseam: true, ..MergeLanes::default() };
4060    let mut joins = Vec::new();
4061    let edge_ids = |face: &FaceRecord| {
4062        face.loops
4063            .iter()
4064            .flat_map(|loop_record| &loop_record.coedges)
4065            .filter(|coedge| !edges[&coedge.edge_id].degenerate)
4066            .map(|coedge| coedge.edge_id)
4067            .collect::<HashSet<u64>>()
4068    };
4069    for shell in &mut result.shells {
4070        'restart: loop {
4071            for lower in 0..shell.faces.len() {
4072                let lower_edges = edge_ids(&shell.faces[lower]);
4073                for higher in lower + 1..shell.faces.len() {
4074                    let (older, newer) = (&shell.faces[lower], &shell.faces[higher]);
4075                    if older.same_sense != newer.same_sense
4076                        || face_is_pinned(older, keep_unmerged)
4077                        || face_is_pinned(newer, keep_unmerged)
4078                        || edge_ids(newer).is_disjoint(&lower_edges)
4079                        || !same_surface(&older.surface, &newer.surface, tolerance)
4080                    {
4081                        continue;
4082                    }
4083                    if let Some(merged) = try_merge_pair_lanes(older, newer, &edges, tolerance, 1e-7, lanes)? {
4084                        joins.push((older.id, newer.id));
4085                        shell.faces[lower] = merged;
4086                        shell.faces.remove(higher);
4087                        continue 'restart;
4088                    }
4089                }
4090            }
4091            break;
4092        }
4093    }
4094    if joins.is_empty() {
4095        return Ok(None);
4096    }
4097    match finish_merge(solid, result, true, None) {
4098        Ok(result) => Ok(Some((result, joins))),
4099        Err(_) => Ok(None),
4100    }
4101}
4102
4103pub fn merge_same_surface_faces(
4104    solid: &BrepSolid,
4105    tolerance: f64,
4106) -> Result<BrepSolid, KernelRefusal> {
4107    merge_same_surface_faces_impl(solid, tolerance, true, 1e-7, &[], None)
4108}
4109
4110/// [`merge_same_surface_faces_excluding`] whose closing validation reads
4111/// the geometry of the faces in `scope` and of the faces the merge built;
4112/// every pair still merges exactly as the plain call merges it (an operand's
4113/// own coplanar neighbours included: the 2026-10-10 census found a mesh
4114/// import whose five such pairs the boolean fuses). A boolean passes the
4115/// faces its operation touched and their neighbours
4116/// (`BooleanOptions::untouched_passthrough`); the rest were validated by the
4117/// assembler and left this pass as they came.
4118pub fn merge_same_surface_faces_scoped(
4119    solid: &BrepSolid,
4120    tolerance: f64,
4121    keep_unmerged: &[String],
4122    scope: &HashSet<u64>,
4123) -> Result<BrepSolid, KernelRefusal> {
4124    merge_same_surface_faces_impl(solid, tolerance, true, 1e-7, keep_unmerged, Some(scope))
4125}
4126
4127/// Like [`merge_same_surface_faces`], but any face whose `name` CONTAINS one of
4128/// `keep_unmerged` is pinned: it never merges with a coplanar/cosurface
4129/// neighbour and is emitted unchanged, while every other face merges exactly as
4130/// [`merge_same_surface_faces`] would. An empty `keep_unmerged` is identical to
4131/// the plain call.
4132pub fn merge_same_surface_faces_excluding(
4133    solid: &BrepSolid,
4134    tolerance: f64,
4135    keep_unmerged: &[String],
4136) -> Result<BrepSolid, KernelRefusal> {
4137    merge_same_surface_faces_impl(solid, tolerance, true, 1e-7, keep_unmerged, None)
4138}
4139
4140pub fn merge_same_surface_faces_open(
4141    solid: &BrepSolid,
4142    tolerance: f64,
4143) -> Result<BrepSolid, KernelRefusal> {
4144    merge_same_surface_faces_impl(solid, tolerance, false, 5e-3, &[], None)
4145}
4146
4147
4148