BREP_topology 0.34.1

Rust B-rep CAD kernel (next.BREP.io): topology layer: B-rep solids, validation, soundness, classification, mass properties and tessellation.
Documentation
use super::*;

/// Coedge uses by edge ID, counting both uses of a seam independently.
pub fn edge_use_counts(solid: &BrepSolid) -> rustc_hash::FxHashMap<u64, usize> {
    let mut counts = rustc_hash::FxHashMap::default();
    for coedge in solid
        .shells
        .iter()
        .flat_map(|shell| &shell.faces)
        .flat_map(|face| &face.loops)
        .flat_map(|loop_record| &loop_record.coedges)
    {
        *counts.entry(coedge.edge_id).or_default() += 1;
    }
    counts
}

/// Nearest successfully projected edge and its distance, clamped to the edge's
/// trimmed interval. Strict comparison preserves edge order when distances tie.
pub fn nearest_edge(solid: &BrepSolid, point: Vec3) -> Option<(u64, f64)> {
    // Every point of a curve with positive weights lies in the box of its
    // control points, so the distance to that box bounds the edge's distance
    // from below. An edge whose bound is past a distance another edge already
    // reaches (`reach`, read from the edge with the smallest bound) cannot
    // become the answer. The scan below skips those edges and keeps the
    // original order and strict comparison, so it returns the first edge at
    // the minimum, as the full scan does. Bodies of a thousand faces held a
    // projection per edge per pick (the benchy stern round: 1.1 s for nine
    // picks).
    let bounds: Vec<f64> = solid.edges.iter().map(|edge| hull_distance_bound(&edge.curve, point)).collect();
    let reach = bounds
        .iter()
        .enumerate()
        .filter(|(_, bound)| bound.is_finite())
        .min_by(|a, b| a.1.total_cmp(b.1))
        .and_then(|(index, _)| edge_distance(&solid.edges[index], point))
        .filter(|distance| distance.is_finite());
    let mut best: Option<(u64, f64)> = None;
    for (edge, bound) in solid.edges.iter().zip(&bounds) {
        if let Some(reach) = reach {
            // The bound is exact arithmetic on the control points; the
            // margin covers the rounding of the curve's evaluation.
            if *bound > reach + 1e-9 * (1.0 + reach + point.length()) {
                continue;
            }
        }
        let Some(distance) = edge_distance(edge, point) else {
            continue;
        };
        if best.map(|(_, known)| distance < known).unwrap_or(true) {
            best = Some((edge.id, distance));
        }
    }
    // `BREP_NEAREST_EDGE_CHECK=1`: the full scan too, compared to the bit.
    if crate::debug_flag!("BREP_NEAREST_EDGE_CHECK") {
        let mut full: Option<(u64, f64)> = None;
        for edge in &solid.edges {
            let Some(distance) = edge_distance(edge, point) else { continue };
            if full.map(|(_, known)| distance < known).unwrap_or(true) {
                full = Some((edge.id, distance));
            }
        }
        let same = match (best, full) {
            (Some((a, d)), Some((b, e))) => a == b && d.to_bits() == e.to_bits(),
            (None, None) => true,
            _ => false,
        };
        eprintln!("nearest_edge.check{} edges={} pruned={:?} full={:?}", if same { "" } else { " DIFFER" }, solid.edges.len(), best, full);
    }
    best
}

/// The distance from `point` to the edge's projection clamped into its
/// trimmed interval; `None` when the projection or the evaluation fails.
fn edge_distance(edge: &EdgeRecord, point: Vec3) -> Option<f64> {
    let projection = crate::project_point_to_curve(&edge.curve, point).ok()?;
    let clamped = projection.u.clamp(edge.t0.min(edge.t1), edge.t0.max(edge.t1));
    let sample = edge.curve.evaluate(clamped).ok()?;
    Some(sample.sub(point).length())
}

/// A lower bound on the distance from `point` to any point of `curve`: the
/// distance to the box of its control points. Zero (never skipped) when a
/// weight is not positive or a value is not finite.
fn hull_distance_bound(curve: &NurbsCurve, point: Vec3) -> f64 {
    let mut low = [f64::INFINITY; 3];
    let mut high = [f64::NEG_INFINITY; 3];
    for control in &curve.control_points {
        if !(control.w > 0.0) || !control.w.is_finite() {
            return 0.0;
        }
        let at = [control.x / control.w, control.y / control.w, control.z / control.w];
        for axis in 0..3 {
            if !at[axis].is_finite() {
                return 0.0;
            }
            low[axis] = low[axis].min(at[axis]);
            high[axis] = high[axis].max(at[axis]);
        }
    }
    if curve.control_points.is_empty() {
        return 0.0;
    }
    let at = [point.x, point.y, point.z];
    let mut squared = 0.0;
    for axis in 0..3 {
        let gap = (low[axis] - at[axis]).max(at[axis] - high[axis]).max(0.0);
        squared += gap * gap;
    }
    let bound = squared.sqrt();
    if bound.is_finite() { bound } else { 0.0 }
}

/// Match edge endpoints within tolerance; `true` means reversed. If both
/// directions match, preserve the sewing code's preference for reversal.
pub fn edge_endpoint_alignment(
    first: &EdgeRecord,
    second: &EdgeRecord,
    points: &HashMap<u64, Vec3>,
    tolerance: f64,
) -> Option<bool> {
    let direct = points[&first.start_vertex_id]
        .sub(points[&second.start_vertex_id])
        .length()
        <= tolerance
        && points[&first.end_vertex_id]
            .sub(points[&second.end_vertex_id])
            .length()
            <= tolerance;
    let reversed = points[&first.start_vertex_id]
        .sub(points[&second.end_vertex_id])
        .length()
        <= tolerance
        && points[&first.end_vertex_id]
            .sub(points[&second.start_vertex_id])
            .length()
            <= tolerance;
    (direct || reversed).then_some(reversed)
}

/// Previous pcurve end and next pcurve start around the first use of an edge.
/// Missing edges or unevaluable neighbors yield `None`.
pub fn coedge_neighbor_endpoints<'a>(
    loops: impl IntoIterator<Item = &'a LoopRecord>,
    edge_id: u64,
) -> Option<(Vec3, Vec3)> {
    let loop_record = loops.into_iter().find(|loop_record| {
        loop_record
            .coedges
            .iter()
            .any(|coedge| coedge.edge_id == edge_id)
    })?;
    let count = loop_record.coedges.len();
    let index = loop_record
        .coedges
        .iter()
        .position(|coedge| coedge.edge_id == edge_id)?;
    let prev = &loop_record.coedges[(index + count - 1) % count];
    let next = &loop_record.coedges[(index + 1) % count];
    let prev_domain = prev.pcurve.domain().ok()?;
    let next_domain = next.pcurve.domain().ok()?;
    Some((
        prev.pcurve.evaluate(prev_domain[1]).ok()?,
        next.pcurve.evaluate(next_domain[0]).ok()?,
    ))
}