BREP_blend 0.34.1

Rust B-rep CAD kernel (next.BREP.io): fillets, chamfers and blends.
Documentation
//! A closed rim's blend whose rail lands ON the ring edge across its mate
//! face: that face is consumed whole.
//!
//! The reported part is a shelled cylinder whose 1 mm rim (an annulus between
//! r = 4 and r = 5) has both its edges filleted r = 0.5. The first blend's
//! rail is the circle r = 4.5; the second blend's rail is the same circle. The
//! closed lane rebuilt the annulus between them as a planar face of two one-
//! edge loops on coincident circles: area 2e-14, `validate()`-clean, closure
//! clean, the right volume, and drawn by the tessellator as two wild flaps.
//!
//! After the surgery each mate face is read: when it is exactly two rings, one
//! edge each, and the two edges retrace each other within [`consumed_band`]
//! (sampled in 3D under the fraction map `validate` itself reads a coedge by,
//! same or opposite direction), the face is dropped, the other user of one
//! ring is sewn onto the other ring with its sense set by the direction, and
//! the ring's vertex is merged. Pcurves stay: a coedge's pcurve runs in its
//! own traversal direction, and that traversal does not move in 3D.
//!
//! Anything else (the rings' vertices apart, a ring with more than one other
//! user, the two other users not opposing) keeps the built body unchanged,
//! and so does a snap that breaks the shell's closure.
//! `BREP_FILLET_RING_COLLAPSE=0` turns it off.
use super::*;

/// On by default; `BREP_FILLET_RING_COLLAPSE=0` keeps the zero-width face.
pub(super) fn ring_collapse_on() -> bool {
    switch!("BREP_FILLET_RING_COLLAPSE", true)
}

/// Samples per ring for the coincidence read (fractions `k / SAMPLES`).
const SAMPLES: usize = 64;

struct RingCollapse {
    face_id: u64,
    keep_edge: u64,
    drop_edge: u64,
    /// The dropped ring's other user: (face id, loop index, coedge index).
    user: (u64, usize, usize),
    /// That user's sense on the kept edge.
    user_forward: bool,
    keep_vertex: u64,
    drop_vertex: u64,
    deviation: f64,
}

/// Collapse every face in `face_ids` that the blend left as two coincident
/// rings. `input` is the solid before the blend (its band and its closure).
pub(super) fn collapse_coincident_rings(input: &BrepSolid, mut result: BrepSolid, face_ids: [u64; 2]) -> Result<BrepSolid, KernelRefusal> {
    if !ring_collapse_on() {
        return Ok(result);
    }
    let band = super::super::consumed_band(input);
    for face_id in face_ids {
        let Some(plan) = plan(&result, face_id, band)? else {
            continue;
        };
        let before = result.clone();
        apply(&mut result, &plan);
        if super::super::check_snap_closure(&before, &result, plan.deviation).is_err() {
            result = before;
            continue;
        }
        crate::blend::record_count("count.closed.ring_collapse", 1);
    }
    Ok(result)
}

fn plan(solid: &BrepSolid, face_id: u64, band: f64) -> Result<Option<RingCollapse>, KernelRefusal> {
    let Some(face) = solid.shells.iter().flat_map(|shell| &shell.faces).find(|face| face.id == face_id) else {
        return Ok(None);
    };
    if face.loops.len() != 2 || face.loops.iter().any(|loop_record| loop_record.coedges.len() != 1) {
        return Ok(None);
    }
    let (first, second) = (face.loops[0].coedges[0].edge_id, face.loops[1].coedges[0].edge_id);
    if first == second {
        return Ok(None);
    }
    // Keep the older edge: the one an earlier feature already named.
    let (keep_id, drop_id) = (first.min(second), first.max(second));
    let edge = |id: u64| solid.edges.iter().find(|edge| edge.id == id);
    let (Some(keep), Some(drop)) = (edge(keep_id), edge(drop_id)) else {
        return Ok(None);
    };
    for ring in [keep, drop] {
        if ring.degenerate || ring.start_vertex_id != ring.end_vertex_id || !(ring.t1 > ring.t0) {
            return Ok(None);
        }
    }
    // Each ring has exactly one other user, on another face.
    let other_user = |edge_id: u64| -> Option<(u64, usize, usize, bool)> {
        let mut found = None;
        for other in solid.shells.iter().flat_map(|shell| &shell.faces) {
            for (loop_index, loop_record) in other.loops.iter().enumerate() {
                for (coedge_index, coedge) in loop_record.coedges.iter().enumerate() {
                    if coedge.edge_id != edge_id || other.id == face_id {
                        continue;
                    }
                    if found.is_some() {
                        return None;
                    }
                    found = Some((other.id, loop_index, coedge_index, coedge.forward));
                }
            }
        }
        found
    };
    let (Some(keep_user), Some(drop_user)) = (other_user(keep_id), other_user(drop_id)) else {
        return Ok(None);
    };
    if keep_user.0 == drop_user.0 {
        return Ok(None);
    }
    // The two rings retrace each other, read by fraction the way `validate`
    // reads a coedge: the same direction, or the opposite one. Fraction 0
    // and 1 are the rings' own vertex, so this also places the vertices.
    let at = |ring: &EdgeRecord, fraction: f64| ring.curve.evaluate(ring.t0 + (ring.t1 - ring.t0) * fraction).or_refuse(KernelStage::Refine, "evaluate");
    let (mut same, mut opposite) = (0.0f64, 0.0f64);
    for sample in 0..=SAMPLES {
        let fraction = sample as f64 / SAMPLES as f64;
        let on_drop = at(drop, fraction)?;
        same = same.max(on_drop.sub(at(keep, fraction)?).length());
        opposite = opposite.max(on_drop.sub(at(keep, 1.0 - fraction)?).length());
    }
    let reversed = opposite < same;
    let deviation = same.min(opposite);
    if !(deviation <= band) {
        return Ok(None);
    }
    // The sewn user must oppose the kept ring's own other user.
    let user_forward = drop_user.3 != reversed;
    if user_forward == keep_user.3 {
        return Ok(None);
    }
    Ok(Some(RingCollapse {
        face_id,
        keep_edge: keep_id,
        drop_edge: drop_id,
        user: (drop_user.0, drop_user.1, drop_user.2),
        user_forward,
        keep_vertex: keep.start_vertex_id,
        drop_vertex: drop.start_vertex_id,
        deviation,
    }))
}

fn apply(solid: &mut BrepSolid, plan: &RingCollapse) {
    for shell in &mut solid.shells {
        shell.faces.retain(|face| face.id != plan.face_id);
        for face in &mut shell.faces {
            if face.id != plan.user.0 {
                continue;
            }
            let coedge = &mut face.loops[plan.user.1].coedges[plan.user.2];
            coedge.edge_id = plan.keep_edge;
            coedge.forward = plan.user_forward;
        }
    }
    solid.edges.retain(|edge| edge.id != plan.drop_edge);
    if plan.drop_vertex != plan.keep_vertex {
        for edge in &mut solid.edges {
            if edge.start_vertex_id == plan.drop_vertex {
                edge.start_vertex_id = plan.keep_vertex;
            }
            if edge.end_vertex_id == plan.drop_vertex {
                edge.end_vertex_id = plan.keep_vertex;
            }
        }
        solid.vertices.retain(|vertex| vertex.id != plan.drop_vertex);
    }
}