use serde::Serialize;
use super::evidence::common_valid_solid;
use crate::kernel::brep::Part;
use crate::kernel::geom::{Curve, Surface, V3, cross, sub};
use crate::kernel::py;
use crate::kernel::sampling::edge_interval;
const POSITION_TOL: f64 = 1e-6;
const DIRECTION_TOL: f64 = 2e-8;
#[derive(Clone, Debug, PartialEq, Serialize)]
#[non_exhaustive]
pub struct ProfileLine {
pub start: V3,
pub end: V3,
}
impl ProfileLine {
pub fn direction(&self) -> V3 {
let length = py::dist(&self.start, &self.end);
[0, 1, 2].map(|i| (self.end[i] - self.start[i]) / length)
}
}
#[derive(Clone, Debug, PartialEq, Serialize)]
#[non_exhaustive]
pub struct ProfileArc {
pub start: V3,
pub end: V3,
pub center: V3,
pub radius: f64,
pub sweep: f64,
}
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(tag = "kind", rename_all = "lowercase")]
#[non_exhaustive]
pub enum ProfileSupport {
Line(ProfileLine),
Arc(ProfileArc),
}
impl ProfileSupport {
pub fn start(&self) -> V3 {
match self {
ProfileSupport::Line(l) => l.start,
ProfileSupport::Arc(a) => a.start,
}
}
pub fn end(&self) -> V3 {
match self {
ProfileSupport::Line(l) => l.end,
ProfileSupport::Arc(a) => a.end,
}
}
fn reversed(&self) -> Self {
match self {
ProfileSupport::Line(l) => ProfileSupport::Line(ProfileLine {
start: l.end,
end: l.start,
}),
ProfileSupport::Arc(a) => ProfileSupport::Arc(ProfileArc {
start: a.end,
end: a.start,
sweep: -a.sweep,
..a.clone()
}),
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize)]
#[non_exhaustive]
pub struct PlanarOuterProfile {
pub origin: V3,
pub normal: V3,
pub supports: Vec<ProfileSupport>,
pub inner_loop_count: usize,
pub schema_version: u8,
pub boundary_kind: &'static str,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum OuterProfileRefusalReason {
NotPlanar,
AmbiguousBody,
UnsupportedCurve,
InsufficientLineSupports,
ConcaveProfile,
InvalidBoundary,
}
impl OuterProfileRefusalReason {
pub fn python_value(self) -> &'static str {
match self {
Self::NotPlanar => "not_planar",
Self::AmbiguousBody => "ambiguous_body",
Self::UnsupportedCurve => "unsupported_curve",
Self::InsufficientLineSupports => "insufficient_line_supports",
Self::ConcaveProfile => "concave_profile",
Self::InvalidBoundary => "invalid_boundary",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct RefusedPlanarOuterProfile {
pub reason: OuterProfileRefusalReason,
}
#[derive(Clone, Debug, PartialEq)]
pub struct PlanarOuterProfileEvidence {
pub profile: PlanarOuterProfile,
pub face: usize,
pub body_faces: Vec<usize>,
pub edges: Vec<usize>,
}
fn refused(reason: OuterProfileRefusalReason) -> RefusedPlanarOuterProfile {
RefusedPlanarOuterProfile { reason }
}
fn tangent(support: &ProfileSupport, normal: V3, end: bool) -> Option<V3> {
match support {
ProfileSupport::Line(l) => Some(l.direction()),
ProfileSupport::Arc(a) => {
let radius = sub(if end { a.end } else { a.start }, a.center);
let t = cross(normal, radius);
let length = py::hypot(&t);
if length == 0.0 {
return None;
}
let sign = 1.0f64.copysign(a.sweep);
Some(t.map(|v| v * sign / length))
}
}
}
fn turns(supports: &[ProfileSupport], normal: V3) -> Option<Vec<f64>> {
let n = supports.len();
let curvature = |s: &ProfileSupport| match s {
ProfileSupport::Line(_) => 0.0,
ProfileSupport::Arc(a) => 1.0f64.copysign(a.sweep) / a.radius,
};
(0..n)
.map(|at| {
let (first, second) = (&supports[at], &supports[(at + 1) % n]);
let before = tangent(first, normal, true)?;
let after = tangent(second, normal, false)?;
let turn = py::dot(&cross(before, after), &normal).atan2(py::dot(&before, &after));
let (k1, k2) = (curvature(first), curvature(second));
let sum = k1 + k2;
Some(
if turn.abs() > std::f64::consts::PI - DIRECTION_TOL
&& sum.abs() > 1e-9 * (k1.abs() + k2.abs())
{
-std::f64::consts::PI.copysign(sum)
} else {
turn
},
)
})
.collect()
}
fn winding(turns: &[f64], supports: &[ProfileSupport]) -> f64 {
py::fsum(turns.iter().copied())
+ py::fsum(supports.iter().filter_map(|s| match s {
ProfileSupport::Arc(a) => Some(a.sweep),
ProfileSupport::Line(_) => None,
}))
}
fn finite(p: V3) -> bool {
p.iter().all(|v| v.is_finite())
}
fn line(start: V3, end: V3) -> Option<ProfileLine> {
let length = py::dist(&start, &end);
(finite(start) && finite(end) && length.is_finite() && length != 0.0)
.then_some(ProfileLine { start, end })
}
fn arc(start: V3, end: V3, center: V3, radius: f64, sweep: f64) -> Option<ProfileArc> {
(finite(start)
&& finite(end)
&& finite(center)
&& radius.is_finite()
&& radius > 0.0
&& sweep.is_finite()
&& 0.0 < sweep.abs()
&& sweep.abs() < std::f64::consts::TAU)
.then_some(ProfileArc {
start,
end,
center,
radius,
sweep,
})
}
fn profile(
origin: V3,
normal: V3,
supports: Vec<ProfileSupport>,
inner_loop_count: usize,
) -> Option<PlanarOuterProfile> {
if !finite(origin) || !finite(normal) || (py::hypot(&normal) - 1.0).abs() > 1e-8 {
return None;
}
let n = supports.len();
if n < 2 {
return None;
}
let off_plane = |p: V3| py::dot(&sub(p, origin), &normal).abs() > 1e-6;
for (at, support) in supports.iter().enumerate() {
if support.end() != supports[(at + 1) % n].start() {
return None;
}
if off_plane(support.start()) || off_plane(support.end()) {
return None;
}
if let ProfileSupport::Arc(a) = support {
if off_plane(a.center)
|| [a.start, a.end]
.iter()
.any(|p| (py::dist(p, &a.center) - a.radius).abs() > 1e-6)
{
return None;
}
let radial = sub(a.start, a.center);
let crossed = cross(normal, radial);
let reconstructed = [0, 1, 2]
.map(|i| a.center[i] + a.sweep.cos() * radial[i] + a.sweep.sin() * crossed[i]);
if py::dist(&reconstructed, &a.end) > 1e-6 {
return None;
}
}
}
let turns = turns(&supports, normal)?;
if (winding(&turns, &supports) - std::f64::consts::TAU).abs() > 2e-8 {
return None;
}
let lines = supports
.iter()
.filter(|s| matches!(s, ProfileSupport::Line(_)))
.count();
let schema_version = if turns.iter().any(|&t| t < -2e-8) || lines < 2 {
2
} else {
1
};
Some(PlanarOuterProfile {
origin,
normal,
supports,
inner_loop_count,
schema_version,
boundary_kind: "outer",
})
}
fn read_profile(
part: &Part,
face: usize,
) -> Result<(PlanarOuterProfile, Vec<usize>), RefusedPlanarOuterProfile> {
use OuterProfileRefusalReason::*;
let f = &part.faces[face];
if !matches!(f.surface, Surface::Plane { .. }) {
return Err(refused(NotPlanar));
}
let invalid = || refused(InvalidBoundary);
let outer = part.outer_loop(face).ok_or_else(invalid)?;
let inner_loop_count = f.loops.len() - 1;
let wire = &f.loops[outer].edges;
if wire.is_empty() || (1..wire.len()).any(|i| wire[..i].iter().any(|w| w.0 == wire[i].0)) {
return Err(invalid());
}
if wire.iter().any(|&(e, _)| {
part.unresolved_edges().contains(&e)
|| !matches!(
part.edges[e].curve,
Curve::Line { .. } | Curve::Circle { .. }
)
}) {
return Err(refused(UnsupportedCurve));
}
if wire.len() < 2 {
return Err(invalid());
}
let normal = part.face_normal(face, 0.0, 0.0).ok_or_else(invalid)?;
let first = |&(e, forward): &(usize, bool)| {
let edge = &part.edges[e];
if forward {
(edge.vertices.0, edge.start)
} else {
(edge.vertices.1, edge.end)
}
};
let last = |&(e, forward): &(usize, bool)| {
let edge = &part.edges[e];
if forward {
edge.vertices.1
} else {
edge.vertices.0
}
};
let points: Vec<V3> = wire.iter().map(|w| first(w).1).collect();
let origin = points[0];
let mut supports = Vec::with_capacity(wire.len());
for (at, w) in wire.iter().enumerate() {
let following = (at + 1) % wire.len();
if last(w) != first(&wire[following]).0 {
return Err(invalid());
}
let (start, end) = (points[at], points[following]);
if py::dist(&start, &end) == 0.0 {
return Err(invalid());
}
let edge = &part.edges[w.0];
let (a, b) = edge_interval(
&edge.curve,
edge.start,
edge.end,
edge.same_sense,
edge.is_closed(),
);
let curve_ends = (edge.curve.value(a), edge.curve.value(b));
let apart = |(p, q): (V3, V3)| py::dist(&start, &p).max(py::dist(&end, &q));
if apart(curve_ends).min(apart((curve_ends.1, curve_ends.0))) > POSITION_TOL {
return Err(invalid());
}
let midpoint = edge.curve.value(0.5 * (a + b));
if [start, end, midpoint]
.iter()
.any(|p| py::dot(&sub(*p, origin), &normal).abs() > POSITION_TOL)
{
return Err(invalid());
}
match &edge.curve {
Curve::Line { .. } => {
let support = line(start, end).ok_or_else(invalid)?;
let source = line(curve_ends.0, curve_ends.1)
.ok_or_else(invalid)?
.direction();
let d = support.direction();
if py::dist(&d, &source).min(py::dist(&d, &source.map(|v| -v))) > DIRECTION_TOL {
return Err(invalid());
}
supports.push(ProfileSupport::Line(support));
}
Curve::Circle { frame, radius } => {
let center = frame.origin;
let sense = py::dot(&cross(sub(start, center), sub(midpoint, center)), &normal);
if sense == 0.0 {
return Err(invalid());
}
let length = radius * (b - a).abs();
let sweep = (length / radius).copysign(sense);
supports.push(ProfileSupport::Arc(
arc(start, end, center, *radius, sweep).ok_or_else(invalid)?,
));
}
_ => unreachable!("curves were checked above"),
}
}
let mut edges: Vec<usize> = wire.iter().map(|w| w.0).collect();
let turns = turns(&supports, normal).ok_or_else(invalid)?;
let mut winding = winding(&turns, &supports);
if winding < 0.0 {
supports = supports
.iter()
.rev()
.map(ProfileSupport::reversed)
.collect();
edges.reverse();
winding = -winding;
}
if (winding - std::f64::consts::TAU).abs() > DIRECTION_TOL {
return Err(invalid());
}
let starts: Vec<V3> = supports.iter().map(ProfileSupport::start).collect();
let mut least = 0;
for at in 1..starts.len() {
if py::tuple_order(&starts[at], &starts[least]).is_lt() {
least = at;
}
}
supports.rotate_left(least);
edges.rotate_left(least);
let profile =
profile(supports[0].start(), normal, supports, inner_loop_count).ok_or_else(invalid)?;
Ok((profile, edges))
}
internal_entry! {
pub fn planar_outer_profile(
part: &Part,
face: usize,
) -> Result<PlanarOuterProfileEvidence, RefusedPlanarOuterProfile> {
let ambiguous = || refused(OuterProfileRefusalReason::AmbiguousBody);
let owner = common_valid_solid(part, &[face]).ok_or_else(ambiguous)?;
let mut body_faces = part.solids[owner].faces.clone();
if common_valid_solid(part, &body_faces) != Some(owner) {
return Err(ambiguous());
}
body_faces.sort_unstable();
body_faces.dedup();
let (profile, edges) = read_profile(part, face)?;
Ok(PlanarOuterProfileEvidence {
profile,
face,
body_faces,
edges,
})
}
}
impl PlanarOuterProfileEvidence {
pub fn profile_edge(&self, index: usize) -> usize {
self.edges[index]
}
}
#[cfg(test)]
mod tests {
use super::*;
fn square(z: f64) -> Vec<ProfileSupport> {
let p = [[0.0, 0.0, z], [1.0, 0.0, z], [1.0, 1.0, z], [0.0, 1.0, z]];
(0..4)
.map(|i| {
ProfileSupport::Line(ProfileLine {
start: p[i],
end: p[(i + 1) % 4],
})
})
.collect()
}
#[test]
fn a_square_is_schema_one_and_its_reverse_is_refused() {
let z = [0.0, 0.0, 1.0];
let p = profile([0.0; 3], z, square(0.0), 0).unwrap();
assert_eq!(p.schema_version, 1);
let reversed: Vec<_> = square(0.0)
.iter()
.rev()
.map(ProfileSupport::reversed)
.collect();
assert!(profile([0.0; 3], z, reversed, 0).is_none());
}
#[test]
fn incoherent_profiles_are_refused() {
let z = [0.0, 0.0, 1.0];
assert!(profile([0.0, 0.0, 7.0], z, square(0.0), 0).is_none());
assert!(profile([0.0; 3], [0.0; 3], square(0.0), 0).is_none());
let mut open = square(0.0);
open.pop();
assert!(profile([0.0; 3], z, open, 0).is_none());
}
#[test]
fn serialises_as_python_to_dict() {
let p = profile([0.0; 3], [0.0, 0.0, 1.0], square(0.0), 2).unwrap();
let v = serde_json::to_value(&p).unwrap();
assert_eq!(v["supports"][0]["kind"], "line");
assert_eq!(v["schema_version"], 1);
assert_eq!(v["boundary_kind"], "outer");
assert_eq!(v["inner_loop_count"], 2);
}
}