BREP_blend 0.33.0

Rust B-rep CAD kernel (next.BREP.io): fillets, chamfers and blends.
Documentation
//! `BREP_FILLET_ROLLOVER_BUILD` (default off): an OPEN convex edge whose one
//! mate is a planar STRIP narrower than the ball's reach, a quad whose far
//! edge runs abreast of the blended edge with a tangent round (the "pad")
//! beyond it, and whose two end edges lie on the faces that cap the edge.
//!
//! The ball never touches the strip: it rides the wall and the pad, and the
//! strip is consumed whole (the closed-rim form is `closed_consumed.rs`). The
//! open lane marches and sews the wall against the pad on a SCRATCH copy of
//! the body in which the strip is gone: the pad's coedge on the strip's far
//! edge becomes a coedge of the blended edge (its pcurve read by the blended
//! edge's parameter fraction, exact because the two edges are abreast), the
//! strip's end edges leave the end faces, and the far edge's vertices are
//! identified with the blended edge's. The scratch is not a body: only the
//! parts of it the surgery cuts away (the end boundaries between the
//! blended edge's vertices and the rails' crossings) are out of place, and
//! the surgery removes them. The built body is validated; anything else is
//! `Ok(None)` or an error the caller drops, so the refusal stands unchanged.
use super::*;
use super::super::closed::{consumed_abreast as abreast, consumed_clears_strip as clears_strip, consumed_pad_rho as pad_rho, support_exits_at};

/// Try the consumed-strip build of the open edge `edge_id` at the constant
/// `radius`; `Ok(None)` when the shape is not this case or the build does
/// not stand.
pub(crate) fn blend_consumed_open_strip(solid: &BrepSolid, edge_id: u64, radius: f64, name: Option<&str>) -> Result<Option<BrepSolid>, KernelRefusal> {
    if !(radius > 0.0) || !radius.is_finite() {
        return Ok(None);
    }
    let debug = std::env::var("BREP_DEBUG_NETWORK").is_ok();
    let Some(edge) = solid.edges.iter().find(|candidate| candidate.id == edge_id) else {
        return Ok(None);
    };
    if edge.start_vertex_id == edge.end_vertex_id {
        return Ok(None);
    }
    let first = locate_mate(solid, edge_id, None)?;
    let second = locate_mate(solid, edge_id, Some((first.0.id, first.1)))?;
    let mates = [first, second];
    let Some((strip_side, far)) = (0..2).find_map(|side| strip_shape(mates[side].0, mates[side].1, edge_id).map(|far| (side, far))) else {
        return Ok(None);
    };
    let (strip, strip_loop, _) = mates[strip_side];
    let (wall, wall_loop, _) = mates[1 - strip_side];
    let coedges = &strip.loops[strip_loop].coedges;
    let far_coedge = &coedges[far];
    let find = |id: u64| solid.edges.iter().find(|candidate| candidate.id == id);
    let (Some(rim), Some(before), Some(after)) = (find(far_coedge.edge_id), find(coedges[(far + 1) % 4].edge_id), find(coedges[(far + 3) % 4].edge_id)) else {
        return Ok(None);
    };
    let rim_vertices = [rim.start_vertex_id, rim.end_vertex_id];
    if rim_vertices[0] == rim_vertices[1] || rim_vertices.iter().any(|vertex| *vertex == edge.start_vertex_id || *vertex == edge.end_vertex_id) {
        return Ok(None);
    }
    let (pad, pad_loop, pad_coedge) = locate_mate(solid, rim.id, Some((strip.id, strip_loop)))?;
    if pad.id == wall.id || pad.id == strip.id {
        return Ok(None);
    }
    // The pad coedge is read by the blended edge's fraction: both edges must
    // run the same way and start abreast.
    if !abreast(edge, rim, crate::solid_scale(solid))? {
        if debug {
            eprintln!("consumed open strip: edge {} and the strip's far edge {} are not abreast", edge.id, rim.id);
        }
        return Ok(None);
    }
    // The strip's end edges, each joining one end of the blended edge to the
    // same end of the far edge.
    let joins = |record: &EdgeRecord, a: u64, b: u64| {
        (record.start_vertex_id == a && record.end_vertex_id == b) || (record.start_vertex_id == b && record.end_vertex_id == a)
    };
    let ends = if joins(before, edge.start_vertex_id, rim.start_vertex_id) && joins(after, edge.end_vertex_id, rim.end_vertex_id) {
        [before.id, after.id]
    } else if joins(after, edge.start_vertex_id, rim.start_vertex_id) && joins(before, edge.end_vertex_id, rim.end_vertex_id) {
        [after.id, before.id]
    } else {
        return Ok(None);
    };
    // Each far vertex is met by the far edge, its strip end edge and one pad
    // end edge only, which the scratch moves onto the blended edge's vertex.
    for vertex in rim_vertices {
        let valence = solid.edges.iter().filter(|record| record.start_vertex_id == vertex || record.end_vertex_id == vertex).count();
        if valence != 3 {
            return Ok(None);
        }
    }
    // Signed radii from the wall and the strip, which meet at the edge. The
    // ball is inside the material (a convex edge), and the pad is tangent to
    // the strip along the far edge, so its centre side carries over.
    let (rho_first, rho_second) = signed_radii(edge, mates[0].0, mates[0].2, mates[1].0, mates[1].2, radius)?;
    let (rho_wall, rho_strip) = if strip_side == 1 { (rho_first, rho_second) } else { (rho_second, rho_first) };
    let strip_sense = if strip.same_sense { 1.0 } else { -1.0 };
    if rho_strip * strip_sense >= 0.0 {
        return Ok(None);
    }
    let Some(rho_pad) = pad_rho(strip, far_coedge, rim, pad, pad_coedge, rho_strip)? else {
        if debug {
            eprintln!("consumed open strip: the pad {} does not continue the strip {} tangentially along edge {}", pad.id, strip.id, rim.id);
        }
        return Ok(None);
    };

    let scratch = rewired(solid, edge, rim, strip.id, ends);
    let face_in = |id: u64| scratch.shells.iter().flat_map(|shell| &shell.faces).find(|face| face.id == id);
    let (Some(scratch_wall), Some(scratch_pad)) = (face_in(wall.id), face_in(pad.id)) else {
        return Ok(None);
    };
    let (Some(scratch_wall_coedge), Some(scratch_pad_coedge)) = (rim_coedge(scratch_wall, wall_loop, edge_id), rim_coedge(scratch_pad, pad_loop, edge_id)) else {
        return Ok(None);
    };
    let wall_mate = BlendMate { face: scratch_wall, coedge: scratch_wall_coedge, loop_index: wall_loop, rho: rho_wall };
    let pad_mate = BlendMate { face: scratch_pad, coedge: scratch_pad_coedge, loop_index: pad_loop, rho: rho_pad };
    // The mates in the edge's own order.
    let (first_mate, second_mate) = if strip_side == 1 { (&wall_mate, &pad_mate) } else { (&pad_mate, &wall_mate) };

    // The ball must ride the wall and the pad inside their trims, and clear
    // the strip it consumes, at every station along the edge.
    let radius_at = |_: f64| radius;
    let (stations, [low, high], _, _) =
        march_open_stations_core(edge, first_mate, second_mate, &radius_at, 0.0, [edge.t0, edge.t1], STATIONS, [false, false], [false, false], None, 0, true)?;
    let Some(along) = stations.get(low..=high).filter(|along| along.len() > 1) else {
        return Ok(None);
    };
    for station in along {
        let (uv_wall, uv_pad) = if strip_side == 1 { (station.uv1, station.uv2) } else { (station.uv2, station.uv1) };
        if support_exits_at(wall, uv_wall) || support_exits_at(pad, uv_pad) {
            if debug {
                eprintln!("consumed open strip: a contact leaves the wall {} or the pad {}", wall.id, pad.id);
            }
            return Ok(None);
        }
        if !clears_strip(strip, &[edge, rim], station.center, radius)? {
            if debug {
                eprintln!("consumed open strip: the ball at {:?} touches the strip {}", station.center, strip.id);
            }
            return Ok(None);
        }
    }
    let Some(scratch_edge) = scratch.edges.iter().find(|candidate| candidate.id == edge_id) else {
        return Ok(None);
    };
    let built = super::blend_open_edge_mated(&scratch, scratch_edge, first_mate, second_mate, &radius_at, Some(radius), false, name)?;
    let issues = built.validate();
    if !issues.is_empty() {
        if debug {
            eprintln!("consumed open strip: the built body does not validate: {issues:?}");
        }
        return Ok(None);
    }
    crate::blend::record_count("count.open.consumed_strip", 1);
    Ok(Some(built))
}

