Skip to main content

brep_blend/blending/fillet/
linear_asym.rs

1//! A two-distance CHAMFER whose distances run LINEARLY along a straight edge
2//! between two planes: `chamfer_edges_asymmetric_linear`.
3//!
4//! At each point of the edge the section square to it is the line from the
5//! point `d1` into face 1 to the point `d2` into face 2 (the constant
6//! two-distance chamfer's section, `chamfer_cross_section_offsets`). With
7//! both distances linear along the edge, the rails on the two faces are
8//! straight, and the chamfer is the ruled surface of the section lines
9//! between the two end sections: a bilinear patch, a hyperbolic paraboloid
10//! where the rails are skew and a plane where they are not. The cutter is the
11//! loft between the two end triangles, ruled exactly, and the boolean takes
12//! it from the body as the constant chamfer's prism is taken.
13//!
14//! Only where the cutter is flush: each end of the edge on a plane square to
15//! it that holds that end's section. Anything else is refused by name.
16use super::analyze::{analyze_edge, EdgePath};
17use super::chamfer_extent::check_chamfer_extent;
18use super::edges::resolve_edge_by_point;
19use super::tool::{apply_tool, scaffold_tag, settle_cutter_scaffold};
20use crate::analytic_surface::AnalyticSurface;
21use crate::{make_line, BrepSolid, KernelRefusal, KernelStage, OrRefuse, Vec3};
22
23const ENTRY: &str = "chamfer_edges_asymmetric_linear";
24
25fn unsupported(what: &'static str, message: impl Into<String>) -> KernelRefusal {
26    KernelRefusal::unsupported(KernelStage::Classify, what, format!("{ENTRY}: {}", message.into()))
27}
28
29/// Two-distance chamfers of the straight edges through `edge_points`, one
30/// after another, each with the distances `start` (`[d1, d2]`, `d1` on the
31/// edge's first face as [`crate::fillet::chamfer_edges_asymmetric`] reads it)
32/// at the end of the edge nearer `start_at` and `end` at its other end, both
33/// linear between. Each edge lies between two planes and ends on planes
34/// square to it.
35pub fn chamfer_edges_asymmetric_linear(
36    solid: &BrepSolid,
37    edge_points: &[Vec3],
38    start_at: Vec3,
39    start: [f64; 2],
40    end: [f64; 2],
41    name: Option<&str>,
42) -> Result<BrepSolid, KernelRefusal> {
43    let _operation = crate::blend::BlendOperation::enter();
44    if edge_points.is_empty() {
45        return Err(KernelRefusal::input(KernelStage::Collect, "asymmetric_selection", format!("{ENTRY}: no edges selected")));
46    }
47    if start.iter().chain(&end).any(|d| !(d.is_finite() && *d > 0.0)) {
48        return Err(KernelRefusal::input(
49            KernelStage::Collect,
50            "setback_distances",
51            format!("{ENTRY}: every setback distance must be positive and finite, not {start:?} to {end:?}"),
52        ));
53    }
54    let mut result = solid.clone();
55    for point in edge_points {
56        let edge_id = resolve_edge_by_point(&result, *point)?;
57        result = chamfer_one(&result, edge_id, start_at, start, end, name)?;
58    }
59    if let Some(first) = result.validate_memoised().into_iter().find(|issue| issue.severity == "error") {
60        return Err(KernelRefusal::new(
61            crate::RefusalClass::InvalidResultTopology { issues: 1 },
62            KernelStage::Validate,
63            format!("{ENTRY}: the chamfer built a solid that fails validation (first: {}); refused rather than returned", first.message),
64        ));
65    }
66    Ok(result)
67}
68
69fn chamfer_one(solid: &BrepSolid, edge_id: u64, start_at: Vec3, start: [f64; 2], end: [f64; 2], name: Option<&str>) -> Result<BrepSolid, KernelRefusal> {
70    let smallest = start.iter().chain(&end).copied().fold(f64::INFINITY, f64::min);
71    let cross = analyze_edge(solid, edge_id, smallest)?;
72    let EdgePath::Straight { direction, length } = cross.path else {
73        return Err(unsupported("linear_asymmetric_edge", "the edge is not a straight edge between two planes"));
74    };
75    let reach = [start[0].max(end[0]), start[1].max(end[1])];
76    check_chamfer_extent(solid, edge_id, reach, ENTRY)?;
77    // The law's start at the edge's end nearer `start_at`.
78    let far = cross.start.add(direction.scale(length));
79    let (first, last) = if far.sub(start_at).length() < cross.start.sub(start_at).length() { (end, start) } else { (start, end) };
80    let tolerance = crate::KernelTolerances::for_solid(solid, 1e-7).intersection_fit;
81    let section = |origin: Vec3, d: [f64; 2]| [origin, origin.add(cross.into_first.scale(d[0])), origin.add(cross.into_second.scale(d[1]))];
82    let sections = [section(cross.start, first), section(far, last)];
83    // Flush ends: each end section on a plane face of the body, square to
84    // the edge.
85    for corners in &sections {
86        let flush = solid.shells.iter().flat_map(|shell| &shell.faces).any(|face| match face.surface.analytic() {
87            Some(AnalyticSurface::Plane { origin, u_dir, v_dir, .. }) => match u_dir.cross(*v_dir).normalized() {
88                Ok(normal) => normal.cross(direction).length() <= 1e-9 && corners.iter().all(|c| normal.dot(c.sub(*origin)).abs() <= tolerance),
89                Err(_) => false,
90            },
91            _ => false,
92        });
93        if !flush {
94            return Err(unsupported("linear_asymmetric_end", "an end of the edge is not on a plane square to it"));
95        }
96    }
97    let line = |from: Vec3, to: Vec3| make_line(from, to).or_refuse(KernelStage::Fragment, "linear_asymmetric_line");
98    let profile = |[o, a, b]: [Vec3; 3]| -> Result<Vec<crate::NurbsCurve>, KernelRefusal> { Ok(vec![line(o, a)?, line(a, b)?, line(b, o)?]) };
99    let mut tool = crate::loft_profile_brep(&[profile(sections[0])?, profile(sections[1])?])?;
100    // The chamfer is the cutter's face ruled between the two chords; every
101    // other face is its scaffold.
102    let chords = [sections[0][1], sections[0][2], sections[1][1], sections[1][2]];
103    let ruled_on_chords = |face: &crate::FaceRecord| {
104        let poles: Vec<Vec3> = face.surface.control_points.iter().flatten().map(|p| Vec3::new(p.x / p.w, p.y / p.w, p.z / p.w)).collect();
105        let near = |q: Vec3| poles.iter().any(|p| p.sub(q).length() <= tolerance);
106        chords.iter().all(|&q| near(q)) && poles.iter().all(|p| chords.iter().any(|q| p.sub(*q).length() <= tolerance))
107    };
108    let mut named = 0;
109    for face in tool.shells.iter_mut().flat_map(|shell| &mut shell.faces) {
110        if ruled_on_chords(face) {
111            face.name = name.map(str::to_string);
112            named += 1;
113        } else {
114            face.name = Some(scaffold_tag(name));
115        }
116    }
117    if named != 1 {
118        return Err(KernelRefusal::internal(KernelStage::Fragment, "linear_asymmetric_cutter", format!("{ENTRY}: the cutter's chamfer face is not one face ({named})")));
119    }
120    apply_tool(solid, &tool, cross.convex).map(settle_cutter_scaffold)
121}