BREP_blend 0.33.0

Rust B-rep CAD kernel (next.BREP.io): fillets, chamfers and blends.
Documentation
//! `BREP_FILLET_ROLLOVER_BUILD` (default off): a convex closed rim whose one
//! mate is a planar STRIP narrower than the ball's reach, bounded on its far
//! side by a single closed edge across which a tangent round continues.
//!
//! The ball never touches the strip: it rides the wall and the round beside
//! the strip (the "pad"), and the strip is consumed whole. There is no
//! crossing for the closed-rim rollover to split at, so the lane marches the
//! wall against the pad directly. The pad's mate coedge is its own coedge on
//! the strip's far edge, read by the blended edge's parameter fraction, which
//! is exact only when the two edges run the same way and start abreast: that
//! is checked, and anything else declines. The surgery trims the pad at that
//! far edge and deletes the strip.
//!
//! Every answer other than a built body is `Ok(None)` or an error the caller
//! drops, so the ordinary refusal stands unchanged.
use super::*;

/// Try the consumed-strip build for `edge` between `mates`; `Ok(None)` when
/// the shape is not this case.
#[allow(clippy::too_many_arguments)]
pub(super) fn blend_consumed_strip(
    solid: &BrepSolid,
    edge: &EdgeRecord,
    mates: [&BlendMate; 2],
    radius_at: &dyn Fn(f64) -> f64,
    radius: f64,
    rail_bar: f64,
    wall_check: Option<crate::blend::stations::ClosedWallCheck>,
    name: Option<&str>,
) -> Result<Option<BrepSolid>, KernelRefusal> {
    let debug = std::env::var("BREP_DEBUG_NETWORK").is_ok();
    let Some((strip_side, far_loop)) = (0..2).find_map(|side| strip_shape(solid, edge, mates[side]).map(|far| (side, far))) else {
        return Ok(None);
    };
    let strip = mates[strip_side];
    let wall = mates[1 - strip_side];
    let far_coedge = &strip.face.loops[far_loop].coedges[0];
    let rim = solid
        .edges
        .iter()
        .find(|candidate| candidate.id == far_coedge.edge_id)
        .ok_or(KernelRefusal::internal(KernelStage::Classify, "consumed_strip_rim", "blend: the strip's far edge is missing"))?;
    if rim.start_vertex_id != rim.end_vertex_id || rim.id == edge.id {
        return Ok(None);
    }
    let (pad, pad_loop, pad_coedge) = locate_mate(solid, rim.id, Some((strip.face.id, far_loop)))?;
    if pad.id == wall.face.id || pad.id == strip.face.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 strip: edge {} and the strip's far edge {} are not abreast", edge.id, rim.id);
        }
        return Ok(None);
    }
    // Signed radii from the wall and the strip, which meet at the edge. The
    // ball is inside the material (a convex rim), 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, wall.face, wall.coedge, strip.face, strip.coedge, radius)?;
    let (rho_wall, rho_strip) = (rho_first, rho_second);
    let strip_sense = if strip.face.same_sense { 1.0 } else { -1.0 };
    if rho_strip * strip_sense >= 0.0 {
        return Ok(None);
    }
    let Some(rho_pad) = pad_rho(strip.face, far_coedge, rim, pad, pad_coedge, rho_strip)? else {
        if debug {
            eprintln!("consumed strip: the pad {} does not continue the strip {} tangentially along edge {}", pad.id, strip.face.id, rim.id);
        }
        return Ok(None);
    };
    let wall_mate = BlendMate { face: wall.face, coedge: wall.coedge, loop_index: wall.loop_index, rho: rho_wall };
    let pad_mate = BlendMate { face: pad, coedge: pad_coedge, loop_index: pad_loop, rho: rho_pad };

    // Seam-structured mates as the closed lane orders them.
    let seam_wall = wall_mate.face.loops[wall_mate.loop_index].coedges.len() > 1;
    let seam_pad = pad.loops[pad_loop].coedges.len() > 1;
    let (first, second) = if seam_wall || !seam_pad { (wall_mate, pad_mate) } else { (pad_mate, wall_mate) };
    let anchored = first.face.loops[first.loop_index].coedges.len() > 1;
    let second_seam = anchored && second.face.loops[second.loop_index].coedges.len() > 1;
    let anchor_u = if anchored { Some(first.face.surface.domain_u().or_refuse(KernelStage::Refine, "domain_u")?[0]) } else { None };

    let exact_revolution = crate::blend::stations::closed_revolution_axis(&first, &second).is_some();
    let depth_budget = if exact_revolution { 0 } else { MAX_REFINEMENT_DEPTH };
    use crate::blend::chain::FoldPolicy;
    let march = |anchor: Option<f64>| {
        march_stations_with_rail_bar(edge, &first, &second, radius_at, anchor, FoldPolicy::Refuse, depth_budget, rail_bar, wall_check)
            .map_err(|failure| match failure.into_initial() {
                Ok(error) | Err(error) => error,
            })
    };
    let stations = match march(anchor_u) {
        Ok(stations) => stations,
        Err(anchored_error) if anchor_u.is_some() => match march(None) {
            Ok(stations) => stations,
            Err(_) => return Err(anchored_error),
        },
        Err(error) => return Err(error),
    };

    // The ball must ride the wall and the pad inside their trims, and clear
    // the strip it consumes at every station.
    let pad_second = std::ptr::eq(second.face, pad);
    let (wall_face, pad_face) = (wall.face, pad);
    for station in &stations {
        let (uv_wall, uv_pad) = if pad_second { (station.uv1, station.uv2) } else { (station.uv2, station.uv1) };
        if support_exits_at(wall_face, uv_wall) || support_exits_at(pad_face, uv_pad) {
            if debug {
                eprintln!("consumed strip: a contact leaves the wall {} or the pad {}", wall_face.id, pad_face.id);
            }
            return Ok(None);
        }
        if !clears_strip(strip.face, &[edge, rim], station.center, radius)? {
            if debug {
                eprintln!("consumed strip: the ball at {:?} touches the strip {}", station.center, strip.face.id);
            }
            return Ok(None);
        }
    }
    crate::blend::record_count("count.closed.consumed_strip", 1);

    let parameters = crate::blend::stations::closed_station_parameters(&stations, [&first.face.surface, &second.face.surface]);
    let rows = match exact_closed_revolution_rows(&stations, &first, &second, false) {
        Some(rows) => rows?,
        None => {
            let mut rows = fit_closed_rows(&stations, &parameters, false)?;
            let read_first = crate::blend::closed_trim_read_first_on();
            for (rail, pcurve, surface) in [
                (&rows.cr, &mut rows.cr_pcurve, &first.face.surface),
                (&rows.cs, &mut rows.cs_pcurve, &second.face.surface),
            ] {
                *pcurve = if read_first {
                    closed_support_trim(rail, pcurve, surface)?
                } else {
                    refit_closed_support_pcurve(rail, pcurve, surface)?
                };
            }
            rows
        }
    };
    let second_split = if second_seam { second_seam_split(second.face, &stations, &parameters, &rows)? } else { None };
    let consumed = ConsumedStrip { pad_face: pad.id, pad_rim: rim.clone(), strip_face: strip.face.id };
    let built = build_surgery(solid, edge, &first, &second, rows, second_split, name, None, Some(&consumed))?;
    Ok(Some(built))
}