/// The coedge of `edge_id` in loop `loop_index` of `face`.
fn rim_coedge(face: &FaceRecord, loop_index: usize, edge_id: u64) -> Option<&CoedgeRecord> {
    face.loops.get(loop_index)?.coedges.iter().find(|coedge| coedge.edge_id == edge_id)
}

/// The index of the strip's far coedge when the mate `face` (loop
/// `loop_index`) is a planar quad: one loop of four coedges, the blended
/// edge's among them.
fn strip_shape(face: &FaceRecord, loop_index: usize, edge_id: u64) -> Option<usize> {
    if !matches!(face.surface.analytic(), Some(crate::AnalyticSurface::Plane { .. })) || face.loops.len() != 1 {
        return None;
    }
    let coedges = &face.loops.get(loop_index)?.coedges;
    if coedges.len() != 4 {
        return None;
    }
    let at = coedges.iter().position(|coedge| coedge.edge_id == edge_id)?;
    Some((at + 2) % 4)
}

/// The scratch body: the strip face and its far and end edges removed, the
/// far edge's vertices identified with the blended edge's (the pad's end
/// edges now meet the wall's at the blended edge's vertices), and the pad's
/// coedge on the far edge made a coedge of the blended edge.
fn rewired(solid: &BrepSolid, edge: &EdgeRecord, rim: &EdgeRecord, strip: u64, ends: [u64; 2]) -> BrepSolid {
    let mut scratch = solid.clone();
    let moved = |vertex: u64| {
        if vertex == rim.start_vertex_id {
            edge.start_vertex_id
        } else if vertex == rim.end_vertex_id {
            edge.end_vertex_id
        } else {
            vertex
        }
    };
    scratch.edges.retain(|record| record.id != rim.id && !ends.contains(&record.id));
    for record in &mut scratch.edges {
        record.start_vertex_id = moved(record.start_vertex_id);
        record.end_vertex_id = moved(record.end_vertex_id);
    }
    scratch.vertices.retain(|vertex| vertex.id != rim.start_vertex_id && vertex.id != rim.end_vertex_id);
    for shell in &mut scratch.shells {
        shell.faces.retain(|face| face.id != strip);
        for face in &mut shell.faces {
            for loop_record in &mut face.loops {
                loop_record.coedges.retain(|coedge| !ends.contains(&coedge.edge_id));
                for coedge in &mut loop_record.coedges {
                    if coedge.edge_id == rim.id {
                        coedge.edge_id = edge.id;
                    }
                }
            }
        }
    }
    scratch
}