use super::Mesh3;
use super::section::{TriIntr, chain_segments};
use crate::common::PCoords;
use crate::geom3::IsoExtensions3;
use crate::{IndexMask, Iso3, Plane3, Point3, Result, UnitVec3, Vector3};
use levenberg_marquardt::{LeastSquaresProblem, LevenbergMarquardt};
use parry3d_f64::na::{Matrix, Matrix2, Matrix3, Owned, U2, UnitQuaternion, Vector, Vector2};
use parry3d_f64::partitioning::TraversalAction;
use std::f64::consts::FRAC_PI_2;
const DELTA: f64 = 1e-4;
const MIN_COVERAGE: f64 = 1e-3;
const MIN_SENSITIVITY: f64 = 1e-3;
const DEFAULT_BAND_FRACTION: f64 = 0.01;
const SCOPE_REACH: f64 = 4.0;
#[derive(Debug, Clone, Copy)]
pub struct TransverseOptions {
pub taper_tilt: f64,
pub band: Option<f64>,
pub max_evaluations: usize,
pub tol: f64,
}
impl Default for TransverseOptions {
fn default() -> Self {
Self {
taper_tilt: 70.0_f64.to_radians(),
band: None,
max_evaluations: 100,
tol: 1e-9,
}
}
}
impl TransverseOptions {
fn validate(&self) -> Result<()> {
if !(self.taper_tilt > 0.0 && self.taper_tilt < FRAC_PI_2) {
return Err(format!(
"taper_tilt must lie strictly between 0 and pi/2 radians, got {}",
self.taper_tilt
)
.into());
}
if let Some(band) = self.band
&& !(band > 0.0 && band.is_finite())
{
return Err(format!("band must be positive and finite, got {band}").into());
}
if self.max_evaluations == 0 {
return Err("max_evaluations must be at least 1".into());
}
if !(self.tol > 0.0 && self.tol.is_finite()) {
return Err(format!("tol must be positive and finite, got {}", self.tol).into());
}
Ok(())
}
}
#[derive(Debug, Clone)]
pub struct TransversePlane {
pub plane: Plane3,
pub evaluations: usize,
pub residual: f64,
pub coverage: f64,
pub sensitivity: f64,
pub face_count: usize,
pub band: f64,
}
impl Mesh3 {
pub fn transverse_plane(
&self,
point: &impl PCoords<3>,
guess: &UnitVec3,
faces: Option<&IndexMask>,
options: Option<TransverseOptions>,
) -> Result<TransversePlane> {
let options = options.unwrap_or_default();
options.validate()?;
let point = Point3::from(point.coords());
let problem = TransverseFit::new(self, point, guess, faces, options)?;
let (result, report) = LevenbergMarquardt::new()
.with_patience(options.max_evaluations)
.with_xtol(options.tol)
.minimize(problem);
if !report.termination.was_successful() {
return Err(format!(
"the transverse plane solve did not converge: {:?}",
report.termination
)
.into());
}
let balance = result
.balance
.as_ref()
.ok_or("the transverse plane solve ended without a section")?;
let (e1, e2) = result.in_plane_axes();
let coverage = balance.coverage(&e1, &e2);
if coverage < MIN_COVERAGE {
return Err(underdetermined(coverage));
}
let jacobian = result
.jacobian()
.ok_or("the section could not be evaluated around the solution")?;
let sensitivity = jacobian
.singular_values()
.iter()
.cloned()
.fold(f64::INFINITY, f64::min);
if sensitivity < MIN_SENSITIVITY {
return Err(format!(
"the balance residual is insensitive to a tilt of the plane at the solution \
(sensitivity {sensitivity:.2e}), so the transverse direction is undetermined"
)
.into());
}
let mut normal = result.normal();
if normal.dot(guess) < 0.0 {
normal = -normal;
}
Ok(TransversePlane {
plane: Plane3::from_point_normal(&point, &normal),
evaluations: report.number_of_evaluations + 4,
residual: balance.residual().norm(),
coverage,
sensitivity,
face_count: balance.count,
band: result.band,
})
}
}
fn underdetermined(coverage: f64) -> Box<dyn std::error::Error> {
format!(
"the section's outward normals do not span the plane (coverage {coverage:.2e}), so the \
transverse direction is undetermined"
)
.into()
}
struct Balance {
r: Vector3,
m: Matrix3<f64>,
sum_l: f64,
count: usize,
}
impl Balance {
fn residual(&self) -> Vector3 {
self.r / self.sum_l
}
fn coverage(&self, e1: &Vector3, e2: &Vector3) -> f64 {
let a = e1.dot(&(self.m * e1));
let b = e1.dot(&(self.m * e2));
let d = e2.dot(&(self.m * e2));
let mean = 0.5 * (a + d);
let half_gap = (0.25 * (a - d).powi(2) + b * b).sqrt();
(mean - half_gap) / self.sum_l
}
}
fn balance(
mesh: &Mesh3,
point: &Point3,
n: &UnitVec3,
faces: Option<&IndexMask>,
band: f64,
options: &TransverseOptions,
) -> Result<Option<Balance>> {
let plane = Plane3::from_point_normal(point, n);
let segments = mesh.section_segments(&plane, faces)?;
if segments.is_empty() {
return Ok(None);
}
let scope: Vec<&TriIntr> = nearest_chain(&segments, point)
.into_iter()
.map(|i| &segments[i])
.collect();
let reach = SCOPE_REACH * band;
let n = n.into_inner();
let cos_knee = options.taper_tilt.cos();
let mut result = Balance {
r: Vector3::zeros(),
m: Matrix3::zeros(),
sum_l: 0.0,
count: 0,
};
for face in band_faces(mesh, &plane, band, faces) {
let Some(face_n) = mesh.shape.triangle(face).normal() else {
continue;
};
let (area, centroid) = clipped_area(mesh, face, &plane, band);
if area <= 0.0 {
continue;
}
if scope
.iter()
.all(|seg| segment_distance(seg, ¢roid) > reach)
{
continue;
}
let s = face_n.dot(&n);
let in_plane = face_n.into_inner() - n * s;
let c = in_plane.norm();
if c <= f64::EPSILON {
continue;
}
let m = in_plane / c;
let weight = if c >= cos_knee {
s / c
} else {
s * c / (cos_knee * cos_knee)
};
let length = area * c / (2.0 * band);
result.r += length * weight * m;
result.m += length * m * m.transpose();
result.sum_l += length;
result.count += 1;
}
Ok((result.count > 0).then_some(result))
}
fn band_faces(mesh: &Mesh3, plane: &Plane3, band: f64, faces: Option<&IndexMask>) -> Vec<u32> {
let mut candidates = Vec::new();
mesh.shape.bvh().traverse(|node| {
let (lo, hi) = node
.aabb()
.vertices()
.iter()
.map(|v| plane.signed_distance_to_point(v))
.fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), d| {
(lo.min(d), hi.max(d))
});
if lo > band || hi < -band {
return TraversalAction::Prune;
}
if let Some(index) = node.leaf_data()
&& faces.is_none_or(|mask| mask.get(index as usize))
{
candidates.push(index);
}
TraversalAction::Continue
});
candidates
}
fn clipped_area(mesh: &Mesh3, face: u32, plane: &Plane3, band: f64) -> (f64, Point3) {
let tri = mesh.shape.triangle(face);
let mut polygon = vec![tri.a, tri.b, tri.c];
polygon = clip_polygon(&polygon, |p| band - plane.signed_distance_to_point(p));
polygon = clip_polygon(&polygon, |p| band + plane.signed_distance_to_point(p));
if polygon.len() < 3 {
return (0.0, Point3::origin());
}
let mut area_vec = Vector3::zeros();
let mut centroid = Vector3::zeros();
for i in 1..polygon.len() - 1 {
let cross = (polygon[i] - polygon[0]).cross(&(polygon[i + 1] - polygon[0]));
let a = 0.5 * cross.norm();
area_vec += cross;
centroid += a * (polygon[0].coords + polygon[i].coords + polygon[i + 1].coords) / 3.0;
}
let area = 0.5 * area_vec.norm();
if area <= 0.0 {
return (0.0, Point3::origin());
}
(area, Point3::from(centroid / area))
}
fn clip_polygon(polygon: &[Point3], inside: impl Fn(&Point3) -> f64) -> Vec<Point3> {
let mut out = Vec::with_capacity(polygon.len() + 2);
for i in 0..polygon.len() {
let a = polygon[i];
let b = polygon[(i + 1) % polygon.len()];
let da = inside(&a);
let db = inside(&b);
if da >= 0.0 {
out.push(a);
}
if (da >= 0.0) != (db >= 0.0) {
let t = da / (da - db);
out.push(a + (b - a) * t);
}
}
out
}
fn nearest_chain(segments: &[TriIntr], point: &Point3) -> Vec<usize> {
let chains = chain_segments(segments);
let mut best = (f64::INFINITY, 0);
for (k, chain) in chains.iter().enumerate() {
for &i in chain.iter() {
let d = segment_distance(&segments[i], point);
if d < best.0 {
best = (d, k);
}
}
}
chains.into_iter().nth(best.1).unwrap_or_default()
}
fn segment_distance(seg: &TriIntr, point: &Point3) -> f64 {
let ab = seg.b - seg.a;
let len2 = ab.norm_squared();
let t = if len2 > 0.0 {
((point - seg.a).dot(&ab) / len2).clamp(0.0, 1.0)
} else {
0.0
};
(point - (seg.a + ab * t)).norm()
}
struct TransverseFit<'a> {
mesh: &'a Mesh3,
point: Point3,
faces: Option<&'a IndexMask>,
options: TransverseOptions,
base: UnitVec3,
axis_x: UnitVec3,
axis_y: UnitVec3,
band: f64,
params: Vector2<f64>,
balance: Option<Balance>,
}
impl<'a> TransverseFit<'a> {
fn new(
mesh: &'a Mesh3,
point: Point3,
guess: &UnitVec3,
faces: Option<&'a IndexMask>,
options: TransverseOptions,
) -> Result<Self> {
let band = match options.band {
Some(band) => band,
None => {
let plane = Plane3::from_point_normal(&point, guess);
let segments = mesh.section_segments(&plane, faces)?;
let length: f64 = segments.iter().map(|seg| seg.length()).sum();
if length <= 0.0 {
return Err(
"the plane through the guess does not cut any of the selected faces".into(),
);
}
DEFAULT_BAND_FRACTION * length
}
};
let frame = Iso3::from_z_arbitrary_xy(guess, None);
let mut problem = Self {
mesh,
point,
faces,
options,
base: *guess,
axis_x: frame.x(),
axis_y: frame.y(),
band,
params: Vector2::zeros(),
balance: None,
};
let balance = problem
.evaluate(&problem.params)?
.ok_or("the plane through the guess does not cut any of the selected faces")?;
let (e1, e2) = problem.in_plane_axes();
let coverage = balance.coverage(&e1, &e2);
if coverage < MIN_COVERAGE {
return Err(underdetermined(coverage));
}
problem.balance = Some(balance);
Ok(problem)
}
fn rotation_at(&self, p: &Vector2<f64>) -> UnitQuaternion<f64> {
let rot_x = UnitQuaternion::from_axis_angle(&self.axis_x, p[0]);
let rot_y = UnitQuaternion::from_axis_angle(&self.axis_y, p[1]);
rot_y * rot_x
}
fn normal_at(&self, p: &Vector2<f64>) -> UnitVec3 {
UnitVec3::new_normalize(self.rotation_at(p) * self.base.into_inner())
}
fn normal(&self) -> UnitVec3 {
self.normal_at(&self.params)
}
fn in_plane_axes(&self) -> (Vector3, Vector3) {
let rot = self.rotation_at(&self.params);
(
rot * self.axis_x.into_inner(),
rot * self.axis_y.into_inner(),
)
}
fn evaluate(&self, p: &Vector2<f64>) -> Result<Option<Balance>> {
balance(
self.mesh,
&self.point,
&self.normal_at(p),
self.faces,
self.band,
&self.options,
)
}
fn residual_at(&self, p: &Vector2<f64>) -> Option<Vector2<f64>> {
let balance = self.evaluate(p).ok()??;
let rot = self.rotation_at(p);
let r = balance.residual();
Some(Vector2::new(
r.dot(&(rot * self.axis_x.into_inner())),
r.dot(&(rot * self.axis_y.into_inner())),
))
}
}
impl LeastSquaresProblem<f64, U2, U2> for TransverseFit<'_> {
type ResidualStorage = Owned<f64, U2>;
type JacobianStorage = Owned<f64, U2, U2>;
type ParameterStorage = Owned<f64, U2>;
fn set_params(&mut self, x: &Vector<f64, U2, Self::ParameterStorage>) {
self.params = *x;
self.balance = self.evaluate(x).ok().flatten();
}
fn params(&self) -> Vector<f64, U2, Self::ParameterStorage> {
self.params
}
fn residuals(&self) -> Option<Vector<f64, U2, Self::ResidualStorage>> {
let balance = self.balance.as_ref()?;
let (e1, e2) = self.in_plane_axes();
let r = balance.residual();
Some(Vector2::new(r.dot(&e1), r.dot(&e2)))
}
fn jacobian(&self) -> Option<Matrix<f64, U2, U2, Self::JacobianStorage>> {
let mut jac = Matrix2::zeros();
for k in 0..2 {
let mut plus = self.params;
plus[k] += DELTA;
let mut minus = self.params;
minus[k] -= DELTA;
let d = (self.residual_at(&plus)? - self.residual_at(&minus)?) / (2.0 * DELTA);
jac.set_column(k, &d);
}
Some(jac)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::common::arc_segments_for_tol;
use crate::common::random_geometry::RandomGeometry3;
use crate::geom2::{BoundaryData2, BoundaryEditor};
use crate::geom3::{ExtrudedBoundary3, RevolvedBoundary3};
use crate::{Iso3, Vector3};
use std::f64::consts::TAU;
struct Case {
mesh: Mesh3,
point: Point3,
expected: UnitVec3,
mask: Option<IndexMask>,
}
impl Case {
fn new(mesh: Mesh3, point: Point3, expected: Vector3) -> Self {
Self {
mesh,
point,
expected: UnitVec3::new_normalize(expected),
mask: None,
}
}
fn mask_centers(mut self, keep: impl Fn(&Point3) -> bool) -> Self {
let centers = self.mesh.compute_face_centers().unwrap();
let mut mask = self.mesh.face_mask(false);
for (i, c) in centers.iter().enumerate() {
mask.set(i, keep(c));
}
self.mask = Some(mask);
self
}
fn mask_normals(mut self, keep: impl Fn(&UnitVec3) -> bool) -> Self {
let normals = self.mesh.compute_face_normals().unwrap();
let mut mask = self.mesh.face_mask(false);
for (i, n) in normals.iter().enumerate() {
mask.set(i, keep(n));
}
self.mask = Some(mask);
self
}
fn transformed(self, iso: &Iso3) -> Self {
let mut mesh = self.mesh;
mesh.transform_in_place(iso);
Self {
mesh,
point: iso * self.point,
expected: iso * self.expected,
mask: self.mask,
}
}
fn perturbed_guess(&self, angle: f64, rng: &mut RandomGeometry3) -> UnitVec3 {
let perp = UnitVec3::new_normalize(self.expected.cross(&rng.unit_vec()));
UnitQuaternion::from_axis_angle(&perp, angle) * self.expected
}
fn solve(
&self,
guess: &UnitVec3,
options: Option<TransverseOptions>,
) -> Result<TransversePlane> {
self.mesh
.transverse_plane(&self.point, guess, self.mask.as_ref(), options)
}
fn error_from(&self, angle: f64, rng: &mut RandomGeometry3) -> f64 {
let guess = self.perturbed_guess(angle, rng);
let result = self.solve(&guess, None).unwrap();
let actual = result.plane.normal;
assert!(
result.coverage > 0.05,
"coverage {} is too low to trust",
result.coverage
);
actual.dot(&self.expected).abs().min(1.0).acos()
}
}
fn check(case: Case, tol: f64) {
let mut rng = RandomGeometry3::from_seed(0x7a3e);
let e0 = case.error_from(25.0_f64.to_radians(), &mut rng);
assert!(
e0 < tol,
"untransformed: error {e0:.3e} rad exceeds {tol:.1e}"
);
let moved = case.transformed(&rng.iso3(10.0));
let e1 = moved.error_from(25.0_f64.to_radians(), &mut rng);
assert!(
e1 < tol,
"transformed: error {e1:.3e} rad exceeds {tol:.1e}"
);
}
fn cylinder_wall(point: Point3) -> Case {
let mesh = Mesh3::create_cylinder(1.0, 4.0, 1e-3).unwrap();
Case::new(mesh, point, Vector3::z()).mask_normals(|n| n.z.abs() < 0.5)
}
fn cone(half_angle: f64) -> Case {
let height = 2.0;
let radius = height * half_angle.tan();
let mesh = Mesh3::create_cone(radius, height, 1e-3).unwrap();
Case::new(mesh, Point3::origin(), Vector3::z()).mask_normals(|n| n.z > -0.5)
}
fn tapered_box(k_top: f64, k_bottom: f64) -> Mesh3 {
let box_mesh = Mesh3::create_box(4.0, 2.0, 2.0, false);
let points: Vec<Point3> = box_mesh
.points()
.iter()
.map(|p| {
let x = p.x + 2.0;
let top = 1.0 - k_top * x;
let bottom = -1.0 + k_bottom * x;
let y = bottom + 0.5 * (p.y + 1.0) * (top - bottom);
Point3::new(x, y, p.z)
})
.collect();
Mesh3::new(points, box_mesh.faces().to_vec(), false)
}
fn extruded(profile: &[(f64, f64)], closed: bool, length: f64) -> Mesh3 {
let mut data = if closed {
BoundaryData2::new_closed()
} else {
BoundaryData2::new_open_xy(profile[0].0, profile[0].1)
};
let mut cursor = data.get_cursor(None);
for &(x, y) in profile.iter().skip(if closed { 0 } else { 1 }) {
cursor.add_seg_xy(x, y);
}
let b = data.try_to_boundary().unwrap();
ExtrudedBoundary3::new(b, Iso3::identity(), length)
.to_mesh(1e-3)
.unwrap()
}
fn revolved(profile: &[(f64, f64)], closed: bool, tol: f64) -> Mesh3 {
let mut data = if closed {
BoundaryData2::new_closed()
} else {
BoundaryData2::new_open_xy(profile[0].0, profile[0].1)
};
let mut cursor = data.get_cursor(None);
for &(x, y) in profile.iter().skip(if closed { 0 } else { 1 }) {
cursor.add_seg_xy(x, y);
}
let b = data.try_to_boundary().unwrap();
RevolvedBoundary3::new(b, Iso3::identity(), TAU)
.to_mesh(tol)
.unwrap()
}
fn ring_mid_angle(r_max: f64, tol: f64) -> f64 {
let n = arc_segments_for_tol(r_max, TAU, tol).unwrap();
0.5 * TAU / n as f64
}
fn revolved_point(x: f64, y: f64, t: f64) -> Point3 {
Point3::new(x * t.cos(), y, -x * t.sin())
}
fn revolved_tangent(t: f64) -> Vector3 {
Vector3::new(-t.sin(), 0.0, -t.cos())
}
#[test]
fn cylinder_from_a_point_on_the_wall() {
check(cylinder_wall(Point3::new(1.0, 0.0, 0.3)), 1e-7);
}
#[test]
fn cylinder_from_a_point_on_the_axis() {
check(cylinder_wall(Point3::new(0.0, 0.0, -0.4)), 1e-7);
}
#[test]
fn cylinder_without_a_mask_still_finds_the_axis() {
let mesh = Mesh3::create_cylinder(1.0, 4.0, 1e-3).unwrap();
check(
Case::new(mesh, Point3::new(1.0, 0.0, 0.0), Vector3::z()),
1e-7,
);
}
#[test]
fn cones_of_every_half_angle() {
for deg in [10.0_f64, 30.0, 35.264, 45.0, 60.0] {
let case = cone(deg.to_radians());
check(case, 1e-7);
}
}
#[test]
fn cone_from_a_point_on_the_surface() {
let half_angle = 20.0_f64.to_radians();
let height = 2.0;
let radius = height * half_angle.tan();
let mesh = Mesh3::create_cone(radius, height, 1e-3).unwrap();
let case = Case::new(mesh, Point3::new(0.5 * radius, 0.0, 0.0), Vector3::z())
.mask_normals(|n| n.z > -0.5);
check(case, 1e-7);
}
#[test]
fn symmetric_wedge_balances_its_two_faces() {
let mesh = tapered_box(0.125, 0.125);
let case = Case::new(mesh, Point3::new(2.0, 0.75, 0.3), Vector3::x())
.mask_normals(|n| n.x.abs() < 0.9);
check(case, 1e-7);
}
#[test]
fn one_sided_wedge_finds_the_bisector() {
let mesh = tapered_box(0.125, 0.0);
let top = Vector3::new(4.0, -0.5, 0.0).normalize();
let bisector = top + Vector3::x();
let case = Case::new(mesh, Point3::new(2.0, -1.0, 0.3), bisector)
.mask_normals(|n| n.x.abs() < 0.9);
check(case, 1e-7);
}
#[test]
fn torus_section_is_normal_to_the_spine() {
let tol = 1e-3;
let r_tube = 0.5;
let r_spine = 2.0;
let profile: Vec<(f64, f64)> = (0..32)
.map(|i| {
let a = TAU * i as f64 / 32.0;
(r_spine + r_tube * a.cos(), r_tube * a.sin())
})
.collect();
let mesh = revolved(&profile, true, tol);
let t = ring_mid_angle(r_spine + r_tube, tol);
let point = revolved_point(r_spine + r_tube, 0.0, t);
let case = Case::new(mesh, point, revolved_tangent(t));
check(case, 1e-7);
}
#[test]
fn straight_groove_with_and_without_a_mask() {
let profile = [
(-1.5, 0.0),
(-0.5, 0.0),
(-0.5, -0.5),
(0.5, -0.5),
(0.5, 0.0),
(1.5, 0.0),
];
let mesh = extruded(&profile, false, 2.0);
let point = Point3::new(0.1, -0.5, 1.0);
check(Case::new(mesh.clone(), point, Vector3::z()), 1e-7);
let case = Case::new(mesh, point, Vector3::z()).mask_centers(|c| c.x.abs() < 0.6);
assert!(case.mask.as_ref().unwrap().count_true() > 0);
check(case, 1e-7);
}
#[test]
fn circumferential_groove_on_a_shaft() {
let tol = 1e-3;
let profile = [
(2.0, -1.0),
(2.0, -0.25),
(1.5, -0.25),
(1.5, 0.25),
(2.0, 0.25),
(2.0, 1.0),
];
let mesh = revolved(&profile, false, tol);
let t = ring_mid_angle(2.0, tol);
let point = revolved_point(1.5, 0.0, t);
let case = Case::new(mesh, point, revolved_tangent(t))
.mask_centers(|c| (c.x * c.x + c.z * c.z).sqrt() < 1.99 || c.y.abs() < 0.26);
assert!(case.mask.as_ref().unwrap().count_true() > 0);
check(case, 1e-7);
}
#[test]
fn a_fragmented_section_uses_the_run_nearest_the_point() {
let case = cylinder_wall(Point3::new(1.0, 0.0, 0.0)).mask_centers(|c| c.x.abs() > 0.3);
let mut rng = RandomGeometry3::from_seed(5);
let guess = case.perturbed_guess(25.0_f64.to_radians(), &mut rng);
let result = case.solve(&guess, None).unwrap();
let err = result
.plane
.normal
.dot(&case.expected)
.abs()
.min(1.0)
.acos();
assert!(err < 1e-7, "error {err:.3e} rad");
assert!(
result.coverage > 0.2 && result.coverage < 0.5,
"{}",
result.coverage
);
}
#[test]
fn a_neighbouring_feature_is_left_out() {
let single = cylinder_wall(Point3::new(1.0, 0.0, 0.0));
let alone = single.solve(&single.expected, None).unwrap();
let mut mesh = Mesh3::create_cylinder(1.0, 4.0, 1e-3).unwrap();
let mut other = Mesh3::create_cylinder(1.0, 4.0, 1e-3).unwrap();
other.transform_in_place(&Iso3::translation(3.0, 0.0, 0.0));
mesh.append_in_place(&other).unwrap();
let case = Case::new(mesh, Point3::new(1.0, 0.0, 0.0), Vector3::z())
.mask_normals(|n| n.z.abs() < 0.5);
let mut rng = RandomGeometry3::from_seed(21);
let guess = case.perturbed_guess(25.0_f64.to_radians(), &mut rng);
let result = case.solve(&guess, None).unwrap();
let err = result
.plane
.normal
.dot(&case.expected)
.abs()
.min(1.0)
.acos();
assert!(err < 1e-7, "error {err:.3e} rad");
assert_eq!(result.face_count, alone.face_count);
}
#[test]
fn half_cylinder_still_determines_the_axis() {
let case = cylinder_wall(Point3::new(1.0, 0.0, 0.0)).mask_centers(|c| c.x > 0.05);
let mut rng = RandomGeometry3::from_seed(3);
let guess = case.perturbed_guess(25.0_f64.to_radians(), &mut rng);
let result = case.solve(&guess, None).unwrap();
let err = result
.plane
.normal
.dot(&case.expected)
.abs()
.min(1.0)
.acos();
assert!(err < 1e-7, "error {err:.3e} rad");
assert!(
result.coverage > 0.2 && result.coverage < 0.5,
"{}",
result.coverage
);
}
#[test]
fn a_full_loop_has_half_coverage() {
let case = cylinder_wall(Point3::new(0.0, 0.0, 0.0));
let result = case.solve(&case.expected, None).unwrap();
assert!((result.coverage - 0.5).abs() < 1e-3, "{}", result.coverage);
assert!(
(result.sensitivity - 0.5).abs() < 1e-3,
"{}",
result.sensitivity
);
assert!(result.residual < 1e-12);
}
#[test]
fn a_single_flat_face_is_underdetermined() {
let mesh = Mesh3::create_box(2.0, 2.0, 2.0, false);
let case =
Case::new(mesh, Point3::new(0.0, 0.0, 1.0), Vector3::x()).mask_normals(|n| n.z > 0.5);
let err = case
.solve(&Vector3::x_axis(), None)
.unwrap_err()
.to_string();
assert!(err.contains("undetermined"), "{err}");
}
#[test]
fn a_plane_missing_the_faces_is_an_error() {
let case = cylinder_wall(Point3::new(0.0, 0.0, 10.0));
let err = case
.solve(&Vector3::z_axis(), None)
.unwrap_err()
.to_string();
assert!(err.contains("does not cut"), "{err}");
}
#[test]
fn invalid_options_are_rejected() {
let case = cylinder_wall(Point3::origin());
let bad = TransverseOptions {
taper_tilt: FRAC_PI_2,
..Default::default()
};
assert!(case.solve(&Vector3::z_axis(), Some(bad)).is_err());
}
#[test]
fn longitudinal_plane_of_a_cylinder_is_refused() {
let case = cylinder_wall(Point3::origin());
let err = case
.solve(&Vector3::x_axis(), None)
.unwrap_err()
.to_string();
assert!(err.contains("undetermined"), "{err}");
}
#[test]
fn basin_of_the_across_plane_reaches_at_least_45_degrees() {
let mut rng = RandomGeometry3::from_seed(99);
for deg in [35.0_f64, 45.0] {
let case = cylinder_wall(Point3::new(1.0, 0.0, 0.0));
let err = case.error_from(deg.to_radians(), &mut rng);
assert!(err < 1e-6, "cylinder, guess {deg} deg off: error {err:.3e}");
let case = cone(20.0_f64.to_radians());
let err = case.error_from(deg.to_radians(), &mut rng);
assert!(err < 1e-6, "cone, guess {deg} deg off: error {err:.3e}");
}
}
}