/// The strip's far loop when `mate` is a planar strip of two loops: the
/// blended edge's loop and one other, each a single closed coedge.
fn strip_shape(solid: &BrepSolid, edge: &EdgeRecord, mate: &BlendMate) -> Option<usize> {
    let face = mate.face;
    if !matches!(face.surface.analytic(), Some(crate::AnalyticSurface::Plane { .. })) || face.loops.len() != 2 {
        return None;
    }
    if face.loops[mate.loop_index].coedges.len() != 1 || face.loops[mate.loop_index].coedges[0].edge_id != edge.id {
        return None;
    }
    let far = 1 - mate.loop_index;
    let coedges = &face.loops[far].coedges;
    (coedges.len() == 1 && solid.edges.iter().any(|candidate| candidate.id == coedges[0].edge_id)).then_some(far)
}

/// Whether `rim` runs the same way as `edge` and abreast of it at the same
/// parameter fractions: the tangents agree and the offset between the two
/// points is square to them.
pub(in crate::blend) fn abreast(edge: &EdgeRecord, rim: &EdgeRecord, scale: f64) -> Result<bool, KernelRefusal> {
    for fraction in [0.0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875] {
        let at = |record: &EdgeRecord| -> Result<(Vec3, Vec3), KernelRefusal> {
            let t = record.t0 + (record.t1 - record.t0) * fraction;
            let point = record.curve.evaluate(t).or_refuse(KernelStage::Classify, "evaluate")?;
            let tangent = record
                .curve
                .unit_tangent(t, record.t0, record.t1)
                .map_err(|error| format!("blend: edge {}: {error}", record.id))
                .or_refuse(KernelStage::Classify, "unit_tangent")?;
            Ok((point, tangent))
        };
        let (p_edge, d_edge) = at(edge)?;
        let (p_rim, d_rim) = at(rim)?;
        if d_edge.dot(d_rim) < 1.0 - 1e-9 || p_edge.sub(p_rim).dot(d_edge).abs() > 1e-9 * scale.max(1.0) {
            return Ok(false);
        }
    }
    Ok(true)
}

