use super::*;
pub const MAX_JOINT_TANGENT_BREAK: f64 = 0.02;
const MAX_JOINT_CURVATURE_BREAK: f64 = 1e-9;
const MAX_PLANARITY_DEVIATION: f64 = 1e-7;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum JointContinuity {
G0,
G1,
G2,
}
impl JointContinuity {
pub fn label(self) -> &'static str {
match self {
JointContinuity::G0 => "G0",
JointContinuity::G1 => "G1",
JointContinuity::G2 => "G2",
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct PathJoint {
pub before: usize,
pub after: usize,
pub tangent_break: f64,
pub curvature_break: f64,
pub continuity: JointContinuity,
pub closing: bool,
}
#[derive(Debug, Clone)]
pub struct SweepPath {
pub curves: Vec<NurbsCurve>,
pub names: Vec<String>,
pub closed: bool,
pub planar: Option<Vec3>,
pub joints: Vec<PathJoint>,
pub straight: bool,
pub screw_axes: Vec<Option<Vec3>>,
}
impl SweepPath {
pub fn new(curves: Vec<NurbsCurve>, names: Vec<String>) -> Result<Self, KernelRefusal> {
if curves.is_empty() {
return Err(KernelRefusal::input(
KernelStage::Collect,
"chain_empty",
"sweepSolid: path chain is empty",
));
}
let mut endpoints = Vec::with_capacity(curves.len());
for curve in &curves {
let [t0, t1] = curve.domain().or_refuse(KernelStage::Classify, "domain")?;
endpoints.push((curve.evaluate(t0).or_refuse(KernelStage::Classify, "evaluate")?, curve.evaluate(t1).or_refuse(KernelStage::Classify, "evaluate")?));
}
let first_start = endpoints[0].0;
let scale = endpoints
.iter()
.flat_map(|(a, b)| [a, b])
.map(|point| point.sub(first_start).length())
.fold(1.0_f64, f64::max);
let join_tolerance = 1e-5 * scale;
let mut samples = Vec::with_capacity(16 * curves.len() + 1);
for curve in &curves {
let [t0, t1] = curve.domain().or_refuse(KernelStage::Classify, "domain")?;
for index in 0..16 {
samples.push(curve.evaluate(t0 + (t1 - t0) * index as f64 / 16.0).or_refuse(KernelStage::Classify, "evaluate")?);
}
}
samples.push(endpoints[curves.len() - 1].1);
let travel: f64 = samples
.windows(2)
.map(|pair| pair[1].sub(pair[0]).length())
.sum();
let closed = travel > join_tolerance
&& endpoints[curves.len() - 1]
.1
.sub(first_start)
.length()
<= join_tolerance;
let planar = match crate::polygon::newell_normal(&samples).normalized() {
Ok(normal) => {
let deviation = samples
.iter()
.map(|point| point.sub(first_start).dot(normal).abs())
.fold(0.0_f64, f64::max);
(deviation <= MAX_PLANARITY_DEVIATION * scale).then_some(normal)
}
Err(_) => None,
};
let mut joints = Vec::with_capacity(curves.len());
for index in 1..curves.len() {
joints.push(Self::joint(&curves, index - 1, index, false)?);
}
if closed {
joints.push(Self::joint(&curves, curves.len() - 1, 0, true)?);
}
let straight = curves
.iter()
.all(|curve| curve.degree == 1 && curve.control_points.len() == 2);
let screw_axes = vec![None; curves.len()];
Ok(Self {
curves,
names,
closed,
planar,
joints,
straight,
screw_axes,
})
}
pub fn with_screw_axes(mut self, axes: Vec<Option<Vec3>>) -> Result<Self, KernelRefusal> {
if axes.len() != self.curves.len() {
return Err(KernelRefusal::input(
KernelStage::Collect,
"screw_axes_count",
format!(
"sweepSolid: {} screw axes for a {}-segment path",
axes.len(),
self.curves.len()
),
));
}
self.screw_axes = axes
.into_iter()
.enumerate()
.map(|(index, axis)| {
axis.map(|axis| {
axis.normalized().map_err(|_| {
KernelRefusal::input(
KernelStage::Collect,
"screw_axis",
format!(
"sweepSolid: path segment '{}' has a degenerate screw axis",
self.name(index)
),
)
})
})
.transpose()
})
.collect::<Result<_, _>>()?;
Ok(self)
}
pub fn from_curves(curves: &[NurbsCurve], names: &[String]) -> Result<Self, KernelRefusal> {
Self::new(curves.to_vec(), names.to_vec())
}
fn joint(
curves: &[NurbsCurve],
before: usize,
after: usize,
closing: bool,
) -> Result<PathJoint, KernelRefusal> {
let arriving = Self::frame_at(&curves[before], true, before, "end")?;
let departing = Self::frame_at(&curves[after], false, after, "start")?;
let tangent_break = arriving.0.dot(departing.0).clamp(-1.0, 1.0).acos();
let curvature_break = departing.1.sub(arriving.1).length();
let curvature_bar = MAX_JOINT_CURVATURE_BREAK
* (1.0 + arriving.1.length() + departing.1.length());
let continuity = if tangent_break > MAX_JOINT_TANGENT_BREAK {
JointContinuity::G0
} else if curvature_break > curvature_bar {
JointContinuity::G1
} else {
JointContinuity::G2
};
Ok(PathJoint {
before,
after,
tangent_break,
curvature_break,
continuity,
closing,
})
}
fn frame_at(
curve: &NurbsCurve,
at_end: bool,
index: usize,
which: &str,
) -> Result<(Vec3, Vec3), KernelRefusal> {
let [t0, t1] = curve.domain().or_refuse(KernelStage::Classify, "domain")?;
let parameter = if at_end { t1 } else { t0 };
let derivatives = curve.derivatives(parameter, 2).or_refuse(KernelStage::Classify, "derivatives")?;
let speed = derivatives[1].length();
let tangent = match derivatives[1].normalized() {
Ok(tangent) => tangent,
Err(_) => {
let side = if at_end { PathSide::Arriving } else { PathSide::Departing };
let limit = stationary_limit(curve, parameter, side)
.map_err(|fault| fault.refusal(&format!("the {which} of segment {index}"), parameter))?;
return Ok((limit.tangent, limit.curvature));
}
};
let curvature = derivatives[1]
.cross(derivatives[2])
.cross(derivatives[1])
.scale(1.0 / speed.powi(4));
Ok((tangent, curvature))
}
pub fn len(&self) -> usize {
self.curves.len()
}
pub fn is_empty(&self) -> bool {
self.curves.is_empty()
}
pub fn name(&self, index: usize) -> &str {
self.names
.get(index)
.map(String::as_str)
.unwrap_or("<unnamed>")
}
pub fn corner(&self) -> Option<&PathJoint> {
self.joints
.iter()
.find(|joint| joint.continuity == JointContinuity::G0)
}
pub fn cornered_polyline(&self) -> bool {
self.straight && self.corner().is_some()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum PathSide {
Departing,
Arriving,
}
#[derive(Clone, Copy, Debug)]
pub(super) struct StationaryLimit {
pub tangent: Vec3,
pub curvature: Vec3,
}
#[derive(Clone, Debug)]
pub(super) enum StationaryFault {
Everywhere,
Unbounded { order: usize, leaves: usize, coefficient: f64, exponent: f64 },
Reverses { angle: f64 },
Unreadable(String),
}
impl StationaryFault {
pub(super) fn refusal(&self, where_: &str, parameter: f64) -> KernelRefusal {
match self {
StationaryFault::Everywhere | StationaryFault::Unreadable(_) => KernelRefusal::input(
KernelStage::Classify,
"path_tangent",
match self {
StationaryFault::Unreadable(detail) => format!(
"sweepSolid: path tangent is degenerate at {where_} (t = {parameter}): the \
parameter is stationary there and its one-sided limit could not be read \
({detail})"
),
_ => format!(
"sweepSolid: path tangent is degenerate at {where_} (t = {parameter}): \
every derivative of the curve vanishes there"
),
},
),
StationaryFault::Unbounded { order, leaves, coefficient, exponent } => KernelRefusal::input(
KernelStage::Classify,
"path_curvature",
format!(
"sweepSolid: the path's curvature is unbounded at {where_} (t = {parameter}): \
the parameter is stationary there (first non-zero derivative of order \
{order}) and the curve leaves its tangent line at order {leaves}, below \
{double}, so κ ≈ {coefficient:.4e}·s^-{exponent:.3} in arc length s from \
that point and any section folds through itself beside it. A section \
reaching d into the bend folds over the first (d·{coefficient:.4e})^{inverse:.3} \
of the path. Give the path a non-zero tangent there (separate the coincident \
control points) or trim the stationary end off",
double = 2 * order,
inverse = 1.0 / exponent,
),
),
StationaryFault::Reverses { angle } => KernelRefusal::input(
KernelStage::Classify,
"path_cusp",
format!(
"sweepSolid: the path turns back on itself at {where_} (t = {parameter}): the \
parameter is stationary there and the curve leaves it {:.3}° away from the \
direction it arrived in — a cusp, which no section can be carried round. \
Split the path at the cusp and sweep the pieces",
angle.to_degrees()
),
),
}
}
}
const STATIONARY_TERM_FLOOR: f64 = 1e-9;
pub(super) fn stationary_limit(
curve: &NurbsCurve,
parameter: f64,
side: PathSide,
) -> Result<StationaryLimit, StationaryFault> {
let unreadable = |error: String| StationaryFault::Unreadable(error);
let [t0, t1] = curve.domain().map_err(unreadable)?;
let span = (t1 - t0).abs();
let interior = parameter > t0 + 1e-12 * span.max(1.0) && parameter < t1 - 1e-12 * span.max(1.0);
let limit = |(tangent, curvature): (Vec3, Result<Vec3, StationaryFault>)| {
curvature.map(|curvature| StationaryLimit { tangent, curvature })
};
if !interior {
let side = if parameter <= t0 + 1e-12 * span.max(1.0) { PathSide::Departing } else { PathSide::Arriving };
return limit(one_sided_limit(curve, parameter, side)?);
}
let (before, after) = curve.split(parameter).map_err(unreadable)?;
let arriving = one_sided_limit(&before, before.domain().map_err(unreadable)?[1], PathSide::Arriving)?;
let departing = one_sided_limit(&after, after.domain().map_err(unreadable)?[0], PathSide::Departing)?;
let angle = arriving.0.dot(departing.0).clamp(-1.0, 1.0).acos();
if angle > MAX_JOINT_TANGENT_BREAK {
return Err(StationaryFault::Reverses { angle });
}
let arriving = limit(arriving)?;
let departing = limit(departing)?;
Ok(match side {
PathSide::Departing => departing,
PathSide::Arriving => arriving,
})
}
fn one_sided_limit(
curve: &NurbsCurve,
parameter: f64,
side: PathSide,
) -> Result<(Vec3, Result<Vec3, StationaryFault>), StationaryFault> {
let unreadable = |error: String| StationaryFault::Unreadable(error);
let degree = curve.degree;
let rational = curve
.control_points
.iter()
.any(|point| (point.w - curve.control_points[0].w).abs() > 1e-15 * point.w.abs().max(1.0));
let derivatives = curve.derivatives(parameter, degree).map_err(unreadable)?;
let h = {
let mut knots: Vec<f64> = curve.knots.clone();
knots.dedup_by(|a, b| (*a - *b).abs() <= 0.0);
let (lower, upper) = match side {
PathSide::Departing => (
parameter,
knots.iter().copied().find(|knot| *knot > parameter).unwrap_or(parameter),
),
PathSide::Arriving => (
knots.iter().rev().copied().find(|knot| *knot < parameter).unwrap_or(parameter),
parameter,
),
};
upper - lower
};
if !(h > 0.0) {
return Err(StationaryFault::Unreadable(format!("no knot span on the {side:?} side of t = {parameter}")));
}
let size = {
let points: Vec<Vec3> = curve
.control_points
.iter()
.map(|point| point.point())
.collect::<Result<_, _>>()
.map_err(unreadable)?;
let mut low = points[0];
let mut high = points[0];
for point in &points {
low = Vec3::new(low.x.min(point.x), low.y.min(point.y), low.z.min(point.z));
high = Vec3::new(high.x.max(point.x), high.y.max(point.y), high.z.max(point.z));
}
high.sub(low).length()
};
if !(size > 0.0) {
return Err(StationaryFault::Everywhere);
}
let mut factorial = [1.0f64; 32];
for index in 1..factorial.len() {
factorial[index] = factorial[index - 1] * index as f64;
}
let term = |order: usize, vector: Vec3| vector.length() * h.powi(order as i32) / factorial[order.min(31)];
let floor = STATIONARY_TERM_FLOOR * size;
let order = (1..=degree.min(31))
.find(|&order| term(order, derivatives[order]) > floor)
.ok_or(StationaryFault::Everywhere)?;
let a = derivatives[order];
let along = a.normalized().map_err(unreadable)?;
let sign = match side {
PathSide::Departing => 1.0,
PathSide::Arriving => {
if (order - 1) % 2 == 0 {
1.0
} else {
-1.0
}
}
};
let tangent = along.scale(sign);
let across = |vector: Vec3| vector.sub(along.scale(vector.dot(along)));
let leaves = (order + 1..=degree.min(31)).find(|&leaves| term(leaves, across(derivatives[leaves])) > floor);
let curvature = match leaves {
None if rational => Err(StationaryFault::Unreadable(format!(
"a rational curve stationary to order {order} with no bend up to its degree {degree}"
))),
None => Ok(Vec3::default()),
Some(leaves) if leaves > 2 * order => Ok(Vec3::default()),
Some(leaves) if leaves == 2 * order => {
let bend = across(derivatives[leaves]);
let scale = 2.0 / factorial[leaves] * factorial[order] * factorial[order] / a.dot(a);
Ok(bend.scale(scale))
}
Some(leaves) => {
let q = leaves as f64 / order as f64;
let c = (across(derivatives[leaves]).length() / factorial[leaves])
/ (a.length() / factorial[order]).powf(q);
Err(StationaryFault::Unbounded {
order,
leaves,
coefficient: c * q * (q - 1.0),
exponent: 2.0 - q,
})
}
};
Ok((tangent, curvature))
}