mod detect;
mod rounded_square;
use crate::AngleDir::Ccw;
use crate::airfoil::helpers::{
OrientedCircles, extract_curve_beyond_station, extract_edge_sub_curve,
inscribed_from_spanning_ray, refine_stations,
};
use crate::airfoil::{AirfoilEdge, EdgeGeometry, EdgeLocate, InscribedCircle};
use crate::common::linear_space;
use crate::common::points::{dist, mid_point};
use crate::geom2::{Ray2, Segment2, rot90};
use crate::{BestFit, Circle2, Curve2, Result};
use parry2d_f64::query::Ray;
pub use detect::EdgeAutoDetect;
pub use rounded_square::{RoundedSquareEdge, best_fit_rounded_square};
pub struct OpenEdge {}
impl Default for OpenEdge {
fn default() -> Self {
Self::new()
}
}
impl OpenEdge {
pub fn new() -> Self {
OpenEdge {}
}
pub fn make() -> Box<dyn EdgeLocate> {
Box::new(OpenEdge::new())
}
}
impl EdgeLocate for OpenEdge {
fn find_edge(
&self,
_section: &Curve2,
stations: Vec<InscribedCircle>,
_front: bool,
_af_tol: f64,
) -> Result<(Option<AirfoilEdge>, Vec<InscribedCircle>)> {
Ok((
Some(AirfoilEdge::open(stations.last().unwrap().circle.center)),
stations,
))
}
}
pub struct OpenIntersectGap {
max_iterations: usize,
}
impl OpenIntersectGap {
pub fn new(max_iterations: usize) -> Self {
OpenIntersectGap { max_iterations }
}
pub fn make(max_iterations: usize) -> Box<dyn EdgeLocate> {
Box::new(OpenIntersectGap::new(max_iterations))
}
}
impl EdgeLocate for OpenIntersectGap {
fn find_edge(
&self,
section: &Curve2,
stations: Vec<InscribedCircle>,
front: bool,
af_tol: f64,
) -> Result<(Option<AirfoilEdge>, Vec<InscribedCircle>)> {
let mut working_stations = OrientedCircles::new(stations, front);
let end_cap = Segment2::try_new(§ion.at_front(), §ion.at_back())?;
let mut end_point = working_stations.end_intersection_with_seg(&end_cap)?;
let mut drift = f64::INFINITY;
let mut iterations = 0;
while drift > af_tol {
let end_sp = working_stations.end_sp()?;
let max_dist = end_sp
.scalar_projection(&end_cap.a)
.min(end_sp.scalar_projection(&end_cap.b));
if max_dist < 0.0 {
return Err("Failed to find intersection with open section edge.".into());
}
let d = max_dist / 2.0;
let test_ray = Ray::new(
end_sp.at_distance(d),
rot90(Ccw) * end_sp.normal.into_inner(),
);
if let Some(spanning_ray) = section.try_create_spanning_ray(&test_ray) {
let mut stack = Vec::new();
let circle = inscribed_from_spanning_ray(section, &spanning_ray, af_tol * 1e-2);
stack.push(circle);
refine_stations(
section,
&mut working_stations,
&mut stack,
af_tol,
af_tol * 1e-2,
);
}
let next_end_point = working_stations.end_intersection_with_seg(&end_cap)?;
drift = dist(&end_point, &next_end_point);
end_point = next_end_point;
if iterations > self.max_iterations {
return Err("Exceeded maximum iterations in open intersect gap algorithm.".into());
}
iterations += 1;
}
Ok((
Some(AirfoilEdge::open(end_point)),
working_stations.take_circles(),
))
}
}
pub struct IntersectEdge {}
impl Default for IntersectEdge {
fn default() -> Self {
Self::new()
}
}
impl IntersectEdge {
pub fn new() -> Self {
IntersectEdge {}
}
pub fn make() -> Box<dyn EdgeLocate> {
Box::new(IntersectEdge::new())
}
}
impl EdgeLocate for IntersectEdge {
fn find_edge(
&self,
section: &Curve2,
stations: Vec<InscribedCircle>,
front: bool,
_af_tol: f64,
) -> Result<(Option<AirfoilEdge>, Vec<InscribedCircle>)> {
let circles = OrientedCircles::new(stations, front);
let edge_point = circles.intersect_from_end(section)?;
Ok((
Some(AirfoilEdge::closed_only(edge_point)),
circles.take_circles(),
))
}
}
pub struct TraceToMaxCurvature {
max_tol: Option<f64>,
}
impl TraceToMaxCurvature {
pub fn new(max_tol: Option<f64>) -> Self {
TraceToMaxCurvature { max_tol }
}
pub fn make(max_tol: Option<f64>) -> Box<dyn EdgeLocate> {
Box::new(TraceToMaxCurvature::new(max_tol))
}
}
impl EdgeLocate for TraceToMaxCurvature {
fn find_edge(
&self,
section: &Curve2,
stations: Vec<InscribedCircle>,
front: bool,
af_tol: f64,
) -> Result<(Option<AirfoilEdge>, Vec<InscribedCircle>)> {
let station = if front {
stations
.first()
.ok_or("Empty inscribed circles container.")?
} else {
stations
.last()
.ok_or("Empty inscribed circles container.")?
};
let last_radius = station.radius();
let edge_curve = extract_edge_sub_curve(section, station, Some(0.4))
.ok_or("Failed to extract edge curve on trace to max curvature algorithm.")?;
let mut working_stations = OrientedCircles::new(stations, front);
let curvature = edge_curve.get_curvature_series().abs();
let (max_x, max_y) = curvature.abs().global_maxima_xy();
let max = curvature
.plateau_at_maxima(max_x, max_y * self.max_tol.unwrap_or(0.005))
.ok_or("Failed to find maximum curvature plateau.")?;
let intersection = working_stations.intersect_from_end(&edge_curve)?;
let length_i = edge_curve.at_closest_to_point(&intersection).length_along();
let edge_point = edge_curve
.at_length(max.clamp(length_i))
.ok_or("Failed to find edge point.")?
.point();
let mut stack = Vec::new();
for _i in 0..3 {
let camber_end = working_stations.get_end_curve(last_radius)?;
let end_line = camber_end.at_back().direction_line();
let mid = mid_point(&end_line.origin, &edge_point);
let dir = rot90(Ccw) * (edge_point - end_line.origin).normalize();
let test_ray = Ray::new(mid, dir);
if let Some(spanning_ray) = edge_curve.try_create_spanning_ray(&test_ray) {
let circle = inscribed_from_spanning_ray(&edge_curve, &spanning_ray, af_tol * 1e-2);
stack.push(circle);
refine_stations(
&edge_curve,
&mut working_stations,
&mut stack,
af_tol,
af_tol * 1e-2,
);
} else {
break;
}
}
Ok((
Some(AirfoilEdge::closed_only(edge_point)),
working_stations.take_circles(),
))
}
}
pub struct FitRadiusEdge {
tol: Option<f64>,
}
impl FitRadiusEdge {
pub fn new(tol: Option<f64>) -> Self {
FitRadiusEdge { tol }
}
pub fn make(tol: Option<f64>) -> Box<dyn EdgeLocate> {
Box::new(FitRadiusEdge::new(tol))
}
}
impl EdgeLocate for FitRadiusEdge {
fn find_edge(
&self,
section: &Curve2,
stations: Vec<InscribedCircle>,
front: bool,
af_tol: f64,
) -> Result<(Option<AirfoilEdge>, Vec<InscribedCircle>)> {
let check_tol = self.tol.unwrap_or(af_tol);
let mut working_stations = OrientedCircles::new(stations, front);
let mut iterations = 0;
while iterations < 1000 {
let station = working_stations
.last()
.ok_or("Empty inscribed circles container.")?;
let end_sp = working_stations.end_sp()?.normal;
let edge_curve = extract_curve_beyond_station(section, station, &end_sp)
.ok_or("Failed to extract edge curve on fit radius edge algorithm.")?;
let test = Circle2::fitting_circle(
edge_curve.points(),
&station.circle,
BestFit::Gaussian(2.0),
)?;
let residual = max_circle_residual(&edge_curve, &test);
if residual < check_tol {
let edge_point = working_stations.intersect_from_end(&edge_curve)?;
let arc = station.contact_arc(&end_sp);
let edge = AirfoilEdge::new(edge_point, EdgeGeometry::Arc(arc));
return Ok((Some(edge), working_stations.take_circles()));
}
let shift = (test.center - station.circle.center) * 0.5;
let test_ray = Ray::new(station.circle.center + shift, rot90(Ccw) * shift);
if let Some(ray) = section.try_create_spanning_ray(&test_ray) {
let result = inscribed_from_spanning_ray(section, &ray, af_tol * 1e-2);
working_stations.push(result);
} else {
return Err("Failed to create spanning ray in fit radius edge algorithm.".into());
}
iterations += 1;
}
Err("Exceeded maximum iterations in fit radius edge algorithm.".into())
}
}
fn max_circle_residual(curve: &Curve2, circle: &Circle2) -> f64 {
curve
.points()
.iter()
.map(|p| circle.distance_to(p).abs())
.fold(0.0, |a, b| a.max(b))
}
pub struct ConstRadiusEdge {
tol: Option<f64>,
}
impl ConstRadiusEdge {
pub fn new(tol: Option<f64>) -> Self {
ConstRadiusEdge { tol }
}
pub fn make(tol: Option<f64>) -> Box<dyn EdgeLocate> {
Box::new(ConstRadiusEdge::new(tol))
}
}
impl EdgeLocate for ConstRadiusEdge {
fn find_edge(
&self,
section: &Curve2,
stations: Vec<InscribedCircle>,
front: bool,
af_tol: f64,
) -> Result<(Option<AirfoilEdge>, Vec<InscribedCircle>)> {
let check_tol = self.tol.unwrap_or(af_tol);
let mut working_stations = OrientedCircles::new(stations, front);
let c0 = working_stations
.last()
.ok_or("Empty inscribed circles container.")?
.clone();
let edge_curve = extract_edge_sub_curve(section, &c0, Some(0.4))
.ok_or("Failed to extract edge curve on constant radius edge algorithm.")?;
let arcs = edge_curve
.equivalent_arcs(check_tol, 4)
.iter()
.map(|(_, _, a)| *a)
.collect::<Vec<_>>();
let best_arc = arcs
.iter()
.min_by(|a, b| a.radius().partial_cmp(&b.radius()).unwrap())
.ok_or("Could not find smallest constant radius arc.")?;
let a0 = best_arc.point_at_fraction(0.0);
let a1 = best_arc.point_at_fraction(1.0);
let test_ray = Ray::new(best_arc.center(), a1 - a0);
let spanning = section
.try_create_spanning_ray(&test_ray)
.ok_or("Failed to create final spanning ray for constant radius edge algorithm.")?;
let last_circle = InscribedCircle::new(spanning, a0, a1, best_arc.circle());
working_stations.push(last_circle);
let edge_point = working_stations.intersect_from_end(&edge_curve)?;
let edge = AirfoilEdge::new(edge_point, EdgeGeometry::Arc(*best_arc));
Ok((Some(edge), working_stations.take_circles()))
}
}
pub struct ConvergeTangentEdge {
tol: Option<f64>,
}
impl ConvergeTangentEdge {
pub fn new(tol: Option<f64>) -> Self {
ConvergeTangentEdge { tol }
}
pub fn make(tol: Option<f64>) -> Box<dyn EdgeLocate> {
Box::new(ConvergeTangentEdge::new(tol))
}
}
impl EdgeLocate for ConvergeTangentEdge {
fn find_edge(
&self,
section: &Curve2,
stations: Vec<InscribedCircle>,
front: bool,
af_tol: f64,
) -> Result<(Option<AirfoilEdge>, Vec<InscribedCircle>)> {
let temp_circles = OrientedCircles::new(stations, front);
let c0 = temp_circles
.last()
.ok_or("Empty inscribed circles container.")?
.circle;
let check_tol = self.tol.unwrap_or(c0.r() * 0.01);
let max_curvature = TraceToMaxCurvature::new(Some(0.01));
let (_, stations) =
max_curvature.find_edge(section, temp_circles.take_circles(), front, af_tol)?;
let mut working_stations = OrientedCircles::new(stations, front);
let station = working_stations
.last()
.ok_or("Empty inscribed circles container.")?;
let edge_curve = extract_edge_sub_curve(section, station, Some(0.4))
.ok_or("Failed to extract edge curve on converging tangent edge algorithm.")?;
let oriented_camber = working_stations.get_full_curve()?;
let (fwd_i, _) = edge_curve
.max_point_in_direction(&oriented_camber.at_back().normal())
.ok_or("Failed to find max point in direction, did the curve end up empty?.")?;
let fwd_arc = edge_curve
.equivalent_arc_at(fwd_i, af_tol)
.map(|(_, _, a)| a);
let x0 = oriented_camber
.at_closest_to_point(&c0.center)
.length_along();
let steps = 1000;
let x_start = 0.0;
let space = linear_space(x_start, oriented_camber.length() - 1.0e-6, steps);
let mut measured = Vec::new();
for x in space.values().iter() {
let camber_point = oriented_camber.at_length(*x).ok_or(format!(
"Failed to find camber point at length {} on curve of length {}.",
x,
oriented_camber.length()
))?;
let camber_dir = camber_point.interpolated_direction_point();
let max_point = if let Some(arc) = fwd_arc {
arc.center() + camber_dir.normal.into_inner() * arc.radius()
} else {
let (_, mp) = edge_curve
.max_point_in_direction(&camber_dir.normal)
.ok_or("Failed to find max point in direction, did the curve end up empty?.")?;
mp
};
let error = camber_dir.planar_distance(&max_point);
if error < check_tol {
measured.push(((x - x0).abs(), camber_dir, max_point));
}
}
if measured.iter().any(|(d, _, _)| !d.is_finite()) {
return Err("Non-finite values found in converging tangent edge algorithm.".into());
}
if let Some((_, dir, point)) = measured
.iter()
.min_by(|a, b| a.0.partial_cmp(&b.0).unwrap())
{
working_stations.discard_sections_beyond_point(&dir.point);
Ok((
Some(AirfoilEdge::closed_only(*point)),
working_stations.take_circles(),
))
} else {
Ok((None, working_stations.take_circles()))
}
}
}
pub struct RansacRadiusEdge {
in_tol: f64,
iterations: usize,
}
impl RansacRadiusEdge {
pub fn new(in_tol: f64, iterations: usize) -> Self {
RansacRadiusEdge { in_tol, iterations }
}
pub fn make(in_tol: f64, iterations: usize) -> Box<dyn EdgeLocate> {
Box::new(RansacRadiusEdge::new(in_tol, iterations))
}
}
impl EdgeLocate for RansacRadiusEdge {
fn find_edge(
&self,
section: &Curve2,
stations: Vec<InscribedCircle>,
front: bool,
_af_tol: f64,
) -> Result<(Option<AirfoilEdge>, Vec<InscribedCircle>)> {
let mut working_stations = OrientedCircles::new(stations, front);
let station = working_stations
.last()
.ok_or("Empty inscribed circles container.")?;
let end_sp = working_stations.end_sp()?.normal;
let edge_curve = extract_curve_beyond_station(section, station, &end_sp)
.ok_or("Failed to extract edge curve on RANSAC radius edge algorithm.")?;
let last_circle = Circle2::ransac(
edge_curve.points(),
self.in_tol,
Some(self.iterations),
None,
Some(station.radius()),
)?;
let (s0, s1) = station
.circle
.outer_tangents_to(&last_circle)
.ok_or("Failed to find tangents between last station and RANSAC circle.")?;
let ray_dir = s0.b - s1.b;
let ray = Ray2::new(last_circle.center, ray_dir);
let spanning = section
.try_create_spanning_ray(&ray)
.ok_or("Failed to create spanning ray in RANSAC radius edge algorithm.")?;
let inscribed = InscribedCircle::new(spanning, s0.b, s1.b, last_circle);
working_stations.push(inscribed);
let edge_point = working_stations.intersect_from_end(&edge_curve)?;
let end_arc = working_stations
.last()
.ok_or("Empty inscribed circles container.")?
.contact_arc(&end_sp);
Ok((
Some(AirfoilEdge::arc(edge_point, end_arc)),
working_stations.take_circles(),
))
}
}