use std::collections::BTreeMap;
use std::f64::consts::PI;
use serde::{Deserialize, Serialize};
use super::Context;
use super::bevel::{convex_bevel, transverse_corner};
use super::cylinders::CylinderEvidence;
use super::evidence::{self, EvidenceError, Occurrence};
use super::placed::{Grid, Placed};
use super::planes::nearest_axis_aligned_planes;
use super::policy::AXIS_ALIGNED_COS;
use super::turned;
use crate::kernel::brep::Part;
use crate::kernel::classify::material_at;
use crate::kernel::geom::{self, Surface, V3, dominant_axis};
use crate::kernel::py;
const MIN_RADIUS: f64 = 0.6;
const FILLET_MAX_EXTENT: f64 = PI * 1.05;
const TURNED_FILLET_MAX_EXTENT: f64 = PI / 2.0 * 1.05;
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct Fillet {
pub axis: char,
pub radius: f64,
pub at: Placed<V3>,
pub turned: bool,
pub side: &'static str,
}
#[derive(Clone, Copy, Debug, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct FilletOptions {
pub min_radius: Option<f64>,
pub max_radius_frac: f64,
pub include_cylindrical: bool,
}
impl Default for FilletOptions {
fn default() -> Self {
FilletOptions {
min_radius: None,
max_radius_frac: 0.45,
include_cylindrical: true,
}
}
}
internal_entry! {
pub fn recognise_fillets(part: &Part, opts: &FilletOptions) -> Vec<Fillet> {
discover(&Context::new(part), opts)
.into_iter()
.map(|o| o.record)
.collect()
}
}
internal_entry! {
pub fn discover_verified(
ctx: &Context<'_>,
opts: &FilletOptions,
) -> Result<Vec<Occurrence<Fillet>>, EvidenceError> {
evidence::verified(ctx.part, discover(ctx, opts))
}
}
internal_entry! {
pub fn fillet_anchor(part: &Part, face: usize) -> Option<V3> {
let (u0, u1, v0, v1) = part.uv_bounds(face)?;
Some(
part.faces[face]
.surface
.value(0.5 * (u0 + u1), 0.5 * (v0 + v1)),
)
}
}
fn occurrence(
axis: usize,
radius: f64,
at: V3,
turned: bool,
face: usize,
context: Vec<usize>,
) -> Occurrence<Fillet> {
Occurrence {
record: Fillet {
axis: ['x', 'y', 'z'][axis],
radius: py::round_to3(radius),
at: Placed::new(at, Grid::Decimals(3)),
turned,
side: "convex",
},
defining: vec![face],
context,
}
}
fn principal_axis(direction: V3) -> Option<usize> {
let comp = direction.map(f64::abs);
(comp[0].max(comp[1]).max(comp[2]) > AXIS_ALIGNED_COS).then(|| dominant_axis(comp))
}
internal_entry! {
pub fn discover(ctx: &Context<'_>, opts: &FilletOptions) -> Vec<Occurrence<Fillet>> {
let part = ctx.part;
let min_radius = opts.min_radius.unwrap_or(MIN_RADIUS);
let max_radius = opts.max_radius_frac * ctx.bounds().max_extent();
let mut out = Vec::new();
if opts.include_cylindrical {
for face in 0..part.faces.len() {
if let Some(found) = prismatic(ctx, face, min_radius, max_radius) {
out.push(found);
}
}
}
let external = turned::external_cylinders(ctx);
for face in 0..part.faces.len() {
if let Some(found) = turned(part, face, min_radius, max_radius, &external) {
out.push(found);
}
}
out.sort_by(|a, b| {
let key = |o: &Occurrence<Fillet>| (o.record.axis, o.record.at);
let (ka, kb) = (key(a), key(b));
ka.0.cmp(&kb.0).then_with(|| py::tuple_order(&ka.1[..], &kb.1[..]))
});
out
}
}
fn prismatic(
ctx: &Context<'_>,
face: usize,
min_radius: f64,
max_radius: f64,
) -> Option<Occurrence<Fillet>> {
let part = ctx.part;
let Surface::Cylinder { frame, radius } = part.faces[face].surface else {
return None;
};
let (u0, u1, _, _) = part.uv_bounds(face)?;
if u1 - u0 >= FILLET_MAX_EXTENT || radius < min_radius || radius > max_radius {
return None;
}
let edge_axis = principal_axis(frame.z)?;
if part.frame_points_outward(face) != Some(true) {
return None;
}
let centre = part.face_bounds(face).centre();
let planes = nearest_axis_aligned_planes(part, face, centre, edge_axis, true);
let at = fillet_anchor(part, face)?;
if (0..3).all(|j| j == edge_axis || planes.contains_key(&j)) {
if !convex_bevel(ctx, centre, edge_axis, &planes) {
return None;
}
} else {
let corner = transverse_corner(part, face, at, frame.z)?;
if corner.normals.iter().any(|&n| {
(geom::dot(geom::sub(frame.origin, corner.point), n).abs() - radius).abs()
> super::policy::length_tol(radius, 1e-7)
}) {
return None;
}
let corner = corner.point;
let near = geom::add(
corner,
geom::scale(geom::sub(at, corner), super::policy::INTERIOR_PROBE_FRAC),
);
if material_at(ctx.classifier(), near) {
return None;
}
}
Some(occurrence(edge_axis, radius, at, false, face, vec![]))
}
fn turned(
part: &Part,
face: usize,
min_radius: f64,
max_radius: f64,
external: &BTreeMap<usize, &CylinderEvidence>,
) -> Option<Occurrence<Fillet>> {
let Surface::Torus { frame, minor, .. } = part.faces[face].surface else {
return None;
};
if minor < min_radius || minor > max_radius {
return None;
}
let (_, _, v0, v1) = part.uv_bounds(face)?;
if (v1 - v0).abs() > TURNED_FILLET_MAX_EXTENT {
return None;
}
let edge_axis = principal_axis(frame.z)?;
let context = turned_context(part, face, &part.neighbours(face), external)?;
let at = fillet_anchor(part, face)?;
Some(occurrence(edge_axis, minor, at, true, face, context))
}
internal_entry! {
pub fn turned_context(
part: &Part,
torus: usize,
neighbours: &[usize],
external: &BTreeMap<usize, &CylinderEvidence>,
) -> Option<Vec<usize>> {
let Surface::Torus { frame, .. } = part.faces[torus].surface else {
return None;
};
let coaxial = turned::coaxial_cylinders(neighbours, external, frame.origin, frame.z);
if coaxial.is_empty() {
return None;
}
let transverse = turned::transverse_planes(part, neighbours, frame.z);
let continuations: Vec<usize> = neighbours
.iter()
.copied()
.filter(|&n| matches!(part.faces[n].surface, Surface::Sphere { .. }))
.collect();
if transverse.is_empty() && !turned::bridges_two_bands(&coaxial) && continuations.is_empty() {
return None; }
let mut context: Vec<usize> = Vec::new();
for f in coaxial
.iter()
.map(|c| c.face)
.chain(transverse)
.chain(continuations)
{
if !context.contains(&f) {
context.push(f);
}
}
Some(context)
}
}