Skip to main content

brep_kernel/edit/direct_edit/
face_offset.rs

1use super::*;
2use crate::{KernelRefusal, KernelStage, OrRefuse};
3
4#[path = "face_offset_plan.rs"]
5mod plan;
6use plan::RebuildPlan;
7#[path = "face_offset_tangent.rs"]
8mod tangent;
9
10// ---------------------------------------------------------------------------
11// Push a CURVED analytic face (cylinder / cone) by OFFSETTING its carrier.
12//
13// The methodology (user directive 2026-08-28, the architecture principle made
14// literal): a face is a TRIMMED region of an infinite carrier surface. To push
15// a curved face we OFFSET its untrimmed carrier surface, then re-derive the trim
16// as the INTERSECTIONS of that offset surface with the (unchanged) untrimmed
17// carriers of the neighbour faces — `intersect_analytic_pair` does the surface ∩
18// surface, `build_pcurve_on_surface` re-trims. This is the same engine the
19// boolean imprint uses; here one surface (the pushed face's) is replaced by its
20// offset and the incident edges are recut.
21//
22// Slice 1 scope (honest refusals, never a bad solid): the PUSHED face is a
23// cylinder or cone (`RuledRevolution`); its neighbours across each boundary edge
24// are PLANAR. Ruled/sphere/torus neighbours and free-form pushed faces are
25// deferred.
26// ---------------------------------------------------------------------------
27
28/// The exact analytic offset of a ruled-revolution CARRIER surface (cylinder or
29/// cone) by `signed_distance` along its OUTWARD normal — the untrimmed surface
30/// S′ whose re-intersection with the neighbour carriers gives the new trim.
31///
32/// A normal offset of a ruled revolution is another ruled revolution with the
33/// SAME axis and half-angle: in the (axial z, radial ρ) meridian, the generatrix
34/// line `ρ = rho0 + m·z` (m = dρ/dz = (rho1−rho0)/height; m = 0 for a cylinder)
35/// offsets to the PARALLEL line `ρ = rho0 + m·z + δ·√(1+m²)` — a uniform radial
36/// growth `grow = δ·√(1+m²)` at every z. So S′ is built by revolving the grown
37/// generatrix about the SAME frame, over the SAME axial span `[0, height]` and
38/// seam azimuth (`frame.x_axis`) as the source — the span keeps the neighbour
39/// caps IN the surface's domain (an axis-translation offset would slide the
40/// finite patch off them) and the shared seam meridian stays put.
41///
42/// `signed_distance > 0` grows the surface outward (radius increases). Refuses a
43/// carrier whose grown radius reaches/crosses the axis at either end.
44fn offset_ruled_carrier(
45    surface: &NurbsSurface,
46    signed_distance: f64,
47    tolerance: f64,
48) -> Result<NurbsSurface, KernelRefusal> {
49    let Some(AnalyticSurface::RuledRevolution {
50        frame,
51        rho0,
52        rho1,
53        height,
54    }) = surface.analytic()
55    else {
56        return Err(KernelRefusal::internal(
57            KernelStage::Classify,
58            "carrier_kind",
59            "offset_ruled_carrier: face carrier is not a ruled revolution",
60        ));
61    };
62    let (frame, rho0, rho1, height) = (frame.clone(), *rho0, *rho1, *height);
63    let slope = (rho1 - rho0) / height;
64    let grow = signed_distance * (1.0 + slope * slope).sqrt();
65    let rho0_new = rho0 + grow;
66    let rho1_new = rho1 + grow;
67    if rho0_new <= tolerance || rho1_new <= tolerance {
68        return Err(KernelRefusal::input(
69            KernelStage::Classify,
70            "axis_collapse",
71            "offset (push): the ruled carrier collapses to or past its axis — refusing",
72        ));
73    }
74    // Revolve the grown generatrix over the SAME axial span + seam azimuth.
75    let start = frame.origin.add(frame.x_axis.scale(rho0_new));
76    let end = frame
77        .origin
78        .add(frame.axis.scale(height))
79        .add(frame.x_axis.scale(rho1_new));
80    let generatrix = make_line(start, end).or_refuse(KernelStage::Classify, "make_line")?;
81    make_revolution(frame.origin, frame.axis, &generatrix, std::f64::consts::TAU)
82        .or_refuse(KernelStage::Classify, "make_revolution")
83}
84
85/// The rim of two COAXIAL ruled revolutions whose straight meridians cross
86/// outside one carrier's finite axial span, or `None` when they do not cross
87/// (parallel meridians, or a crossing on or past the axis).
88///
89/// In the meridian half-plane both carriers are lines, `ρ = ρ0 + m·t` along
90/// the shared axis, so the crossing station is closed-form. Each carrier is
91/// rebuilt over its own span prolonged to that station (same frame, same
92/// seam azimuth, same slope: the same surface, a longer patch) and the pair
93/// is handed to the same exact intersector, which then finds the circle.
94fn coaxial_rim_past_spans(
95    pushed: &NurbsSurface,
96    neighbour: &NurbsSurface,
97    tolerance: f64,
98) -> Result<Option<Vec<NurbsCurve>>, KernelRefusal> {
99    let ruled = |surface: &NurbsSurface| match surface.analytic() {
100        Some(AnalyticSurface::RuledRevolution { frame, rho0, rho1, height }) => {
101            Some((frame.clone(), *rho0, *rho1, *height))
102        }
103        _ => None,
104    };
105    let (Some((frame_a, rho0_a, rho1_a, height_a)), Some((frame_b, rho0_b, rho1_b, height_b))) =
106        (ruled(pushed), ruled(neighbour))
107    else {
108        return Ok(None);
109    };
110    // Both meridians in A's axial coordinate `t`: B's own coordinate of the
111    // axis point at `t` is `c + sign·t`.
112    let slope_a = (rho1_a - rho0_a) / height_a;
113    let slope_b = (rho1_b - rho0_b) / height_b;
114    let sign = frame_a.axis.dot(frame_b.axis).signum();
115    let c = frame_a.origin.sub(frame_b.origin).dot(frame_b.axis);
116    let denominator = slope_a - slope_b * sign;
117    if denominator.abs() <= 1e-12 {
118        return Ok(None);
119    }
120    let t = (rho0_b + slope_b * c - rho0_a) / denominator;
121    let radius = rho0_a + slope_a * t;
122    if !t.is_finite() || radius <= tolerance {
123        return Ok(None);
124    }
125    // Prolong one carrier over `[min(0, station), max(height, station)]` of
126    // its own coordinate, with a margin so the circle lies strictly inside.
127    let prolong = |frame: &crate::RevolutionFrame,
128                   rho0: f64,
129                   slope: f64,
130                   height: f64,
131                   station: f64|
132     -> Result<Option<NurbsSurface>, KernelRefusal> {
133        let margin = 0.05 * height.max(station.abs());
134        let low = (station - margin).min(0.0);
135        let high = (station + margin).max(height);
136        let (rho_low, rho_high) = (rho0 + slope * low, rho0 + slope * high);
137        if rho_low <= tolerance || rho_high <= tolerance {
138            return Ok(None);
139        }
140        let start = frame.origin.add(frame.axis.scale(low)).add(frame.x_axis.scale(rho_low));
141        let end = frame.origin.add(frame.axis.scale(high)).add(frame.x_axis.scale(rho_high));
142        let generatrix = make_line(start, end).or_refuse(KernelStage::Refine, "make_line")?;
143        make_revolution(frame.origin, frame.axis, &generatrix, std::f64::consts::TAU)
144            .map(Some)
145            .or_refuse(KernelStage::Refine, "make_revolution")
146    };
147    let Some(long_a) = prolong(&frame_a, rho0_a, slope_a, height_a, t)? else {
148        return Ok(None);
149    };
150    let Some(long_b) = prolong(&frame_b, rho0_b, slope_b, height_b, c + sign * t)? else {
151        return Ok(None);
152    };
153    Ok(intersect_analytic_pair(&long_a, &long_b, tolerance).filter(|curves| !curves.is_empty()))
154}
155
156/// The face's OUTWARD unit normal at its parameter-domain midpoint, oriented by
157/// `same_sense` (the convention `push_face::planar_face_normal` uses).
158fn outward_normal_mid(face: &FaceRecord) -> Result<(Vec3, Vec3), KernelRefusal> {
159    let [u0, u1] = face.surface.domain_u().or_refuse(KernelStage::Classify, "domain_u")?;
160    let [v0, v1] = face.surface.domain_v().or_refuse(KernelStage::Classify, "domain_v")?;
161    let (um, vm) = (0.5 * (u0 + u1), 0.5 * (v0 + v1));
162    let point = face.surface.evaluate(um, vm).or_refuse(KernelStage::Classify, "evaluate")?;
163    let mut normal = face.surface.normal(um, vm).or_refuse(KernelStage::Classify, "normal")?;
164    if !face.same_sense {
165        normal = normal.scale(-1.0);
166    }
167    Ok((point, normal))
168}
169
170/// Push a CYLINDER or CONE face along its outward normal by `distance` (positive
171/// grows the solid) by OFFSETTING its carrier surface and re-deriving the trim as
172/// the intersection of that offset surface with the neighbour carriers.
173///
174/// Slice-1 scope (honest refusal, never a bad solid): a full-revolution
175/// cylinder/cone SIDE face whose neighbour across every non-seam boundary edge is
176/// PLANAR (its end caps). The pushed face's own periodic SEAM edge rides the
177/// offset carrier's meridian; each rim edge re-intersects its cap
178/// (`intersect_analytic_pair`, exact circle); the caps re-trim as planar faces.
179/// Ruled/curved neighbours and non-full-revolution ruled faces are deferred.
180///
181/// The offset re-trims the pushed face against the faces it borders only, so a
182/// push that carries it into a face it does not border (two holes widened until
183/// they run into each other) closes incidence-clean on a body that passes
184/// through itself. [`crate::accept_sound`] is the floor on the way out of this
185/// entry, as it is for [`crate::move_faces`]: it repairs where the crossing can
186/// be proved and refuses by name where it cannot. [`offset_ruled_face_unchecked`]
187/// is the offset alone, for a caller that runs its own acceptance on the
188/// result (several pushes in a row, accepted once).
189pub fn offset_ruled_face(
190    solid: &BrepSolid,
191    face_id: u64,
192    distance: f64,
193) -> Result<BrepSolid, KernelRefusal> {
194    crate::accept_sound(offset_ruled_face_unchecked(solid, face_id, distance)?, "offsetRuledFace")
195}
196
197/// [`offset_ruled_face`] without its soundness floor: the offset and re-trim,
198/// returned as soon as its incidences validate. The result can pass through
199/// itself; the caller owes it an acceptance scan ([`crate::accept_sound`])
200/// before it is used as a body.
201pub fn offset_ruled_face_unchecked(
202    solid: &BrepSolid,
203    face_id: u64,
204    distance: f64,
205) -> Result<BrepSolid, KernelRefusal> {
206    if !distance.is_finite() {
207        return Err(KernelRefusal::input(
208            KernelStage::Collect,
209            "distance",
210            "offset_ruled_face: distance must be finite",
211        ));
212    }
213    if let Some(directory) = census_directory() {
214        record_push_census(&directory, solid, face_id, distance);
215    }
216    let scale = solid_model_scale(solid);
217    let tolerance = (scale * 1e-7).max(1e-9);
218    let plane_tolerance = (scale * 1e-6).max(1e-7);
219
220    let (pshell, pface) = find_face(solid, face_id).ok_or_else(|| {
221        KernelRefusal::input(
222            KernelStage::Collect,
223            "face_id",
224            format!("offset_ruled_face: no face {face_id}"),
225        )
226    })?;
227    let pushed = &solid.shells[pshell].faces[pface];
228    let Some(AnalyticSurface::RuledRevolution { frame, .. }) = pushed.surface.analytic() else {
229        return Err(KernelRefusal::input(
230            KernelStage::Collect,
231            "not_ruled",
232            "offset_ruled_face: the pushed face is not a cylinder or cone",
233        ));
234    };
235    let (frame_origin, frame_axis) = (frame.origin, frame.axis);
236
237    // Sign the offset: the carrier grows outward (radius +) along the face's
238    // OUTWARD normal. If that normal points radially inward (a hole wall), a
239    // positive push shrinks the radius.
240    let (mid_point, mid_normal) = outward_normal_mid(pushed)?;
241    let radial = {
242        let d = mid_point.sub(frame_origin);
243        d.sub(frame_axis.scale(d.dot(frame_axis)))
244    };
245    if radial.length() <= tolerance {
246        return Err(KernelRefusal::internal(
247            KernelStage::Classify,
248            "radial_direction",
249            "offset_ruled_face: degenerate radial direction (face on the axis)",
250        ));
251    }
252    let outward_sign = if mid_normal.dot(radial) >= 0.0 { 1.0 } else { -1.0 };
253    let signed_distance = distance * outward_sign;
254
255    let s_prime = offset_ruled_carrier(&pushed.surface, signed_distance, tolerance)?;
256
257    // Edge -> incident faces, to classify each of the pushed face's boundary
258    // edges as a SEAM (both incidences are the pushed face) or a RIM (the other
259    // face is the fixed neighbour cap).
260    let mut faces_of_edge: HashMap<u64, Vec<u64>> = HashMap::default();
261    for shell in &solid.shells {
262        for face in &shell.faces {
263            for loop_record in &face.loops {
264                for coedge in &loop_record.coedges {
265                    faces_of_edge
266                        .entry(coedge.edge_id)
267                        .or_default()
268                        .push(face.id);
269                }
270            }
271        }
272    }
273    let edge_by_id: HashMap<u64, &EdgeRecord> =
274        solid.edges.iter().map(|edge| (edge.id, edge)).collect();
275
276    let mut new_curve: HashMap<u64, NurbsCurve> = HashMap::default();
277    let mut new_vertex: HashMap<u64, Vec3> = HashMap::default();
278    let mut cap_faces: HashSet<u64> = HashSet::default();
279    // Coaxial ruled neighbours (a stepped/telescoping bore or boss: a cylinder
280    // meeting a coaxial cone, or two coaxial cones) — retrimmed on their own
281    // (axially-grown) carriers rather than as planar caps.
282    let mut ruled_faces: HashSet<u64> = HashSet::default();
283    // CURVED neighbours re-intersected through the shared generic lane — a
284    // sphere dome, a fillet torus, a general revolution, a non-coaxial
285    // cylinder. Their carriers do NOT move and need no growth (unlike a plane's
286    // finite patch or a ruled band's axial span, a sphere's and a torus's
287    // domains are already closed over their whole surface, and a re-intersected
288    // rim by construction lands on the carrier it was intersected with), so
289    // they are re-trimmed in place: pcurves rebuilt around the moved rim, and
290    // every OTHER edge they own re-trimmed by parameter on the curve it already
291    // carries — see `retrim_curved_neighbour_ranges`.
292    let mut curved_faces: HashSet<u64> = HashSet::default();
293    let mut seam_edges: Vec<u64> = Vec::new();
294    // Current vertex positions, for rebuilding a ruled neighbour's seam whose
295    // far endpoint (its unmoved rim vertex) is not relocated by any rim.
296    let vertex_pos: HashMap<u64, Vec3> =
297        solid.vertices.iter().map(|v| (v.id, v.point)).collect();
298    // The mouth's TANGENT vertices, where the rim touches a floor that a third
299    // face pinches to a point (a bore inscribed in a hex pocket). Read off
300    // topology before the rim pass, so a non-planar floor refuses by name.
301    let tangents =
302        tangent::tangent_vertices(solid, face_id, &faces_of_edge, &edge_by_id, plane_tolerance)?;
303
304    // OPEN rim arcs (a multi-loop pushed face: a window / slot cut through the
305    // wall). Collected here and trimmed in a second pass, once every corner
306    // vertex has been solved, so both arcs meeting at a corner agree on it.
307    let mut open_rims: Vec<OpenRim> = Vec::new();
308    // Every RIM edge rebuilt below, closed circles and open arcs alike: the
309    // pushed face's pcurves for these are refitted when a multi-loop rebuild
310    // ran, because the replacement conic carries its own parameterization.
311    let mut rim_edges: Vec<u64> = Vec::new();
312
313    // PRE-PASS — a HOLE cut clean through the wall by ONE crossing carrier.
314    //
315    // A window bored by a crossing cylinder, a dome or a torus leaves an
316    // interior loop every one of whose edges is shared with the SAME neighbour
317    // face, and whose corner vertices have valence two: no third face meets
318    // there, so no triple point determines them and `resolve_open_rim_end` —
319    // which solves a triple point against a PLANE — has nothing to solve. The
320    // loop is one closed section that the arrangement stored as arcs, and the
321    // right rebuild is to re-intersect once and cut the section at the samples
322    // nearest the vertices it replaces. Handled here, ahead of the per-edge
323    // loop, because the decision is a property of the whole loop.
324    let mut hole_edges: HashSet<u64> = HashSet::default();
325    for loop_record in &pushed.loops {
326        let Some(hole) = single_neighbour_hole(
327            loop_record,
328            face_id,
329            solid,
330            &faces_of_edge,
331            &edge_by_id,
332            frame_origin,
333            frame_axis,
334            scale,
335        )?
336        else {
337            continue;
338        };
339        rebuild_single_neighbour_hole(
340            solid,
341            &s_prime,
342            &hole,
343            &edge_by_id,
344            &vertex_pos,
345            tolerance,
346            scale,
347            &mut new_curve,
348            &mut new_vertex,
349        )?;
350        for edge_id in &hole.edge_ids {
351            hole_edges.insert(*edge_id);
352            if !rim_edges.contains(edge_id) {
353                rim_edges.push(*edge_id);
354            }
355        }
356        curved_faces.insert(hole.neighbour);
357    }
358
359    for loop_record in &pushed.loops {
360        let coedge_count = loop_record.coedges.len();
361        for coedge_index in 0..coedge_count {
362            let coedge = &loop_record.coedges[coedge_index];
363            let edge = *edge_by_id
364                .get(&coedge.edge_id)
365                .ok_or_else(|| {
366                    KernelRefusal::internal(
367                        KernelStage::Classify,
368                        "missing_edge",
369                        format!("offset_ruled_face: missing edge {}", coedge.edge_id),
370                    )
371                })?;
372            if hole_edges.contains(&edge.id) {
373                continue; // rebuilt whole, by the pre-pass above.
374            }
375            let incident = faces_of_edge.get(&edge.id).cloned().unwrap_or_default();
376            let is_seam = incident.iter().all(|f| *f == face_id);
377            if is_seam {
378                if !seam_edges.contains(&edge.id) {
379                    seam_edges.push(edge.id);
380                }
381                continue;
382            }
383            // RIM: the fixed neighbour is the other face. Three lanes, in
384            // decreasing exactness and increasing generality:
385            //
386            //   * a PLANE (an end cap) or a ruled revolution COAXIAL with the
387            //     pushed carrier (a stepped/telescoping bore or boss) — the two
388            //     original lanes, whose closed forms are reached by the exact
389            //     call this function has always made, unchanged;
390            //   * ANY OTHER carrier — sphere, torus, general revolution,
391            //     non-coaxial cylinder/cone, free-form — through the shared
392            //     re-intersection service (`offset/reintersect.rs`), which tries
393            //     the same closed forms first and marches the pair when they
394            //     decline. This is the lane the audit's §2.3 says push-face
395            //     lacks and offset-shell has.
396            //
397            // The generic lane is admitted only where THIS rebuild can express
398            // the answer: a CLOSED rim, whose single vertex is a bookkeeping
399            // seam point rather than a triple point. An open arc against a
400            // curved neighbour needs `resolve_open_rim_end` to solve a triple
401            // point against a curved `N'`, which it cannot (it takes a plane),
402            // so that stays a refusal with its own reason.
403            let neighbour = *incident
404                .iter()
405                .find(|f| **f != face_id)
406                .ok_or_else(|| {
407                    KernelRefusal::internal(
408                        KernelStage::Classify,
409                        "no_neighbour",
410                        format!("offset_ruled_face: edge {} has no neighbour", edge.id),
411                    )
412                })?;
413            let (nshell, nface) = find_face(solid, neighbour).ok_or_else(|| {
414                KernelRefusal::internal(
415                    KernelStage::Classify,
416                    "missing_neighbour",
417                    format!("offset_ruled_face: missing neighbour {neighbour}"),
418                )
419            })?;
420            let neighbour_surface = &solid.shells[nshell].faces[nface].surface;
421            let is_plane =
422                matches!(neighbour_surface.analytic(), Some(AnalyticSurface::Plane { .. }));
423            let is_coaxial_ruled =
424                ruled_neighbour_is_coaxial(neighbour_surface, frame_origin, frame_axis, scale);
425            let is_curved = !is_plane && !is_coaxial_ruled;
426            let separated = || {
427                KernelRefusal::unsupported(
428                    KernelStage::Classify,
429                    "separated",
430                    "offset_ruled_face: the pushed carrier no longer meets a neighbour \
431                 (the push separated them, or the rim left the neighbour's domain) — refusing",
432                )
433            };
434            // New rim = offset carrier ∩ neighbour carrier, the branch nearest
435            // the old edge.
436            let old_mid = edge.curve.evaluate(0.5 * (edge.t0 + edge.t1)).or_refuse(KernelStage::Refine, "evaluate")?;
437            let mut marched = false;
438            let curves = if is_curved {
439                if edge.start_vertex_id != edge.end_vertex_id {
440                    return Err(KernelRefusal::unsupported(
441                        KernelStage::Classify,
442                        "open_curved_rim",
443                        format!(
444                        "offset_ruled_face: the rim against curved neighbour {neighbour} is an \
445                         OPEN arc (edge {}); an arc's corner is a triple point solved against a \
446                         PLANE only — deferred (refusing)",
447                        edge.id
448                    ),
449                    ));
450                }
451                let policy = MarchPolicy {
452                    tolerance,
453                    // The rebuilt rim must sit on BOTH carriers tightly enough
454                    // that its pcurves build and `validate` accepts them; the
455                    // free-form push's own residual gate (0.05% of model scale)
456                    // is the in-tree precedent for "how far an approximate
457                    // offset result may be off".
458                    residual_tolerance: (scale * 5e-4).max(5e-6),
459                    // The boundary being replaced is the best seed set for the
460                    // boundary replacing it.
461                    seeds: edge_seeds(edge, 9)?,
462                };
463                match reintersect_carriers(&s_prime, neighbour_surface, &policy) {
464                    Ok(found) => {
465                        marched = found.lane == RimLane::Marched;
466                        if std::env::var("BREP_PUSH_HOLE_DEBUG").is_ok() {
467                            eprintln!(
468                                "RIM neighbour {neighbour}: lane {:?}, {} branch(es), \
469                                 residual {:.3e} (gate {:.3e})",
470                                found.lane,
471                                found.sections.len(),
472                                found.residual,
473                                policy.residual_tolerance
474                            );
475                        }
476                        found.curves()
477                    }
478                    Err(ReintersectRefusal::Separated) => return Err(separated()),
479                    // A residual past the gate is the march declining its own answer; a
480                    // lower-level failure is a defect. Both keep the text they had.
481                    Err(other @ ReintersectRefusal::Residual { .. }) => {
482                        return Err(KernelRefusal::non_convergence(
483                            KernelStage::Refine,
484                            "reintersect_residual",
485                            format!("offset_ruled_face: {}", other.describe()),
486                        ));
487                    }
488                    Err(other) => {
489                        return Err(KernelRefusal::internal(
490                            KernelStage::Refine,
491                            "reintersect_failed",
492                            format!("offset_ruled_face: {}", other.describe()),
493                        ));
494                    }
495                }
496            } else {
497                // UNCHANGED: the exact call, with the same arguments in the same
498                // order, so every pair this function answered before is answered
499                // bit-identically now.
500                match intersect_analytic_pair(&s_prime, neighbour_surface, tolerance)
501                    .filter(|curves| !curves.is_empty())
502                {
503                    Some(curves) => curves,
504                    // A coaxial ruled pair whose meridians still cross, only
505                    // past the end of one carrier's finite span: the rim slides
506                    // further along the axis than either patch reached (a
507                    // countersink pushed out runs its rim down the bore it
508                    // sinks). The two carriers are prolonged to the crossing
509                    // and re-intersected; the retrim below grows each face's
510                    // carrier over the moved rim, as it does for any rim that
511                    // slid inside the spans.
512                    None if is_coaxial_ruled => {
513                        coaxial_rim_past_spans(&s_prime, neighbour_surface, tolerance)?
514                            .ok_or_else(separated)?
515                    }
516                    None => return Err(separated()),
517                }
518            };
519            let rim = nearest_curve(&curves, old_mid)?;
520            if !rim_edges.contains(&edge.id) {
521                rim_edges.push(edge.id);
522            }
523            if edge.start_vertex_id == edge.end_vertex_id {
524                // A closed rim is a whole conic, so it must also run the way the
525                // edge it replaces ran — see `match_closed_rim_direction`.
526                let rim = if marched {
527                    // A MARCHED section begins wherever the trace was seeded,
528                    // not on the carrier's seam, so the start-tangent test would
529                    // compare two unrelated places. Ask the same question at the
530                    // old curve's nearest parameter instead.
531                    match_marched_rim_direction(rim, edge)?
532                } else {
533                    match_closed_rim_direction(rim, edge)?
534                };
535                // CLOSED rim (the canonical cap circle of a single-loop push):
536                // its seam-azimuth point is the relocated corner and matches the
537                // offset carrier's meridian. A recognized carrier's u = 0 IS its
538                // seam, and the shared rim's one seam vertex sits on both
539                // carriers' seams, so this placement keeps the coaxial
540                // neighbour's straight meridian on its carrier too. A marched
541                // section has no such convention, so its own domain start is
542                // where its single vertex goes — the vertex is a bookkeeping
543                // split of a closed curve, not a geometric corner.
544                let seam_point = if marched {
545                    let [d0, _] = rim.domain().or_refuse(KernelStage::Refine, "domain")?;
546                    rim.evaluate(d0).or_refuse(KernelStage::Refine, "evaluate")?
547                } else {
548                    rim.evaluate(0.0).or_refuse(KernelStage::Refine, "evaluate")?
549                };
550                new_vertex.insert(edge.start_vertex_id, seam_point);
551                new_vertex.insert(edge.end_vertex_id, seam_point);
552                new_curve.insert(edge.id, rim);
553            } else {
554                // OPEN rim: an arc / generatrix bounding a window cut through
555                // the wall. `rim` is the WHOLE conic the two carriers share, so
556                // each endpoint must be re-solved (it is the triple point
557                // `S' ∩ N ∩ N'` against the ADJACENT rim's neighbour, or the
558                // pushed carrier's own seam) and the conic trimmed between them.
559                // Collapsing both onto `rim.evaluate(0.0)` — the closed-rim rule
560                // — is what used to tear a multi-loop push apart.
561                let previous =
562                    &loop_record.coedges[(coedge_index + coedge_count - 1) % coedge_count];
563                let next = &loop_record.coedges[(coedge_index + 1) % coedge_count];
564                let (at_start, at_end) = if coedge.forward {
565                    (previous, next)
566                } else {
567                    (next, previous)
568                };
569                let mut resolve = |adjacent_coedge: &CoedgeRecord,
570                                   vertex_id: u64|
571                 -> Result<RimEnd, KernelRefusal> {
572                    let adjacent = *edge_by_id.get(&adjacent_coedge.edge_id).ok_or_else(|| {
573                        KernelRefusal::internal(
574                            KernelStage::Refine,
575                            "adjacent_edge",
576                            format!(
577                            "offset_ruled_face: missing edge {}",
578                            adjacent_coedge.edge_id
579                        ),
580                        )
581                    })?;
582                    let old_point = vertex_pos
583                        .get(&vertex_id)
584                        .copied()
585                        .ok_or_else(|| {
586                            KernelRefusal::internal(
587                                KernelStage::Refine,
588                                "corner_vertex_pos",
589                                format!("offset_ruled_face: missing vertex {vertex_id}"),
590                            )
591                        })?;
592                    let (end, point) = resolve_open_rim_end(
593                        solid,
594                        face_id,
595                        &faces_of_edge,
596                        &rim,
597                        adjacent,
598                        old_point,
599                        plane_tolerance,
600                    )?;
601                    // Both arcs meeting at a corner solve the SAME triple point
602                    // from their own conic; a disagreement means the branch pick
603                    // went to different roots, so refuse rather than tear.
604                    match new_vertex.get(&vertex_id).copied() {
605                        Some(existing) if existing.sub(point).length() > plane_tolerance => {
606                            return Err(KernelRefusal::internal(
607                                KernelStage::Refine,
608                                "corner_agreement",
609                                "offset_ruled_face: the two rims meeting at a multi-loop corner \
610                                 disagree on its new position — refusing",
611                            ))
612                        }
613                        Some(_) => {}
614                        None => {
615                            new_vertex.insert(vertex_id, point);
616                        }
617                    }
618                    Ok(end)
619                };
620                let start = resolve(at_start, edge.start_vertex_id)?;
621                let end = resolve(at_end, edge.end_vertex_id)?;
622                open_rims.push(OpenRim {
623                    edge_id: edge.id,
624                    conic: rim,
625                    start,
626                    end,
627                    old_mid,
628                    start_vertex_id: edge.start_vertex_id,
629                    end_vertex_id: edge.end_vertex_id,
630                });
631            }
632            if is_plane {
633                cap_faces.insert(neighbour);
634            } else if is_coaxial_ruled {
635                ruled_faces.insert(neighbour);
636            } else {
637                curved_faces.insert(neighbour);
638            }
639        }
640    }
641
642    // Second pass: trim each open rim's conic to the arc BETWEEN its two solved
643    // endpoints — the one that CONTAINS the old edge, picked by the old
644    // midpoint's parameter — and orient it start-vertex → end-vertex.
645    //
646    // Both endpoints are parameters on the same conic (a seam end is solved on
647    // the seam meridian, see `RimEnd::Seam`), so there is one rule for every
648    // arc: the wanted piece is `[low, high]` when the midpoint lies in it, and
649    // the COMPLEMENT — the piece that runs the other way round, across the
650    // conic's period boundary — when it does not. The complement used to be an
651    // unconditional refusal; it is an ordinary arc whenever one of its two
652    // halves is empty, which is exactly the case of an endpoint that landed ON
653    // the period boundary. The reporter's gear bore has two of them: its top
654    // rim is split at the carrier's own seam azimuth, so the vertex there
655    // solves to parameter 0 while the arc it starts is `[0.9946, 1]`.
656    for rim in &open_rims {
657        let [d0, d1] = rim.conic.domain().or_refuse(KernelStage::Fragment, "domain")?;
658        let middle = project_point_to_curve(&rim.conic, rim.old_mid).or_refuse(KernelStage::Fragment, "project_point_to_curve")?.u;
659        let (a, b) = (rim.start.parameter(), rim.end.parameter());
660        let (low, high) = if a <= b { (a, b) } else { (b, a) };
661        if std::env::var("BREP_PUSH_HOLE_DEBUG").is_ok() {
662            let describe = |end: RimEnd| match end {
663                RimEnd::Corner(u) => format!("Corner({u:.9})"),
664                RimEnd::Seam(u) => format!("Seam({u:.9})"),
665            };
666            let at = |vid: u64| {
667                new_vertex
668                    .get(&vid)
669                    .map(|p: &Vec3| format!("({:.5},{:.5},{:.5})", p.x, p.y, p.z))
670                    .unwrap_or_else(|| "-".to_string())
671            };
672            eprintln!(
673                "OPENRIM edge {} domain=[{d0},{d1}] start={} end={} middle={middle:.9} \
674                 v{}{} -> v{}{}",
675                rim.edge_id,
676                describe(rim.start),
677                describe(rim.end),
678                rim.start_vertex_id,
679                at(rim.start_vertex_id),
680                rim.end_vertex_id,
681                at(rim.end_vertex_id),
682            );
683        }
684        if let (RimEnd::Seam(_), RimEnd::Seam(_)) = (rim.start, rim.end) {
685            return Err(KernelRefusal::unsupported(
686                KernelStage::Fragment,
687                "seam_both_ends",
688                "offset_ruled_face: a multi-loop rim arc ends on the seam at BOTH ends — \
689                 refusing",
690            ));
691        }
692        let mut trimmed = rim_arc_between(&rim.conic, low, high, middle, tolerance)?;
693        let start_point = *new_vertex.get(&rim.start_vertex_id).ok_or_else(|| {
694            KernelRefusal::internal(
695                KernelStage::Fragment,
696                "corner_start_unrelocated",
697                "offset_ruled_face: a multi-loop rim corner was not relocated — refusing",
698            )
699        })?;
700        let end_point = *new_vertex.get(&rim.end_vertex_id).ok_or_else(|| {
701            KernelRefusal::internal(
702                KernelStage::Fragment,
703                "corner_end_unrelocated",
704                "offset_ruled_face: a multi-loop rim corner was not relocated — refusing",
705            )
706        })?;
707        let [t0, _] = trimmed.domain().or_refuse(KernelStage::Fragment, "domain")?;
708        let head = trimmed.evaluate(t0).or_refuse(KernelStage::Fragment, "evaluate")?;
709        if head.sub(start_point).length() > head.sub(end_point).length() {
710            trimmed = trimmed.reversed().or_refuse(KernelStage::Fragment, "reversed")?;
711        }
712        new_curve.insert(rim.edge_id, trimmed);
713    }
714
715    // A tangent vertex cannot follow the rim — its flat stays — so it is split:
716    // the plan gets the new rim vertex, and a bridge edge or a merged floor.
717    // With no tangent vertex the plan stays geometry-only.
718    let mut plan = RebuildPlan::default();
719    tangent::plan_tangent_vertices(
720        solid,
721        face_id,
722        &tangents,
723        &faces_of_edge,
724        &edge_by_id,
725        &vertex_pos,
726        &s_prime,
727        plane_tolerance,
728        &mut new_vertex,
729        &mut cap_faces,
730        &mut plan,
731    )?;
732
733    let pos = |vid: u64| -> Vec3 {
734        new_vertex
735            .get(&vid)
736            .copied()
737            .unwrap_or_else(|| vertex_pos[&vid])
738    };
739
740    // Seam edge(s): the straight generatrix segment of the offset carrier, from
741    // the relocated bottom seam vertex to the top one. Both endpoints were placed
742    // on S′'s seam meridian by the rim re-intersections above, so a line between
743    // them rides u = 0 of S′ over the SAME axial range the seam had — using the
744    // full `iso_curve_u` meridian would wrongly span the untrimmed carrier (a
745    // boolean-drilled wall's surface runs past the plate faces).
746    for seam_id in &seam_edges {
747        let seam = *edge_by_id.get(seam_id).ok_or_else(|| {
748            KernelRefusal::internal(
749                KernelStage::Fragment,
750                "missing_seam_edge",
751                format!("offset_ruled_face: missing seam edge {seam_id}"),
752            )
753        })?;
754        let start = *new_vertex.get(&seam.start_vertex_id).ok_or_else(|| {
755            KernelRefusal::internal(
756                KernelStage::Fragment,
757                "seam_start_unrelocated",
758                "offset_ruled_face: seam endpoint was not relocated by a rim — refusing",
759            )
760        })?;
761        let end = *new_vertex.get(&seam.end_vertex_id).ok_or_else(|| {
762            KernelRefusal::internal(
763                KernelStage::Fragment,
764                "seam_end_unrelocated",
765                "offset_ruled_face: seam endpoint was not relocated by a rim — refusing",
766            )
767        })?;
768        new_curve.insert(*seam_id, make_line(start, end).or_refuse(KernelStage::Fragment, "make_line")?);
769    }
770
771    // A COAXIAL ruled neighbour also has its own straight seam meridian ending
772    // at the shared rim's (now moved) seam vertex. Rebuild it as the chord
773    // between its endpoints — one relocated by the rim, the other its unmoved
774    // rim vertex — which, both lying on the neighbour's straight generatrix, is
775    // exactly the meridian segment.
776    for ruled in &ruled_faces {
777        let (nshell, nface) = find_face(solid, *ruled).ok_or_else(|| {
778            KernelRefusal::internal(
779                KernelStage::Fragment,
780                "missing_ruled_neighbour",
781                format!("offset_ruled_face: missing ruled neighbour {ruled}"),
782            )
783        })?;
784        for loop_record in &solid.shells[nshell].faces[nface].loops {
785            for coedge in &loop_record.coedges {
786                let edge = *edge_by_id.get(&coedge.edge_id).ok_or_else(|| {
787                    KernelRefusal::internal(
788                        KernelStage::Fragment,
789                        "ruled_seam_edge",
790                        format!("offset_ruled_face: missing edge {}", coedge.edge_id),
791                    )
792                })?;
793                let incident = faces_of_edge.get(&edge.id).cloned().unwrap_or_default();
794                let is_seam = incident.iter().all(|f| *f == *ruled);
795                let touches_moved = new_vertex.contains_key(&edge.start_vertex_id)
796                    || new_vertex.contains_key(&edge.end_vertex_id);
797                if is_seam && touches_moved && !new_curve.contains_key(&edge.id) {
798                    new_curve.insert(
799                        edge.id,
800                        make_line(pos(edge.start_vertex_id), pos(edge.end_vertex_id)).or_refuse(KernelStage::Fragment, "make_line")?,
801                    );
802                }
803            }
804        }
805    }
806
807    // A CURVED neighbour keeps its surface, so it keeps every 3D CURVE it owns
808    // — a sphere's seam meridian is the same great-circle arc after the push as
809    // before it. What changes is where that curve is TRIMMED: the endpoint the
810    // moved rim carried with it slides along the curve to a new parameter.
811    // Re-solving it as a parameter on the existing curve is EXACT, and it is
812    // strictly better than rebuilding: the coaxial-ruled lane above can chord
813    // its seam only because a ruled revolution's meridian is straight, and a
814    // sphere's is not.
815    let mut new_range: HashMap<u64, (f64, f64)> = HashMap::default();
816    for curved in &curved_faces {
817        let (nshell, nface) = find_face(solid, *curved).ok_or_else(|| {
818            KernelRefusal::internal(
819                KernelStage::Fragment,
820                "missing_curved_neighbour",
821                format!("offset_ruled_face: missing curved neighbour {curved}"),
822            )
823        })?;
824        for loop_record in &solid.shells[nshell].faces[nface].loops {
825            for coedge in &loop_record.coedges {
826                let edge = *edge_by_id.get(&coedge.edge_id).ok_or_else(|| {
827                    KernelRefusal::internal(
828                        KernelStage::Fragment,
829                        "curved_neighbour_edge",
830                        format!("offset_ruled_face: missing edge {}", coedge.edge_id),
831                    )
832                })?;
833                if new_curve.contains_key(&edge.id) || new_range.contains_key(&edge.id) {
834                    continue;
835                }
836                let start_moved = new_vertex.get(&edge.start_vertex_id).copied();
837                let end_moved = new_vertex.get(&edge.end_vertex_id).copied();
838                if start_moved.is_none() && end_moved.is_none() {
839                    continue;
840                }
841                if edge.start_vertex_id == edge.end_vertex_id {
842                    // A closed or degenerate edge of the neighbour (its own
843                    // opposite rim, or a pole) whose vertex a rim relocated:
844                    // the whole curve would have to move, which this lane does
845                    // not do.
846                    return Err(KernelRefusal::unsupported(
847                        KernelStage::Fragment,
848                        "closed_neighbour_edge",
849                        format!(
850                        "offset_ruled_face: the push moved the vertex of curved neighbour \
851                         {curved}'s CLOSED edge {} — deferred (refusing)",
852                        edge.id
853                    ),
854                    ));
855                }
856                let mut range = (edge.t0, edge.t1);
857                for (moved, slot) in [(start_moved, 0usize), (end_moved, 1usize)] {
858                    let Some(point) = moved else { continue };
859                    let projection = project_point_to_curve(&edge.curve, point).or_refuse(KernelStage::Fragment, "project_point_to_curve")?;
860                    if projection.distance > plane_tolerance {
861                        return Err(KernelRefusal::unsupported(
862                            KernelStage::Fragment,
863                            "vertex_off_neighbour_edge",
864                            format!(
865                            "offset_ruled_face: a relocated rim vertex left curved neighbour \
866                             {curved}'s edge {} (off by {:.3e}) — refusing",
867                            edge.id, projection.distance
868                        ),
869                        ));
870                    }
871                    if slot == 0 {
872                        range.0 = projection.u;
873                    } else {
874                        range.1 = projection.u;
875                    }
876                }
877                new_range.insert(edge.id, range);
878            }
879        }
880    }
881    // Fail-safe: every relocated vertex must belong only to edges this push
882    // rebuilt or re-trimmed. A vertex that also ends an edge of some other face
883    // would leave that face's boundary behind, which is exactly the silent
884    // tear the ruled lane's own corner guard refuses.
885    if !curved_faces.is_empty() {
886        for edge in &solid.edges {
887            if new_curve.contains_key(&edge.id) || new_range.contains_key(&edge.id) {
888                continue;
889            }
890            if new_vertex.contains_key(&edge.start_vertex_id)
891                || new_vertex.contains_key(&edge.end_vertex_id)
892            {
893                return Err(KernelRefusal::unsupported(
894                    KernelStage::Fragment,
895                    "third_edge_moved",
896                    format!(
897                    "offset_ruled_face: relocating a curved neighbour's rim moved the end of \
898                     edge {}, which this push does not rebuild — refusing",
899                    edge.id
900                ),
901                ));
902            }
903        }
904    }
905
906    // A multi-loop window's corner is a TRIPLE point, so it is also the end of a
907    // third edge that belongs to neither the pushed face nor a rim: the two
908    // fixed neighbour planes' own shared edge (a slot floor meeting a slot
909    // side wall). Both carriers are fixed, so that edge stays on their
910    // intersection line and the chord between its (possibly relocated)
911    // endpoints IS the rebuilt edge. Skipped entirely when no open rim was
912    // rebuilt, so the single-loop paths are untouched.
913    if !open_rims.is_empty() {
914        let mut corner_edges: Vec<(u64, NurbsCurve)> = Vec::new();
915        for edge in &solid.edges {
916            if new_curve.contains_key(&edge.id) {
917                continue;
918            }
919            if !new_vertex.contains_key(&edge.start_vertex_id)
920                && !new_vertex.contains_key(&edge.end_vertex_id)
921            {
922                continue;
923            }
924            if edge.curve.straight_segment(tolerance).is_none() {
925                return Err(KernelRefusal::unsupported(
926                    KernelStage::Fragment,
927                    "curved_third_edge",
928                    "offset_ruled_face: the push moved the end of a CURVED edge that is not a \
929                     rebuilt rim — refusing",
930                ));
931            }
932            let start = pos(edge.start_vertex_id);
933            let end = pos(edge.end_vertex_id);
934            for neighbour in faces_of_edge.get(&edge.id).cloned().unwrap_or_default() {
935                if !cap_faces.contains(&neighbour) {
936                    // Name the vertex, the edge and the face. This is the
937                    // refusal a rim corner PINNED by a third, fixed face gives
938                    // — the reporter's gear bore is inscribed in a hex pocket,
939                    // so each of its six tangent corners also ends the bottom
940                    // edge of a hex flat, and moving the rim off those flats is
941                    // a topology change (the six floor faces merge) that push
942                    // face does not perform. Without the ids the message says
943                    // nothing about which corner is stuck.
944                    let stuck = [edge.start_vertex_id, edge.end_vertex_id]
945                        .into_iter()
946                        .find(|vertex| new_vertex.contains_key(vertex))
947                        .unwrap_or(edge.start_vertex_id);
948                    return Err(KernelRefusal::unsupported(
949                        KernelStage::Fragment,
950                        "pinned_corner",
951                        format!(
952                        "offset_ruled_face: the push relocates rim corner vertex {stuck}, which \
953                         also ends edge {} of face {neighbour} — a face this push does not \
954                         re-trim, so the rim would tear away from it (refusing)",
955                        edge.id
956                    ),
957                    ));
958                }
959                let (nshell, nface) = find_face(solid, neighbour).ok_or_else(|| {
960                    KernelRefusal::internal(
961                        KernelStage::Fragment,
962                        "corner_neighbour",
963                        format!("offset_ruled_face: missing neighbour {neighbour}"),
964                    )
965                })?;
966                let plane = plane_of_surface(
967                    &solid.shells[nshell].faces[nface].surface,
968                    plane_tolerance,
969                    "offset_ruled_face",
970                )
971                ?;
972                for point in [start, end] {
973                    if point.sub(plane.origin).dot(plane.normal).abs() > plane_tolerance {
974                        return Err(KernelRefusal::unsupported(
975                            KernelStage::Fragment,
976                            "corner_off_plane",
977                            "offset_ruled_face: a relocated corner left one of its fixed \
978                             neighbour planes — refusing",
979                        ));
980                    }
981                }
982            }
983            corner_edges.push((edge.id, make_line(start, end).or_refuse(KernelStage::Fragment, "make_line")?));
984        }
985        for (edge_id, curve) in corner_edges {
986            new_curve.insert(edge_id, curve);
987        }
988    }
989
990    // --- Apply the plan to a fresh clone (the input is never mutated) -------
991    //
992    // Everything above is the classification step; what it decided is the plan.
993    plan.curves = new_curve;
994    plan.ranges = new_range;
995    plan.moved = new_vertex;
996    let (mut result, applied) = plan.apply(solid)?;
997    // Every edge this push touched, by curve, by trim range or by being added —
998    // the selective re-fit's work list.
999    let changed_edges = plan.changed_edges(&applied);
1000    let (pshell, pface) = find_face(&result, face_id).ok_or_else(|| {
1001        KernelRefusal::internal(
1002            KernelStage::Fragment,
1003            "pushed_face_lookup",
1004            format!("offset_ruled_face: missing face {face_id}"),
1005        )
1006    })?;
1007    // The pushed face rides the offset carrier. S′ shares the source's parameter
1008    // domain + seam azimuth (same make_revolution frame/span), so the face's
1009    // existing (u, v) pcurves stay valid when every rim stayed at its axial
1010    // station (the planar-cap push) — only the surface swaps.
1011    result.shells[pshell].faces[pface].surface = s_prime;
1012
1013    let final_edges: HashMap<u64, EdgeRecord> =
1014        result.edges.iter().map(|e| (e.id, e.clone())).collect();
1015
1016    // A COAXIAL ruled neighbour moves the shared rim ALONG the axis, so the
1017    // pushed face's pcurve for that rim (and the seam whose endpoint moved) is
1018    // no longer at its old v — refit both the pushed face and every ruled
1019    // neighbour on their (axially-grown-if-needed) carriers. The planar-only
1020    // push skips this and keeps the exact pcurve reuse above.
1021    //
1022    // A CURVED neighbour moves the shared rim just as much (a dome's rim climbs
1023    // the sphere as the rod it caps grows), so it joins the same pass — but its
1024    // own carrier neither moves nor grows: a sphere, a torus and a full
1025    // revolution are already closed over their whole surface, and the rim was
1026    // intersected WITH that surface, so it is on it by construction. Its retrim
1027    // is therefore the same driver with a growth that does nothing.
1028    if !ruled_faces.is_empty() {
1029        retrim_offset_ruled_face(&mut result, face_id, &final_edges, tolerance)?;
1030        for ruled in &ruled_faces {
1031            retrim_offset_ruled_face(&mut result, *ruled, &final_edges, tolerance)?;
1032        }
1033        for curved in &curved_faces {
1034            refit_changed_pcurves(&mut result, *curved, &final_edges, &changed_edges, tolerance)?;
1035        }
1036    } else if !curved_faces.is_empty() {
1037        // The pushed carrier still has to GROW where the rim climbed past its
1038        // axial span — the same exact prolongation the ruled lane uses — but its
1039        // pcurves are re-fitted selectively, not wholesale.
1040        let (gshell, gface) = find_face(&result, face_id).ok_or_else(|| {
1041            KernelRefusal::internal(
1042                KernelStage::Sew,
1043                "grow_face_lookup",
1044                format!("offset_ruled_face: missing face {face_id}"),
1045            )
1046        })?;
1047        let samples = boundary_samples(
1048            &result.shells[gshell].faces[gface],
1049            &final_edges,
1050            "offset_ruled_face",
1051        )?;
1052        extend_ruled_neighbour_over(&mut result, face_id, &samples, tolerance)?;
1053        refit_changed_pcurves(&mut result, face_id, &final_edges, &changed_edges, tolerance)?;
1054        for curved in &curved_faces {
1055            refit_changed_pcurves(&mut result, *curved, &final_edges, &changed_edges, tolerance)?;
1056        }
1057    } else if !rim_edges.is_empty() {
1058        // Every rebuilt RIM needs a fresh pcurve on S'. An open rim because its
1059        // azimuth span (an arc) or station (a generatrix) genuinely moved; a
1060        // CLOSED rim because the replacement conic carries the INTERSECTOR's
1061        // parameterization, which need not be the one the incoming curve had —
1062        // a boolean-cut cylinder's cap circle comes back re-parameterized, and
1063        // a closed rim under an OBLIQUE planar cap is an ellipse whose height
1064        // profile v(u) changes with the offset (the cap plane climbs as the
1065        // carrier grows: measured 0.382 against a 0.206 limit when the old
1066        // pcurve was kept on the oblique-cut cone of PushFaceTest2). So this
1067        // pass runs for every rebuilt rim, not only when an open rim exists;
1068        // for a perpendicular cap circle it rebuilds the same v = const line.
1069        // `validate` pairs pcurve to curve by FRACTION of their domains, so a
1070        // pointwise-identical circle with a different parameter distribution
1071        // still reads as a gross deviation (measured 5.96 and 12.0 on the slot
1072        // fixture, against a 0.394 limit).
1073        //
1074        // The SEAM edges keep their u — and with it the two coedges sitting on
1075        // OPPOSITE sides of the periodic seam — but their v is REFRESHED, which
1076        // is where this used to be wrong.
1077        //
1078        // The claim that stood here was that a seam is "rebuilt as a straight
1079        // chord over the same axial range, so fraction ↦ height is unchanged".
1080        // That is true of a cap PERPENDICULAR to the axis and false of an
1081        // OBLIQUE one: a tilted plane meets the generatrix at azimuth `u` at an
1082        // axial station that depends on the RADIUS, so changing the radius by
1083        // `d` slides the seam's endpoint along the axis by `d·tan θ`, where `θ`
1084        // is the angle between the axis and the cap's normal. Measured on a
1085        // radius-3 bore drilled at 30° and pushed by 0.5: the seam's pcurve sat
1086        // `2.887e-1` off its own edge — exactly `0.5·tan 30°` — and
1087        // `validate()`'s scale-derived pcurve limit passed it, so the only
1088        // symptom was the body's volume, `1.9e-7` relative against its closed
1089        // form where the axis-aligned control reads `1.6e-13`.
1090        let rebuilt: HashSet<u64> = rim_edges.iter().copied().collect();
1091        let seams: HashSet<u64> = seam_edges.iter().copied().collect();
1092        let surface = result.shells[pshell].faces[pface].surface.clone();
1093        let [u_start, u_end] = surface.domain_u().or_refuse(KernelStage::Sew, "domain_u")?;
1094        let u_period = u_end - u_start;
1095        for loop_record in &mut result.shells[pshell].faces[pface].loops {
1096            for coedge in &mut loop_record.coedges {
1097                if !rebuilt.contains(&coedge.edge_id) {
1098                    continue;
1099                }
1100                let edge = final_edges.get(&coedge.edge_id).ok_or_else(|| {
1101                    KernelRefusal::internal(
1102                        KernelStage::Sew,
1103                        "rim_pcurve_edge",
1104                        format!("offset_ruled_face: missing edge {}", coedge.edge_id),
1105                    )
1106                })?;
1107                let mut pcurve = build_pcurve_on_surface(&surface, &edge.curve)
1108                    .or_refuse(KernelStage::Sew, "build_pcurve_on_surface")?;
1109                if !coedge.forward {
1110                    pcurve = pcurve.reversed().or_refuse(KernelStage::Sew, "reversed")?;
1111                }
1112                coedge.pcurve = reanchor_pcurve_u(&pcurve, &coedge.pcurve, u_period)?;
1113            }
1114        }
1115        // The seam pass, in the same loop shape but keeping u: a generatrix's
1116        // azimuth does not change under a radial offset, only the station its
1117        // ends sit at.
1118        for loop_record in &mut result.shells[pshell].faces[pface].loops {
1119            for coedge in &mut loop_record.coedges {
1120                if !seams.contains(&coedge.edge_id) {
1121                    continue;
1122                }
1123                let edge = final_edges.get(&coedge.edge_id).ok_or_else(|| {
1124                    KernelRefusal::internal(
1125                        KernelStage::Sew,
1126                        "seam_pcurve_edge",
1127                        format!("offset_ruled_face: missing edge {}", coedge.edge_id),
1128                    )
1129                })?;
1130                coedge.pcurve = reseat_seam_pcurve(&surface, &coedge.pcurve, edge, coedge.forward)?;
1131            }
1132        }
1133    }
1134
1135    // The fixed caps re-trim as planar faces around their grown rim circles.
1136    for cap in &cap_faces {
1137        let (cshell, cface) = find_face(&result, *cap).ok_or_else(|| {
1138            KernelRefusal::internal(
1139                KernelStage::Sew,
1140                "missing_cap",
1141                format!("offset_ruled_face: missing cap {cap}"),
1142            )
1143        })?;
1144        let plane = plane_of_surface(
1145            &result.shells[cshell].faces[cface].surface,
1146            plane_tolerance,
1147            "offset_ruled_face",
1148        )?;
1149        retrim_planar_face(
1150            &mut result.shells[cshell].faces[cface],
1151            &plane,
1152            &final_edges,
1153            scale,
1154            "offset_ruled_face",
1155        )?;
1156    }
1157
1158    let issues = result.validate();
1159    if !issues.is_empty() {
1160        if std::env::var("BREP_PUSH_HOLE_DEBUG").is_ok() {
1161            // Which coedge of the pushed face drifted, and by how much, with
1162            // the pcurve's endpoints so a re-anchoring or direction mistake is
1163            // visible next to a fitting one.
1164            let (pshell, pface) = find_face(&result, face_id).expect("pushed face survives");
1165            let face = &result.shells[pshell].faces[pface];
1166            for (li, loop_record) in face.loops.iter().enumerate() {
1167                for coedge in &loop_record.coedges {
1168                    let Some(edge) = result.edges.iter().find(|e| e.id == coedge.edge_id) else {
1169                        continue;
1170                    };
1171                    let (Ok([p0, p1]), Ok(c0)) = (coedge.pcurve.domain(), edge.curve.evaluate(edge.t0))
1172                    else {
1173                        continue;
1174                    };
1175                    let mut worst = 0.0f64;
1176                    for k in 0..=32 {
1177                        let f = k as f64 / 32.0;
1178                        let t = if coedge.forward {
1179                            edge.t0 + (edge.t1 - edge.t0) * f
1180                        } else {
1181                            edge.t1 - (edge.t1 - edge.t0) * f
1182                        };
1183                        if let (Ok(q), Ok(target)) =
1184                            (coedge.pcurve.evaluate(p0 + (p1 - p0) * f), edge.curve.evaluate(t))
1185                        {
1186                            if let Ok(on_s) = face.surface.evaluate(q.x, q.y) {
1187                                worst = worst.max(on_s.sub(target).length());
1188                            }
1189                        }
1190                    }
1191                    let (Ok(a), Ok(b)) = (coedge.pcurve.evaluate(p0), coedge.pcurve.evaluate(p1)) else {
1192                        continue;
1193                    };
1194                    eprintln!(
1195                        "PUSH-DEBUG face {} loop {li} edge {} fwd={} rebuilt={} t=[{:.4},{:.4}] dom={:?} \
1196                         curve(t0)=({:.4},{:.4},{:.4}) pcurve ({:.4},{:.4})->({:.4},{:.4}) dev={worst:.4}",
1197                        face.id,
1198                        edge.id,
1199                        coedge.forward,
1200                        rim_edges.contains(&edge.id),
1201                        edge.t0,
1202                        edge.t1,
1203                        edge.curve.domain().ok(),
1204                        c0.x,
1205                        c0.y,
1206                        c0.z,
1207                        a.x,
1208                        a.y,
1209                        b.x,
1210                        b.y
1211                    );
1212                }
1213            }
1214        }
1215        return Err(KernelRefusal::internal(
1216            KernelStage::Validate,
1217            "validate",
1218            format!(
1219            "offset_ruled_face: pushed solid failed validation: {issues:?}"
1220        ),
1221        ));
1222    }
1223    // Sign only, through the per-face term memo (`solid_signed_volume_for_sign`,
1224    // the verdict against the bar is the exact integral's): the body before the
1225    // push was read about the same reference by the feature that built it, and
1226    // the pushed body differs from it in the pushed face and its re-trimmed
1227    // neighbours. The exact reads cost 0.26 s a body on the shelled-box
1228    // report's push (34 faces, 42 of them fitted).
1229    if let (Ok(before), Ok(after)) =
1230        (crate::signed_volume_against(solid, 0.0), crate::signed_volume_against(&result, 0.0))
1231    {
1232        if before * after <= 0.0 {
1233            return Err(KernelRefusal::internal(
1234                KernelStage::Validate,
1235                INVERTED,
1236                "offset_ruled_face: the push inverts the solid — refusing",
1237            ));
1238        }
1239    }
1240    Ok(result)
1241}
1242
1243/// Put a SEAM meridian's pcurve back on its own (rebuilt) chord without moving
1244/// it off the periodic seam: the u coordinates are carried over verbatim from
1245/// the pcurve being replaced — they are what put the two coedges of a seam on
1246/// OPPOSITE sides of the period — and only v is re-solved.
1247///
1248/// `v` is solved exactly rather than fitted. A ruled revolution is affine in
1249/// `v` along a fixed `u`, so the station of a point on that generatrix is its
1250/// projection onto the segment the v-domain spans, and two surface evaluations
1251/// give the whole map.
1252fn reseat_seam_pcurve(
1253    surface: &NurbsSurface,
1254    pcurve: &NurbsCurve,
1255    edge: &EdgeRecord,
1256    forward: bool,
1257) -> Result<NurbsCurve, KernelRefusal> {
1258    let [q0, q1] = pcurve.domain().or_refuse(KernelStage::Sew, "domain")?;
1259    let (head, tail) = (pcurve.evaluate(q0).or_refuse(KernelStage::Sew, "evaluate")?, pcurve.evaluate(q1).or_refuse(KernelStage::Sew, "evaluate")?);
1260    let [v0, v1] = surface.domain_v().or_refuse(KernelStage::Sew, "domain_v")?;
1261    let station = |u: f64, target: Vec3| -> Result<f64, KernelRefusal> {
1262        let base = surface.evaluate(u, v0).or_refuse(KernelStage::Sew, "evaluate")?;
1263        let top = surface.evaluate(u, v1).or_refuse(KernelStage::Sew, "evaluate")?;
1264        let direction = top.sub(base);
1265        let length_squared = direction.length_squared();
1266        if length_squared <= 0.0 {
1267            return Err(KernelRefusal::internal(
1268                KernelStage::Sew,
1269                "generatrix_length",
1270                "offset_ruled_face: the pushed carrier's generatrix has zero length — refusing",
1271            ));
1272        }
1273        Ok(v0 + (v1 - v0) * (target.sub(base).dot(direction) / length_squared))
1274    };
1275    let (at_head, at_tail) = if forward {
1276        (edge.curve.evaluate(edge.t0).or_refuse(KernelStage::Sew, "evaluate")?, edge.curve.evaluate(edge.t1).or_refuse(KernelStage::Sew, "evaluate")?)
1277    } else {
1278        (edge.curve.evaluate(edge.t1).or_refuse(KernelStage::Sew, "evaluate")?, edge.curve.evaluate(edge.t0).or_refuse(KernelStage::Sew, "evaluate")?)
1279    };
1280    let reseated = crate::make_line(
1281        Vec3::new(head.x, station(head.x, at_head)?, 0.0),
1282        Vec3::new(tail.x, station(tail.x, at_tail)?, 0.0),
1283    ).or_refuse(KernelStage::Sew, "make_line")?;
1284    // Checked, not asserted: the reseated pcurve must land on the chord it
1285    // carries, at both ends and in the middle.
1286    let [r0, r1] = reseated.domain().or_refuse(KernelStage::Sew, "domain")?;
1287    for (parameter, target) in [(r0, at_head), (r1, at_tail)] {
1288        let uv = reseated.evaluate(parameter).or_refuse(KernelStage::Sew, "evaluate")?;
1289        let drift = surface.evaluate(uv.x, uv.y).or_refuse(KernelStage::Sew, "evaluate")?.sub(target).length();
1290        if drift > 1e-6 * (1.0 + target.length()) {
1291            return Err(KernelRefusal::internal(
1292                KernelStage::Sew,
1293                "seam_reseat",
1294                format!(
1295                "offset_ruled_face: the reseated seam pcurve misses its own chord by \
1296                 {drift:.3e} — refusing"
1297            ),
1298            ));
1299        }
1300    }
1301    Ok(reseated)
1302}
1303
1304/// Where an OPEN rim arc's endpoint sits on the rebuilt conic — in every case
1305/// a PARAMETER on that conic, solved from geometry.
1306#[derive(Clone, Copy)]
1307enum RimEnd {
1308    /// A genuine corner: the TRIPLE point `offset carrier ∩ this rim's
1309    /// neighbour ∩ the ADJACENT rim's neighbour`, carried as the conic
1310    /// parameter that lands on it.
1311    Corner(f64),
1312    /// The pushed carrier's periodic SEAM split this rim in two, so the
1313    /// endpoint rides the offset carrier's seam MERIDIAN — the parameter at
1314    /// which the conic crosses that meridian's axial half-plane.
1315    ///
1316    /// It is NOT parameter 0 of the conic. `S'` is revolved about the same
1317    /// frame as the source carrier, so parameter 0 sits at `frame.x_axis`'s
1318    /// azimuth — and a face's topological seam edge need not be there. An
1319    /// imported cylinder can carry its seam edge anywhere on the carrier: the
1320    /// reporter's gear bore (`IMPORT3D1_Face_29`) has its seam edge at
1321    /// u = 0.5, a full 180° from `frame.x_axis`, and reading it as parameter 0
1322    /// relocated both seam vertices to the wrong meridian and trimmed each
1323    /// abutting arc from `[0, corner]` instead of `[0.5, corner]`.
1324    Seam(f64),
1325}
1326
1327impl RimEnd {
1328    /// The conic parameter this endpoint lands on.
1329    fn parameter(self) -> f64 {
1330        match self {
1331            RimEnd::Corner(parameter) | RimEnd::Seam(parameter) => parameter,
1332        }
1333    }
1334}
1335
1336/// One open rim arc, held between the two passes of the rebuild.
1337struct OpenRim {
1338    edge_id: u64,
1339    /// The WHOLE conic `S' ∩ N`, before trimming.
1340    conic: NurbsCurve,
1341    start: RimEnd,
1342    end: RimEnd,
1343    /// The OLD edge's midpoint: picks which of the two complementary arcs
1344    /// between the corners is the one this edge actually was.
1345    old_mid: Vec3,
1346    start_vertex_id: u64,
1347    end_vertex_id: u64,
1348}
1349
1350/// Resolve ONE endpoint of an open rim arc against the edge that follows it
1351/// around the loop.
1352///
1353/// Two cases, and nothing else is admitted:
1354/// * the adjacent edge is the pushed face's own SEAM — the endpoint rides the
1355///   offset carrier's seam meridian, i.e. it is where this rim's conic crosses
1356///   that meridian's axial half-plane ([`seam_axial_plane`], the same closed
1357///   form the single-neighbour-hole lane pins its corners with);
1358/// * the adjacent edge's fixed neighbour `N'` is a PLANE — the endpoint is the
1359///   triple point `S' ∩ N ∩ N'`, i.e. where this rim's conic (already the
1360///   `S' ∩ N` curve) crosses `N'`. The crossing nearest the old vertex is the
1361///   branch, so a conic that meets `N'` twice picks the right corner.
1362///
1363/// A conic that LIES IN `N'` means the boolean merely split one rim in two
1364/// (`N == N'`); there is no triple point, and the split simply keeps its
1365/// azimuth on the rebuilt conic. Any other adjacent neighbour (a curved
1366/// carrier) makes `plane_of_surface` refuse, which is the fail-safe.
1367fn resolve_open_rim_end(
1368    solid: &BrepSolid,
1369    face_id: u64,
1370    faces_of_edge: &HashMap<u64, Vec<u64>>,
1371    conic: &NurbsCurve,
1372    adjacent: &EdgeRecord,
1373    old_point: Vec3,
1374    plane_tolerance: f64,
1375) -> Result<(RimEnd, Vec3), KernelRefusal> {
1376    let incident = faces_of_edge.get(&adjacent.id).cloned().unwrap_or_default();
1377    if incident.iter().all(|f| *f == face_id) {
1378        let (pshell, pface) = find_face(solid, face_id).ok_or_else(|| {
1379            KernelRefusal::internal(
1380                KernelStage::Refine,
1381                "pushed_face_seam",
1382                format!("offset_ruled_face: missing pushed face {face_id}"),
1383            )
1384        })?;
1385        let meridian = seam_axial_plane(&solid.shells[pshell].faces[pface].surface, adjacent)
1386            .ok_or_else(|| {
1387                KernelRefusal::internal(
1388                    KernelStage::Refine,
1389                    "seam_meridian",
1390                    format!(
1391                    "offset_ruled_face: the pushed face's seam (edge {}) is not a meridian of \
1392                     its carrier — refusing",
1393                    adjacent.id
1394                ),
1395                )
1396            })?;
1397        // The meridian's plane is a WHOLE axial plane, so it also carries the
1398        // opposite azimuth; the seam vertex being replaced picks the right one.
1399        // The two are a diameter apart and the new one is |r − r'| from the old,
1400        // which is smaller than r + r' for any push the carrier survives.
1401        let parameter = conic_crossing_nearest(conic, &meridian, old_point, plane_tolerance)?
1402            .ok_or_else(|| {
1403                KernelRefusal::internal(
1404                    KernelStage::Refine,
1405                    "seam_crossing",
1406                    format!(
1407                    "offset_ruled_face: the rebuilt rim never crosses the pushed face's own seam \
1408                     meridian (edge {}) — refusing",
1409                    adjacent.id
1410                ),
1411                )
1412            })?;
1413        return Ok((RimEnd::Seam(parameter), conic.evaluate(parameter).or_refuse(KernelStage::Refine, "evaluate")?));
1414    }
1415    let other = *incident
1416        .iter()
1417        .find(|f| **f != face_id)
1418        .ok_or_else(|| {
1419            KernelRefusal::internal(
1420                KernelStage::Refine,
1421                "adjacent_no_neighbour",
1422                format!("offset_ruled_face: edge {} has no neighbour", adjacent.id),
1423            )
1424        })?;
1425    let (nshell, nface) = find_face(solid, other).ok_or_else(|| {
1426        KernelRefusal::internal(
1427            KernelStage::Refine,
1428            "adjacent_neighbour",
1429            format!("offset_ruled_face: missing neighbour {other}"),
1430        )
1431    })?;
1432    // The fail-safe named above: a curved adjacent neighbour is a deferral, and
1433    // `plane_of_surface`'s own text says which carrier it was.
1434    let plane = plane_of_surface(
1435        &solid.shells[nshell].faces[nface].surface,
1436        plane_tolerance,
1437        "offset_ruled_face",
1438    )
1439    .map_err(|message| KernelRefusal::unsupported(KernelStage::Refine, "curved_adjacent", message))?;
1440    if curve_lies_in_plane(conic, &plane, plane_tolerance)? {
1441        let projection = project_point_to_curve(conic, old_point).or_refuse(KernelStage::Refine, "project_point_to_curve")?;
1442        return Ok((RimEnd::Corner(projection.u), conic.evaluate(projection.u).or_refuse(KernelStage::Refine, "evaluate")?));
1443    }
1444    census_push("corner_crossings", || {
1445        let [d0, d1] = conic.domain().unwrap_or([f64::NAN, f64::NAN]);
1446        let height = |t: f64| conic.evaluate(t).map(|p| p.sub(plane.origin).dot(plane.normal)).unwrap_or(f64::NAN);
1447        serde_json::json!({
1448            "h_start": height(d0),
1449            "h_end": height(d1),
1450            "roots": plane_crossing_params(conic, &plane).map(|roots| roots.iter().map(|t| (t - d0) / (d1 - d0)).collect::<Vec<_>>()).unwrap_or_default(),
1451            "closed": conic.evaluate(d0).and_then(|a| conic.evaluate(d1).map(|b| a.sub(b).length())).unwrap_or(f64::NAN) <= plane_tolerance,
1452        })
1453    });
1454    let mut best: Option<(f64, f64)> = None;
1455    for parameter in plane_crossing_params(conic, &plane)? {
1456        let distance = conic.evaluate(parameter).or_refuse(KernelStage::Refine, "evaluate")?.sub(old_point).length();
1457        if best.map(|(best, _)| distance < best).unwrap_or(true) {
1458            best = Some((distance, parameter));
1459        }
1460    }
1461    let (_, parameter) = best.ok_or_else(|| {
1462        KernelRefusal::unsupported(
1463            KernelStage::Refine,
1464            "window_off_neighbour",
1465            "offset_ruled_face: a multi-loop rim corner no longer meets its adjacent neighbour \
1466         (the push pulled the window off it) — refusing",
1467        )
1468    })?;
1469    Ok((RimEnd::Corner(parameter), conic.evaluate(parameter).or_refuse(KernelStage::Refine, "evaluate")?))
1470}
1471
1472/// TRUE when the whole curve lies in the plane (so it cannot cross it): the
1473/// adjacent rim shares this rim's carrier plane and the shared vertex is a
1474/// SPLIT point, not a triple point.
1475fn curve_lies_in_plane(
1476    curve: &NurbsCurve,
1477    plane: &Plane,
1478    plane_tolerance: f64,
1479) -> Result<bool, KernelRefusal> {
1480    let [d0, d1] = curve.domain().or_refuse(KernelStage::Refine, "domain")?;
1481    for step in 0..=16 {
1482        let t = d0 + (d1 - d0) * step as f64 / 16.0;
1483        if curve
1484            .evaluate(t).or_refuse(KernelStage::Refine, "evaluate")?
1485            .sub(plane.origin)
1486            .dot(plane.normal)
1487            .abs()
1488            > plane_tolerance
1489        {
1490            return Ok(false);
1491        }
1492    }
1493    Ok(true)
1494}
1495
1496/// Every parameter at which `curve` crosses `plane`, by dense sampling of the
1497/// signed plane distance plus bisection on each sign change. The curves here
1498/// are conics (a circle crosses a slot wall twice, a generatrix line crosses a
1499/// slot floor once), so a sampled sign-change sweep finds every root; bisection
1500/// then drives it to the last bit rather than to a fit tolerance.
1501fn plane_crossing_params(curve: &NurbsCurve, plane: &Plane) -> Result<Vec<f64>, KernelRefusal> {
1502    let [d0, d1] = curve.domain().or_refuse(KernelStage::Refine, "domain")?;
1503    let signed = |t: f64| -> Result<f64, KernelRefusal> {
1504        Ok(curve.evaluate(t).or_refuse(KernelStage::Refine, "evaluate")?.sub(plane.origin).dot(plane.normal))
1505    };
1506    const SAMPLES: usize = 512;
1507    let mut roots = Vec::new();
1508    let mut previous = (d0, signed(d0)?);
1509    for index in 1..=SAMPLES {
1510        let t = d0 + (d1 - d0) * index as f64 / SAMPLES as f64;
1511        let value = signed(t)?;
1512        if previous.1 == 0.0 {
1513            roots.push(previous.0);
1514        } else if (previous.1 < 0.0) != (value < 0.0) {
1515            let (mut low, mut high) = (previous.0, t);
1516            let mut low_value = previous.1;
1517            for _ in 0..100 {
1518                let middle = 0.5 * (low + high);
1519                if middle <= low || middle >= high {
1520                    break;
1521                }
1522                let middle_value = signed(middle)?;
1523                if (low_value < 0.0) != (middle_value < 0.0) {
1524                    high = middle;
1525                } else {
1526                    low = middle;
1527                    low_value = middle_value;
1528                }
1529            }
1530            roots.push(0.5 * (low + high));
1531        }
1532        previous = (t, value);
1533    }
1534    if previous.1 == 0.0 {
1535        roots.push(previous.0);
1536    }
1537    Ok(roots)
1538}
1539
1540/// The parameter at which `curve` crosses `plane` NEAREST `reference`, or
1541/// `None` when it never crosses it.
1542///
1543/// Written for the seam endpoint of an open rim, where the plane is an axial
1544/// half-plane's whole plane and the crossing wanted is the one replacing a
1545/// known old point. Two things [`plane_crossing_params`] alone does not give:
1546///
1547/// * **the domain ENDS count.** A closed conic whose parameter origin already
1548///   sits on the plane — the canonical case, where the carrier's seam azimuth
1549///   IS `frame.x_axis` — has a root exactly at `d0` (== `d1`). The sampled
1550///   sweep only reports it when the signed distance there is *bit*-zero, and
1551///   a bisected near-endpoint root is a few ulp off the exact end. So both
1552///   ends are offered first, and a root that duplicates an offered end is
1553///   dropped: the canonical case then returns `d0` exactly, and
1554///   `conic.evaluate(d0)` stays the point this function has always returned.
1555/// * **a pick.** An axial plane cuts a conic about the same axis twice, at
1556///   opposite azimuths; only the old point can say which is the seam's.
1557fn conic_crossing_nearest(
1558    curve: &NurbsCurve,
1559    plane: &Plane,
1560    reference: Vec3,
1561    plane_tolerance: f64,
1562) -> Result<Option<f64>, KernelRefusal> {
1563    let [d0, d1] = curve.domain().or_refuse(KernelStage::Refine, "domain")?;
1564    let span = (d1 - d0).max(1e-12);
1565    let mut candidates: Vec<f64> = Vec::new();
1566    let mut ends = [false, false];
1567    for (slot, end) in [d0, d1].into_iter().enumerate() {
1568        if curve.evaluate(end).or_refuse(KernelStage::Refine, "evaluate")?.sub(plane.origin).dot(plane.normal).abs() <= plane_tolerance {
1569            ends[slot] = true;
1570            candidates.push(end);
1571        }
1572    }
1573    for root in plane_crossing_params(curve, plane)? {
1574        if (ends[0] && (root - d0).abs() <= 1e-6 * span)
1575            || (ends[1] && (root - d1).abs() <= 1e-6 * span)
1576        {
1577            continue;
1578        }
1579        candidates.push(root);
1580    }
1581    let mut best: Option<(f64, f64)> = None;
1582    for parameter in candidates {
1583        let distance = curve.evaluate(parameter).or_refuse(KernelStage::Refine, "evaluate")?.sub(reference).length();
1584        if best.map(|(known, _)| distance < known).unwrap_or(true) {
1585            best = Some((distance, parameter));
1586        }
1587    }
1588    Ok(best.map(|(_, parameter)| parameter))
1589}
1590
1591/// The piece of `curve` over `[from, to]`. `NurbsCurve::split` keeps the parent
1592/// parameterization, so the result's own domain IS `[from, to]` — which is what
1593/// the edge's `t0`/`t1` are then set from.
1594fn subcurve(curve: &NurbsCurve, from: f64, to: f64) -> Result<NurbsCurve, KernelRefusal> {
1595    let [d0, d1] = curve.domain().or_refuse(KernelStage::Fragment, "domain")?;
1596    let span = (d1 - d0).max(1e-12);
1597    if to - from <= 1e-9 * span {
1598        return Err(KernelRefusal::unsupported(
1599            KernelStage::Fragment,
1600            "arc_collapse",
1601            "offset_ruled_face: a rebuilt rim arc collapsed to a point — refusing",
1602        ));
1603    }
1604    let mut trimmed = curve.clone();
1605    if to < d1 - 1e-9 * span {
1606        trimmed = trimmed.split(to).or_refuse(KernelStage::Fragment, "split")?.0;
1607    }
1608    if from > d0 + 1e-9 * span {
1609        trimmed = trimmed.split(from).or_refuse(KernelStage::Fragment, "split")?.1;
1610    }
1611    Ok(trimmed)
1612}
1613
1614/// The arc of `conic` between the parameters `low <= high` that CONTAINS
1615/// `middle` — the old edge's own midpoint, which is what says which of the two
1616/// complementary arcs the edge being replaced actually was.
1617///
1618/// `[low, high]` when the midpoint lies in it. Otherwise the edge is the
1619/// COMPLEMENT, the arc that runs the other way round across the conic's period
1620/// boundary, and that is an ordinary sub-arc exactly when one of its two halves
1621/// — `[d0, low]` and `[high, d1]` — is empty, i.e. when an endpoint landed ON
1622/// the boundary. It does, whenever a rim was split at the pushed carrier's own
1623/// seam azimuth: the reporter's gear bore (`IMPORT3D1_Face_29`) carries such a
1624/// split, and its two arcs there are `[0.9946, 1]` (endpoint at 0) and
1625/// `[0, 0.5]` (endpoint at 1). Both used to be refused as "wraps the pushed
1626/// carrier's periodic seam" although neither needs anything joined.
1627///
1628/// The genuinely two-piece complement stays a refusal: joining two rational
1629/// NURBS pieces across the boundary is a curve rebuild this lane does not do,
1630/// and no corpus document asks for one.
1631fn rim_arc_between(
1632    conic: &NurbsCurve,
1633    low: f64,
1634    high: f64,
1635    middle: f64,
1636    tolerance: f64,
1637) -> Result<NurbsCurve, KernelRefusal> {
1638    let [d0, d1] = conic.domain().or_refuse(KernelStage::Fragment, "domain")?;
1639    if middle >= low && middle <= high {
1640        return subcurve(conic, low, high);
1641    }
1642    // The two halves of the complement can only be ONE arc if the conic closes.
1643    if conic.evaluate(d0).or_refuse(KernelStage::Fragment, "evaluate")?.sub(conic.evaluate(d1).or_refuse(KernelStage::Fragment, "evaluate")?).length() > tolerance {
1644        return Err(KernelRefusal::internal(
1645            KernelStage::Fragment,
1646            "open_conic",
1647            "offset_ruled_face: a multi-loop rim arc runs outside its OPEN conic's domain — \
1648             refusing",
1649        ));
1650    }
1651    let span = (d1 - d0).max(1e-12);
1652    let head_is_empty = low - d0 <= 1e-9 * span;
1653    let tail_is_empty = d1 - high <= 1e-9 * span;
1654    match (head_is_empty, tail_is_empty) {
1655        (true, false) => subcurve(conic, high, d1),
1656        (false, true) => subcurve(conic, d0, low),
1657        _ => Err(KernelRefusal::unsupported(
1658            KernelStage::Fragment,
1659            "two_piece_arc",
1660            "offset_ruled_face: a multi-loop rim arc crosses the rebuilt conic's period \
1661             boundary with material on BOTH sides, so it is two pieces to join — deferred \
1662             (refusing)",
1663        )),
1664    }
1665}
1666
1667/// Orient a rebuilt CLOSED rim the way the edge it replaces ran.
1668///
1669/// `intersect_analytic_pair` always emits its conics in its OWN direction
1670/// (increasing azimuth about the carrier frame). The edge being replaced need
1671/// not run that way: a wall's top and bottom cap circles are traversed in
1672/// OPPOSITE directions around the face loop, so one of them arrives decreasing.
1673/// Both are the same point set and a closed rim's two endpoints are the same
1674/// vertex, so `validate` cannot tell them apart — but the face's pcurve for the
1675/// reversed one runs `u: 1 → 0`, and handing the loop an increasing rim tears it
1676/// open in parameter space, which the Green's-theorem volume integral reads as a
1677/// completely different solid (measured 138.18 against a true 1024.11).
1678///
1679/// Decided on the START TANGENT, which is local and exact: a closed rim starts
1680/// on the carrier's seam and so does the rebuilt conic, so the two tangents
1681/// there either agree or oppose. OPEN rims are not orientated here — they are
1682/// trimmed to their solved corners first and then turned to run
1683/// start-vertex → end-vertex.
1684fn match_closed_rim_direction(
1685    rim: NurbsCurve,
1686    previous: &EdgeRecord,
1687) -> Result<NurbsCurve, KernelRefusal> {
1688    let [d0, _] = rim.domain().or_refuse(KernelStage::Refine, "domain")?;
1689    let incoming = previous.curve.derivatives(previous.t0, 1).or_refuse(KernelStage::Refine, "derivatives")?;
1690    let rebuilt = rim.derivatives(d0, 1).or_refuse(KernelStage::Refine, "derivatives")?;
1691    if incoming[1].dot(rebuilt[1]) < 0.0 {
1692        return rim.reversed().or_refuse(KernelStage::Refine, "reversed");
1693    }
1694    Ok(rim)
1695}
1696
1697/// Put a freshly fitted pcurve back on the periodic BRANCH of `u` that the
1698/// pcurve it replaces used, by the whole-period shift that aligns their starts.
1699///
1700/// This is not cosmetic. `build_pcurve_on_surface` CLAMPS an analytic carrier's
1701/// parameters into `[u0, u1]`, but a face loop on a full revolution legitimately
1702/// carries `u` one period PAST the domain: the two coedges of the periodic seam
1703/// sit on opposite sides of it, so the coedge that closes the loop across the
1704/// seam runs (say) `u: 1 → 2`. `validate` accepts either branch — it evaluates
1705/// the surface with `evaluate_extended`, which wraps — but the Green's-theorem
1706/// area/volume integral does NOT: it integrates the wire as drawn in parameter
1707/// space, and a rim dropped back to `u: 0 → 1` tears the loop open and yields a
1708/// nonsense volume (measured 138.18 for a solid whose true volume is 1024.11).
1709///
1710/// The replacement rim traverses the same path in the same direction as the edge
1711/// it replaces — only its parameter DISTRIBUTION and (for an open arc) its
1712/// endpoints change — so aligning the starts fixes the branch, and the endpoint
1713/// check refuses anything that is not merely re-anchored.
1714fn reanchor_pcurve_u(
1715    pcurve: &NurbsCurve,
1716    previous: &NurbsCurve,
1717    u_period: f64,
1718) -> Result<NurbsCurve, KernelRefusal> {
1719    if !(u_period.is_finite() && u_period > 0.0) {
1720        return Ok(pcurve.clone());
1721    }
1722    let [a0, a1] = pcurve.domain().or_refuse(KernelStage::Sew, "domain")?;
1723    let [b0, b1] = previous.domain().or_refuse(KernelStage::Sew, "domain")?;
1724    let shift = ((previous.evaluate(b0).or_refuse(KernelStage::Sew, "evaluate")?.x - pcurve.evaluate(a0).or_refuse(KernelStage::Sew, "evaluate")?.x) / u_period).round() * u_period;
1725    let shifted = if shift == 0.0 {
1726        pcurve.clone()
1727    } else {
1728        let controls = pcurve
1729            .control_points
1730            .iter()
1731            .map(|control| {
1732                let mut point = control.point().or_refuse(KernelStage::Sew, "point")?;
1733                point.x += shift;
1734                Ok(crate::Vec4::from_point(point, control.w))
1735            })
1736            .collect::<Result<Vec<_>, KernelRefusal>>()?;
1737        NurbsCurve::new(pcurve.degree, pcurve.knots.clone(), controls).or_refuse(KernelStage::Sew, "nurbs_curve")?
1738    };
1739    // Both ends must land within a quarter period of the ones they replace: a
1740    // rim that reversed direction, or that jumped a branch mid-curve, is not a
1741    // re-anchoring and must not be silently accepted.
1742    let end_drift = (shifted.evaluate(a1).or_refuse(KernelStage::Sew, "evaluate")?.x - previous.evaluate(b1).or_refuse(KernelStage::Sew, "evaluate")?.x).abs();
1743    if end_drift > 0.25 * u_period {
1744        return Err(KernelRefusal::internal(
1745            KernelStage::Sew,
1746            "pcurve_reanchor",
1747            format!(
1748            "offset_ruled_face: a rebuilt rim traverses the carrier's periodic parameter \
1749             differently from the edge it replaces (end drift {end_drift}) — refusing"
1750        ),
1751        ));
1752    }
1753    Ok(shifted)
1754}
1755
1756/// TRUE when `neighbour` is a ruled revolution (cylinder or cone) sharing the
1757/// pushed carrier's axis LINE — same axis direction (up to sign) and the axes
1758/// coincident. Only such a neighbour has a closed-form re-intersection with the
1759/// offset carrier (`intersect_coaxial_revolutions`); the tolerances mirror that
1760/// intersector so an accepted neighbour is one it can actually solve.
1761pub(super) fn ruled_neighbour_is_coaxial(
1762    neighbour: &NurbsSurface,
1763    axis_origin: Vec3,
1764    axis_dir: Vec3,
1765    scale: f64,
1766) -> bool {
1767    let Some(AnalyticSurface::RuledRevolution { frame, .. }) = neighbour.analytic() else {
1768        return false;
1769    };
1770    if frame.axis.dot(axis_dir).abs() < 1.0 - 1e-9 {
1771        return false;
1772    }
1773    let offset = frame.origin.sub(axis_origin);
1774    let perpendicular = offset.sub(axis_dir.scale(offset.dot(axis_dir)));
1775    perpendicular.length() <= 1e-9 * scale.max(1.0)
1776}
1777
1778/// Re-trim a ruled-revolution face (the pushed carrier itself, now S′, or a
1779/// coaxial ruled neighbour) whose boundary moved axially: grow the carrier along
1780/// its axis to cover the updated boundary (`extend_ruled_neighbour_over`, exact),
1781/// then rebuild every pcurve from the already-updated edge curves. The offset
1782/// analogue of `retrim_planar_face` — all loops are visited, so holes carry.
1783///
1784/// The three-phase body is `crate::offset_retrim::retrim_face_in_solid`; this is
1785/// the ruled growth strategy and the `offset_ruled_face` refusal prefix.
1786pub(super) fn retrim_offset_ruled_face(
1787    result: &mut BrepSolid,
1788    face_id: u64,
1789    final_edges: &HashMap<u64, EdgeRecord>,
1790    tolerance: f64,
1791) -> Result<(), KernelRefusal> {
1792    let (shell, face_pos) = find_face(result, face_id).ok_or_else(|| {
1793        KernelRefusal::internal(
1794            KernelStage::Sew,
1795            "missing_ruled_face",
1796            format!("offset_ruled_face: missing ruled face {face_id}"),
1797        )
1798    })?;
1799    retrim_face_in_solid(
1800        result,
1801        shell,
1802        face_pos,
1803        final_edges,
1804        |solid, points| Ok(extend_ruled_neighbour_over(solid, face_id, points, tolerance)?),
1805        tolerance,
1806        "offset_ruled_face",
1807    )
1808    
1809}
1810
1811/// A window through the wall bounded entirely by ONE crossing carrier.
1812struct SingleNeighbourHole {
1813    neighbour: u64,
1814    /// Every edge of the loop, in loop order, de-duplicated.
1815    edge_ids: Vec<u64>,
1816    /// Corner vertices that are ALSO the end of one of the neighbour's own
1817    /// edges — its seam meridian, in every case the corpus reaches. Such a
1818    /// corner is NOT a free bookkeeping split: it is pinned to that meridian,
1819    /// so it moves along it rather than to the nearest point of the new
1820    /// section. `(vertex id, the neighbour edge it is pinned to)`.
1821    pinned: Vec<(u64, u64)>,
1822}
1823
1824/// The axial half-plane a revolution carrier's SEAM meridian lies in.
1825///
1826/// Every seam of every revolution carrier this lane admits — a cylinder, a
1827/// cone, a sphere, a torus, a general revolution — is a meridian, and a
1828/// meridian lies in the half-plane spanned by the axis and its own radial
1829/// direction. So "where does the new section cross the neighbour's seam" is a
1830/// curve × plane crossing, in closed form, for all five at once. Returns `None`
1831/// for a carrier that is not a revolution or a seam that runs ON the axis.
1832fn seam_axial_plane(surface: &NurbsSurface, seam: &EdgeRecord) -> Option<Plane> {
1833    let structure = crate::revolution_structure(surface)?;
1834    let midpoint = seam
1835        .curve
1836        .evaluate(0.5 * (seam.t0 + seam.t1))
1837        .ok()?;
1838    let offset = midpoint.sub(structure.frame.origin);
1839    let radial = offset
1840        .sub(structure.frame.axis.scale(offset.dot(structure.frame.axis)))
1841        .normalized()
1842        .ok()?;
1843    let normal = structure.frame.axis.cross(radial).normalized().ok()?;
1844    Some(Plane {
1845        origin: structure.frame.origin,
1846        u_dir: structure.frame.axis,
1847        v_dir: radial,
1848        normal,
1849    })
1850}
1851
1852/// Recognise a loop that is a hole cut by ONE crossing carrier, or say why not.
1853///
1854/// Four conditions, each of which the rebuild depends on and none of which it
1855/// can check afterwards:
1856///
1857/// * every coedge's other face is the SAME neighbour — otherwise a corner IS a
1858///   triple point and belongs to `resolve_open_rim_end`;
1859/// * that neighbour is neither planar nor coaxial-ruled — the two lanes with
1860///   their own exact rebuilds, which must keep them (bit-identity);
1861/// * every edge is OPEN (a closed edge is the single-rim lane's business) —
1862///   except a loop that is ONE closed edge whose vertex is PINNED to the
1863///   neighbour's seam. That vertex is a corner, not the bookkeeping split the
1864///   single-rim lane places at the march's domain start (which lands it off the
1865///   seam: 2.923 on the crossing-pipe tee), and it is exactly the two-arc
1866///   window this lane already rebuilt, stored as the one edge it is;
1867/// * every corner vertex has valence two across the WHOLE solid, so relocating
1868///   it cannot strand a third face's boundary. This is what rules out the hole
1869///   that straddles the pushed carrier's periodic seam: its arcs are stitched
1870///   into the outer loop, so the loop fails the first condition long before the
1871///   valence test — and either way it is refused rather than torn.
1872///
1873/// Returns `Ok(None)` for a loop that is simply not this shape (the outer loop
1874/// of any ordinary push), so the caller falls through to the lanes it always
1875/// used.
1876#[allow(clippy::too_many_arguments)]
1877fn single_neighbour_hole(
1878    loop_record: &crate::topology::LoopRecord,
1879    face_id: u64,
1880    solid: &BrepSolid,
1881    faces_of_edge: &HashMap<u64, Vec<u64>>,
1882    edge_by_id: &HashMap<u64, &EdgeRecord>,
1883    frame_origin: Vec3,
1884    frame_axis: Vec3,
1885    scale: f64,
1886) -> Result<Option<SingleNeighbourHole>, KernelRefusal> {
1887    let debug = std::env::var("BREP_PUSH_HOLE_DEBUG").is_ok();
1888    let mut neighbour: Option<u64> = None;
1889    let mut edge_ids: Vec<u64> = Vec::new();
1890    for coedge in &loop_record.coedges {
1891        let edge = *edge_by_id.get(&coedge.edge_id).ok_or_else(|| {
1892            KernelRefusal::internal(
1893                KernelStage::Classify,
1894                "hole_edge",
1895                format!("offset_ruled_face: missing edge {}", coedge.edge_id),
1896            )
1897        })?;
1898        if edge.start_vertex_id == edge.end_vertex_id && loop_record.coedges.len() != 1 {
1899            if debug { eprintln!("HOLE reject: edge {} is closed", edge.id); }
1900            return Ok(None); // a closed rim among others: not one window.
1901        }
1902        let incident = faces_of_edge.get(&edge.id).cloned().unwrap_or_default();
1903        let others: Vec<u64> = incident.into_iter().filter(|f| *f != face_id).collect();
1904        if others.len() != 1 {
1905            if debug { eprintln!("HOLE reject: edge {} has {} others", edge.id, others.len()); }
1906            return Ok(None); // a seam, or a non-manifold edge.
1907        }
1908        match neighbour {
1909            Some(known) if known != others[0] => {
1910                if debug { eprintln!("HOLE reject: mixed neighbours {known} / {}", others[0]); }
1911                return Ok(None);
1912            }
1913            Some(_) => {}
1914            None => neighbour = Some(others[0]),
1915        }
1916        if !edge_ids.contains(&edge.id) {
1917            edge_ids.push(edge.id);
1918        }
1919    }
1920    let Some(neighbour) = neighbour else {
1921        return Ok(None);
1922    };
1923    // A lone CLOSED edge qualifies only once its vertex is shown to be pinned
1924    // (below); an OPEN lone edge never closes a window.
1925    let lone_closed = edge_ids.len() == 1
1926        && edge_by_id
1927            .get(&edge_ids[0])
1928            .is_some_and(|edge| edge.start_vertex_id == edge.end_vertex_id);
1929    if edge_ids.len() < 2 && !lone_closed {
1930        if debug { eprintln!("HOLE reject: only {} edges", edge_ids.len()); }
1931        return Ok(None);
1932    }
1933    let (nshell, nface) = find_face(solid, neighbour).ok_or_else(|| {
1934        KernelRefusal::internal(
1935            KernelStage::Classify,
1936            "hole_neighbour",
1937            format!("offset_ruled_face: missing neighbour {neighbour}"),
1938        )
1939    })?;
1940    let surface = &solid.shells[nshell].faces[nface].surface;
1941    if matches!(surface.analytic(), Some(AnalyticSurface::Plane { .. }))
1942        || ruled_neighbour_is_coaxial(surface, frame_origin, frame_axis, scale)
1943    {
1944        if debug { eprintln!("HOLE reject: neighbour {neighbour} is planar/coaxial"); }
1945        return Ok(None); // the two lanes that already have exact rebuilds.
1946    }
1947    // Every corner is either a free bookkeeping split (nothing else ends there)
1948    // or PINNED to one edge of the neighbour — its seam. Anything else ending
1949    // at a corner makes it a genuine junction of three or more faces, which
1950    // this lane does not solve.
1951    let neighbour_edges: HashSet<u64> = solid.shells[nshell].faces[nface]
1952        .loops
1953        .iter()
1954        .flat_map(|loop_record| &loop_record.coedges)
1955        .map(|coedge| coedge.edge_id)
1956        .collect();
1957    let mut pinned: Vec<(u64, u64)> = Vec::new();
1958    for edge_id in &edge_ids {
1959        let edge = *edge_by_id.get(edge_id).ok_or_else(|| {
1960            KernelRefusal::internal(
1961                KernelStage::Classify,
1962                "hole_pin_edge",
1963                format!("offset_ruled_face: missing edge {edge_id}"),
1964            )
1965        })?;
1966        for vertex_id in [edge.start_vertex_id, edge.end_vertex_id] {
1967            for other in &solid.edges {
1968                if other.start_vertex_id != vertex_id && other.end_vertex_id != vertex_id {
1969                    continue;
1970                }
1971                if edge_ids.contains(&other.id) {
1972                    continue;
1973                }
1974                if !neighbour_edges.contains(&other.id) {
1975                    if debug {
1976                        eprintln!("HOLE reject: vertex {vertex_id} also on foreign edge {}", other.id);
1977                    }
1978                    return Ok(None);
1979                }
1980                if pinned
1981                    .iter()
1982                    .any(|(known, pin)| *known == vertex_id && *pin != other.id)
1983                {
1984                    if debug {
1985                        eprintln!("HOLE reject: vertex {vertex_id} pinned by two neighbour edges");
1986                    }
1987                    return Ok(None);
1988                }
1989                if !pinned.iter().any(|(known, _)| *known == vertex_id) {
1990                    pinned.push((vertex_id, other.id));
1991                }
1992            }
1993        }
1994    }
1995    if lone_closed && pinned.is_empty() {
1996        // A free closed rim: its vertex is bookkeeping, the single-rim lane's.
1997        if debug { eprintln!("HOLE reject: lone closed edge {} is not pinned", edge_ids[0]); }
1998        return Ok(None);
1999    }
2000    if debug {
2001        eprintln!("HOLE accept: neighbour {neighbour} edges {edge_ids:?} pinned {pinned:?}");
2002    }
2003    Ok(Some(SingleNeighbourHole {
2004        neighbour,
2005        edge_ids,
2006        pinned,
2007    }))
2008}
2009
2010/// Rebuild a single-neighbour hole: re-intersect once, then cut the section.
2011#[allow(clippy::too_many_arguments)]
2012fn rebuild_single_neighbour_hole(
2013    solid: &BrepSolid,
2014    s_prime: &NurbsSurface,
2015    hole: &SingleNeighbourHole,
2016    edge_by_id: &HashMap<u64, &EdgeRecord>,
2017    vertex_pos: &HashMap<u64, Vec3>,
2018    tolerance: f64,
2019    scale: f64,
2020    new_curve: &mut HashMap<u64, NurbsCurve>,
2021    new_vertex: &mut HashMap<u64, Vec3>,
2022) -> Result<(), KernelRefusal> {
2023    let (nshell, nface) = find_face(solid, hole.neighbour).ok_or_else(|| {
2024        KernelRefusal::internal(
2025            KernelStage::Refine,
2026            "hole_rebuild_neighbour",
2027            format!("offset_ruled_face: missing neighbour {}", hole.neighbour),
2028        )
2029    })?;
2030    let neighbour_surface = &solid.shells[nshell].faces[nface].surface;
2031
2032    // Seed the march with the WHOLE old loop: the section replacing it runs
2033    // near it for any push small against the feature, and a blind seed grid on
2034    // two large carriers can miss a small window entirely.
2035    let mut seeds: Vec<Vec3> = Vec::new();
2036    let mut reference: Vec<Vec3> = Vec::new();
2037    for edge_id in &hole.edge_ids {
2038        let edge = *edge_by_id.get(edge_id).ok_or_else(|| {
2039            KernelRefusal::internal(
2040                KernelStage::Refine,
2041                "hole_seed_edge",
2042                format!("offset_ruled_face: missing edge {edge_id}"),
2043            )
2044        })?;
2045        let samples = edge_seeds(edge, 9)?;
2046        reference.extend(samples.iter().copied());
2047        seeds.extend(samples);
2048    }
2049    let policy = MarchPolicy {
2050        tolerance,
2051        residual_tolerance: (scale * 5e-4).max(5e-6),
2052        seeds,
2053    };
2054    let found = match reintersect_carriers(s_prime, neighbour_surface, &policy) {
2055        Ok(found) => found,
2056        Err(ReintersectRefusal::Separated) => {
2057            return Err(KernelRefusal::unsupported(
2058                KernelStage::Refine,
2059                "hole_separated",
2060                "offset_ruled_face: the pushed carrier no longer meets a neighbour \
2061                 (the push separated them, or the rim left the neighbour's domain) — refusing",
2062            ))
2063        }
2064        Err(other @ ReintersectRefusal::Residual { .. }) => {
2065            return Err(KernelRefusal::non_convergence(
2066                KernelStage::Refine,
2067                "hole_reintersect_residual",
2068                format!("offset_ruled_face: {}", other.describe()),
2069            ))
2070        }
2071        Err(other) => {
2072            return Err(KernelRefusal::internal(
2073                KernelStage::Refine,
2074                "hole_reintersect_failed",
2075                format!("offset_ruled_face: {}", other.describe()),
2076            ))
2077        }
2078    };
2079    if found.lane != RimLane::Marched {
2080        // An analytic section has no polyline to cut, and the exact lanes that
2081        // produce one already have their own arc rebuild. Refusing here keeps
2082        // this lane from re-deciding a case the closed forms own.
2083        return Err(KernelRefusal::unsupported(
2084            KernelStage::Refine,
2085            "hole_closed_form",
2086            format!(
2087            "offset_ruled_face: the window bounded by face {} re-intersects in CLOSED FORM, \
2088             whose arc rebuild is the analytic lane's — deferred (refusing)",
2089            hole.neighbour
2090        ),
2091        ));
2092    }
2093    if std::env::var("BREP_PUSH_HOLE_DEBUG").is_ok() {
2094        eprintln!(
2095            "HOLE rebuild neighbour {}: lane {:?}, {} branch(es), residual {:.3e} \
2096             (gate {:.3e})",
2097            hole.neighbour,
2098            found.lane,
2099            found.sections.len(),
2100            found.residual,
2101            policy.residual_tolerance
2102        );
2103    }
2104    // Which branch is THIS window: two windows cut by one crossing carrier
2105    // share a surface and so come back as two branches of one section set.
2106    let section = found
2107        .nearest_section(&reference)
2108        .map_err(|error| {
2109            KernelRefusal::internal(
2110                KernelStage::Refine,
2111                "nearest_section",
2112                format!("offset_ruled_face: {error}"),
2113            )
2114        })?;
2115
2116    // Corners first, so every arc is cut against the same relocated vertices.
2117    //
2118    // A corner PINNED to the neighbour's seam is not free to go to the nearest
2119    // sample: it must stay on that meridian, so it goes where the new section
2120    // CROSSES the meridian's axial half-plane. Placing it at the nearest sample
2121    // instead leaves it off the seam by the amount the section drifted, which
2122    // the neighbour's own re-trim then reports as "a relocated rim vertex left
2123    // curved neighbour N's edge" — a refusal where a correct answer exists.
2124    for edge_id in &hole.edge_ids {
2125        let edge = *edge_by_id.get(edge_id).ok_or_else(|| {
2126            KernelRefusal::internal(
2127                KernelStage::Fragment,
2128                "hole_corner_edge",
2129                format!("offset_ruled_face: missing edge {edge_id}"),
2130            )
2131        })?;
2132        for vertex_id in [edge.start_vertex_id, edge.end_vertex_id] {
2133            if new_vertex.contains_key(&vertex_id) {
2134                continue;
2135            }
2136            let old = *vertex_pos.get(&vertex_id).ok_or_else(|| {
2137                KernelRefusal::internal(
2138                    KernelStage::Fragment,
2139                    "hole_corner_vertex",
2140                    format!("offset_ruled_face: missing vertex {vertex_id}"),
2141                )
2142            })?;
2143            let point = match hole
2144                .pinned
2145                .iter()
2146                .find(|(known, _)| *known == vertex_id)
2147                .map(|(_, pin)| *pin)
2148            {
2149                Some(pin) => {
2150                    let seam = *edge_by_id.get(&pin).ok_or_else(|| {
2151                        KernelRefusal::internal(
2152                            KernelStage::Fragment,
2153                            "hole_pin_seam",
2154                            format!("offset_ruled_face: missing edge {pin}"),
2155                        )
2156                    })?;
2157                    let plane = seam_axial_plane(neighbour_surface, seam).ok_or_else(|| {
2158                        KernelRefusal::unsupported(
2159                            KernelStage::Fragment,
2160                            "pinned_non_revolution",
2161                            format!(
2162                            "offset_ruled_face: the window's corner is pinned to edge {pin} of a \
2163                             neighbour that is not a surface of revolution — refusing"
2164                        ),
2165                        )
2166                    })?;
2167                    // The correct crossing is inside the window itself, so the
2168                    // search reach is the window's own extent about this corner
2169                    // — the opposite meridian cannot win.
2170                    let reach = reference
2171                        .iter()
2172                        .map(|point| point.sub(old).length())
2173                        .fold(0.0f64, f64::max)
2174                        .max(tolerance * 100.0);
2175                    // A strict sign change, not `curve_plane_crossing_or_end_near`:
2176                    // `arc_of_section` cuts only a CLOSED traced section, and a
2177                    // closed curve does not stop on the seam plane — it passes
2178                    // through it, and where its parameter origin lies on the
2179                    // plane its two ends carry the same round-off, so the first
2180                    // or the last sampled interval brackets that crossing either
2181                    // way. Measured on every pinned corner in the lib, suite and
2182                    // case populations: the strict and the end-accepting crossing
2183                    // are the same point.
2184                    census_push("seam_crossings", || {
2185                        crossing_note(
2186                            &section.curve,
2187                            &plane,
2188                            curve_plane_crossing_near(&section.curve, &plane, old, reach),
2189                            curve_plane_crossing_or_end_near(&section.curve, &plane, old, reach, tolerance),
2190                            section.closed,
2191                        )
2192                    });
2193                    curve_plane_crossing_near(&section.curve, &plane, old, reach)
2194                        .map(|(_, point)| point)
2195                        .ok_or_else(|| {
2196                            KernelRefusal::internal(
2197                                KernelStage::Fragment,
2198                                "pinned_seam_crossing",
2199                                format!(
2200                                "offset_ruled_face: the rebuilt window never crosses the seam \
2201                                 (edge {pin}) its corner is pinned to — refusing"
2202                            ),
2203                            )
2204                        })?
2205                }
2206                None => section_corner(section, old).map_err(|error| {
2207                    KernelRefusal::internal(
2208                        KernelStage::Fragment,
2209                        "section_corner",
2210                        format!("offset_ruled_face: {error}"),
2211                    )
2212                })?,
2213            };
2214            new_vertex.insert(vertex_id, point);
2215        }
2216    }
2217    for edge_id in &hole.edge_ids {
2218        let edge = *edge_by_id.get(edge_id).ok_or_else(|| {
2219            KernelRefusal::internal(
2220                KernelStage::Fragment,
2221                "hole_arc_edge",
2222                format!("offset_ruled_face: missing edge {edge_id}"),
2223            )
2224        })?;
2225        let from = new_vertex[&edge.start_vertex_id];
2226        let to = new_vertex[&edge.end_vertex_id];
2227        // A closed edge asks `arc_of_section` for the whole section, whose
2228        // direction is read off a point the old edge reaches early: a quarter
2229        // of the way round by ARC LENGTH, and an open arc's midpoint the same
2230        // way. A fraction of the edge's PARAMETER range is that point only for a
2231        // uniform speed law; the crossing-pipe tee's window re-weighted by a
2232        // Möbius substitution put its quarter-parameter point past the half
2233        // turn, cut the section the wrong way round, and refused as "a rebuilt
2234        // rim traverses the carrier's periodic parameter differently".
2235        let through = if edge.start_vertex_id == edge.end_vertex_id {
2236            arc_length_stations(edge, 5, true)?[1]
2237        } else {
2238            arc_length_stations(edge, 3, true)?[1]
2239        };
2240        let arc = arc_of_section(section, from, to, through, tolerance).map_err(|error| {
2241            KernelRefusal::internal(
2242                KernelStage::Fragment,
2243                "arc_of_section",
2244                format!("offset_ruled_face: {error}"),
2245            )
2246        })?;
2247        new_curve.insert(edge.id, arc);
2248    }
2249    Ok(())
2250}
2251
2252/// Re-fit ONLY the pcurves whose edge actually changed, each back onto the
2253/// periodic branch of `u` the pcurve it replaces was on.
2254///
2255/// This is the CURVED-neighbour lane's re-trim, and it is deliberately not
2256/// [`crate::offset_retrim::retrim_face_in_solid`]. That driver rebuilds *every*
2257/// pcurve of the face, which is right for a ruled revolution (whose seam
2258/// coedges are straight generatrices whose rebuilt pcurves land back on their
2259/// own sides by luck of the parameterization) and **measurably wrong** for a
2260/// sphere or a torus. Measured on the ball-capped rod, `d = +0.5`:
2261///
2262/// | face | rebuilt-all | correct (independently built r = 3.5 solid) |
2263/// |---|---|---|
2264/// | wall seam coedge | `u: 0 → 0` | `u: 1 → 1` |
2265/// | dome seam coedge | `u: 0 → 0` | `u: 1 → 1` |
2266/// | dome pole coedge | `(0,1) → (0,1)` | `(1,1) → (0,1)` |
2267///
2268/// with a resulting solid that `validate()` accepts and whose Green's-theorem
2269/// volume reads **207.86 against the true 534.10** — the dome's parameter-space
2270/// loop collapsed to zero area because both of its seam sides ended up on the
2271/// same branch. Exactly the failure [`reanchor_pcurve_u`] was written for.
2272///
2273/// Two rules together fix it, and both are needed:
2274/// * **touch only what moved.** A neighbour that keeps its surface keeps every
2275///   pcurve whose edge did not change; rebuilding one is a chance to land on
2276///   the wrong branch for no gain.
2277/// * **re-anchor what is rebuilt**, by the whole-period shift that aligns its
2278///   start with the pcurve it replaces — the rebuilt rim traverses the same path
2279///   in the same direction, so aligning the starts fixes the branch, and
2280///   [`reanchor_pcurve_u`]'s end-drift check refuses anything that is not
2281///   merely re-anchored.
2282fn refit_changed_pcurves(
2283    result: &mut BrepSolid,
2284    face_id: u64,
2285    final_edges: &HashMap<u64, EdgeRecord>,
2286    changed: &HashSet<u64>,
2287    tolerance: f64,
2288) -> Result<(), KernelRefusal> {
2289    let (shell, face_pos) = find_face(result, face_id).ok_or_else(|| {
2290        KernelRefusal::internal(
2291            KernelStage::Sew,
2292            "refit_face",
2293            format!("offset_ruled_face: missing face {face_id}"),
2294        )
2295    })?;
2296    let surface = result.shells[shell].faces[face_pos].surface.clone();
2297    let [u_start, u_end] = surface.domain_u().or_refuse(KernelStage::Sew, "domain_u")?;
2298    let u_period = u_end - u_start;
2299    for loop_record in &mut result.shells[shell].faces[face_pos].loops {
2300        for coedge in &mut loop_record.coedges {
2301            if !changed.contains(&coedge.edge_id) {
2302                continue;
2303            }
2304            let edge = final_edges.get(&coedge.edge_id).ok_or_else(|| {
2305                KernelRefusal::internal(
2306                    KernelStage::Sew,
2307                    "refit_edge",
2308                    format!("offset_ruled_face: missing edge {}", coedge.edge_id),
2309                )
2310            })?;
2311            // Same subrange rule as `offset_retrim::rebuild_loop_pcurves`, so a rim that is
2312            // a strict piece of a full-domain curve keeps the range-aware fit it
2313            // has always had.
2314            let [d0, d1] = edge.curve.domain().or_refuse(KernelStage::Sew, "domain")?;
2315            let span = (d1 - d0).max(1e-12);
2316            let is_subrange =
2317                (edge.t0 - d0).abs() > 1e-9 * span || (edge.t1 - d1).abs() > 1e-9 * span;
2318            let pcurve = if is_subrange {
2319                build_pcurve_on_surface_range(
2320                    &surface,
2321                    &edge.curve,
2322                    edge.t0,
2323                    edge.t1,
2324                    coedge.forward,
2325                    tolerance,
2326                ).or_refuse(KernelStage::Sew, "build_pcurve_on_surface_range")?
2327            } else {
2328                let mut pcurve = build_pcurve_on_surface(&surface, &edge.curve).or_refuse(KernelStage::Sew, "build_pcurve_on_surface")?;
2329                if !coedge.forward {
2330                    pcurve = pcurve.reversed().or_refuse(KernelStage::Sew, "reversed")?;
2331                }
2332                pcurve
2333            };
2334            coedge.pcurve = reanchor_pcurve_u(&pcurve, &coedge.pcurve, u_period)?;
2335        }
2336    }
2337    Ok(())
2338}
2339
2340/// The curve in `curves` whose midpoint is nearest `reference` (branch selection
2341/// for a surface∩surface intersection that returns more than one component).
2342fn nearest_curve(curves: &[NurbsCurve], reference: Vec3) -> Result<NurbsCurve, KernelRefusal> {
2343    let mut best: Option<(f64, &NurbsCurve)> = None;
2344    for curve in curves {
2345        let mid = curve.evaluate(0.5).or_refuse(KernelStage::Refine, "evaluate")?;
2346        let d = mid.sub(reference).length();
2347        if best.map(|(best_d, _)| d < best_d).unwrap_or(true) {
2348            best = Some((d, curve));
2349        }
2350    }
2351    best.map(|(_, curve)| curve.clone())
2352        .ok_or_else(|| {
2353            KernelRefusal::internal(
2354                KernelStage::Refine,
2355                "empty_intersection",
2356                "offset_ruled_face: empty intersection",
2357            )
2358        })
2359}
2360