use crate::{extrude_profile_brep, make_arc, BrepSolid, KernelRefusal, KernelStage, NurbsCurve, NurbsSurface, Vec3, Vec4};
use std::f64::consts::{PI, TAU};
pub const GEAR_FIT_TOLERANCE: f64 = 5e-7;
#[derive(Clone, Debug)]
pub struct SpurGear {
pub module: f64,
pub teeth: usize,
pub pressure_angle: f64,
pub profile_shift: f64,
pub addendum: f64,
pub dedendum: f64,
pub root_fillet: f64,
pub backlash: f64,
pub face_width: f64,
}
impl Default for SpurGear {
fn default() -> Self {
Self {
module: 2.0,
teeth: 20,
pressure_angle: 20f64.to_radians(),
profile_shift: 0.0,
addendum: 1.0,
dedendum: 1.25,
root_fillet: 0.38,
backlash: 0.0,
face_width: 10.0,
}
}
}
#[derive(Clone, Debug, Default)]
pub struct GearData {
pub pitch_diameter: f64,
pub base_diameter: f64,
pub tip_diameter: f64,
pub root_diameter: f64,
pub form_diameter: f64,
pub tooth_thickness: f64,
pub tip_thickness: f64,
pub undercut: bool,
pub min_shift_without_undercut: f64,
}
#[derive(Clone, Debug)]
pub struct SectionCurve {
pub curve: NurbsCurve,
pub role: &'static str,
pub tooth: usize,
}
impl SectionCurve {
pub fn suffix(&self) -> String {
format!("{}{}", self.role, self.tooth)
}
}
#[derive(Clone, Debug)]
pub struct GearSection {
pub curves: Vec<SectionCurve>,
pub data: GearData,
}
fn refuse(code: &str, message: String) -> KernelRefusal {
KernelRefusal::input(KernelStage::Collect, code, message)
}
fn rotate(point: [f64; 2], angle: f64) -> [f64; 2] {
let (s, c) = angle.sin_cos();
[c * point[0] - s * point[1], s * point[0] + c * point[1]]
}
fn polar_angle(point: [f64; 2]) -> f64 {
point[1].atan2(point[0])
}
fn radius_of(point: [f64; 2]) -> f64 {
point[0].hypot(point[1])
}
struct RackCutter {
r: f64,
alpha: f64,
x_ref: f64,
y0: f64,
r_f: f64,
rho: f64,
centre: [f64; 2],
}
impl RackCutter {
fn new(gear: &SpurGear) -> Self {
let m = gear.module;
let r = m * gear.teeth as f64 / 2.0;
let p = PI * m;
let alpha = gear.pressure_angle;
let x_ref = r + gear.profile_shift * m;
let y0 = p / 4.0 - gear.backlash / 2.0;
let r_f = x_ref - gear.dedendum * m;
let rho = gear.root_fillet * m;
let x_c = r_f + rho;
let y_c = y0 + (rho + (x_ref - x_c) * alpha.sin()) / alpha.cos();
Self { r, alpha, x_ref, y0, r_f, rho, centre: [x_c, y_c] }
}
fn envelope(&self, q: [f64; 2], n: [f64; 2]) -> [f64; 2] {
let s = (q[0] - self.r) * n[1] / n[0] - q[1];
rotate([q[0], q[1] + s], -s / self.r)
}
fn flank(&self, x: f64) -> [f64; 2] {
let a = self.alpha;
let q = [x, self.y0 + (self.x_ref - x) * a.tan()];
self.envelope(q, [-a.sin(), -a.cos()])
}
fn fillet(&self, psi: f64) -> [f64; 2] {
let n = [-psi.cos(), -psi.sin()];
if self.rho == 0.0 {
return self.envelope(self.centre, n);
}
let q = [self.centre[0] + self.rho * n[0], self.centre[1] + self.rho * n[1]];
self.envelope(q, n)
}
fn flank_x_at_radius(&self, radius: f64) -> f64 {
let c = 1.0 / self.alpha.tan();
let c2 = c * c;
let disc = (self.r * self.r * c2 * c2 - (1.0 + c2) * (self.r * self.r * c2 - radius * radius)).max(0.0);
(self.r * c2 + disc.sqrt()) / (1.0 + c2)
}
}
fn fit_planar(f: &dyn Fn(f64) -> [f64; 2], a: f64, b: f64, tolerance: f64) -> Result<NurbsCurve, KernelRefusal> {
let derivative = |t: f64| {
let h = 1e-6 * (b - a).abs().max(1e-12);
let p = f(t + h);
let q = f(t - h);
[(p[0] - q[0]) / (2.0 * h), (p[1] - q[1]) / (2.0 * h)]
};
let span_points = |t0: f64, t1: f64| {
let (p0, p1) = (f(t0), f(t1));
let (d0, d1) = (derivative(t0), derivative(t1));
let k = (t1 - t0) / 3.0;
[p0, [p0[0] + d0[0] * k, p0[1] + d0[1] * k], [p1[0] - d1[0] * k, p1[1] - d1[1] * k], p1]
};
let bezier = |c: &[[f64; 2]; 4], u: f64| {
let v = 1.0 - u;
let w = [v * v * v, 3.0 * v * v * u, 3.0 * v * u * u, u * u * u];
[
w[0] * c[0][0] + w[1] * c[1][0] + w[2] * c[2][0] + w[3] * c[3][0],
w[0] * c[0][1] + w[1] * c[1][1] + w[2] * c[2][1] + w[3] * c[3][1],
]
};
let mut pending: Vec<(f64, f64, usize)> = (0..4).rev().map(|i| {
let t0 = a + (b - a) * i as f64 / 4.0;
let t1 = a + (b - a) * (i + 1) as f64 / 4.0;
(t0, t1, 0)
}).collect();
let mut spans: Vec<(f64, f64, [[f64; 2]; 4])> = Vec::new();
while let Some((t0, t1, depth)) = pending.pop() {
let c = span_points(t0, t1);
let worst = [0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875]
.iter()
.map(|&u| {
let exact = f(t0 + (t1 - t0) * u);
let fitted = bezier(&c, u);
(exact[0] - fitted[0]).hypot(exact[1] - fitted[1])
})
.fold(0.0, f64::max);
if worst > tolerance && depth < 16 {
let mid = 0.5 * (t0 + t1);
pending.push((mid, t1, depth + 1));
pending.push((t0, mid, depth + 1));
} else if worst > tolerance {
return Err(refuse("gear_fit", format!("gear curve fit did not converge ({worst:.3e} > {tolerance:.3e})")));
} else {
spans.push((t0, t1, c));
}
}
let scale = 1.0 / (b - a);
let to_point = |p: [f64; 2]| Vec4::from_point(Vec3::new(p[0], p[1], 0.0), 1.0);
let mut knots = vec![0.0; 4];
let mut points = vec![to_point(spans[0].2[0])];
for (index, (_, t1, c)) in spans.iter().enumerate() {
points.push(to_point(c[1]));
points.push(to_point(c[2]));
if index + 1 < spans.len() {
let k = (t1 - a) * scale;
knots.extend([k, k]);
} else {
points.push(to_point(c[3]));
}
}
knots.extend([1.0; 4]);
NurbsCurve::new(3, knots, points).map_err(|error| refuse("gear_fit", error))
}
fn mirrored(curve: &NurbsCurve) -> NurbsCurve {
let mut copy = curve.clone();
for point in &mut copy.control_points {
point.y = -point.y;
}
NurbsCurve::new(copy.degree, copy.knots, copy.control_points).expect("a mirrored curve is a valid curve")
}
fn rotated(curve: &NurbsCurve, angle: f64) -> NurbsCurve {
let (s, c) = angle.sin_cos();
let points = curve
.control_points
.iter()
.map(|p| Vec4 { x: c * p.x - s * p.y, y: s * p.x + c * p.y, z: p.z, w: p.w })
.collect();
NurbsCurve::new(curve.degree, curve.knots.clone(), points).expect("a rotated curve is a valid curve")
}
fn arc(radius: f64, from: f64, to: f64) -> Result<NurbsCurve, KernelRefusal> {
make_arc(Vec3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0), radius, from, to)
.map_err(|error| refuse("gear_arc", error))
}
fn check_spur(gear: &SpurGear, max_pressure_degrees: f64) -> Result<(), KernelRefusal> {
let positive = |value: f64, what: &str| {
if value.is_finite() && value > 0.0 {
Ok(())
} else {
Err(refuse("gear_input", format!("The {what} must be greater than zero (it is {value}).")))
}
};
positive(gear.module, "module")?;
positive(gear.face_width, "face width")?;
positive(gear.addendum, "addendum coefficient")?;
positive(gear.dedendum, "dedendum coefficient")?;
if gear.teeth < 3 {
return Err(refuse("gear_input", format!("A gear needs at least 3 teeth (it has {}).", gear.teeth)));
}
let degrees = gear.pressure_angle.to_degrees();
if !(10.0 - 1e-9..=max_pressure_degrees + 1e-9).contains(°rees) {
return Err(refuse("gear_input", format!("The pressure angle must be between 10° and {max_pressure_degrees}° (it is {degrees}°).")));
}
if !(gear.root_fillet >= 0.0) || !(gear.backlash >= 0.0) || !gear.profile_shift.is_finite() {
return Err(refuse("gear_input", "The root fillet and the backlash cannot be negative.".into()));
}
Ok(())
}
pub fn spur_section(gear: &SpurGear) -> Result<GearSection, KernelRefusal> {
check_spur(gear, 35.0)?;
generated_section(gear)
}
fn transverse_section(gear: &SpurGear) -> Result<GearSection, KernelRefusal> {
check_spur(gear, 60.0)?;
generated_section(gear)
}
fn generated_section(gear: &SpurGear) -> Result<GearSection, KernelRefusal> {
let m = gear.module;
let z = gear.teeth as f64;
let rack = RackCutter::new(gear);
let alpha = rack.alpha;
let r = rack.r;
let r_b = r * alpha.cos();
let r_a = r + (gear.addendum + gear.profile_shift) * m;
let r_f = rack.r_f;
let half_pitch = PI / z;
let tolerance = GEAR_FIT_TOLERANCE * m;
if r_f <= 1e-9 * m {
return Err(refuse(
"root_below_centre",
format!("The root circle diameter is zero or negative (d = {:.4}): too few teeth for this dedendum.", 2.0 * r_f),
));
}
let rho_max = ((PI * m / 2.0 - rack.y0) * alpha.cos() - (rack.x_ref - r_f) * alpha.sin()) / (1.0 - alpha.sin());
if rack.rho > rho_max + 1e-9 * m {
return Err(refuse(
"root_fillet_too_large",
format!(
"The root fillet coefficient {:.4} is larger than the {:.4} that fits this tooth space; lower it.",
gear.root_fillet,
rho_max / m
),
));
}
let psi_end = PI / 2.0 - alpha;
let x_flank_tangent = rack.centre[0] - rack.rho * alpha.sin();
let x_interference = r * alpha.cos().powi(2);
let min_shift = gear.dedendum - gear.root_fillet * (1.0 - alpha.sin()) - z / 2.0 * alpha.sin().powi(2);
let undercut = x_flank_tangent < x_interference - 1e-12 * m;
let (x_join, psi_join) = if !undercut {
(x_flank_tangent, psi_end)
} else {
let difference = |psi: f64| -> Option<f64> {
let point = rack.fillet(psi);
let radius = radius_of(point);
if radius <= r_b {
return None;
}
Some(polar_angle(point) - polar_angle(rack.flank(rack.flank_x_at_radius(radius))))
};
let (mut below, mut above) = (0.0, psi_end);
for _ in 0..200 {
let mid = 0.5 * (below + above);
if radius_of(rack.fillet(mid)) <= r_b { below = mid } else { above = mid }
}
let psi_base = above;
let steps = 4000;
let mut found = None;
let mut previous: Option<(f64, f64)> = None;
for step in 0..=steps {
let psi = psi_end - (psi_end - psi_base) * step as f64 / steps as f64;
if let Some(value) = difference(psi) {
if let Some((last_psi, last_value)) = previous {
if (value <= 0.0) != (last_value <= 0.0) {
found = Some((psi, last_psi));
break;
}
}
previous = Some((psi, value));
}
}
let (mut lo, mut hi) = found.unwrap_or((psi_base, psi_base));
let sign_lo = difference(lo).unwrap_or(-1.0) <= 0.0;
for _ in 0..200 {
let mid = 0.5 * (lo + hi);
match difference(mid) {
Some(value) if (value <= 0.0) == sign_lo => lo = mid,
Some(_) => hi = mid,
None => lo = mid,
}
}
let psi = 0.5 * (lo + hi);
(rack.flank_x_at_radius(radius_of(rack.fillet(psi))), psi)
};
let join = rack.fillet(psi_join);
let form_radius = radius_of(join);
if r_a <= form_radius + 1e-9 * m {
return Err(refuse(
"tip_below_form",
format!(
"The tip circle (d = {:.4}) does not reach above the form circle (d = {:.4}); raise the addendum or lower the dedendum.",
2.0 * r_a,
2.0 * form_radius
),
));
}
let x_tip = rack.flank_x_at_radius(r_a);
let tip = rack.flank(x_tip);
let thickness = PI * m / 2.0 + 2.0 * gear.profile_shift * m * alpha.tan() - gear.backlash;
let involute = |angle: f64| angle.tan() - angle;
let half_angle = |radius: f64| thickness / (2.0 * r) + involute(alpha) - involute((r_b / radius).min(1.0).acos());
let tip_angle = half_angle(r_a);
let tip_offset = polar_angle(tip) - tip_angle;
if tip_angle * r_a <= 1e-6 * m || tip_offset.abs() > 1e-9 {
let (mut lo, mut hi) = (form_radius.max(r_b), r_a);
for _ in 0..200 {
let mid = 0.5 * (lo + hi);
if half_angle(mid) > 0.0 { lo = mid } else { hi = mid }
}
return Err(refuse(
"pointed_tip",
format!(
"The teeth come to a point at d = {:.4}, inside the tip circle (d = {:.4}); reduce the addendum or the profile shift, or add teeth.",
2.0 * lo,
2.0 * r_a
),
));
}
if tip_angle >= half_pitch {
return Err(refuse("teeth_overlap", "The tooth tips overlap their neighbours.".into()));
}
for step in 0..=64 {
let point = rack.fillet(psi_join * step as f64 / 64.0);
let angle = polar_angle(point);
if angle <= 0.0 || angle > half_pitch + 1e-12 {
return Err(refuse("teeth_overlap", "The tooth gaps cross: the root form of one gap cuts the next tooth.".into()));
}
}
let flank_fit = fit_planar(&|x| rack.flank(x), x_join, x_tip, tolerance)?; let fillet_fit = fit_planar(&|psi| rack.fillet(psi), 0.0, psi_join, tolerance)?; let root_angle = rack.centre[1] / r;
let land = 2.0 * half_pitch - 2.0 * root_angle;
let mut tooth: Vec<(&'static str, NurbsCurve)> = vec![
("V", mirrored(&fillet_fit)),
("R", mirrored(&flank_fit)),
("K", arc(r_a, -tip_angle, tip_angle)?),
("L", flank_fit.reversed().map_err(|e| refuse("gear_fit", e))?),
("W", fillet_fit.reversed().map_err(|e| refuse("gear_fit", e))?),
];
if land > 1e-9 {
tooth.push(("G", arc(r_f, root_angle, 2.0 * half_pitch - root_angle)?));
}
let mut curves = Vec::with_capacity(tooth.len() * gear.teeth);
for index in 0..gear.teeth {
let angle = TAU * index as f64 / z;
for (role, curve) in &tooth {
curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
}
}
snap_junctions(&mut curves);
let thickness_angle = |radius: f64| polar_angle(rack.flank(rack.flank_x_at_radius(radius)));
let data = GearData {
pitch_diameter: 2.0 * r,
base_diameter: 2.0 * r_b,
tip_diameter: 2.0 * r_a,
root_diameter: 2.0 * r_f,
form_diameter: 2.0 * form_radius,
tooth_thickness: 2.0 * r * thickness_angle(r.max(r_b)),
tip_thickness: 2.0 * r_a * tip_angle,
undercut,
min_shift_without_undercut: min_shift,
};
Ok(GearSection { curves, data })
}
pub fn spur_solid(gear: &SpurGear) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
let section = spur_section(gear)?;
let solid = extrude_section(§ion, gear.face_width)?;
let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
names.push("F".into());
names.push("B".into());
Ok((solid, names, section.data))
}
pub fn extrude_section(section: &GearSection, width: f64) -> Result<BrepSolid, KernelRefusal> {
let curves: Vec<NurbsCurve> = section.curves.iter().map(|piece| piece.curve.clone()).collect();
extrude_profile_brep(&curves, Vec3::new(0.0, 0.0, 1.0), width)
}
#[derive(Clone, Debug)]
pub struct Rack {
pub module: f64,
pub teeth: usize,
pub pressure_angle: f64,
pub addendum: f64,
pub dedendum: f64,
pub root_fillet: f64,
pub backlash: f64,
pub face_width: f64,
pub height: f64,
pub helix_angle: f64,
}
impl Default for Rack {
fn default() -> Self {
Self {
module: 2.0,
teeth: 10,
pressure_angle: 20f64.to_radians(),
addendum: 1.0,
dedendum: 1.25,
root_fillet: 0.38,
backlash: 0.0,
face_width: 10.0,
height: 6.0,
helix_angle: 0.0,
}
}
}
fn line(a: [f64; 2], b: [f64; 2]) -> Result<NurbsCurve, KernelRefusal> {
crate::make_line(Vec3::new(a[0], a[1], 0.0), Vec3::new(b[0], b[1], 0.0)).map_err(|error| refuse("gear_line", error))
}
fn centred_arc(centre: [f64; 2], radius: f64, from: f64, to: f64) -> Result<NurbsCurve, KernelRefusal> {
make_arc(Vec3::new(centre[0], centre[1], 0.0), Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0), radius, from, to)
.map_err(|error| refuse("gear_arc", error))
}
pub fn rack_section(rack: &Rack) -> Result<GearSection, KernelRefusal> {
rack_section_checked(rack, 35.0)
}
fn rack_section_checked(rack: &Rack, max_pressure_degrees: f64) -> Result<GearSection, KernelRefusal> {
let m = rack.module;
let positive = |value: f64, what: &str| {
if value.is_finite() && value > 0.0 {
Ok(())
} else {
Err(refuse("gear_input", format!("The {what} must be greater than zero (it is {value}).")))
}
};
positive(m, "module")?;
positive(rack.face_width, "face width")?;
positive(rack.addendum, "addendum coefficient")?;
positive(rack.dedendum, "dedendum coefficient")?;
if rack.teeth < 1 {
return Err(refuse("gear_input", "A rack needs at least one tooth.".into()));
}
let degrees = rack.pressure_angle.to_degrees();
if !(10.0 - 1e-9..=max_pressure_degrees + 1e-9).contains(°rees) {
return Err(refuse("gear_input", format!("The pressure angle must be between 10° and {max_pressure_degrees}° (it is {degrees}°).")));
}
if !(rack.root_fillet >= 0.0) || !(rack.backlash >= 0.0) {
return Err(refuse("gear_input", "The root fillet and the backlash cannot be negative.".into()));
}
let alpha = rack.pressure_angle;
let (ha, hf) = (rack.addendum * m, rack.dedendum * m);
if rack.height <= hf + 1e-9 * m {
return Err(refuse(
"rack_too_thin",
format!("The rack height below the pitch line ({:.4}) must exceed the dedendum ({:.4}).", rack.height, hf),
));
}
let p = PI * m;
let w = p / 4.0 - rack.backlash / 2.0; let tip_half = w - ha * alpha.tan();
if tip_half <= 1e-6 * m {
return Err(refuse(
"pointed_tip",
"The rack teeth come to a point below their tip line; reduce the addendum, the pressure angle or the backlash.".into(),
));
}
let rho = rack.root_fillet * m;
let y_p = -hf + rho - rho * alpha.sin();
let flank_x = |y: f64| w - y * alpha.tan();
let centre = [flank_x(y_p) + rho * alpha.cos(), -hf + rho];
let root_half = centre[0]; if y_p >= ha - 1e-9 * m {
return Err(refuse(
"root_fillet_too_large",
format!(
"The root fillet (coefficient {:.4}) reaches above the tooth tip; lower it or raise the addendum.",
rack.root_fillet
),
));
}
if root_half > p / 2.0 + 1e-9 * m {
let max = (p / 2.0 - w - hf * alpha.tan()) * alpha.cos() / (1.0 - alpha.sin());
return Err(refuse(
"root_fillet_too_large",
format!("The root fillet coefficient {:.4} is larger than the {:.4} that fits this tooth space; lower it.", rack.root_fillet, max / m),
));
}
let length = p * rack.teeth as f64;
let mut curves: Vec<SectionCurve> = Vec::new();
let mut push = |curve: NurbsCurve, role: &'static str, tooth: usize| curves.push(SectionCurve { curve, role, tooth });
let base = -rack.height;
push(line([0.0, base], [length, base])?, "BASE", 0);
push(line([length, base], [length, -hf])?, "E1", 0);
let mut x_prev_root = length; for k in (0..rack.teeth).rev() {
let c = (k as f64 + 0.5) * p;
let right_root = [c + root_half, -hf];
if x_prev_root - right_root[0] > 1e-9 * m {
push(line([x_prev_root, -hf], right_root)?, "G", k + 1);
}
let right_centre = [c + centre[0], centre[1]];
let right_flank_low = [c + flank_x(y_p), y_p];
if rho > 0.0 {
push(centred_arc(right_centre, rho, PI + alpha, 1.5 * PI)?.reversed().map_err(|e| refuse("gear_arc", e))?, "V", k);
}
let right_tip = [c + tip_half, ha];
let left_tip = [c - tip_half, ha];
let left_flank_low = [c - flank_x(y_p), y_p];
push(line(if rho > 0.0 { right_flank_low } else { right_root }, right_tip)?, "R", k);
push(line(right_tip, left_tip)?, "K", k);
let left_root = [c - root_half, -hf];
push(line(left_tip, if rho > 0.0 { left_flank_low } else { left_root })?, "L", k);
if rho > 0.0 {
let left_centre = [c - centre[0], centre[1]];
push(centred_arc(left_centre, rho, 1.5 * PI, 2.0 * PI - alpha)?.reversed().map_err(|e| refuse("gear_arc", e))?, "W", k);
}
x_prev_root = left_root[0];
}
if x_prev_root > 1e-9 * m {
push(line([x_prev_root, -hf], [0.0, -hf])?, "G", 0);
}
push(line([0.0, -hf], [0.0, base])?, "E0", 0);
snap_junctions(&mut curves);
let data = GearData {
pitch_diameter: f64::INFINITY,
tooth_thickness: 2.0 * w,
tip_thickness: 2.0 * tip_half,
..GearData::default()
};
Ok(GearSection { curves, data })
}
pub fn rack_solid(rack: &Rack) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
let beta = rack.helix_angle;
if !(beta.abs().to_degrees() <= 45.0 + 1e-9) {
return Err(refuse("bad_helix", format!("The rack's helix angle must be between −45° and 45° (it is {:.4}°).", beta.to_degrees())));
}
let degrees = rack.pressure_angle.to_degrees();
if !(10.0 - 1e-9..=35.0 + 1e-9).contains(°rees) {
return Err(refuse("gear_input", format!("The pressure angle must be between 10° and 35° (it is {degrees}°).")));
}
if beta == 0.0 {
let section = rack_section(rack)?;
let solid = extrude_section(§ion, rack.face_width)?;
let mut names: Vec<String> = section.curves.iter().map(rack_suffix).collect();
names.push("F".into());
names.push("B".into());
return Ok((solid, names, section.data));
}
let c = beta.cos();
let mut section = rack_section(rack)?;
for piece in &mut section.curves {
for point in &mut piece.curve.control_points {
point.x /= c;
}
}
section.data.tooth_thickness /= c;
section.data.tip_thickness /= c;
let curves: Vec<NurbsCurve> = section.curves.iter().map(|piece| piece.curve.clone()).collect();
let direction = Vec3::new(beta.tan(), 0.0, 1.0);
let solid = extrude_profile_brep(&curves, direction, rack.face_width / c)?;
let mut names: Vec<String> = section.curves.iter().map(rack_suffix).collect();
names.push("F".into());
names.push("B".into());
Ok((solid, names, section.data))
}
fn rack_suffix(piece: &SectionCurve) -> String {
match piece.role {
"BASE" | "E0" | "E1" => piece.role.to_string(),
_ => piece.suffix(),
}
}
fn snap_junctions(curves: &mut [SectionCurve]) {
let count = curves.len();
for index in 0..count {
let start = curves[(index + 1) % count].curve.control_points[0];
let curve = &mut curves[index].curve;
let last = curve.control_points.len() - 1;
let w = curve.control_points[last].w;
curve.control_points[last] = Vec4 { x: start.x / start.w * w, y: start.y / start.w * w, z: start.z / start.w * w, w };
}
}
#[derive(Clone, Debug)]
pub struct RingGear {
pub module: f64,
pub teeth: usize,
pub pressure_angle: f64,
pub profile_shift: f64,
pub addendum: f64,
pub dedendum: f64,
pub root_fillet: f64,
pub backlash: f64,
pub face_width: f64,
pub rim: f64,
}
impl Default for RingGear {
fn default() -> Self {
Self {
module: 2.0,
teeth: 60,
pressure_angle: 20f64.to_radians(),
profile_shift: 0.0,
addendum: 1.0,
dedendum: 1.25,
root_fillet: 0.38,
backlash: 0.0,
face_width: 10.0,
rim: 6.0,
}
}
}
pub fn ring_section(gear: &RingGear) -> Result<GearSection, KernelRefusal> {
ring_section_checked(gear, 35.0)
}
fn ring_section_checked(gear: &RingGear, max_pressure_degrees: f64) -> Result<GearSection, KernelRefusal> {
let m = gear.module;
let positive = |value: f64, what: &str| {
if value.is_finite() && value > 0.0 {
Ok(())
} else {
Err(refuse("gear_input", format!("The {what} must be greater than zero (it is {value}).")))
}
};
positive(m, "module")?;
positive(gear.face_width, "face width")?;
positive(gear.addendum, "addendum coefficient")?;
positive(gear.dedendum, "dedendum coefficient")?;
positive(gear.rim, "rim thickness")?;
if gear.teeth < 6 {
return Err(refuse("gear_input", format!("An internal gear needs at least 6 teeth (it has {}).", gear.teeth)));
}
let degrees = gear.pressure_angle.to_degrees();
if !(10.0 - 1e-9..=max_pressure_degrees + 1e-9).contains(°rees) {
return Err(refuse("gear_input", format!("The pressure angle must be between 10° and {max_pressure_degrees}° (it is {degrees}°).")));
}
if !(gear.root_fillet >= 0.0) || !(gear.backlash >= 0.0) || !gear.profile_shift.is_finite() {
return Err(refuse("gear_input", "The root fillet and the backlash cannot be negative.".into()));
}
let z = gear.teeth as f64;
let alpha = gear.pressure_angle;
let r = m * z / 2.0;
let r_b = r * alpha.cos();
let r_a = r - (gear.addendum - gear.profile_shift) * m; let r_f = r + (gear.dedendum + gear.profile_shift) * m; let rho = gear.root_fillet * m;
let half_pitch = PI / z;
let tolerance = GEAR_FIT_TOLERANCE * m;
if r_a <= r_b + 1e-9 * m {
return Err(refuse(
"tip_inside_base",
format!(
"An internal gear's tip circle (d = {:.4}) must lie outside its base circle (d = {:.4}); raise the tooth count, lower the pressure angle or the addendum.",
2.0 * r_a,
2.0 * r_b
),
));
}
let space = PI * m / 2.0 + 2.0 * gear.profile_shift * m * alpha.tan() + gear.backlash;
let involute = |angle: f64| angle.tan() - angle;
let half_space = |radius: f64| space / (2.0 * r) + involute(alpha) - involute((r_b / radius).min(1.0).acos());
let flank = |radius: f64| {
let angle = half_space(radius);
[radius * angle.cos(), radius * angle.sin()]
};
if half_space(r_a) >= half_pitch - 1e-6 * m / r_a {
return Err(refuse(
"pointed_tip",
"The ring teeth come to a point at the tip circle: reduce the profile shift, the backlash or the addendum.".into(),
));
}
if half_space(r_f) <= 1e-6 * m / r_f {
let (mut lo, mut hi) = (r_a, r_f);
for _ in 0..200 {
let mid = 0.5 * (lo + hi);
if half_space(mid) > 0.0 { lo = mid } else { hi = mid }
}
return Err(refuse(
"teeth_overlap",
format!(
"The tooth spaces close at d = {:.4}, inside the root circle (d = {:.4}); reduce the dedendum or the profile shift.",
2.0 * lo,
2.0 * r_f
),
));
}
let normal_into_space = |radius: f64| {
let h = 1e-6 * m;
let (a, b) = (flank(radius - h), flank(radius + h));
let (tx, ty) = (b[0] - a[0], b[1] - a[1]);
let length = tx.hypot(ty);
[ty / length, -tx / length]
};
let centre_at = |radius: f64| {
let point = flank(radius);
let n = normal_into_space(radius);
[point[0] + rho * n[0], point[1] + rho * n[1]]
};
let (join_radius, centre) = if rho == 0.0 {
(r_f, flank(r_f))
} else {
let target = r_f - rho;
let (mut lo, mut hi) = (r_a, r_f);
if radius_of(centre_at(lo)) > target {
return Err(refuse("root_fillet_too_large", "The root fillet is too large for the tooth depth; lower it.".into()));
}
for _ in 0..200 {
let mid = 0.5 * (lo + hi);
if radius_of(centre_at(mid)) < target { lo = mid } else { hi = mid }
}
let radius = 0.5 * (lo + hi);
(radius, centre_at(radius))
};
let root_angle = polar_angle(centre);
if rho > 0.0 && root_angle <= 1e-9 {
return Err(refuse(
"root_fillet_too_large",
"The root fillet is larger than fits the tooth space; lower it.".into(),
));
}
let tip_angle = half_space(r_a);
let flank_fit = fit_planar(&|radius| flank(radius), r_a, join_radius, tolerance)?; let mut space: Vec<(&'static str, NurbsCurve)> = Vec::new();
space.push(("R", mirrored(&flank_fit)));
if rho > 0.0 {
let join = flank(join_radius);
let from = root_angle;
let mut to = (join[1] - centre[1]).atan2(join[0] - centre[0]);
while to <= from {
to += TAU;
}
let left = centred_arc(centre, rho, from, to)?; space.push(("V", mirrored(&left).reversed().map_err(|e| refuse("gear_arc", e))?));
space.push(("G", arc(r_f, -root_angle, root_angle)?));
space.push(("W", left));
} else {
space.push(("G", arc(r_f, -root_angle, root_angle)?));
}
space.push(("L", flank_fit.reversed().map_err(|e| refuse("gear_fit", e))?));
space.push(("K", arc(r_a, tip_angle, 2.0 * half_pitch - tip_angle)?));
let mut curves = Vec::with_capacity(space.len() * gear.teeth);
for index in 0..gear.teeth {
let angle = TAU * index as f64 / z;
for (role, curve) in &space {
curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
}
}
snap_junctions(&mut curves);
let data = GearData {
pitch_diameter: 2.0 * r,
base_diameter: 2.0 * r_b,
tip_diameter: 2.0 * r_a,
root_diameter: 2.0 * r_f,
form_diameter: 2.0 * join_radius,
tooth_thickness: 2.0 * r * (half_pitch - half_space(r)),
tip_thickness: 2.0 * r_a * (half_pitch - tip_angle),
undercut: false,
min_shift_without_undercut: 0.0,
};
Ok(GearSection { curves, data })
}
pub fn ring_solid(gear: &RingGear) -> Result<(BrepSolid, GearData), KernelRefusal> {
let section = ring_section(gear)?;
let outer = section.data.root_diameter / 2.0 + gear.rim;
let axis = Vec3::new(0.0, 0.0, 1.0);
let mut blank = crate::make_cylinder_brep(Vec3::new(0.0, 0.0, 0.0), axis, outer, gear.face_width)
.map_err(|error| refuse("gear_blank", error))?;
for (face, name) in blank.shells[0].faces.iter_mut().zip(["OD", "F", "B"]) {
face.name = Some(name.into());
}
let reach = gear.face_width * 0.1 + gear.module;
let shifted: Vec<SectionCurve> = section
.curves
.iter()
.map(|piece| SectionCurve { curve: translated(&piece.curve, -reach), role: piece.role, tooth: piece.tooth })
.collect();
let mut tool = extrude_section(&GearSection { curves: shifted.clone(), data: section.data.clone() }, gear.face_width + 2.0 * reach)?;
for (face, piece) in tool.shells[0].faces.iter_mut().zip(&shifted) {
face.name = Some(piece.suffix());
}
let ring = crate::boolean_operation_nary(&[blank, tool], crate::BooleanOperation::Subtract)?;
Ok((ring, section.data))
}
pub fn ring_solid_helical(gear: &RingGear, helix_angle: f64, hand: Hand, herringbone: bool) -> Result<(BrepSolid, GearData), KernelRefusal> {
let beta = helix_angle;
if !(beta.to_degrees() >= 0.5 - 1e-9 && beta.to_degrees() <= 45.0 + 1e-9) {
return Err(refuse("bad_helix", format!("The helix angle must be between 0.5° and 45° (it is {:.4}°).", beta.to_degrees())));
}
let normal = gear.pressure_angle.to_degrees();
if !(10.0 - 1e-9..=35.0 + 1e-9).contains(&normal) {
return Err(refuse("gear_input", format!("The normal pressure angle must be between 10° and 35° (it is {normal}°).")));
}
let c = beta.cos();
let transverse = RingGear {
module: gear.module / c,
pressure_angle: (gear.pressure_angle.tan() / c).atan(),
profile_shift: gear.profile_shift * c,
addendum: gear.addendum * c,
dedendum: gear.dedendum * c,
root_fillet: gear.root_fillet * c,
..gear.clone()
};
let section = ring_section_checked(&transverse, 60.0)?;
let r = transverse.module * transverse.teeth as f64 / 2.0;
let sign = if hand == Hand::Right { 1.0 } else { -1.0 };
let rate = sign * beta.tan() / r; let outer = section.data.root_diameter / 2.0 + gear.rim;
let mut blank = crate::make_cylinder_brep(Vec3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), outer, gear.face_width)
.map_err(|error| refuse("gear_blank", error))?;
for (face, name) in blank.shells[0].faces.iter_mut().zip(["OD", "F", "B"]) {
face.name = Some(name.into());
}
let reach = gear.face_width * 0.1 + transverse.module;
let height = gear.face_width + 2.0 * reach;
let start: Vec<SectionCurve> = section
.curves
.iter()
.map(|piece| SectionCurve { curve: rotated(&piece.curve, -rate * reach), role: piece.role, tooth: piece.tooth })
.collect();
let twist = if herringbone { Twist::Herringbone { turn: rate * height } } else { Twist::Helical { turn: rate * height } };
let tool = twisted_prism(&GearSection { curves: start.clone(), data: section.data.clone() }, height, twist, GEAR_FIT_TOLERANCE * transverse.module)?;
let shift = crate::AffineTransform::new([1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, -reach, 0.0, 0.0, 0.0, 1.0])
.map_err(|e| refuse("gear_transform", e))?;
let mut tool = crate::transform_brep(&tool, shift, false).map_err(|e| refuse("gear_transform", e))?;
for (face, piece) in tool.shells[0].faces.iter_mut().zip(&start) {
face.name = Some(piece.suffix());
}
let ring = crate::boolean_operation_nary(&[blank, tool], crate::BooleanOperation::Subtract)?;
Ok((ring, section.data))
}
fn translated(curve: &NurbsCurve, dz: f64) -> NurbsCurve {
let points = curve.control_points.iter().map(|p| Vec4 { x: p.x, y: p.y, z: p.z + p.w * dz, w: p.w }).collect();
NurbsCurve::new(curve.degree, curve.knots.clone(), points).expect("a translated curve is a valid curve")
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SprocketForm {
Minimum,
Maximum,
Mean,
}
#[derive(Clone, Debug)]
pub struct Sprocket {
pub pitch: f64,
pub roller_diameter: f64,
pub teeth: usize,
pub form: SprocketForm,
pub width: f64,
}
pub fn sprocket_section(sprocket: &Sprocket) -> Result<GearSection, KernelRefusal> {
let p = sprocket.pitch;
let d1 = sprocket.roller_diameter;
if !(p > 0.0 && d1 > 0.0 && d1 < p && sprocket.width > 0.0) {
return Err(refuse(
"gear_input",
format!("The chain pitch ({p}), the roller diameter ({d1}, less than the pitch) and the width must be positive."),
));
}
if sprocket.teeth < 6 || sprocket.teeth > 300 {
return Err(refuse("gear_input", format!("A sprocket needs from 6 to 300 teeth (it has {}).", sprocket.teeth)));
}
let z = sprocket.teeth as f64;
let tau = TAU / z;
let d = p / (PI / z).sin();
let ri_min = 0.505 * d1;
let ri_max = 0.505 * d1 + 0.069 * d1.cbrt();
let re_min = 0.008 * d1 * (z * z + 180.0);
let re_max = 0.12 * d1 * (z + 2.0);
let a_min = (120.0 - 90.0 / z).to_radians();
let a_max = (140.0 - 90.0 / z).to_radians();
let da_min = d + p * (1.0 - 1.6 / z) - d1;
let da_max = d + 1.25 * p - d1;
let (ri, re, alpha, da) = match sprocket.form {
SprocketForm::Minimum => (ri_min, re_max, a_max, da_min),
SprocketForm::Maximum => (ri_max, re_min, a_min, da_max),
SprocketForm::Mean => (0.5 * (ri_min + ri_max), 0.5 * (re_min + re_max), 0.5 * (a_min + a_max), 0.5 * (da_min + da_max)),
};
let ra = da / 2.0;
let c = [d / 2.0, 0.0];
let u = [-(alpha / 2.0).cos(), (alpha / 2.0).sin()]; let t_up = [c[0] + ri * u[0], c[1] + ri * u[1]];
let f = [c[0] + (ri + re) * u[0], c[1] + (ri + re) * u[1]]; let half = tau / 2.0;
let a_t = (t_up[1] - f[1]).atan2(t_up[0] - f[0]);
let on_flank = |angle: f64| [f[0] + re * angle.cos(), f[1] + re * angle.sin()];
let step = 1e-4;
let sense = if radius_of(on_flank(a_t + step)) > radius_of(on_flank(a_t - step)) { 1.0 } else { -1.0 };
let reach = |angle: f64| {
let q = on_flank(angle);
(radius_of(q) >= ra, polar_angle(q) >= half)
};
let (mut lo, mut hi) = (0.0, PI / 2.0);
if !(reach(a_t + sense * hi).0 || reach(a_t + sense * hi).1) {
return Err(refuse("gear_input", "The sprocket flank does not reach the tip circle.".into()));
}
for _ in 0..200 {
let mid = 0.5 * (lo + hi);
let (tip, centre) = reach(a_t + sense * mid);
if tip || centre { hi = mid } else { lo = mid }
}
let a_end = a_t + sense * hi;
let end = on_flank(a_end);
let pointed = polar_angle(end) >= half - 1e-12 || radius_of(end) < ra - 1e-9 * p;
let (a_end, end) = if pointed {
let (mut lo, mut hi) = (0.0, hi);
for _ in 0..200 {
let mid = 0.5 * (lo + hi);
if polar_angle(on_flank(a_t + sense * mid)) >= half { hi = mid } else { lo = mid }
}
let a = a_t + sense * hi;
(a, on_flank(a))
} else {
(a_end, end)
};
let flank_arc = |from: f64, to: f64| -> Result<NurbsCurve, KernelRefusal> {
if to > from { centred_arc(f, re, from, to) } else { centred_arc(f, re, to, from)?.reversed().map_err(|e| refuse("gear_arc", e)) }
};
let upper = flank_arc(a_t, a_end)?; let seat = centred_arc(c, ri, PI - alpha / 2.0, PI + alpha / 2.0)?.reversed().map_err(|e| refuse("gear_arc", e))?; let lower = mirrored(&upper).reversed().map_err(|e| refuse("gear_arc", e))?; let mut gap: Vec<(&'static str, NurbsCurve)> = vec![("A", lower), ("S", seat), ("C", upper)];
let tip_angle = polar_angle(end);
if !pointed {
gap.push(("K", arc(ra, tip_angle, tau - tip_angle)?));
}
let mut curves = Vec::with_capacity(gap.len() * sprocket.teeth);
for index in 0..sprocket.teeth {
let angle = tau * index as f64 + half;
for (role, curve) in &gap {
curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
}
}
snap_junctions(&mut curves);
let data = GearData {
pitch_diameter: d,
tip_diameter: if pointed { 2.0 * radius_of(end) } else { da },
root_diameter: d - 2.0 * ri,
..GearData::default()
};
Ok(GearSection { curves, data })
}
pub fn sprocket_solid(sprocket: &Sprocket) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
let section = sprocket_section(sprocket)?;
let solid = extrude_section(§ion, sprocket.width)?;
let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
names.push("F".into());
names.push("B".into());
Ok((solid, names, section.data))
}
#[derive(Clone, Copy, Debug)]
pub enum Twist {
Helical { turn: f64 },
Herringbone { turn: f64 },
}
impl Twist {
fn angle(&self, t: f64) -> f64 {
match *self {
Twist::Helical { turn } => turn * t,
Twist::Herringbone { turn } => turn * (0.5 - (t - 0.5).abs()),
}
}
fn rate(&self, t: f64, after_crease: bool) -> f64 {
match *self {
Twist::Helical { turn } => turn,
Twist::Herringbone { turn } => {
if t < 0.5 || (t == 0.5 && !after_crease) { turn } else { -turn }
}
}
}
fn total_turn(&self) -> f64 {
match *self {
Twist::Helical { turn } => turn.abs(),
Twist::Herringbone { turn } => turn.abs(),
}
}
}
fn twist_basis(twist: Twist, reach: f64, tolerance: f64) -> Result<(Vec<f64>, Vec<[f64; 3]>), KernelRefusal> {
let crease = matches!(twist, Twist::Herringbone { .. });
let per = (384.0 * tolerance / reach.max(1e-12)).powf(0.25);
let needed = twist.total_turn() / per;
if !(needed <= 4096.0) {
return Err(refuse(
"twist_too_long",
format!(
"The teeth turn {:.3} times round the axis over the face width; shorten the face width or lower the helix angle (at most {:.1} turns at this size).",
twist.total_turn() / TAU,
4096.0 * per / TAU
),
));
}
let mut spans = (needed.ceil() as usize).max(1);
if crease && spans % 2 == 1 {
spans += 1;
}
let value = |t: f64| {
let a = twist.angle(t);
[a.cos(), a.sin(), t]
};
let slope = |t: f64, after: bool| {
let a = twist.angle(t);
let r = twist.rate(t, after);
[-a.sin() * r, a.cos() * r, 1.0]
};
let mut knots = vec![0.0; 4];
let mut points = vec![value(0.0)];
for index in 0..spans {
let (t0, t1) = (index as f64 / spans as f64, (index + 1) as f64 / spans as f64);
let h = (t1 - t0) / 3.0;
let (p0, p1) = (value(t0), value(t1));
let (d0, d1) = (slope(t0, true), slope(t1, false));
points.push([p0[0] + d0[0] * h, p0[1] + d0[1] * h, p0[2] + d0[2] * h]);
points.push([p1[0] - d1[0] * h, p1[1] - d1[1] * h, p1[2] - d1[2] * h]);
let last = index + 1 == spans;
let at_crease = crease && 2 * (index + 1) == spans;
if last {
points.push(p1);
} else if at_crease {
points.push(p1);
knots.extend([t1, t1, t1]);
} else {
knots.extend([t1, t1]);
}
}
knots.extend([1.0; 4]);
Ok((knots, points))
}
pub fn twisted_prism(section: &GearSection, width: f64, twist: Twist, tolerance: f64) -> Result<BrepSolid, KernelRefusal> {
if !(width > 0.0) {
return Err(refuse("gear_input", format!("The face width must be greater than zero (it is {width}).")));
}
let reach = section
.curves
.iter()
.flat_map(|c| c.curve.control_points.iter())
.map(|p| (p.x / p.w).hypot(p.y / p.w))
.fold(0.0, f64::max);
let (knots_v, basis) = twist_basis(twist, reach, tolerance)?;
let rows = |p: Vec4| -> Vec<Vec4> {
basis.iter().map(|[c, s, t]| Vec4 { x: c * p.x - s * p.y, y: s * p.x + c * p.y, z: p.z + p.w * t * width, w: p.w }).collect()
};
prism_by_rows(section, 3, &knots_v, &rows)
}
pub fn prism_by_rows(section: &GearSection, degree_v: usize, knots_v: &[f64], rows: &dyn Fn(Vec4) -> Vec<Vec4>) -> Result<BrepSolid, KernelRefusal> {
use crate::sweep_topology::{curve_to_plane_parameters, make_plane, parameter_line, CoedgeRecord, EdgeRecord, FaceRecord, LoopRecord, ShellRecord, VertexRecord};
let curves: Vec<NurbsCurve> = section.curves.iter().map(|piece| piece.curve.clone()).collect();
let count = curves.len();
let top_of = |curve: &NurbsCurve| -> Result<NurbsCurve, KernelRefusal> {
let points = curve.control_points.iter().map(|p| *rows(*p).last().expect("a row")).collect();
NurbsCurve::new(curve.degree, curve.knots.clone(), points).map_err(|e| refuse("gear_curve", e))
};
let point_of = |p: Vec4| Vec3::new(p.x / p.w, p.y / p.w, p.z / p.w);
let unit = |p: Vec4| Vec4 { x: p.x / p.w, y: p.y / p.w, z: p.z / p.w, w: 1.0 };
let starts: Vec<Vec4> = curves.iter().map(|c| c.control_points[0]).collect();
let mut vertices = Vec::with_capacity(2 * count);
for (index, start) in starts.iter().enumerate() {
vertices.push(VertexRecord { id: index as u64 + 1, point: point_of(*start) });
}
for (index, start) in starts.iter().enumerate() {
vertices.push(VertexRecord { id: (count + index) as u64 + 1, point: point_of(*rows(unit(*start)).last().expect("a row")) });
}
let edge_id = |kind: usize, index: usize| 10 + (kind * count + index) as u64;
let mut edges = Vec::with_capacity(3 * count);
let mut tops = Vec::with_capacity(count);
for (index, curve) in curves.iter().enumerate() {
let [start, end] = curve.domain().map_err(|e| refuse("gear_domain", e))?;
let next = (index + 1) % count;
let top = top_of(curve)?;
let axial = NurbsCurve::new(degree_v, knots_v.to_vec(), rows(unit(starts[index]))).map_err(|e| refuse("gear_edge", e))?;
edges.push(EdgeRecord { id: edge_id(0, index), curve: curve.clone(), t0: start, t1: end, start_vertex_id: index as u64 + 1, end_vertex_id: next as u64 + 1, degenerate: false, name: None });
edges.push(EdgeRecord { id: edge_id(1, index), curve: top.clone(), t0: start, t1: end, start_vertex_id: (count + index) as u64 + 1, end_vertex_id: (count + next) as u64 + 1, degenerate: false, name: None });
edges.push(EdgeRecord { id: edge_id(2, index), curve: axial, t0: 0.0, t1: 1.0, start_vertex_id: index as u64 + 1, end_vertex_id: (count + index) as u64 + 1, degenerate: false, name: None });
tops.push(top);
}
let line = |a: [f64; 2], b: [f64; 2]| parameter_line(a[0], a[1], b[0], b[1]).map_err(|e| refuse("gear_pcurve", e));
let mut next_id = 10 + 3 * count as u64 + 1000;
let mut faces = Vec::with_capacity(count + 2);
for (index, curve) in curves.iter().enumerate() {
let [start, end] = curve.domain().map_err(|e| refuse("gear_domain", e))?;
let next = (index + 1) % count;
let coedges = vec![
CoedgeRecord { id: next_id, edge_id: edge_id(0, index), forward: true, pcurve: line([start, 0.0], [end, 0.0])? },
CoedgeRecord { id: next_id + 1, edge_id: edge_id(2, next), forward: true, pcurve: line([end, 0.0], [end, 1.0])? },
CoedgeRecord { id: next_id + 2, edge_id: edge_id(1, index), forward: false, pcurve: line([end, 1.0], [start, 1.0])? },
CoedgeRecord { id: next_id + 3, edge_id: edge_id(2, index), forward: false, pcurve: line([start, 1.0], [start, 0.0])? },
];
next_id += 4;
let surface_rows: Vec<Vec<Vec4>> = curve.control_points.iter().map(|p| rows(*p)).collect();
let surface = NurbsSurface::new(curve.degree, degree_v, curve.knots.clone(), knots_v.to_vec(), surface_rows).map_err(|e| refuse("gear_surface", e))?;
faces.push(FaceRecord { id: next_id + 1, surface, same_sense: true, loops: vec![LoopRecord { id: next_id, coedges }], name: None });
next_id += 2;
}
let reach = curves.iter().chain(tops.iter()).flat_map(|c| c.control_points.iter()).map(|p| (p.x / p.w).hypot(p.y / p.w)).fold(0.0, f64::max);
let pad = reach * 1.1 + 1.0;
let x_axis = Vec3::new(1.0, 0.0, 0.0);
let y_axis = Vec3::new(0.0, 1.0, 0.0);
let z0 = vertices[0].point.z;
let z1 = vertices[count].point.z;
let bottom_origin = Vec3::new(-pad, -pad, z0);
let mut bottom = Vec::with_capacity(count);
for index in (0..count).rev() {
bottom.push(CoedgeRecord {
id: next_id,
edge_id: edge_id(0, index),
forward: false,
pcurve: curve_to_plane_parameters(&curves[index], bottom_origin, x_axis, y_axis).and_then(|c| c.reversed()).map_err(|e| refuse("gear_pcurve", e))?,
});
next_id += 1;
}
faces.push(FaceRecord {
id: next_id + 1,
surface: make_plane(bottom_origin, x_axis, y_axis, 2.0 * pad, 2.0 * pad).map_err(|e| refuse("gear_plane", e))?,
same_sense: false,
loops: vec![LoopRecord { id: next_id, coedges: bottom }],
name: None,
});
next_id += 2;
let top_origin = Vec3::new(-pad, -pad, z1);
let mut top = Vec::with_capacity(count);
for (index, curve) in tops.iter().enumerate() {
top.push(CoedgeRecord {
id: next_id,
edge_id: edge_id(1, index),
forward: true,
pcurve: curve_to_plane_parameters(curve, top_origin, x_axis, y_axis).map_err(|e| refuse("gear_pcurve", e))?,
});
next_id += 1;
}
faces.push(FaceRecord {
id: next_id + 1,
surface: make_plane(top_origin, x_axis, y_axis, 2.0 * pad, 2.0 * pad).map_err(|e| refuse("gear_plane", e))?,
same_sense: true,
loops: vec![LoopRecord { id: next_id, coedges: top }],
name: None,
});
next_id += 2;
let solid = BrepSolid {
mass_properties_cache: Default::default(),
cells: Default::default(),
id: next_id + 1,
vertices,
edges,
shells: vec![ShellRecord { id: next_id, faces }],
genus: 0,
kind: crate::BodyKind::Solid,
};
let issues = solid.validate();
if issues.is_empty() {
Ok(solid)
} else {
Err(KernelRefusal::internal(KernelStage::Validate, "validate", format!("gear prism is not valid: {issues:?}")))
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Hand {
Right,
Left,
}
#[derive(Clone, Debug)]
pub struct HelicalGear {
pub spur: SpurGear,
pub helix_angle: f64,
pub hand: Hand,
pub herringbone: bool,
}
pub fn helical_transverse(gear: &HelicalGear) -> Result<SpurGear, KernelRefusal> {
let beta = gear.helix_angle;
let normal = gear.spur.pressure_angle.to_degrees();
if !(10.0 - 1e-9..=35.0 + 1e-9).contains(&normal) {
return Err(refuse("gear_input", format!("The normal pressure angle must be between 10° and 35° (it is {normal}°).")));
}
if !(beta.to_degrees() >= 0.5 - 1e-9 && beta.to_degrees() <= 45.0 + 1e-9) {
return Err(refuse("bad_helix", format!("The helix angle must be between 0.5° and 45° (it is {:.4}°).", beta.to_degrees())));
}
let n = &gear.spur;
let c = beta.cos();
Ok(SpurGear {
module: n.module / c,
teeth: n.teeth,
pressure_angle: (n.pressure_angle.tan() / c).atan(),
profile_shift: n.profile_shift * c,
addendum: n.addendum * c,
dedendum: n.dedendum * c,
root_fillet: n.root_fillet * c,
backlash: n.backlash,
face_width: n.face_width,
})
}
pub fn helical_solid(gear: &HelicalGear) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
let transverse = helical_transverse(gear)?;
let section = transverse_section(&transverse)?;
let r = transverse.module * transverse.teeth as f64 / 2.0;
let width = transverse.face_width;
let sign = if gear.hand == Hand::Right { 1.0 } else { -1.0 };
let twist = if gear.herringbone {
Twist::Herringbone { turn: sign * width * gear.helix_angle.tan() / r }
} else {
Twist::Helical { turn: sign * width * gear.helix_angle.tan() / r }
};
let solid = twisted_prism(§ion, width, twist, 0.1 * GEAR_FIT_TOLERANCE * transverse.module)?;
let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
names.push("F".into());
names.push("B".into());
Ok((solid, names, section.data))
}
#[derive(Clone, Debug)]
pub struct StraightSpline {
pub teeth: usize,
pub minor: f64,
pub major: f64,
pub key_width: f64,
pub length: f64,
}
fn check_straight_spline(spline: &StraightSpline) -> Result<(), KernelRefusal> {
let StraightSpline { teeth, minor, major, key_width, length } = *spline;
if !(minor > 0.0 && major > minor && key_width > 0.0 && length > 0.0) {
return Err(refuse(
"gear_input",
format!("A spline needs 0 < minor diameter ({minor}) < major diameter ({major}), a positive key width ({key_width}) and length ({length})."),
));
}
if teeth < 2 || teeth > 100 {
return Err(refuse("gear_input", format!("A spline needs from 2 to 100 keys (it has {teeth}).")));
}
let half_root = (key_width / minor).asin();
if !(key_width < minor) || 2.0 * half_root >= TAU / teeth as f64 - 1e-9 {
return Err(refuse("keys_overlap", format!("{teeth} keys {key_width} wide do not fit round a {minor} minor diameter.")));
}
Ok(())
}
pub fn straight_spline_section(spline: &StraightSpline) -> Result<GearSection, KernelRefusal> {
check_straight_spline(spline)?;
let (rr, ra, h) = (spline.minor / 2.0, spline.major / 2.0, spline.key_width / 2.0);
let n = spline.teeth as f64;
let foot = [(rr * rr - h * h).sqrt(), h];
let top = [(ra * ra - h * h).sqrt(), h];
let top_angle = (h / ra).asin();
let foot_angle = (h / rr).asin();
let key: Vec<(&'static str, NurbsCurve)> = vec![
("R", line([foot[0], -h], [top[0], -h])?),
("K", arc(ra, -top_angle, top_angle)?),
("L", line(top, foot)?),
("G", arc(rr, foot_angle, TAU / n - foot_angle)?),
];
let mut curves = Vec::with_capacity(4 * spline.teeth);
for index in 0..spline.teeth {
let angle = TAU * index as f64 / n;
for (role, curve) in &key {
curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
}
}
snap_junctions(&mut curves);
Ok(GearSection { curves, data: GearData { tip_diameter: spline.major, root_diameter: spline.minor, ..GearData::default() } })
}
pub fn straight_spline_shaft(spline: &StraightSpline) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
let section = straight_spline_section(spline)?;
let solid = extrude_section(§ion, spline.length)?;
let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
names.push("F".into());
names.push("B".into());
Ok((solid, names, section.data))
}
pub fn hub_from_section(section: &GearSection, outside: f64, length: f64) -> Result<BrepSolid, KernelRefusal> {
let mut reach: f64 = 0.0;
for piece in §ion.curves {
let [t0, t1] = piece.curve.domain().map_err(|e| refuse("gear_domain", e))?;
for i in 0..=32 {
let p = piece.curve.evaluate(t0 + (t1 - t0) * i as f64 / 32.0).map_err(|e| refuse("gear_eval", e))?;
reach = reach.max(p.x.hypot(p.y));
}
}
if !(outside / 2.0 > reach + 1e-9) {
return Err(refuse(
"hub_too_small",
format!("The hub's outside diameter ({outside}) must be larger than its spline's major diameter ({:.4}).", 2.0 * reach),
));
}
let mut blank = crate::make_cylinder_brep(Vec3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), outside / 2.0, length)
.map_err(|error| refuse("gear_blank", error))?;
for (face, name) in blank.shells[0].faces.iter_mut().zip(["OD", "F", "B"]) {
face.name = Some(name.into());
}
let extra = 0.1 * length + 0.1 * reach;
let shifted: Vec<SectionCurve> = section
.curves
.iter()
.map(|piece| SectionCurve { curve: translated(&piece.curve, -extra), role: piece.role, tooth: piece.tooth })
.collect();
let mut tool = extrude_section(&GearSection { curves: shifted.clone(), data: section.data.clone() }, length + 2.0 * extra)?;
for (face, piece) in tool.shells[0].faces.iter_mut().zip(&shifted) {
face.name = Some(piece.suffix());
}
crate::boolean_operation_nary(&[blank, tool], crate::BooleanOperation::Subtract)
}
pub fn straight_spline_hub(spline: &StraightSpline, outside: f64) -> Result<(BrepSolid, GearData), KernelRefusal> {
let section = straight_spline_section(spline)?;
let hub = hub_from_section(§ion, outside, spline.length)?;
Ok((hub, section.data))
}
#[derive(Clone, Debug)]
pub struct TimingPulley {
pub pitch: f64,
pub teeth: usize,
pub pld: f64,
pub bottom_width: f64,
pub depth: f64,
pub side_angle: f64,
pub bottom_radius: f64,
pub top_radius: f64,
pub width: f64,
}
fn arc_through(centre: [f64; 2], from: [f64; 2], to: [f64; 2], ccw: bool) -> Result<NurbsCurve, KernelRefusal> {
let radius = (from[0] - centre[0]).hypot(from[1] - centre[1]);
let a0 = (from[1] - centre[1]).atan2(from[0] - centre[0]);
let a1 = (to[1] - centre[1]).atan2(to[0] - centre[0]);
if ccw {
let mut end = a1;
while end <= a0 {
end += TAU;
}
centred_arc(centre, radius, a0, end)
} else {
let mut start = a1;
while start <= a0 - TAU {
start += TAU;
}
while start >= a0 {
start -= TAU;
}
centred_arc(centre, radius, start, a0)?.reversed().map_err(|e| refuse("gear_arc", e))
}
}
pub fn timing_pulley_section(pulley: &TimingPulley) -> Result<GearSection, KernelRefusal> {
let TimingPulley { pitch, teeth, pld, bottom_width, depth, side_angle, bottom_radius, top_radius, width } = pulley.clone();
if !(pitch > 0.0 && pld >= 0.0 && bottom_width > 0.0 && depth > 0.0 && width > 0.0 && bottom_radius >= 0.0 && top_radius >= 0.0) {
return Err(refuse("gear_input", "The pulley's pitch, groove sizes and width must be positive.".into()));
}
if !(0.0..60f64.to_radians()).contains(&side_angle) {
return Err(refuse("gear_input", "The groove side angle must be between 0° and 60°.".into()));
}
if teeth < 6 || teeth > 400 {
return Err(refuse("gear_input", format!("A pulley needs from 6 to 400 teeth (it has {teeth}).")));
}
let z = teeth as f64;
let ro = pitch * z / PI / 2.0 - pld / 2.0;
let x_bottom = ro - depth;
if !(x_bottom > 0.0) {
return Err(refuse("gear_input", "The groove is deeper than the pulley's radius.".into()));
}
let tau = TAU / z;
let (s, c) = side_angle.sin_cos();
let side = [c, s]; let normal = [-s, c]; let corner = [x_bottom, bottom_width / 2.0];
let b = corner[0] * side[0] + corner[1] * side[1];
let t_top = -b + (b * b - (corner[0] * corner[0] + corner[1] * corner[1] - ro * ro)).sqrt();
let top = [corner[0] + t_top * side[0], corner[1] + t_top * side[1]];
let turn = PI / 2.0 - side_angle;
let reach_b = bottom_radius * (turn / 2.0).tan();
let t1 = [corner[0], corner[1] - reach_b];
let t2 = [corner[0] + reach_b * side[0], corner[1] + reach_b * side[1]];
let centre_b = [t1[0] + bottom_radius, t1[1]];
let rt = top_radius;
let base = [corner[0] + rt * normal[0], corner[1] + rt * normal[1]];
let bb = base[0] * side[0] + base[1] * side[1];
let disc = bb * bb - (base[0] * base[0] + base[1] * base[1] - (ro - rt) * (ro - rt));
if disc < 0.0 {
return Err(refuse("gear_input", "The groove's top radius does not fit.".into()));
}
let t_c = -bb + disc.sqrt();
let centre_t = [base[0] + t_c * side[0], base[1] + t_c * side[1]];
let t3 = [corner[0] + t_c * side[0], corner[1] + t_c * side[1]];
let scale = ro / (centre_t[0].hypot(centre_t[1]));
let t4 = [centre_t[0] * scale, centre_t[1] * scale];
let land_start = polar_angle(t4);
if land_start >= tau / 2.0 - 1e-9 || reach_b > t_c + 1e-12 || t1[1] < 0.0 {
return Err(refuse(
"groove_too_wide",
format!("The grooves and their corner radii do not fit the pitch at {teeth} teeth; add teeth or reduce the radii."),
));
}
let _ = top;
let mut upper: Vec<(&'static str, NurbsCurve)> = Vec::new();
if bottom_radius > 0.0 {
upper.push(("D", arc_through(centre_b, t1, t2, false)?));
}
upper.push(("C", line(t2, t3)?));
if rt > 0.0 {
upper.push(("P", arc_through(centre_t, t3, t4, true)?));
}
let mut groove: Vec<(&'static str, NurbsCurve)> = Vec::new();
let lower_roles = |role: &'static str| match role {
"D" => "U",
"C" => "A",
_ => "Q",
};
for (role, curve) in upper.iter().rev() {
groove.push((lower_roles(role), mirrored(curve).reversed().map_err(|e| refuse("gear_arc", e))?));
}
groove.push(("S", line([t1[0], -t1[1]], t1)?));
groove.extend(upper.into_iter());
groove.push(("K", arc(ro, land_start, tau - land_start)?));
let mut curves = Vec::with_capacity(groove.len() * teeth);
for index in 0..teeth {
let angle = tau * index as f64 + tau / 2.0;
for (role, curve) in &groove {
curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
}
}
snap_junctions(&mut curves);
let data = GearData { pitch_diameter: pitch * z / PI, tip_diameter: 2.0 * ro, root_diameter: 2.0 * x_bottom, ..GearData::default() };
Ok(GearSection { curves, data })
}
pub fn timing_pulley_solid(pulley: &TimingPulley) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
let section = timing_pulley_section(pulley)?;
let solid = extrude_section(§ion, pulley.width)?;
let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
names.push("F".into());
names.push("B".into());
Ok((solid, names, section.data))
}
#[derive(Clone, Debug)]
pub struct Ratchet {
pub teeth: usize,
pub outside: f64,
pub depth: f64,
pub lean: f64,
pub symmetric: bool,
pub clockwise_locks: bool,
pub width: f64,
}
pub fn ratchet_section(ratchet: &Ratchet) -> Result<GearSection, KernelRefusal> {
let Ratchet { teeth, outside, depth, lean, symmetric, clockwise_locks, width } = ratchet.clone();
if !(outside > 0.0 && depth > 0.0 && depth < outside / 2.0 && width > 0.0) {
return Err(refuse("gear_input", format!("A ratchet needs a positive outside diameter ({outside}), a depth ({depth}) under its radius and a positive width.")));
}
if teeth < 3 || teeth > 360 {
return Err(refuse("gear_input", format!("A ratchet needs from 3 to 360 teeth (it has {teeth}).")));
}
if !(lean >= 0.0 && lean.to_degrees() <= 30.0) {
return Err(refuse("gear_input", "The locking face lean must be between 0° and 30°.".into()));
}
let z = teeth as f64;
let tau = TAU / z;
let ra = outside / 2.0;
let rf = ra - depth;
let tip = [ra, 0.0];
let face_angle = PI + lean; let d = [face_angle.cos(), face_angle.sin()];
let b = tip[0] * d[0] + tip[1] * d[1];
let t = -b - (b * b - (ra * ra - rf * rf)).sqrt();
let root = [tip[0] + t * d[0], tip[1] + t * d[1]];
let foot = polar_angle(root);
let (lock, back) = if symmetric {
let mid = [rf * (tau / 2.0).cos(), rf * (tau / 2.0).sin()];
let lock = line(tip, mid)?;
let next = [ra * tau.cos(), ra * tau.sin()];
(lock, line(mid, next)?)
} else {
if foot >= tau - 1e-9 {
return Err(refuse("gear_input", "The locking faces overlap: fewer teeth, less depth or less lean.".into()));
}
let next = [ra * tau.cos(), ra * tau.sin()];
(line(tip, root)?, line(root, next)?)
};
let mut curves = Vec::with_capacity(2 * teeth);
for index in 0..teeth {
let angle = tau * index as f64;
curves.push(SectionCurve { curve: rotated(&lock, angle), role: "LK", tooth: index });
curves.push(SectionCurve { curve: rotated(&back, angle), role: "BK", tooth: index });
}
if clockwise_locks {
let mut mirrored_curves: Vec<SectionCurve> = curves
.iter()
.map(|piece| SectionCurve { curve: mirrored(&piece.curve).reversed().expect("a line reverses"), role: piece.role, tooth: piece.tooth })
.collect();
mirrored_curves.reverse();
curves = mirrored_curves;
}
snap_junctions(&mut curves);
Ok(GearSection { curves, data: GearData { tip_diameter: outside, root_diameter: 2.0 * rf, ..GearData::default() } })
}
pub fn ratchet_solid(ratchet: &Ratchet) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
let section = ratchet_section(ratchet)?;
let solid = extrude_section(§ion, ratchet.width)?;
let mut names: Vec<String> = section.curves.iter().map(|c| c.suffix()).collect();
names.push("F".into());
names.push("B".into());
Ok((solid, names, section.data))
}
#[derive(Clone, Debug)]
pub struct GenevaWheel {
pub slots: usize,
pub centre_distance: f64,
pub pin_diameter: f64,
pub clearance: f64,
pub lock_radius: f64,
pub width: f64,
}
pub fn geneva_sizes(wheel: &GenevaWheel) -> (f64, f64, f64, f64) {
let n = wheel.slots as f64;
let a = wheel.centre_distance;
let crank = a * (PI / n).sin();
let radius = a * (PI / n).cos();
let lock = if wheel.lock_radius > 0.0 { wheel.lock_radius } else { crank - wheel.pin_diameter };
(crank, radius, a - crank, lock)
}
pub fn geneva_section(wheel: &GenevaWheel) -> Result<GearSection, KernelRefusal> {
let GenevaWheel { slots, centre_distance: a, pin_diameter: dp, clearance: c, width, .. } = wheel.clone();
if !(3..=12).contains(&slots) {
return Err(refuse("gear_input", format!("A Geneva wheel has from 3 to 12 slots (it has {slots}).")));
}
if !(a > 0.0 && dp > 0.0 && c >= 0.0 && width > 0.0) {
return Err(refuse("gear_input", "The centre distance, pin diameter and width must be positive (the clearance not negative).".into()));
}
let n = slots as f64;
let (crank, rw, end_centre, lock) = geneva_sizes(wheel);
let half = (dp + c) / 2.0; let rl = lock + c / 2.0;
if !(lock > 0.0 && lock < a - rw + 1e-9 + rw) || !(half < end_centre) || !(half < rw * (PI / n).sin()) {
return Err(refuse("gear_input", format!("The pin ({dp}) is too large for {slots} slots at centre distance {a}.")));
}
if end_centre * (PI / n).sin() <= half * (1.0 + 1e-9) {
return Err(refuse(
"gear_input",
format!("Adjacent slots meet near the hub: {slots} slots {:.4} wide need a larger centre distance than {a}, or a smaller pin.", 2.0 * half),
));
}
let x_top = (rw * rw - half * half).sqrt();
let p1 = [x_top, half];
let beta = PI / n;
let centre = [a * beta.cos(), a * beta.sin()];
let along = (rw * rw - rl * rl + a * a) / (2.0 * a);
let h2 = rw * rw - along * along;
if h2 <= 0.0 {
return Err(refuse("gear_input", "The locking arc does not reach the wheel's rim: increase the locking disc radius.".into()));
}
let h = h2.sqrt();
let e = [beta.cos(), beta.sin()];
let perp = [-beta.sin(), beta.cos()];
let q1 = [along * e[0] - h * perp[0], along * e[1] - h * perp[1]];
let q2 = [along * e[0] + h * perp[0], along * e[1] + h * perp[1]];
let a1 = polar_angle(p1);
if polar_angle(q1) <= a1 + 1e-9 {
return Err(refuse("gear_input", "The locking arc cuts into the slots: reduce the locking disc radius or the pin.".into()));
}
let tau = TAU / n;
let slot: Vec<(&'static str, NurbsCurve)> = vec![
("SL", line([x_top, -half], [end_centre, -half])?),
("SE", arc_through([end_centre, 0.0], [end_centre, -half], [end_centre, half], false)?),
("SU", line([end_centre, half], p1)?),
("RA", arc(rw, a1, polar_angle(q1))?),
("LA", arc_through(centre, q1, q2, false)?),
("RB", arc(rw, polar_angle(q2), tau - a1)?),
];
let mut curves = Vec::with_capacity(6 * slots);
for index in 0..slots {
let angle = tau * index as f64;
for (role, curve) in &slot {
curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
}
}
snap_junctions(&mut curves);
let _ = crank;
Ok(GearSection { curves, data: GearData { tip_diameter: 2.0 * rw, ..GearData::default() } })
}
pub fn geneva_solid(wheel: &GenevaWheel) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
let section = geneva_section(wheel)?;
let solid = extrude_section(§ion, wheel.width)?;
let mut names: Vec<String> = section.curves.iter().map(|c| c.suffix()).collect();
names.push("F".into());
names.push("B".into());
Ok((solid, names, section.data))
}
#[derive(Clone, Debug)]
pub struct Worm {
pub axial_module: f64,
pub starts: usize,
pub reference_diameter: f64,
pub pressure_angle: f64,
pub addendum: f64,
pub dedendum: f64,
pub length: f64,
pub hand: Hand,
}
impl Worm {
pub fn lead(&self) -> f64 {
self.starts as f64 * PI * self.axial_module
}
pub fn axial_thickness(&self, radius: f64) -> f64 {
PI * self.axial_module / 2.0 - 2.0 * (radius - self.reference_diameter / 2.0) * self.pressure_angle.tan()
}
}
pub fn worm_section(worm: &Worm) -> Result<GearSection, KernelRefusal> {
let m = worm.axial_module;
if !(m > 0.0 && worm.reference_diameter > 0.0 && worm.length > 0.0 && worm.addendum > 0.0 && worm.dedendum > 0.0) {
return Err(refuse("gear_input", "The worm's module, diameter, length, addendum and dedendum must be positive.".into()));
}
if worm.starts < 1 || worm.starts > 8 {
return Err(refuse("gear_input", format!("A worm has from 1 to 8 starts (it has {}).", worm.starts)));
}
let degrees = worm.pressure_angle.to_degrees();
if !(10.0 - 1e-9..=35.0 + 1e-9).contains(°rees) {
return Err(refuse("gear_input", format!("The axial pressure angle must be between 10° and 35° (it is {degrees}°).")));
}
let r1 = worm.reference_diameter / 2.0;
let ra = r1 + worm.addendum * m;
let rf = r1 - worm.dedendum * m;
if !(rf > 0.0) {
return Err(refuse("gear_input", format!("The worm's root diameter is not positive ({:.4}): raise the diameter quotient.", 2.0 * rf)));
}
let lead = worm.lead();
let gamma = (lead / (PI * worm.reference_diameter)).atan();
if gamma.to_degrees() > 45.0 {
return Err(refuse("bad_lead", format!("The lead angle {:.3}° is over 45°: fewer starts or a larger diameter.", gamma.to_degrees())));
}
if worm.axial_thickness(ra) <= 1e-6 * m {
return Err(refuse("pointed_tip", "The worm thread comes to a point below its tip: lower the addendum or the pressure angle.".into()));
}
let n = worm.starts as f64;
let pitch = PI * m;
if worm.axial_thickness(rf) >= pitch - 1e-6 * m {
return Err(refuse("teeth_overlap", "The worm's threads meet at the root: lower the dedendum or the pressure angle.".into()));
}
let half = |r: f64| PI * worm.axial_thickness(r) / lead;
let flank = |r: f64| {
let t = half(r);
[r * t.cos(), r * t.sin()]
};
let tolerance = GEAR_FIT_TOLERANCE * m;
let upper = fit_planar(&|r| flank(r), rf, ra, tolerance)?; let tau = TAU / n;
let thread: Vec<(&'static str, NurbsCurve)> = vec![
("R", mirrored(&upper)),
("K", arc(ra, -half(ra), half(ra))?),
("L", upper.reversed().map_err(|e| refuse("gear_fit", e))?),
("G", arc(rf, half(rf), tau - half(rf))?),
];
let mut curves = Vec::with_capacity(4 * worm.starts);
for index in 0..worm.starts {
let angle = tau * index as f64;
for (role, curve) in &thread {
curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
}
}
snap_junctions(&mut curves);
let data = GearData { pitch_diameter: worm.reference_diameter, tip_diameter: 2.0 * ra, root_diameter: 2.0 * rf, ..GearData::default() };
Ok(GearSection { curves, data })
}
pub fn worm_solid(worm: &Worm) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
let section = worm_section(worm)?;
let sign = if worm.hand == Hand::Right { 1.0 } else { -1.0 };
let turn = sign * TAU * worm.length / worm.lead();
let solid = twisted_prism(§ion, worm.length, Twist::Helical { turn }, GEAR_FIT_TOLERANCE * worm.axial_module)?;
let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
names.push("F".into());
names.push("B".into());
Ok((solid, names, section.data))
}
#[derive(Clone, Debug)]
pub struct CycloidalDisc {
pub pins: usize,
pub pin_circle_diameter: f64,
pub pin_diameter: f64,
pub eccentricity: f64,
pub clearance: f64,
pub width: f64,
}
impl CycloidalDisc {
fn trochoid(&self, t: f64) -> ([f64; 2], [f64; 2]) {
let r = self.pin_circle_diameter / 2.0;
let e = self.eccentricity;
let n = self.pins as f64;
(
[r * t.cos() - e * (n * t).cos(), -r * t.sin() + e * (n * t).sin()],
[-r * t.sin() + e * n * (n * t).sin(), -r * t.cos() + e * n * (n * t).cos()],
)
}
pub fn profile(&self, t: f64) -> [f64; 2] {
let (q, d) = self.trochoid(t);
let length = d[0].hypot(d[1]);
let offset = self.pin_diameter / 2.0 + self.clearance / 2.0;
let n = [d[1] / length, -d[0] / length];
[q[0] + offset * n[0], q[1] + offset * n[1]]
}
}
pub fn cycloidal_disc_section(disc: &CycloidalDisc) -> Result<GearSection, KernelRefusal> {
let CycloidalDisc { pins, pin_circle_diameter: dc, pin_diameter: dp, eccentricity: e, clearance, width } = disc.clone();
if !(4..=200).contains(&pins) {
return Err(refuse("gear_input", format!("A cycloidal drive has from 4 to 200 pins (it has {pins}).")));
}
if !(dc > 0.0 && dp > 0.0 && e > 0.0 && clearance >= 0.0 && width > 0.0) {
return Err(refuse("gear_input", "The pin circle, pin diameter, eccentricity and width must be positive.".into()));
}
let n = pins as f64;
let r = dc / 2.0;
if e >= r / n * (1.0 - 1e-9) {
return Err(refuse(
"gear_input",
format!("The eccentricity must be under the pin circle radius / pins = {:.4} (it is {e}).", r / n),
));
}
let offset = dp / 2.0 + clearance / 2.0;
let (rr, ee) = (dc / 2.0, e);
let radius = |t: f64| -> f64 {
let d = [-rr * t.sin() + ee * n * (n * t).sin(), -rr * t.cos() + ee * n * (n * t).cos()];
let dd = [-rr * t.cos() + ee * n * n * (n * t).cos(), rr * t.sin() - ee * n * n * (n * t).sin()];
let cross = d[0] * dd[1] - d[1] * dd[0];
let speed = d[0].hypot(d[1]);
if cross < 0.0 { speed * speed * speed / -cross } else { f64::INFINITY }
};
let period = TAU / (n - 1.0);
let samples = 2000;
let values: Vec<f64> = (0..=samples).map(|i| radius(period * i as f64 / samples as f64)).collect();
let mut least = f64::INFINITY;
for i in 0..=samples {
let previous = values[if i == 0 { samples - 1 } else { i - 1 }];
let next = values[if i == samples { 1 } else { i + 1 }];
if values[i] <= previous && values[i] <= next && values[i].is_finite() {
let (mut lo, mut hi) = (period * (i as f64 - 1.0) / samples as f64, period * (i as f64 + 1.0) / samples as f64);
for _ in 0..100 {
let a = lo + (hi - lo) * 0.381966;
let b = hi - (hi - lo) * 0.381966;
if radius(a) < radius(b) { hi = b } else { lo = a }
}
least = least.min(radius(0.5 * (lo + hi)));
}
}
if offset >= least * (1.0 - 1e-6) {
return Err(refuse(
"undercut",
format!("The pins ({dp}) are too large for this eccentricity and pin circle: the lobes would cusp (the pin radius plus half the clearance must be under {least:.4})."),
));
}
let lobes = pins - 1;
let step = TAU / lobes as f64;
let tolerance = GEAR_FIT_TOLERANCE * dp.min(e * 4.0);
let mut curves = Vec::with_capacity(lobes);
for k in 0..lobes {
let (a, b) = (step * k as f64, step * (k + 1) as f64);
let piece = fit_planar(&|u| disc.profile(-u), a, b, tolerance)?;
curves.push(SectionCurve { curve: piece, role: "LB", tooth: k });
}
snap_junctions(&mut curves);
Ok(GearSection { curves, data: GearData { pitch_diameter: dc, ..GearData::default() } })
}
pub fn cycloidal_disc_solid(disc: &CycloidalDisc) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
let section = cycloidal_disc_section(disc)?;
let solid = extrude_section(§ion, disc.width)?;
let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
names.push("F".into());
names.push("B".into());
Ok((solid, names, section.data))
}
pub fn cycloidal_pin_ring(pins: usize, pin_circle_diameter: f64, pin_diameter: f64, outside: f64, width: f64) -> Result<(BrepSolid, GearData), KernelRefusal> {
if !(4..=200).contains(&pins) || !(pin_diameter > 0.0 && pin_circle_diameter > pin_diameter && width > 0.0) {
return Err(refuse("gear_input", "The pin ring needs 4 to 200 pins, a pin circle larger than the pins and a positive width.".into()));
}
let r = pin_circle_diameter / 2.0;
let rp = pin_diameter / 2.0;
let n = pins as f64;
let tau = TAU / n;
let delta = 2.0 * (rp / (2.0 * r)).asin();
if 2.0 * delta >= tau - 1e-9 || 2.0 * r * (PI / n).sin() <= pin_diameter * (1.0 + 1e-9) {
return Err(refuse("gear_input", format!("{pins} pins of diameter {pin_diameter} overlap on a {pin_circle_diameter} pin circle.")));
}
let centre = [r, 0.0];
let a = [r * (-delta).cos(), r * (-delta).sin()];
let b = [r * delta.cos(), r * delta.sin()];
let cw = arc_through(centre, a, b, false)?;
let pin_arc = {
let [t0, t1] = cw.domain().map_err(|e| refuse("gear_domain", e))?;
let mid = cw.evaluate(0.5 * (t0 + t1)).map_err(|e| refuse("gear_eval", e))?;
if mid.x < r { cw } else { arc_through(centre, a, b, true)? }
};
let space: Vec<(&'static str, NurbsCurve)> = vec![("P", pin_arc), ("G", arc(r, delta, tau - delta)?)];
let mut curves = Vec::with_capacity(2 * pins);
for k in 0..pins {
for (role, curve) in &space {
curves.push(SectionCurve { curve: rotated(curve, tau * k as f64), role, tooth: k });
}
}
snap_junctions(&mut curves);
let section = GearSection { curves, data: GearData { pitch_diameter: pin_circle_diameter, ..GearData::default() } };
let ring = hub_from_section(§ion, outside, width)?;
Ok((ring, section.data))
}
#[derive(Clone, Debug)]
pub struct CycloidalGear {
pub module: f64,
pub teeth: usize,
pub generating_radius: f64,
pub tooth_fraction: f64,
pub addendum: f64,
pub dedendum: f64,
pub width: f64,
}
pub fn cycloidal_gear_section(gear: &CycloidalGear) -> Result<GearSection, KernelRefusal> {
let m = gear.module;
if !(m > 0.0 && gear.generating_radius > 0.0 && gear.addendum > 0.0 && gear.dedendum > 0.0 && gear.width > 0.0) {
return Err(refuse("gear_input", "The module, rolling circle, addendum, dedendum and width must be positive.".into()));
}
if !(gear.tooth_fraction > 0.1 && gear.tooth_fraction < 0.9) {
return Err(refuse("gear_input", "The tooth thickness must be between 0.1 and 0.9 of the pitch.".into()));
}
if gear.teeth < 6 || gear.teeth > 1000 {
return Err(refuse("gear_input", format!("A cycloidal gear needs from 6 to 1000 teeth (it has {}).", gear.teeth)));
}
let z = gear.teeth as f64;
let r = m * z / 2.0;
let rho = gear.generating_radius;
let rf = r - gear.dedendum * m;
if !(rf > 0.0) {
return Err(refuse("root_below_centre", "The root circle is not positive: fewer dedendum or more teeth.".into()));
}
let tau = TAU / z;
let psi = PI * gear.tooth_fraction / z; let k = (r + rho) / rho;
let epi = |phi: f64| {
let p = [(r + rho) * phi.cos() - rho * (k * phi).cos(), (r + rho) * phi.sin() - rho * (k * phi).sin()];
rotate(p, -psi)
};
let ra = r + gear.addendum * m;
let reach = |phi: f64| radius_of(epi(phi)) >= ra || polar_angle(epi(phi)) >= 0.0;
let mut hi = 1e-3;
while !reach(hi) {
hi *= 1.5;
if hi > PI {
return Err(refuse("gear_input", "The addendum curve does not close.".into()));
}
}
let mut lo = 0.0;
for _ in 0..200 {
let mid = 0.5 * (lo + hi);
if reach(mid) { hi = mid } else { lo = mid }
}
let end = epi(hi);
let pointed = polar_angle(end) >= -1e-9;
let phi_end = if pointed {
let (mut lo, mut hi) = (0.0, hi);
for _ in 0..200 {
let mid = 0.5 * (lo + hi);
if polar_angle(epi(mid)) >= 0.0 { hi = mid } else { lo = mid }
}
hi
} else {
hi
};
let tolerance = GEAR_FIT_TOLERANCE * m;
let right_add = fit_planar(&|phi| epi(phi), 0.0, phi_end, tolerance)?; let foot = [rf * (-psi).cos(), rf * (-psi).sin()];
let pitch_point = [r * (-psi).cos(), r * (-psi).sin()];
let mut tooth: Vec<(&'static str, NurbsCurve)> = vec![("R", line(foot, pitch_point)?), ("ER", right_add.clone())];
let tip_angle = -polar_angle(epi(phi_end));
if !pointed {
tooth.push(("K", arc(ra, -tip_angle, tip_angle)?));
}
tooth.push(("EL", mirrored(&right_add).reversed().map_err(|e| refuse("gear_fit", e))?));
tooth.push(("L", line([pitch_point[0], -pitch_point[1]], [foot[0], -foot[1]])?));
tooth.push(("G", arc(rf, psi, tau - psi)?));
let mut curves = Vec::with_capacity(tooth.len() * gear.teeth);
for index in 0..gear.teeth {
let angle = tau * index as f64;
for (role, curve) in &tooth {
curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
}
}
snap_junctions(&mut curves);
let data = GearData {
pitch_diameter: 2.0 * r,
tip_diameter: 2.0 * radius_of(epi(phi_end)),
root_diameter: 2.0 * rf,
tooth_thickness: 2.0 * psi * r,
..GearData::default()
};
Ok(GearSection { curves, data })
}
pub fn cycloidal_gear_solid(gear: &CycloidalGear) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
let section = cycloidal_gear_section(gear)?;
let solid = extrude_section(§ion, gear.width)?;
let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
names.push("F".into());
names.push("B".into());
Ok((solid, names, section.data))
}
#[derive(Clone, Debug)]
pub struct BevelGear {
pub module: f64,
pub teeth: usize,
pub mate_teeth: usize,
pub pressure_angle: f64,
pub addendum: f64,
pub dedendum: f64,
pub face_width: f64,
pub backlash: f64,
}
pub fn bevel_cones(gear: &BevelGear) -> (f64, f64, f64) {
let delta = (gear.teeth as f64).atan2(gear.mate_teeth as f64);
let cone = gear.module * gear.teeth as f64 / (2.0 * delta.sin());
let base = (delta.sin() * gear.pressure_angle.cos()).asin();
(delta, cone, base)
}
fn spherical_involute(r: f64, base: f64, phi: f64) -> [f64; 3] {
let (s, c) = base.sin_cos();
let t = phi * s;
[
r * (t.cos() * s * phi.cos() + t.sin() * phi.sin()),
r * (t.cos() * s * phi.sin() - t.sin() * phi.cos()),
r * t.cos() * c,
]
}
fn cone_angle(p: [f64; 3]) -> f64 {
p[0].hypot(p[1]).atan2(p[2])
}
fn project(p: [f64; 3], h: f64) -> [f64; 2] {
[p[0] * h / p[2], p[1] * h / p[2]]
}
pub fn bevel_section(gear: &BevelGear, h: f64) -> Result<GearSection, KernelRefusal> {
let m = gear.module;
if !(m > 0.0 && gear.face_width > 0.0 && gear.addendum > 0.0 && gear.dedendum > 0.0 && gear.backlash >= 0.0) {
return Err(refuse("gear_input", "The module, face width, addendum and dedendum must be positive.".into()));
}
if gear.teeth < 6 || gear.mate_teeth < 6 {
return Err(refuse("gear_input", "A bevel pair needs at least 6 teeth on each gear.".into()));
}
let degrees = gear.pressure_angle.to_degrees();
if !(10.0 - 1e-9..=35.0 + 1e-9).contains(°rees) {
return Err(refuse("gear_input", format!("The pressure angle must be between 10° and 35° (it is {degrees}°).")));
}
let (delta, r, base) = bevel_cones(gear);
if gear.face_width > r / 3.0 + 1e-9 {
return Err(refuse(
"face_too_wide",
format!("The face width ({}) is over a third of the cone distance ({:.4}): the teeth would be too small at the toe.", gear.face_width, r),
));
}
let z = gear.teeth as f64;
let tip = delta + gear.addendum * m / r;
let root = delta - gear.dedendum * m / r;
if !(root > 0.0) {
return Err(refuse("root_below_centre", "The root cone passes the axis: fewer dedendum or more teeth.".into()));
}
let phi_at = |theta: f64| ((theta.cos() / base.cos()).clamp(-1.0, 1.0)).acos() / base.sin();
let azimuth = |p: [f64; 3]| p[1].atan2(p[0]);
let half = (PI * m / 2.0 - gear.backlash) / (2.0 * r * delta.sin());
let p_pitch = spherical_involute(r, base, phi_at(delta));
let shift = half + azimuth(p_pitch);
let left = |phi: f64| {
let p = spherical_involute(r, base, phi);
let q = [p[0], -p[1], p[2]];
let (s, c) = shift.sin_cos();
[c * q[0] - s * q[1], s * q[0] + c * q[1], q[2]]
};
let tip_phi = phi_at(tip);
if azimuth(left(tip_phi)) <= 1e-6 * m / r {
return Err(refuse("pointed_tip", "The teeth come to a point below the tip cone: reduce the addendum.".into()));
}
let extend = !(root > base); let start_phi = if extend { 0.02 * tip_phi } else { phi_at(root) };
let tolerance = GEAR_FIT_TOLERANCE * m;
let flank = fit_planar(&|phi| project(left(phi), h), start_phi, tip_phi, tolerance)?; let tau = TAU / z;
let base_point = project(left(start_phi), h);
let root_r = h * root.tan();
let tip_r = h * tip.tan();
let foot_angle = base_point[1].atan2(base_point[0]);
let mut tooth: Vec<(&'static str, NurbsCurve)> = Vec::new();
let tip_angle = {
let p = project(left(tip_phi), h);
p[1].atan2(p[0])
};
let radial_foot = [root_r * foot_angle.cos(), root_r * foot_angle.sin()];
if extend {
tooth.push(("V", line([radial_foot[0], -radial_foot[1]], [base_point[0], -base_point[1]])?));
}
tooth.push(("R", mirrored(&flank)));
tooth.push(("K", arc(tip_r, -tip_angle, tip_angle)?));
tooth.push(("L", flank.reversed().map_err(|e| refuse("gear_fit", e))?));
if extend {
tooth.push(("W", line(base_point, radial_foot)?));
}
if foot_angle >= tau / 2.0 - 1e-9 {
return Err(refuse("teeth_overlap", "The tooth roots meet: fewer teeth or a smaller pressure angle.".into()));
}
tooth.push(("G", arc(root_r, foot_angle, tau - foot_angle)?));
let mut curves = Vec::with_capacity(tooth.len() * gear.teeth);
for index in 0..gear.teeth {
let angle = tau * index as f64;
for (role, curve) in &tooth {
curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
}
}
for piece in &mut curves {
for p in &mut piece.curve.control_points {
p.z = p.w * h;
}
}
snap_junctions(&mut curves);
let heel = |angle: f64| 2.0 * r * angle.sin() / (angle - delta).cos();
let data = GearData {
pitch_diameter: 2.0 * r * delta.sin(),
tip_diameter: heel(tip),
root_diameter: heel(root),
..GearData::default()
};
Ok(GearSection { curves, data })
}
pub fn bevel_solid(gear: &BevelGear) -> Result<(BrepSolid, GearData), KernelRefusal> {
let (delta, r, _) = bevel_cones(gear);
let rho = r - gear.face_width;
let m = gear.module;
let tip = delta + gear.addendum * m / r;
let h = r * delta.cos();
let mut section = bevel_section(gear, h)?;
let z_lo = 0.5 * rho * tip.cos() / (tip - delta).cos();
let z_hi = 1.05 * r / delta.cos();
let (s_lo, s_hi) = (z_lo / h, z_hi / h);
for piece in &mut section.curves {
for p in &mut piece.curve.control_points {
p.x *= s_lo;
p.y *= s_lo;
p.z *= s_lo;
}
}
let grow = s_hi / s_lo;
let rows = |p: Vec4| vec![p, Vec4 { x: p.x * grow, y: p.y * grow, z: p.z * grow, w: p.w }];
let mut cone = prism_by_rows(§ion, 1, &[0.0, 0.0, 1.0, 1.0], &rows)?;
let count = section.curves.len();
for (index, face) in cone.shells[0].faces.iter_mut().enumerate() {
face.name = Some(if index < count { section.curves[index].suffix() } else { "CAP".into() });
}
let r_out = r * tip.sin() * 1.2 + m;
let (sd, cd) = delta.sin_cos();
let back_apex = [0.0, r / cd];
let front_apex = [0.0, rho / cd];
let out = |along: f64| {
let t = (r_out - along * sd) / cd;
[along * sd + t * cd, along * cd - t * sd]
};
let (f2, b2) = (out(rho), out(r));
let at = |q: [f64; 2]| Vec3::new(q[0], 0.0, q[1]);
let line3 = |a: [f64; 2], b: [f64; 2]| crate::make_line(at(a), at(b)).map_err(|e| refuse("gear_blank", e));
let revolve = |profile: Vec<NurbsCurve>, names: &[&str]| -> Result<BrepSolid, KernelRefusal> {
let names: Vec<Option<String>> = names.iter().map(|n| Some(n.to_string())).collect();
crate::revolve_profile_brep_named(&profile, Vec3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), TAU, &names, &[])
.map_err(|e| refuse("gear_blank", e))
};
let low = (z_lo * 0.5).min(b2[1]) - m;
let back = revolve(
vec![line3(back_apex, b2)?, line3(b2, [b2[0], low])?, line3([b2[0], low], [0.0, low])?, line3([0.0, low], back_apex)?],
&["BACK", "BX1", "BX2", "BX3"],
)?;
let high = z_hi * 1.1;
let front = revolve(
vec![line3(front_apex, [0.0, high])?, line3([0.0, high], [f2[0], high])?, line3([f2[0], high], f2)?, line3(f2, front_apex)?],
&["FX1", "FX2", "FX3", "FRONT"],
)?;
let cut = crate::boolean_operation_nary(&[cone, back], crate::BooleanOperation::Intersect)?;
let gear_solid = crate::boolean_operation_nary(&[cut, front], crate::BooleanOperation::Intersect)?;
Ok((gear_solid, section.data))
}
#[derive(Clone, Debug)]
pub struct EllipticalGear {
pub module: f64,
pub teeth: usize,
pub eccentricity: f64,
pub pressure_angle: f64,
pub addendum: f64,
pub dedendum: f64,
pub root_fillet: f64,
pub backlash: f64,
pub face_width: f64,
}
struct PitchEllipse {
latus: f64,
e: f64,
table: Vec<f64>,
}
impl PitchEllipse {
const SEGMENTS: usize = 1024;
fn new(latus: f64, e: f64) -> Self {
let mut curve = Self { latus, e, table: Vec::with_capacity(Self::SEGMENTS + 1) };
let nodes = [0.0, -0.538_469_310_105_683_1, 0.538_469_310_105_683_1, -0.906_179_845_938_664, 0.906_179_845_938_664];
let weights = [0.568_888_888_888_888_9, 0.478_628_670_499_366_5, 0.478_628_670_499_366_5, 0.236_926_885_056_189_1, 0.236_926_885_056_189_1];
let step = TAU / Self::SEGMENTS as f64;
let mut total = 0.0;
curve.table.push(0.0);
for i in 0..Self::SEGMENTS {
let mid = (i as f64 + 0.5) * step;
let sum: f64 = nodes.iter().zip(&weights).map(|(x, w)| w * curve.speed(mid + 0.5 * step * x)).sum();
total += 0.5 * step * sum;
curve.table.push(total);
}
curve
}
fn length(&self) -> f64 {
self.table[Self::SEGMENTS]
}
fn derivatives(&self, theta: f64) -> ([f64; 2], [f64; 2], [f64; 2]) {
let (s, c) = theta.sin_cos();
let d = 1.0 + self.e * c;
let d1 = -self.e * s;
let d2 = -self.e * c;
let r = self.latus / d;
let r1 = -self.latus * d1 / (d * d);
let r2 = -self.latus * (d2 * d - 2.0 * d1 * d1) / (d * d * d);
(
[r * c, r * s],
[r1 * c - r * s, r1 * s + r * c],
[r2 * c - 2.0 * r1 * s - r * c, r2 * s + 2.0 * r1 * c - r * s],
)
}
fn speed(&self, theta: f64) -> f64 {
let (_, d1, _) = self.derivatives(theta);
d1[0].hypot(d1[1])
}
fn theta_at(&self, s: f64) -> f64 {
let length = self.length();
let turns = (s / length).floor();
let local = s - turns * length;
let index = self.table.partition_point(|&value| value <= local).clamp(1, Self::SEGMENTS) - 1;
let step = TAU / Self::SEGMENTS as f64;
let (lo, hi) = (index as f64 * step, (index + 1) as f64 * step);
let span = self.table[index + 1] - self.table[index];
let mut theta = lo + step * (local - self.table[index]) / span;
let nodes = [0.0, -0.538_469_310_105_683_1, 0.538_469_310_105_683_1, -0.906_179_845_938_664, 0.906_179_845_938_664];
let weights = [0.568_888_888_888_888_9, 0.478_628_670_499_366_5, 0.478_628_670_499_366_5, 0.236_926_885_056_189_1, 0.236_926_885_056_189_1];
for _ in 0..8 {
let half = 0.5 * (theta - lo);
let arc: f64 = half * nodes.iter().zip(&weights).map(|(x, w)| w * self.speed(lo + half * (1.0 + x))).sum::<f64>();
let error = self.table[index] + arc - local;
theta = (theta - error / self.speed(theta)).clamp(lo, hi);
if error.abs() < 1e-15 * length {
break;
}
}
theta + turns * TAU
}
fn frame(&self, s: f64) -> ([f64; 2], [f64; 2], [f64; 2], f64) {
let (p, d1, d2) = self.derivatives(self.theta_at(s));
let speed = d1[0].hypot(d1[1]);
let t = [d1[0] / speed, d1[1] / speed];
let curvature = (d1[0] * d2[1] - d1[1] * d2[0]) / speed.powi(3);
(p, t, [t[1], -t[0]], curvature)
}
}
pub fn elliptical_sizes(gear: &EllipticalGear) -> (f64, f64, f64, f64) {
let e = gear.eccentricity;
let unit = PitchEllipse::new(1.0 - e * e, e); let a = PI * gear.module * gear.teeth as f64 / unit.length();
(a, e, PI * gear.module * gear.teeth as f64, 2.0 * a)
}
struct RollingRack<'a> {
pitch: &'a PitchEllipse,
}
impl RollingRack<'_> {
fn envelope(&self, q: [f64; 2], n: [f64; 2]) -> [f64; 2] {
let s = q[0] - q[1] * n[0] / n[1];
self.place(q, s)
}
fn place(&self, q: [f64; 2], s: f64) -> [f64; 2] {
let (p, t, n, _) = self.pitch.frame(s);
let u = q[0] - s;
[p[0] + u * t[0] + q[1] * n[0], p[1] + u * t[1] + q[1] * n[1]]
}
fn foot(&self, g: [f64; 2], guess: f64) -> (f64, f64) {
let mut sigma = guess;
for _ in 0..40 {
let (p, t, n, curvature) = self.pitch.frame(sigma);
let v = [g[0] - p[0], g[1] - p[1]];
let along = v[0] * t[0] + v[1] * t[1];
let distance = v[0] * n[0] + v[1] * n[1];
let step = along / (1.0 + curvature * distance);
sigma += step;
if step.abs() < 1e-15 * self.pitch.length() {
break;
}
}
let (p, _, n, _) = self.pitch.frame(sigma);
(sigma, (g[0] - p[0]) * n[0] + (g[1] - p[1]) * n[1])
}
}
pub fn elliptical_section(gear: &EllipticalGear) -> Result<GearSection, KernelRefusal> {
let m = gear.module;
if !(m > 0.0 && gear.face_width > 0.0 && gear.addendum > 0.0 && gear.dedendum > 0.0) {
return Err(refuse("gear_input", "The module, face width, addendum and dedendum must be positive.".into()));
}
if !(gear.root_fillet >= 0.0 && gear.backlash >= 0.0) {
return Err(refuse("gear_input", "The root fillet and the backlash cannot be negative.".into()));
}
if !(0.0..=0.8).contains(&gear.eccentricity) {
return Err(refuse("gear_input", format!("The eccentricity must be from 0 to 0.8 (it is {}).", gear.eccentricity)));
}
if gear.teeth < 8 || gear.teeth > 1000 {
return Err(refuse("gear_input", format!("An elliptical gear needs from 8 to 1000 teeth (it has {}).", gear.teeth)));
}
let degrees = gear.pressure_angle.to_degrees();
if !(10.0 - 1e-9..=35.0 + 1e-9).contains(°rees) {
return Err(refuse("gear_input", format!("The pressure angle must be between 10° and 35° (it is {degrees}°).")));
}
let (a, e, perimeter, _) = elliptical_sizes(gear);
let pitch_curve = PitchEllipse::new(a * (1.0 - e * e), e);
let rack = RollingRack { pitch: &pitch_curve };
let z = gear.teeth as f64;
let p = perimeter / z;
let alpha = gear.pressure_angle;
let (sin_a, cos_a, tan_a) = (alpha.sin(), alpha.cos(), alpha.tan());
let h_a = gear.addendum * m;
let h_f = gear.dedendum * m;
let rho = gear.root_fillet * m;
let tolerance = GEAR_FIT_TOLERANCE * m;
let min_radius = a * (1.0 - e * e);
if h_f >= min_radius {
return Err(refuse(
"undercut",
format!("The root would fold at the ellipse's ends (radius of curvature {min_radius:.4} there): add teeth or lower the eccentricity."),
));
}
let w0 = p / 4.0 + gear.backlash / 2.0;
let centre_y = -h_f + rho;
let centre_x = -w0 - (centre_y - rho * sin_a) * tan_a + rho * cos_a; if centre_x >= 0.0 {
return Err(refuse("root_fillet_too_large", "The root fillet is larger than fits the tooth space; lower it.".into()));
}
let y_join = centre_y - rho * sin_a;
let low_flank = |c: f64, y: f64| rack.envelope([c - w0 - y * tan_a, y], [cos_a, sin_a]);
let high_flank = |c: f64, y: f64| rack.envelope([c + w0 + y * tan_a, y], [-cos_a, sin_a]);
let fillet_normal = |t: f64| {
let psi = -PI + alpha + t * (PI / 2.0 - alpha);
[psi.cos(), psi.sin()]
};
let low_fillet = |c: f64, t: f64| {
let n = fillet_normal(t);
if rho == 0.0 {
return rack.envelope([c + centre_x, centre_y], n);
}
rack.envelope([c + centre_x + rho * n[0], centre_y + rho * n[1]], n)
};
let high_fillet = |c: f64, t: f64| {
let n = fillet_normal(t);
if rho == 0.0 {
return rack.envelope([c - centre_x, centre_y], [-n[0], n[1]]);
}
rack.envelope([c - centre_x - rho * n[0], centre_y + rho * n[1]], [-n[0], n[1]])
};
let root = |x: f64| rack.place([x, -h_f], x);
let tip = |sigma: f64| {
let (q, _, n, _) = pitch_curve.frame(sigma);
[q[0] + h_a * n[0], q[1] + h_a * n[1]]
};
if sin_a * sin_a + y_join / min_radius <= 1e-9 {
return Err(refuse(
"undercut",
format!(
"The teeth would be undercut where the ellipse is sharpest (radius of curvature {min_radius:.4}): add teeth, lower the eccentricity or raise the pressure angle."
),
));
}
let top_of = |flank: &dyn Fn(f64) -> [f64; 2], guess: f64| -> Result<(f64, f64), KernelRefusal> {
let offset = |y: f64| rack.foot(flank(y), guess).1 - h_a;
let (mut lo, mut hi) = (y_join, h_a + 2.0 * m);
if !(offset(lo) < 0.0 && offset(hi) > 0.0) {
return Err(refuse("gear_fit", "The generated flank does not reach the tip curve.".into()));
}
for _ in 0..200 {
let mid = 0.5 * (lo + hi);
if offset(mid) < 0.0 { lo = mid } else { hi = mid }
}
let y = 0.5 * (lo + hi);
Ok((y, rack.foot(flank(y), guess).0))
};
let mut curves = Vec::with_capacity(6 * gear.teeth);
let reversed = |curve: NurbsCurve| curve.reversed().map_err(|error| refuse("gear_fit", error));
for k in 0..gear.teeth {
let before = (k as f64 - 0.5) * p; let after = (k as f64 + 0.5) * p;
let rising = |y: f64| high_flank(before, y);
let falling = |y: f64| low_flank(after, y);
let (y_rise, sigma_rise) = top_of(&rising, k as f64 * p - w0)?;
let (y_fall, sigma_fall) = top_of(&falling, k as f64 * p + w0)?;
if sigma_fall - sigma_rise <= 1e-6 * m {
return Err(refuse("pointed_tip", "The teeth come to a point below the tip curve: reduce the addendum or the backlash.".into()));
}
curves.push(SectionCurve { curve: reversed(fit_planar(&|t| high_fillet(before, t), 0.0, 1.0, tolerance)?)?, role: "V", tooth: k });
curves.push(SectionCurve { curve: fit_planar(&rising, y_join, y_rise, tolerance)?, role: "R", tooth: k });
curves.push(SectionCurve { curve: fit_planar(&tip, sigma_rise, sigma_fall, tolerance)?, role: "K", tooth: k });
curves.push(SectionCurve { curve: reversed(fit_planar(&falling, y_join, y_fall, tolerance)?)?, role: "L", tooth: k });
curves.push(SectionCurve { curve: fit_planar(&|t| low_fillet(after, t), 0.0, 1.0, tolerance)?, role: "W", tooth: k });
if centre_x < -1e-9 * m {
curves.push(SectionCurve { curve: fit_planar(&root, after + centre_x, after - centre_x, tolerance)?, role: "G", tooth: k });
}
}
snap_junctions(&mut curves);
let samples = 4096;
let (mut tip_max, mut root_min) = (0.0_f64, f64::INFINITY);
for i in 0..samples {
let s = perimeter * i as f64 / samples as f64;
tip_max = tip_max.max(radius_of(tip(s)));
root_min = root_min.min(radius_of(rack.place([s, -h_f], s)));
}
let data = GearData {
pitch_diameter: perimeter / PI,
tip_diameter: 2.0 * tip_max,
root_diameter: 2.0 * root_min,
tooth_thickness: p / 2.0 - gear.backlash,
..GearData::default()
};
Ok(GearSection { curves, data })
}
pub fn elliptical_solid(gear: &EllipticalGear) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
let section = elliptical_section(gear)?;
let solid = extrude_section(§ion, gear.face_width)?;
let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
names.push("F".into());
names.push("B".into());
Ok((solid, names, section.data))
}
fn adaptive_breaks(f: &dyn Fn(f64) -> [f64; 2], tolerance: f64) -> Result<Vec<f64>, KernelRefusal> {
let mut breaks = vec![0.0];
let mut pending: Vec<(f64, f64, usize)> = (0..4).rev().map(|i| (i as f64 / 4.0, (i + 1) as f64 / 4.0, 0)).collect();
while let Some((t0, t1, depth)) = pending.pop() {
if hermite_span_error(f, t0, t1) > tolerance {
if depth >= 16 {
return Err(refuse("gear_fit", format!("gear curve fit did not converge on [{t0}, {t1}]")));
}
let mid = 0.5 * (t0 + t1);
pending.push((mid, t1, depth + 1));
pending.push((t0, mid, depth + 1));
} else {
breaks.push(t1);
}
}
Ok(breaks)
}
fn hermite_span(f: &dyn Fn(f64) -> [f64; 2], t0: f64, t1: f64) -> [[f64; 2]; 4] {
let derivative = |t: f64| {
let h = 1e-6;
let (p, q) = (f(t + h), f(t - h));
[(p[0] - q[0]) / (2.0 * h), (p[1] - q[1]) / (2.0 * h)]
};
let (p0, p1) = (f(t0), f(t1));
let (d0, d1) = (derivative(t0), derivative(t1));
let k = (t1 - t0) / 3.0;
[p0, [p0[0] + d0[0] * k, p0[1] + d0[1] * k], [p1[0] - d1[0] * k, p1[1] - d1[1] * k], p1]
}
fn hermite_span_error(f: &dyn Fn(f64) -> [f64; 2], t0: f64, t1: f64) -> f64 {
let c = hermite_span(f, t0, t1);
[0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875]
.iter()
.map(|&u| {
let exact = f(t0 + (t1 - t0) * u);
let v = 1.0 - u;
let w = [v * v * v, 3.0 * v * v * u, 3.0 * v * u * u, u * u * u];
let x = w[0] * c[0][0] + w[1] * c[1][0] + w[2] * c[2][0] + w[3] * c[3][0];
let y = w[0] * c[0][1] + w[1] * c[1][1] + w[2] * c[2][1] + w[3] * c[3][1];
(exact[0] - x).hypot(exact[1] - y)
})
.fold(0.0, f64::max)
}
fn fit_on_breaks(f: &dyn Fn(f64) -> [f64; 2], breaks: &[f64]) -> Result<(NurbsCurve, f64), KernelRefusal> {
let to_point = |p: [f64; 2]| Vec4::from_point(Vec3::new(p[0], p[1], 0.0), 1.0);
let mut knots = vec![0.0; 4];
let mut points = Vec::with_capacity(2 * breaks.len() + 2);
let mut worst = 0.0_f64;
let spans = breaks.len() - 1;
for index in 0..spans {
let (t0, t1) = (breaks[index], breaks[index + 1]);
let c = hermite_span(f, t0, t1);
worst = worst.max(hermite_span_error(f, t0, t1));
if index == 0 {
points.push(to_point(c[0]));
}
points.push(to_point(c[1]));
points.push(to_point(c[2]));
if index + 1 < spans {
knots.extend([t1, t1]);
} else {
points.push(to_point(c[3]));
}
}
knots.extend([1.0; 4]);
Ok((NurbsCurve::new(3, knots, points).map_err(|error| refuse("gear_fit", error))?, worst))
}
#[derive(Clone, Debug)]
pub struct WormWheel {
pub worm: Worm,
pub teeth: usize,
pub addendum: f64,
pub dedendum: f64,
pub face_width: f64,
pub backlash: f64,
}
pub fn worm_wheel_sizes(wheel: &WormWheel) -> (f64, f64, f64, f64) {
let m = wheel.worm.axial_module;
let r2 = m * wheel.teeth as f64 / 2.0;
let a = r2 + wheel.worm.reference_diameter / 2.0;
let throat = r2 + wheel.addendum * m;
let tube = a - throat;
let half = wheel.face_width / 2.0;
(r2, a, throat, a - (tube * tube - half * half).max(0.0).sqrt())
}
struct WheelPlane<'a> {
wheel: &'a WormWheel,
c: f64,
r2: f64,
a: f64,
rho_tip: f64,
r_tip: f64,
rho_clip: [f64; 2],
}
impl<'a> WheelPlane<'a> {
fn new(wheel: &'a WormWheel, c: f64) -> Result<Self, KernelRefusal> {
let m = wheel.worm.axial_module;
let (r2, a, throat, _) = worm_wheel_sizes(wheel);
let rho_tip = a - (r2 - wheel.dedendum * m);
let tube = a - throat;
let r_tip = a - (tube * tube - c * c).sqrt();
let mut plane = Self { wheel, c, r2, a, rho_tip, r_tip, rho_clip: [0.0; 2] };
for (index, side) in [-1.0, 1.0].into_iter().enumerate() {
let (mut lo, mut hi) = (0.5 * (c.abs() + tube), rho_tip);
if !(radius_of(plane.flank(side, lo)) > r_tip && radius_of(plane.flank(side, hi)) < r_tip) {
return Err(refuse("gear_fit", "A worm wheel flank does not reach its throat.".into()));
}
for _ in 0..200 {
let mid = 0.5 * (lo + hi);
if radius_of(plane.flank(side, mid)) > r_tip { lo = mid } else { hi = mid }
}
plane.rho_clip[index] = 0.5 * (lo + hi);
}
Ok(plane)
}
fn hob(&self, side: f64, rho: f64) -> [f64; 2] {
let worm = &self.wheel.worm;
let hand = if worm.hand == Hand::Right { 1.0 } else { -1.0 };
let thickness = worm.axial_thickness(rho) + self.wheel.backlash;
let angle = (self.c / rho).clamp(-1.0, 1.0).asin();
[self.a - (rho * rho - self.c * self.c).max(0.0).sqrt(), side * thickness / 2.0 + hand * worm.lead() * angle / TAU]
}
fn hob_normal(&self, side: f64, rho: f64) -> [f64; 2] {
let worm = &self.wheel.worm;
let hand = if worm.hand == Hand::Right { 1.0 } else { -1.0 };
let root = (rho * rho - self.c * self.c).max(1e-300).sqrt();
let t = [-rho / root, -side * worm.pressure_angle.tan() - hand * worm.lead() * self.c / (TAU * rho * root)];
let length = t[0].hypot(t[1]);
let n = [-t[1] / length, t[0] / length];
if n[1] * side >= 0.0 { n } else { [-n[0], -n[1]] }
}
fn envelope(&self, q: [f64; 2], n: [f64; 2]) -> [f64; 2] {
let s = (q[0] - self.r2) * n[1] / n[0] - q[1];
rotate([q[0], q[1] + s], -s / self.r2)
}
fn flank(&self, side: f64, rho: f64) -> [f64; 2] {
self.envelope(self.hob(side, rho), self.hob_normal(side, rho))
}
fn fillet(&self, side: f64, t: f64) -> [f64; 2] {
let n = self.hob_normal(side, self.rho_tip);
let from = n[1].atan2(n[0]);
let psi = from + t * (side * PI - from);
self.envelope(self.hob(side, self.rho_tip), [psi.cos(), psi.sin()])
}
fn piece(&self, role: usize, t: f64) -> [f64; 2] {
let tau = TAU / self.wheel.teeth as f64;
let half = tau / 2.0;
let turn = |p: [f64; 2], angle: f64| rotate(p, angle);
let root_r = self.a - (self.rho_tip * self.rho_tip - self.c * self.c).sqrt();
match role {
0 => turn(self.fillet(1.0, 1.0 - t), -half),
1 => turn(self.flank(1.0, self.rho_tip + t * (self.rho_clip[1] - self.rho_tip)), -half),
2 => {
let from = polar_angle(self.flank(1.0, self.rho_clip[1]));
let to = tau + polar_angle(self.flank(-1.0, self.rho_clip[0]));
let angle = from + t * (to - from) - half;
[self.r_tip * angle.cos(), self.r_tip * angle.sin()]
}
3 => turn(self.flank(-1.0, self.rho_clip[0] + t * (self.rho_tip - self.rho_clip[0])), half),
4 => turn(self.fillet(-1.0, t), half),
_ => {
let from = polar_angle(self.fillet(-1.0, 1.0));
let to = polar_angle(self.fillet(1.0, 1.0));
let angle = from + t * (to - from) + half;
[root_r * angle.cos(), root_r * angle.sin()]
}
}
}
fn check(&self) -> Result<(), KernelRefusal> {
let m = self.wheel.worm.axial_module;
let tau = TAU / self.wheel.teeth as f64;
let tip_span = tau + polar_angle(self.flank(-1.0, self.rho_clip[0])) - polar_angle(self.flank(1.0, self.rho_clip[1]));
if tip_span * self.r_tip <= 1e-6 * m {
return Err(refuse("pointed_tip", format!("The wheel teeth come to a point below the throat {:.4} from the mid-plane: lower the addendum or the face width.", self.c)));
}
let root_span = polar_angle(self.fillet(1.0, 1.0)) - polar_angle(self.fillet(-1.0, 1.0));
if root_span <= 1e-9 {
return Err(refuse("teeth_overlap", "The worm thread is wider than the wheel's tooth space at the root: lower the dedendum.".into()));
}
for side in [-1.0, 1.0] {
let index = if side < 0.0 { 0 } else { 1 };
let flank: Vec<[f64; 2]> = (0..=96).map(|i| self.flank(side, self.rho_clip[index] + (self.rho_tip - self.rho_clip[index]) * i as f64 / 96.0)).collect();
let fillet: Vec<[f64; 2]> = (0..=48).map(|i| self.fillet(side, i as f64 / 48.0)).collect();
let falling = flank.windows(2).all(|pair| radius_of(pair[1]) < radius_of(pair[0]));
let crosses = flank[..flank.len() - 2].windows(2).any(|f| fillet[1..].windows(2).any(|g| segments_cross(f[0], f[1], g[0], g[1])));
if !falling || crosses {
return Err(refuse(
"undercut",
format!("The worm undercuts the wheel teeth {:.4} from the mid-plane: add wheel teeth, narrow the face width or raise the pressure angle.", self.c),
));
}
}
Ok(())
}
}
fn segments_cross(a: [f64; 2], b: [f64; 2], c: [f64; 2], d: [f64; 2]) -> bool {
let cross = |o: [f64; 2], p: [f64; 2], q: [f64; 2]| (p[0] - o[0]) * (q[1] - o[1]) - (p[1] - o[1]) * (q[0] - o[0]);
let (d1, d2) = (cross(c, d, a), cross(c, d, b));
let (d3, d4) = (cross(a, b, c), cross(a, b, d));
d1 * d2 < 0.0 && d3 * d4 < 0.0
}
const WHEEL_ROLES: [&str; 6] = ["V", "R", "K", "L", "W", "G"];
fn wheel_tooth(plane: &WheelPlane, breaks: &[Vec<f64>], z: f64) -> Result<(Vec<NurbsCurve>, f64), KernelRefusal> {
let mut curves = Vec::with_capacity(6);
let mut worst = 0.0_f64;
for (role, role_breaks) in breaks.iter().enumerate() {
let (mut curve, error) = fit_on_breaks(&|t| plane.piece(role, t), role_breaks)?;
worst = worst.max(error);
for p in &mut curve.control_points {
p.z = z * p.w;
}
curves.push(curve);
}
Ok((curves, worst))
}
fn wheel_section(tooth: &[NurbsCurve], teeth: usize) -> Vec<SectionCurve> {
let tau = TAU / teeth as f64;
let mut curves = Vec::with_capacity(6 * teeth);
for index in 0..teeth {
for (role, curve) in tooth.iter().enumerate() {
curves.push(SectionCurve { curve: rotated(curve, tau * index as f64), role: WHEEL_ROLES[role], tooth: index });
}
}
snap_junctions(&mut curves);
curves
}
pub fn worm_wheel_solid(wheel: &WormWheel) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
let worm = &wheel.worm;
let m = worm.axial_module;
worm_section(worm)?; if wheel.teeth < 12 || wheel.teeth > 400 {
return Err(refuse("gear_input", format!("A worm wheel needs from 12 to 400 teeth (it has {}).", wheel.teeth)));
}
if !(wheel.addendum > 0.0 && wheel.dedendum > 0.0 && wheel.face_width > 0.0 && wheel.backlash >= 0.0) {
return Err(refuse("gear_input", "The wheel's addendum, dedendum and face width must be positive, the backlash not negative.".into()));
}
let (r2, a, throat, _) = worm_wheel_sizes(wheel);
let tube = a - throat;
let limit = 0.9 * tube;
if wheel.face_width / 2.0 > limit {
return Err(refuse(
"face_too_wide",
format!("The face width ({}) must stay inside the throat: at most {:.4} for this worm.", wheel.face_width, 2.0 * limit),
));
}
if worm.axial_thickness(tube) + wheel.backlash >= PI * m - 1e-6 * m {
return Err(refuse("pointed_tip", format!("The backlash ({}) leaves no wheel tooth: the hob's thread fills the whole axial pitch at the throat.", wheel.backlash)));
}
if worm.axial_thickness(a - (r2 - wheel.dedendum * m)) + wheel.backlash <= 1e-6 * m {
return Err(refuse("pointed_tip", "The hob's thread (the worm's, grown to the wheel's root) comes to a point: lower the wheel dedendum.".into()));
}
let half = wheel.face_width / 2.0;
let tolerance = GEAR_FIT_TOLERANCE * m;
let skin_tolerance = 1e-5 * m;
let probe: Vec<WheelPlane> = [-half, 0.0, half].iter().map(|&c| WheelPlane::new(wheel, c)).collect::<Result<_, _>>()?;
for plane in &probe {
plane.check()?;
}
let mut breaks: Vec<Vec<f64>> = Vec::with_capacity(6);
for role in 0..6 {
let mut all: Vec<f64> = Vec::new();
for plane in &probe {
all.extend(adaptive_breaks(&|t| plane.piece(role, t), tolerance)?);
}
all.sort_by(f64::total_cmp);
all.dedup_by(|x, y| (*x - *y).abs() < 1e-12);
breaks.push(all);
}
let mut planes = 8usize;
loop {
let step = wheel.face_width / planes as f64;
let delta = 1e-3 * step;
let mut rows: Vec<Vec<NurbsCurve>> = Vec::with_capacity(planes + 1); let mut slopes: Vec<Vec<Vec<[f64; 2]>>> = Vec::with_capacity(planes + 1);
let mut refit = false;
for j in 0..=planes {
let c = -half + step * j as f64;
let plane = WheelPlane::new(wheel, c)?;
plane.check()?;
let (tooth, worst) = wheel_tooth(&plane, &breaks, c + half)?;
if worst > tolerance {
refit = true;
break;
}
let lo = wheel_tooth(&WheelPlane::new(wheel, c - delta)?, &breaks, 0.0)?.0;
let hi = wheel_tooth(&WheelPlane::new(wheel, c + delta)?, &breaks, 0.0)?.0;
let slope: Vec<Vec<[f64; 2]>> = lo
.iter()
.zip(&hi)
.map(|(l, h)| l.control_points.iter().zip(&h.control_points).map(|(p, q)| [(q.x - p.x) / (2.0 * delta), (q.y - p.y) / (2.0 * delta)]).collect())
.collect();
rows.push(tooth);
slopes.push(slope);
}
if refit {
for role_breaks in &mut breaks {
let mut finer = Vec::with_capacity(2 * role_breaks.len());
for pair in role_breaks.windows(2) {
finer.push(pair[0]);
finer.push(0.5 * (pair[0] + pair[1]));
}
finer.push(1.0);
*role_breaks = finer;
}
continue;
}
let mut worst = 0.0_f64;
for j in 0..planes {
let c = -half + step * (j as f64 + 0.5);
let exact = wheel_tooth(&WheelPlane::new(wheel, c)?, &breaks, 0.0)?.0;
for role in 0..6 {
for (k, p) in exact[role].control_points.iter().enumerate() {
let (p0, p1) = (rows[j][role].control_points[k], rows[j + 1][role].control_points[k]);
let (d0, d1) = (slopes[j][role][k], slopes[j + 1][role][k]);
let x = 0.5 * (p0.x + p1.x) + step * (d0[0] - d1[0]) / 8.0;
let y = 0.5 * (p0.y + p1.y) + step * (d0[1] - d1[1]) / 8.0;
worst = worst.max((x - p.x).hypot(y - p.y));
}
}
}
if worst > skin_tolerance {
if planes >= 256 {
return Err(refuse("gear_fit", format!("The worm wheel's flanks could not be skinned within {skin_tolerance:.2e} ({worst:.2e}).")));
}
planes *= 2;
continue;
}
let sections: Vec<Vec<SectionCurve>> = rows.iter().map(|tooth| wheel_section(tooth, wheel.teeth)).collect();
let tau = TAU / wheel.teeth as f64;
let mut table: std::collections::HashMap<[u64; 4], Vec<Vec4>> = std::collections::HashMap::new();
let h = 1.0 / planes as f64;
for (index, piece) in sections[0].iter().enumerate() {
let (role, tooth) = (index % 6, index / 6);
let (s, cs) = (tau * tooth as f64).sin_cos();
for (k, p) in piece.curve.control_points.iter().enumerate() {
let mut row = Vec::with_capacity(3 * planes + 1);
for j in 0..=planes {
let q = sections[j][index].curve.control_points[k];
let d = slopes[j][role][k];
let dv = [wheel.face_width * (cs * d[0] - s * d[1]), wheel.face_width * (s * d[0] + cs * d[1]), wheel.face_width];
let point = Vec3::new(q.x, q.y, q.z);
if j > 0 {
row.push(Vec4::from_point(Vec3::new(point.x - dv[0] * h / 3.0, point.y - dv[1] * h / 3.0, point.z - dv[2] * h / 3.0), 1.0));
}
if j == 0 || j == planes {
row.push(Vec4::from_point(point, 1.0));
}
if j < planes {
row.push(Vec4::from_point(Vec3::new(point.x + dv[0] * h / 3.0, point.y + dv[1] * h / 3.0, point.z + dv[2] * h / 3.0), 1.0));
}
}
table.insert([p.x.to_bits(), p.y.to_bits(), p.z.to_bits(), p.w.to_bits()], row);
}
}
let mut knots_v = vec![0.0; 4];
for j in 1..planes {
let v = j as f64 * h;
knots_v.extend([v, v]);
}
knots_v.extend([1.0; 4]);
let section = GearSection { curves: sections[0].clone(), data: GearData::default() };
let solid = prism_by_rows(§ion, 3, &knots_v, &|p: Vec4| {
table.get(&[p.x.to_bits(), p.y.to_bits(), p.z.to_bits(), p.w.to_bits()]).cloned().expect("a row for every section control point")
})?;
let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
names.push("F".into());
names.push("B".into());
let data = GearData {
pitch_diameter: 2.0 * r2,
tip_diameter: 2.0 * throat,
root_diameter: 2.0 * (r2 - wheel.dedendum * m),
tip_thickness: 0.0,
..GearData::default()
};
return Ok((solid, names, data));
}
}