/// Whether a ball of `radius` about `center` stays off the planar strip
/// `face` (bounded by `boundary`): it does not reach the strip's plane, or the
/// disc it cuts from that plane lies wholly off the face.
pub(in crate::blend) fn clears_strip(face: &FaceRecord, boundary: &[&EdgeRecord], center: Vec3, radius: f64) -> Result<bool, KernelRefusal> {
    let projection = crate::project_point_to_surface(&face.surface, center).or_refuse(KernelStage::Classify, "project_point_to_surface")?;
    let normal = raw_normal(&face.surface, projection.u, projection.v)?.normalized().or_refuse(KernelStage::Classify, "normalized")?;
    let height = center.sub(projection.point).dot(normal).abs();
    let band = 1e-9 * (1.0 + center.length());
    if height >= radius - band {
        return Ok(true);
    }
    // The disc the ball cuts from the plane, about the foot.
    let disc = (radius * radius - height * height).sqrt();
    let foot = projection.point;
    for &record in boundary {
        let nearest = crate::project_point_to_curve(&record.curve, foot).or_refuse(KernelStage::Classify, "project_point_to_curve")?;
        if nearest.distance < disc + band {
            return Ok(false);
        }
    }
    // Clear of both boundary edges, so wholly on one side: off the face.
    let class = crate::parameter_point_in_face(face, crate::Vec2 { x: projection.u, y: projection.v }, 1e-9)
        .map_err(|error| format!("blend: strip {} containment: {error}", face.id))
        .or_refuse(KernelStage::Classify, "parameter_point_in_face")?;
    Ok(class == crate::PolygonClass::Outside)
}

/// The pad's signed radius when `pad` continues the planar strip `strip`
/// tangentially across `rim` (the strip's coedge `far_coedge`, the pad's
/// `pad_coedge`) on the same material side: the strip's `rho_strip` carried
/// over, sign-matched to the pad's raw normal. `None` when the two are not
/// tangent along the rim, the material sides disagree, or the sign varies.
pub(in crate::blend) fn pad_rho(
    strip: &FaceRecord,
    far_coedge: &CoedgeRecord,
    rim: &EdgeRecord,
    pad: &FaceRecord,
    pad_coedge: &CoedgeRecord,
    rho_strip: f64,
) -> Result<Option<f64>, KernelRefusal> {
    let strip_sense = if strip.same_sense { 1.0 } else { -1.0 };
    let pad_sense = if pad.same_sense { 1.0 } else { -1.0 };
    let mut rho_pad = None;
    for fraction in [0.0, 0.25, 0.5, 0.75] {
        let t = rim.t0 + (rim.t1 - rim.t0) * fraction;
        let uv_strip = edge_uv_on_face(far_coedge, rim, t)?;
        let uv_pad = edge_uv_on_face(pad_coedge, rim, t)?;
        let n_strip = raw_normal(&strip.surface, uv_strip[0], uv_strip[1])?.normalized().or_refuse(KernelStage::Classify, "normalized")?;
        let n_pad = raw_normal(&pad.surface, uv_pad[0], uv_pad[1])?.normalized().or_refuse(KernelStage::Classify, "normalized")?;
        if n_strip.cross(n_pad).length() > 1e-6 {
            return Ok(None);
        }
        // Same material side: the outward normals agree.
        if n_strip.scale(strip_sense).dot(n_pad.scale(pad_sense)) <= 0.0 {
            return Ok(None);
        }
        let rho = rho_strip * n_strip.dot(n_pad).signum();
        if rho_pad.is_some_and(|known| known != rho) {
            return Ok(None);
        }
        rho_pad = Some(rho);
    }
    Ok(rho_pad)
}