Skip to main content

brep_construction/construction/
gears.rs

1//! Gear sections and gear solids.
2//!
3//! An involute gear is built the way it is cut: its section is the envelope of a
4//! rack cutter rolled round the pitch circle. A rack point `q` with outward normal
5//! `n` touches the gear when its normal passes through the pitch point; with the
6//! gear's tooth 0 centred on +x, the rack's rolling line on `x = r` and the rack
7//! displaced by `s` along +y, that is
8//!
9//! ```text
10//!   s = (q.x - r) n.y / n.x - q.y,      gear point = Rot(-s / r) (q.x, q.y + s).
11//! ```
12//!
13//! The cutter's straight flank generates the involute; its tip fillet (radius
14//! `rho`) generates the root fillet, the equidistant of the trochoid traced by
15//! the fillet's centre, and so the real undercut when the tooth count is small.
16//! Neither curve is rational: each is fitted by a cubic B-spline (C1 Hermite
17//! spans, refined until every span is within the fit bound of the closed form at
18//! its sample parameters), while the tip and root lands are exact circular arcs.
19use crate::{extrude_profile_brep, make_arc, BrepSolid, KernelRefusal, KernelStage, NurbsCurve, NurbsSurface, Vec3, Vec4};
20use std::f64::consts::{PI, TAU};
21
22/// The fit bound of every fitted gear curve, as a fraction of the module: the
23/// largest distance, at the span sample parameters, between a fitted curve and
24/// its closed form.
25pub const GEAR_FIT_TOLERANCE: f64 = 5e-7;
26
27/// An external spur gear generated by a standard rack cutter. Lengths in model
28/// units, angles in radians; coefficients are multiples of the module.
29#[derive(Clone, Debug)]
30pub struct SpurGear {
31    pub module: f64,
32    pub teeth: usize,
33    pub pressure_angle: f64,
34    /// Profile shift coefficient x (the cutter moved out by x · module).
35    pub profile_shift: f64,
36    /// Addendum coefficient ha* (tip radius = r + (ha* + x) m).
37    pub addendum: f64,
38    /// Dedendum coefficient hf* (root radius = r - (hf* - x) m).
39    pub dedendum: f64,
40    /// Cutter tip radius coefficient rho_f*.
41    pub root_fillet: f64,
42    /// Circumferential backlash taken off the tooth thickness on the reference circle.
43    pub backlash: f64,
44    pub face_width: f64,
45}
46
47impl Default for SpurGear {
48    fn default() -> Self {
49        Self {
50            module: 2.0,
51            teeth: 20,
52            pressure_angle: 20f64.to_radians(),
53            profile_shift: 0.0,
54            addendum: 1.0,
55            dedendum: 1.25,
56            root_fillet: 0.38,
57            backlash: 0.0,
58            face_width: 10.0,
59        }
60    }
61}
62
63/// Derived data of a generated gear (diameters in model units).
64#[derive(Clone, Debug, Default)]
65pub struct GearData {
66    pub pitch_diameter: f64,
67    pub base_diameter: f64,
68    pub tip_diameter: f64,
69    pub root_diameter: f64,
70    /// Diameter where the involute flank meets the root fillet.
71    pub form_diameter: f64,
72    /// Tooth thickness on the reference (pitch) circle, arc length.
73    pub tooth_thickness: f64,
74    /// Tooth thickness on the tip circle, arc length.
75    pub tip_thickness: f64,
76    /// Whether the root fillet cuts into the involute (generated undercut).
77    pub undercut: bool,
78    /// The smallest profile shift at which this gear has no undercut.
79    pub min_shift_without_undercut: f64,
80}
81
82/// One curve of a gear section with the face role it gives the solid.
83#[derive(Clone, Debug)]
84pub struct SectionCurve {
85    pub curve: NurbsCurve,
86    /// Face role: `V`/`W` root fillets, `R`/`L` flanks, `K` tip land, `G` root land.
87    pub role: &'static str,
88    pub tooth: usize,
89}
90
91impl SectionCurve {
92    /// The face-name suffix this curve's face carries (`R3`, `K0`, …).
93    pub fn suffix(&self) -> String {
94        format!("{}{}", self.role, self.tooth)
95    }
96}
97
98/// A closed gear section in the z = 0 plane, counter-clockwise about +z.
99#[derive(Clone, Debug)]
100pub struct GearSection {
101    pub curves: Vec<SectionCurve>,
102    pub data: GearData,
103}
104
105fn refuse(code: &str, message: String) -> KernelRefusal {
106    KernelRefusal::input(KernelStage::Collect, code, message)
107}
108
109fn rotate(point: [f64; 2], angle: f64) -> [f64; 2] {
110    let (s, c) = angle.sin_cos();
111    [c * point[0] - s * point[1], s * point[0] + c * point[1]]
112}
113
114fn polar_angle(point: [f64; 2]) -> f64 {
115    point[1].atan2(point[0])
116}
117
118fn radius_of(point: [f64; 2]) -> f64 {
119    point[0].hypot(point[1])
120}
121
122/// The rack cutter of a spur gear in the generating frame, and its envelope.
123struct RackCutter {
124    r: f64,
125    alpha: f64,
126    /// Reference line of the cutter (x).
127    x_ref: f64,
128    /// The cutter flank's y on the reference line.
129    y0: f64,
130    /// Root radius = the cutter tip line (x).
131    r_f: f64,
132    rho: f64,
133    /// Tip fillet centre.
134    centre: [f64; 2],
135}
136
137impl RackCutter {
138    fn new(gear: &SpurGear) -> Self {
139        let m = gear.module;
140        let r = m * gear.teeth as f64 / 2.0;
141        let p = PI * m;
142        let alpha = gear.pressure_angle;
143        let x_ref = r + gear.profile_shift * m;
144        let y0 = p / 4.0 - gear.backlash / 2.0;
145        let r_f = x_ref - gear.dedendum * m;
146        let rho = gear.root_fillet * m;
147        let x_c = r_f + rho;
148        let y_c = y0 + (rho + (x_ref - x_c) * alpha.sin()) / alpha.cos();
149        Self { r, alpha, x_ref, y0, r_f, rho, centre: [x_c, y_c] }
150    }
151
152    /// The gear point generated by the rack point `q` with outward normal `n`.
153    fn envelope(&self, q: [f64; 2], n: [f64; 2]) -> [f64; 2] {
154        let s = (q[0] - self.r) * n[1] / n[0] - q[1];
155        rotate([q[0], q[1] + s], -s / self.r)
156    }
157
158    /// The involute flank (left side of tooth 0) generated by the flank point at `x`.
159    fn flank(&self, x: f64) -> [f64; 2] {
160        let a = self.alpha;
161        let q = [x, self.y0 + (self.x_ref - x) * a.tan()];
162        self.envelope(q, [-a.sin(), -a.cos()])
163    }
164
165    /// The root fillet (left side of tooth 0) generated by the cutter tip fillet
166    /// at normal angle `psi` (0 = the tip line, pi/2 - alpha = the flank).
167    fn fillet(&self, psi: f64) -> [f64; 2] {
168        let n = [-psi.cos(), -psi.sin()];
169        if self.rho == 0.0 {
170            // A sharp cutter corner: the point is fixed, its normal still sweeps.
171            return self.envelope(self.centre, n);
172        }
173        let q = [self.centre[0] + self.rho * n[0], self.centre[1] + self.rho * n[1]];
174        self.envelope(q, n)
175    }
176
177    /// The flank point x whose generated point lies at radius `radius` (the involute branch).
178    fn flank_x_at_radius(&self, radius: f64) -> f64 {
179        let c = 1.0 / self.alpha.tan();
180        let c2 = c * c;
181        let disc = (self.r * self.r * c2 * c2 - (1.0 + c2) * (self.r * self.r * c2 - radius * radius)).max(0.0);
182        (self.r * c2 + disc.sqrt()) / (1.0 + c2)
183    }
184}
185
186/// A cubic B-spline (C1 Hermite spans) through `f` on `[a, b]`, refined until each
187/// span is within `tolerance` of `f` at its sample parameters.
188fn fit_planar(f: &dyn Fn(f64) -> [f64; 2], a: f64, b: f64, tolerance: f64) -> Result<NurbsCurve, KernelRefusal> {
189    let derivative = |t: f64| {
190        let h = 1e-6 * (b - a).abs().max(1e-12);
191        let p = f(t + h);
192        let q = f(t - h);
193        [(p[0] - q[0]) / (2.0 * h), (p[1] - q[1]) / (2.0 * h)]
194    };
195    let span_points = |t0: f64, t1: f64| {
196        let (p0, p1) = (f(t0), f(t1));
197        let (d0, d1) = (derivative(t0), derivative(t1));
198        let k = (t1 - t0) / 3.0;
199        [p0, [p0[0] + d0[0] * k, p0[1] + d0[1] * k], [p1[0] - d1[0] * k, p1[1] - d1[1] * k], p1]
200    };
201    let bezier = |c: &[[f64; 2]; 4], u: f64| {
202        let v = 1.0 - u;
203        let w = [v * v * v, 3.0 * v * v * u, 3.0 * v * u * u, u * u * u];
204        [
205            w[0] * c[0][0] + w[1] * c[1][0] + w[2] * c[2][0] + w[3] * c[3][0],
206            w[0] * c[0][1] + w[1] * c[1][1] + w[2] * c[2][1] + w[3] * c[3][1],
207        ]
208    };
209    let mut pending: Vec<(f64, f64, usize)> = (0..4).rev().map(|i| {
210        let t0 = a + (b - a) * i as f64 / 4.0;
211        let t1 = a + (b - a) * (i + 1) as f64 / 4.0;
212        (t0, t1, 0)
213    }).collect();
214    let mut spans: Vec<(f64, f64, [[f64; 2]; 4])> = Vec::new();
215    while let Some((t0, t1, depth)) = pending.pop() {
216        let c = span_points(t0, t1);
217        let worst = [0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875]
218            .iter()
219            .map(|&u| {
220                let exact = f(t0 + (t1 - t0) * u);
221                let fitted = bezier(&c, u);
222                (exact[0] - fitted[0]).hypot(exact[1] - fitted[1])
223            })
224            .fold(0.0, f64::max);
225        if worst > tolerance && depth < 16 {
226            let mid = 0.5 * (t0 + t1);
227            pending.push((mid, t1, depth + 1));
228            pending.push((t0, mid, depth + 1));
229        } else if worst > tolerance {
230            return Err(refuse("gear_fit", format!("gear curve fit did not converge ({worst:.3e} > {tolerance:.3e})")));
231        } else {
232            spans.push((t0, t1, c));
233        }
234    }
235    // Knots in [0, 1] (normalised). The Hermite spans join with C1 continuity,
236    // so each interior knot is doubled and the shared span end, which lies on
237    // the segment between its two neighbours, is implied rather than stored.
238    let scale = 1.0 / (b - a);
239    let to_point = |p: [f64; 2]| Vec4::from_point(Vec3::new(p[0], p[1], 0.0), 1.0);
240    let mut knots = vec![0.0; 4];
241    let mut points = vec![to_point(spans[0].2[0])];
242    for (index, (_, t1, c)) in spans.iter().enumerate() {
243        points.push(to_point(c[1]));
244        points.push(to_point(c[2]));
245        if index + 1 < spans.len() {
246            let k = (t1 - a) * scale;
247            knots.extend([k, k]);
248        } else {
249            points.push(to_point(c[3]));
250        }
251    }
252    knots.extend([1.0; 4]);
253    NurbsCurve::new(3, knots, points).map_err(|error| refuse("gear_fit", error))
254}
255
256fn mirrored(curve: &NurbsCurve) -> NurbsCurve {
257    let mut copy = curve.clone();
258    for point in &mut copy.control_points {
259        point.y = -point.y;
260    }
261    NurbsCurve::new(copy.degree, copy.knots, copy.control_points).expect("a mirrored curve is a valid curve")
262}
263
264fn rotated(curve: &NurbsCurve, angle: f64) -> NurbsCurve {
265    let (s, c) = angle.sin_cos();
266    let points = curve
267        .control_points
268        .iter()
269        .map(|p| Vec4 { x: c * p.x - s * p.y, y: s * p.x + c * p.y, z: p.z, w: p.w })
270        .collect();
271    NurbsCurve::new(curve.degree, curve.knots.clone(), points).expect("a rotated curve is a valid curve")
272}
273
274fn arc(radius: f64, from: f64, to: f64) -> Result<NurbsCurve, KernelRefusal> {
275    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)
276        .map_err(|error| refuse("gear_arc", error))
277}
278
279fn check_spur(gear: &SpurGear, max_pressure_degrees: f64) -> Result<(), KernelRefusal> {
280    let positive = |value: f64, what: &str| {
281        if value.is_finite() && value > 0.0 {
282            Ok(())
283        } else {
284            Err(refuse("gear_input", format!("The {what} must be greater than zero (it is {value}).")))
285        }
286    };
287    positive(gear.module, "module")?;
288    positive(gear.face_width, "face width")?;
289    positive(gear.addendum, "addendum coefficient")?;
290    positive(gear.dedendum, "dedendum coefficient")?;
291    if gear.teeth < 3 {
292        return Err(refuse("gear_input", format!("A gear needs at least 3 teeth (it has {}).", gear.teeth)));
293    }
294    let degrees = gear.pressure_angle.to_degrees();
295    if !(10.0 - 1e-9..=max_pressure_degrees + 1e-9).contains(&degrees) {
296        return Err(refuse("gear_input", format!("The pressure angle must be between 10° and {max_pressure_degrees}° (it is {degrees}°).")));
297    }
298    if !(gear.root_fillet >= 0.0) || !(gear.backlash >= 0.0) || !gear.profile_shift.is_finite() {
299        return Err(refuse("gear_input", "The root fillet and the backlash cannot be negative.".into()));
300    }
301    Ok(())
302}
303
304/// The section of an external spur gear, generated by its rack cutter.
305pub fn spur_section(gear: &SpurGear) -> Result<GearSection, KernelRefusal> {
306    check_spur(gear, 35.0)?;
307    generated_section(gear)
308}
309
310/// [`spur_section`] for a helical gear's transverse section, whose pressure
311/// angle (already checked in the normal section) may exceed 35°.
312fn transverse_section(gear: &SpurGear) -> Result<GearSection, KernelRefusal> {
313    check_spur(gear, 60.0)?;
314    generated_section(gear)
315}
316
317fn generated_section(gear: &SpurGear) -> Result<GearSection, KernelRefusal> {
318    let m = gear.module;
319    let z = gear.teeth as f64;
320    let rack = RackCutter::new(gear);
321    let alpha = rack.alpha;
322    let r = rack.r;
323    let r_b = r * alpha.cos();
324    let r_a = r + (gear.addendum + gear.profile_shift) * m;
325    let r_f = rack.r_f;
326    let half_pitch = PI / z;
327    let tolerance = GEAR_FIT_TOLERANCE * m;
328
329    if r_f <= 1e-9 * m {
330        return Err(refuse(
331            "root_below_centre",
332            format!("The root circle diameter is zero or negative (d = {:.4}): too few teeth for this dedendum.", 2.0 * r_f),
333        ));
334    }
335    // The cutter's tip land must stay; with too large a tip radius the two fillets cross.
336    let rho_max = ((PI * m / 2.0 - rack.y0) * alpha.cos() - (rack.x_ref - r_f) * alpha.sin()) / (1.0 - alpha.sin());
337    if rack.rho > rho_max + 1e-9 * m {
338        return Err(refuse(
339            "root_fillet_too_large",
340            format!(
341                "The root fillet coefficient {:.4} is larger than the {:.4} that fits this tooth space; lower it.",
342                gear.root_fillet,
343                rho_max / m
344            ),
345        ));
346    }
347    let psi_end = PI / 2.0 - alpha;
348    let x_flank_tangent = rack.centre[0] - rack.rho * alpha.sin();
349    let x_interference = r * alpha.cos().powi(2);
350    let min_shift = gear.dedendum - gear.root_fillet * (1.0 - alpha.sin()) - z / 2.0 * alpha.sin().powi(2);
351    let undercut = x_flank_tangent < x_interference - 1e-12 * m;
352
353    // The junction J of the left flank and its root fillet.
354    let (x_join, psi_join) = if !undercut {
355        (x_flank_tangent, psi_end)
356    } else {
357        // The fillet cuts the involute. Above the base circle the fillet lies
358        // outside the involute at the flank tangency (psi_end) and inside it
359        // just above the base circle, so the crossing is in [psi_base, psi_end],
360        // where psi_base is the fillet's base-circle crossing (its radius rises
361        // from the root, which is below the base circle here). Search that
362        // interval at a resolution relative to its own width, so a gear just
363        // past the undercut limit (a very short interval) is found too.
364        let difference = |psi: f64| -> Option<f64> {
365            let point = rack.fillet(psi);
366            let radius = radius_of(point);
367            if radius <= r_b {
368                return None;
369            }
370            Some(polar_angle(point) - polar_angle(rack.flank(rack.flank_x_at_radius(radius))))
371        };
372        let (mut below, mut above) = (0.0, psi_end);
373        for _ in 0..200 {
374            let mid = 0.5 * (below + above);
375            if radius_of(rack.fillet(mid)) <= r_b { below = mid } else { above = mid }
376        }
377        let psi_base = above;
378        let steps = 4000;
379        let mut found = None;
380        let mut previous: Option<(f64, f64)> = None;
381        for step in 0..=steps {
382            let psi = psi_end - (psi_end - psi_base) * step as f64 / steps as f64;
383            if let Some(value) = difference(psi) {
384                if let Some((last_psi, last_value)) = previous {
385                    if (value <= 0.0) != (last_value <= 0.0) {
386                        found = Some((psi, last_psi));
387                        break;
388                    }
389                }
390                previous = Some((psi, value));
391            }
392        }
393        // No crossing resolvable above the base circle: the fillet meets the
394        // flank at the base circle itself (the undercut limit).
395        let (mut lo, mut hi) = found.unwrap_or((psi_base, psi_base));
396        let sign_lo = difference(lo).unwrap_or(-1.0) <= 0.0;
397        for _ in 0..200 {
398            let mid = 0.5 * (lo + hi);
399            match difference(mid) {
400                Some(value) if (value <= 0.0) == sign_lo => lo = mid,
401                Some(_) => hi = mid,
402                None => lo = mid,
403            }
404        }
405        let psi = 0.5 * (lo + hi);
406        (rack.flank_x_at_radius(radius_of(rack.fillet(psi))), psi)
407    };
408    let join = rack.fillet(psi_join);
409    let form_radius = radius_of(join);
410    if r_a <= form_radius + 1e-9 * m {
411        return Err(refuse(
412            "tip_below_form",
413            format!(
414                "The tip circle (d = {:.4}) does not reach above the form circle (d = {:.4}); raise the addendum or lower the dedendum.",
415                2.0 * r_a,
416                2.0 * form_radius
417            ),
418        ));
419    }
420    let x_tip = rack.flank_x_at_radius(r_a);
421    let tip = rack.flank(x_tip);
422    // Half the tooth thickness angle at a radius (the textbook involute form,
423    // unwrapped: a polar angle read off a crossed flank wraps round and would
424    // pass a tooth whose flanks crossed below the tip).
425    let thickness = PI * m / 2.0 + 2.0 * gear.profile_shift * m * alpha.tan() - gear.backlash;
426    let involute = |angle: f64| angle.tan() - angle;
427    let half_angle = |radius: f64| thickness / (2.0 * r) + involute(alpha) - involute((r_b / radius).min(1.0).acos());
428    let tip_angle = half_angle(r_a);
429    let tip_offset = polar_angle(tip) - tip_angle;
430    if tip_angle * r_a <= 1e-6 * m || tip_offset.abs() > 1e-9 {
431        // Where the flanks meet: half_angle falls as the radius grows.
432        let (mut lo, mut hi) = (form_radius.max(r_b), r_a);
433        for _ in 0..200 {
434            let mid = 0.5 * (lo + hi);
435            if half_angle(mid) > 0.0 { lo = mid } else { hi = mid }
436        }
437        return Err(refuse(
438            "pointed_tip",
439            format!(
440                "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.",
441                2.0 * lo,
442                2.0 * r_a
443            ),
444        ));
445    }
446    if tip_angle >= half_pitch {
447        return Err(refuse("teeth_overlap", "The tooth tips overlap their neighbours.".into()));
448    }
449    // Fillet samples must stay inside the half space (else neighbouring gaps cross).
450    for step in 0..=64 {
451        let point = rack.fillet(psi_join * step as f64 / 64.0);
452        let angle = polar_angle(point);
453        if angle <= 0.0 || angle > half_pitch + 1e-12 {
454            return Err(refuse("teeth_overlap", "The tooth gaps cross: the root form of one gap cuts the next tooth.".into()));
455        }
456    }
457
458    let flank_fit = fit_planar(&|x| rack.flank(x), x_join, x_tip, tolerance)?; // J -> tip
459    let fillet_fit = fit_planar(&|psi| rack.fillet(psi), 0.0, psi_join, tolerance)?; // root -> J
460    let root_angle = rack.centre[1] / r;
461    let land = 2.0 * half_pitch - 2.0 * root_angle;
462
463    // Tooth 0, counter-clockwise: V (root -> J_R), R (J_R -> tip), K, L (tip -> J), W (J -> root), G.
464    let mut tooth: Vec<(&'static str, NurbsCurve)> = vec![
465        ("V", mirrored(&fillet_fit)),
466        ("R", mirrored(&flank_fit)),
467        ("K", arc(r_a, -tip_angle, tip_angle)?),
468        ("L", flank_fit.reversed().map_err(|e| refuse("gear_fit", e))?),
469        ("W", fillet_fit.reversed().map_err(|e| refuse("gear_fit", e))?),
470    ];
471    if land > 1e-9 {
472        tooth.push(("G", arc(r_f, root_angle, 2.0 * half_pitch - root_angle)?));
473    }
474
475    let mut curves = Vec::with_capacity(tooth.len() * gear.teeth);
476    for index in 0..gear.teeth {
477        let angle = TAU * index as f64 / z;
478        for (role, curve) in &tooth {
479            curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
480        }
481    }
482    // Share every junction exactly: each curve ends on the next one's first point.
483    snap_junctions(&mut curves);
484
485    let thickness_angle = |radius: f64| polar_angle(rack.flank(rack.flank_x_at_radius(radius)));
486    let data = GearData {
487        pitch_diameter: 2.0 * r,
488        base_diameter: 2.0 * r_b,
489        tip_diameter: 2.0 * r_a,
490        root_diameter: 2.0 * r_f,
491        form_diameter: 2.0 * form_radius,
492        tooth_thickness: 2.0 * r * thickness_angle(r.max(r_b)),
493        tip_thickness: 2.0 * r_a * tip_angle,
494        undercut,
495        min_shift_without_undercut: min_shift,
496    };
497    Ok(GearSection { curves, data })
498}
499
500/// A spur gear solid: the section extruded along +z by the face width. The face
501/// names (suffixes, in the solid's face order) are the section curves' roles,
502/// then `F` (the z = 0 face) and `B` (the z = width face).
503pub fn spur_solid(gear: &SpurGear) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
504    let section = spur_section(gear)?;
505    let solid = extrude_section(&section, gear.face_width)?;
506    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
507    names.push("F".into());
508    names.push("B".into());
509    Ok((solid, names, section.data))
510}
511
512/// Extrude a counter-clockwise gear section along +z.
513pub fn extrude_section(section: &GearSection, width: f64) -> Result<BrepSolid, KernelRefusal> {
514    let curves: Vec<NurbsCurve> = section.curves.iter().map(|piece| piece.curve.clone()).collect();
515    extrude_profile_brep(&curves, Vec3::new(0.0, 0.0, 1.0), width)
516}
517
518/// A straight-toothed rack: the basic rack profile of `teeth` teeth along +x
519/// from x = 0, the pitch line on y = 0, teeth pointing +y, extruded along +z.
520/// Each end stops in the middle of a tooth space.
521#[derive(Clone, Debug)]
522pub struct Rack {
523    pub module: f64,
524    pub teeth: usize,
525    pub pressure_angle: f64,
526    pub addendum: f64,
527    pub dedendum: f64,
528    /// Root fillet radius coefficient (× module).
529    pub root_fillet: f64,
530    /// Circumferential backlash taken off the tooth thickness on the pitch line.
531    pub backlash: f64,
532    pub face_width: f64,
533    /// Distance from the pitch line down to the rack's back face.
534    pub height: f64,
535    /// Helix angle of a helical rack (0: straight teeth); the module, pressure
536    /// angle and coefficients are then those of the normal section. Positive
537    /// leans the teeth one way (right hand), negative the other.
538    pub helix_angle: f64,
539}
540
541impl Default for Rack {
542    fn default() -> Self {
543        Self {
544            module: 2.0,
545            teeth: 10,
546            pressure_angle: 20f64.to_radians(),
547            addendum: 1.0,
548            dedendum: 1.25,
549            root_fillet: 0.38,
550            backlash: 0.0,
551            face_width: 10.0,
552            height: 6.0,
553            helix_angle: 0.0,
554        }
555    }
556}
557
558fn line(a: [f64; 2], b: [f64; 2]) -> Result<NurbsCurve, KernelRefusal> {
559    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))
560}
561
562fn centred_arc(centre: [f64; 2], radius: f64, from: f64, to: f64) -> Result<NurbsCurve, KernelRefusal> {
563    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)
564        .map_err(|error| refuse("gear_arc", error))
565}
566
567/// The section of a straight rack (exact: lines and arcs), counter-clockwise.
568/// Roles: `G<k>` the root land before tooth k (`G<teeth>` the last one),
569/// `W<k>`/`V<k>` the root fillets left/right of tooth k, `L<k>`/`R<k>` its
570/// left (low x) and right flanks, `K<k>` its tip, `BASE` the back face, `E0`
571/// and `E1` the ends at x = 0 and x = length.
572pub fn rack_section(rack: &Rack) -> Result<GearSection, KernelRefusal> {
573    rack_section_checked(rack, 35.0)
574}
575
576fn rack_section_checked(rack: &Rack, max_pressure_degrees: f64) -> Result<GearSection, KernelRefusal> {
577    let m = rack.module;
578    let positive = |value: f64, what: &str| {
579        if value.is_finite() && value > 0.0 {
580            Ok(())
581        } else {
582            Err(refuse("gear_input", format!("The {what} must be greater than zero (it is {value}).")))
583        }
584    };
585    positive(m, "module")?;
586    positive(rack.face_width, "face width")?;
587    positive(rack.addendum, "addendum coefficient")?;
588    positive(rack.dedendum, "dedendum coefficient")?;
589    if rack.teeth < 1 {
590        return Err(refuse("gear_input", "A rack needs at least one tooth.".into()));
591    }
592    let degrees = rack.pressure_angle.to_degrees();
593    if !(10.0 - 1e-9..=max_pressure_degrees + 1e-9).contains(&degrees) {
594        return Err(refuse("gear_input", format!("The pressure angle must be between 10° and {max_pressure_degrees}° (it is {degrees}°).")));
595    }
596    if !(rack.root_fillet >= 0.0) || !(rack.backlash >= 0.0) {
597        return Err(refuse("gear_input", "The root fillet and the backlash cannot be negative.".into()));
598    }
599    let alpha = rack.pressure_angle;
600    let (ha, hf) = (rack.addendum * m, rack.dedendum * m);
601    if rack.height <= hf + 1e-9 * m {
602        return Err(refuse(
603            "rack_too_thin",
604            format!("The rack height below the pitch line ({:.4}) must exceed the dedendum ({:.4}).", rack.height, hf),
605        ));
606    }
607    let p = PI * m;
608    let w = p / 4.0 - rack.backlash / 2.0; // half the tooth thickness on the pitch line
609    let tip_half = w - ha * alpha.tan();
610    if tip_half <= 1e-6 * m {
611        return Err(refuse(
612            "pointed_tip",
613            "The rack teeth come to a point below their tip line; reduce the addendum, the pressure angle or the backlash.".into(),
614        ));
615    }
616    let rho = rack.root_fillet * m;
617    // Right-hand fillet of the tooth centred on x = 0: centre, flank tangent point, root tangent x.
618    let y_p = -hf + rho - rho * alpha.sin();
619    let flank_x = |y: f64| w - y * alpha.tan();
620    let centre = [flank_x(y_p) + rho * alpha.cos(), -hf + rho];
621    let root_half = centre[0]; // the root tangent point's x (right of the tooth centre)
622    if y_p >= ha - 1e-9 * m {
623        return Err(refuse(
624            "root_fillet_too_large",
625            format!(
626                "The root fillet (coefficient {:.4}) reaches above the tooth tip; lower it or raise the addendum.",
627                rack.root_fillet
628            ),
629        ));
630    }
631    if root_half > p / 2.0 + 1e-9 * m {
632        let max = (p / 2.0 - w - hf * alpha.tan()) * alpha.cos() / (1.0 - alpha.sin());
633        return Err(refuse(
634            "root_fillet_too_large",
635            format!("The root fillet coefficient {:.4} is larger than the {:.4} that fits this tooth space; lower it.", rack.root_fillet, max / m),
636        ));
637    }
638    let length = p * rack.teeth as f64;
639    let mut curves: Vec<SectionCurve> = Vec::new();
640    let mut push = |curve: NurbsCurve, role: &'static str, tooth: usize| curves.push(SectionCurve { curve, role, tooth });
641    let base = -rack.height;
642    push(line([0.0, base], [length, base])?, "BASE", 0);
643    push(line([length, base], [length, -hf])?, "E1", 0);
644    // Teeth from the right end leftwards (counter-clockwise along the top).
645    let mut x_prev_root = length; // where the current root land starts (right end)
646    for k in (0..rack.teeth).rev() {
647        let c = (k as f64 + 0.5) * p;
648        let right_root = [c + root_half, -hf];
649        if x_prev_root - right_root[0] > 1e-9 * m {
650            push(line([x_prev_root, -hf], right_root)?, "G", k + 1);
651        }
652        // Right fillet: from the root tangent (angle 270°) back to the flank tangent (180° + alpha).
653        let right_centre = [c + centre[0], centre[1]];
654        let right_flank_low = [c + flank_x(y_p), y_p];
655        if rho > 0.0 {
656            push(centred_arc(right_centre, rho, PI + alpha, 1.5 * PI)?.reversed().map_err(|e| refuse("gear_arc", e))?, "V", k);
657        }
658        let right_tip = [c + tip_half, ha];
659        let left_tip = [c - tip_half, ha];
660        let left_flank_low = [c - flank_x(y_p), y_p];
661        push(line(if rho > 0.0 { right_flank_low } else { right_root }, right_tip)?, "R", k);
662        push(line(right_tip, left_tip)?, "K", k);
663        let left_root = [c - root_half, -hf];
664        push(line(left_tip, if rho > 0.0 { left_flank_low } else { left_root })?, "L", k);
665        if rho > 0.0 {
666            let left_centre = [c - centre[0], centre[1]];
667            push(centred_arc(left_centre, rho, 1.5 * PI, 2.0 * PI - alpha)?.reversed().map_err(|e| refuse("gear_arc", e))?, "W", k);
668        }
669        x_prev_root = left_root[0];
670    }
671    if x_prev_root > 1e-9 * m {
672        push(line([x_prev_root, -hf], [0.0, -hf])?, "G", 0);
673    }
674    push(line([0.0, -hf], [0.0, base])?, "E0", 0);
675    // Share every junction exactly.
676    snap_junctions(&mut curves);
677    let data = GearData {
678        pitch_diameter: f64::INFINITY,
679        tooth_thickness: 2.0 * w,
680        tip_thickness: 2.0 * tip_half,
681        ..GearData::default()
682    };
683    Ok(GearSection { curves, data })
684}
685
686/// A rack solid: the section extruded along +z by the face width; names as
687/// [`rack_section`], then `F` (z = 0) and `B` (z = width).
688pub fn rack_solid(rack: &Rack) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
689    let beta = rack.helix_angle;
690    if !(beta.abs().to_degrees() <= 45.0 + 1e-9) {
691        return Err(refuse("bad_helix", format!("The rack's helix angle must be between −45° and 45° (it is {:.4}°).", beta.to_degrees())));
692    }
693    // A helical rack's transverse section (the plane z = const) is the rack of
694    // the transverse module and pressure angle; the teeth run along (tan beta, 0, 1).
695    let degrees = rack.pressure_angle.to_degrees();
696    if !(10.0 - 1e-9..=35.0 + 1e-9).contains(&degrees) {
697        return Err(refuse("gear_input", format!("The pressure angle must be between 10° and 35° (it is {degrees}°).")));
698    }
699    if beta == 0.0 {
700        // Straight teeth: the rack exactly as given (no transverse conversion).
701        let section = rack_section(rack)?;
702        let solid = extrude_section(&section, rack.face_width)?;
703        let mut names: Vec<String> = section.curves.iter().map(rack_suffix).collect();
704        names.push("F".into());
705        names.push("B".into());
706        return Ok((solid, names, section.data));
707    }
708    // A helical rack's teeth are straight prisms along (tan beta, 0, 1). Its
709    // normal section (across the teeth) is the basic rack; the transverse
710    // section (z = const) is that section stretched along the rack by
711    // 1 / cos beta, exactly: lines stay lines, the root rounds become ellipses
712    // (still rational quadratic arcs).
713    let c = beta.cos();
714    let mut section = rack_section(rack)?;
715    for piece in &mut section.curves {
716        for point in &mut piece.curve.control_points {
717            point.x /= c;
718        }
719    }
720    // The recorded thicknesses are read along the rack (transverse), as the section is.
721    section.data.tooth_thickness /= c;
722    section.data.tip_thickness /= c;
723    let curves: Vec<NurbsCurve> = section.curves.iter().map(|piece| piece.curve.clone()).collect();
724    let direction = Vec3::new(beta.tan(), 0.0, 1.0);
725    let solid = extrude_profile_brep(&curves, direction, rack.face_width / c)?;
726    let mut names: Vec<String> = section.curves.iter().map(rack_suffix).collect();
727    names.push("F".into());
728    names.push("B".into());
729    Ok((solid, names, section.data))
730}
731
732fn rack_suffix(piece: &SectionCurve) -> String {
733    match piece.role {
734        "BASE" | "E0" | "E1" => piece.role.to_string(),
735        _ => piece.suffix(),
736    }
737}
738
739/// Share every junction of a closed loop exactly: each curve ends on the next one's first point.
740fn snap_junctions(curves: &mut [SectionCurve]) {
741    let count = curves.len();
742    for index in 0..count {
743        let start = curves[(index + 1) % count].curve.control_points[0];
744        let curve = &mut curves[index].curve;
745        let last = curve.control_points.len() - 1;
746        let w = curve.control_points[last].w;
747        curve.control_points[last] = Vec4 { x: start.x / start.w * w, y: start.y / start.w * w, z: 0.0, w };
748    }
749}
750
751/// An internal (ring) gear: involute tooth spaces cut into the inside of a
752/// ring. Lengths in model units, angles in radians, coefficients × module.
753#[derive(Clone, Debug)]
754pub struct RingGear {
755    pub module: f64,
756    pub teeth: usize,
757    pub pressure_angle: f64,
758    /// Profile shift: the cutter moved outward by x · module (tip and root
759    /// circles grow by x · module, the spaces widen by 2 x m tan alpha).
760    pub profile_shift: f64,
761    pub addendum: f64,
762    pub dedendum: f64,
763    /// Radius of the root fillet (× module): an exact arc tangent to the
764    /// flank and the root circle.
765    pub root_fillet: f64,
766    /// Circumferential backlash added to each tooth space on the reference circle.
767    pub backlash: f64,
768    pub face_width: f64,
769    /// Radial wall beyond the root circle.
770    pub rim: f64,
771}
772
773impl Default for RingGear {
774    fn default() -> Self {
775        Self {
776            module: 2.0,
777            teeth: 60,
778            pressure_angle: 20f64.to_radians(),
779            profile_shift: 0.0,
780            addendum: 1.0,
781            dedendum: 1.25,
782            root_fillet: 0.38,
783            backlash: 0.0,
784            face_width: 10.0,
785            rim: 6.0,
786        }
787    }
788}
789
790/// The inner (toothed) loop of a ring gear, counter-clockwise about +z, and its data.
791/// Roles per tooth space k: `R<k>` flank on its clockwise side, `V<k>` its
792/// fillet, `G<k>` the root land, `W<k>`, `L<k>`, then `K<k>` the tip land of
793/// the ring tooth after the space.
794pub fn ring_section(gear: &RingGear) -> Result<GearSection, KernelRefusal> {
795    ring_section_checked(gear, 35.0)
796}
797
798fn ring_section_checked(gear: &RingGear, max_pressure_degrees: f64) -> Result<GearSection, KernelRefusal> {
799    let m = gear.module;
800    let positive = |value: f64, what: &str| {
801        if value.is_finite() && value > 0.0 {
802            Ok(())
803        } else {
804            Err(refuse("gear_input", format!("The {what} must be greater than zero (it is {value}).")))
805        }
806    };
807    positive(m, "module")?;
808    positive(gear.face_width, "face width")?;
809    positive(gear.addendum, "addendum coefficient")?;
810    positive(gear.dedendum, "dedendum coefficient")?;
811    positive(gear.rim, "rim thickness")?;
812    if gear.teeth < 6 {
813        return Err(refuse("gear_input", format!("An internal gear needs at least 6 teeth (it has {}).", gear.teeth)));
814    }
815    let degrees = gear.pressure_angle.to_degrees();
816    if !(10.0 - 1e-9..=max_pressure_degrees + 1e-9).contains(&degrees) {
817        return Err(refuse("gear_input", format!("The pressure angle must be between 10° and {max_pressure_degrees}° (it is {degrees}°).")));
818    }
819    if !(gear.root_fillet >= 0.0) || !(gear.backlash >= 0.0) || !gear.profile_shift.is_finite() {
820        return Err(refuse("gear_input", "The root fillet and the backlash cannot be negative.".into()));
821    }
822    let z = gear.teeth as f64;
823    let alpha = gear.pressure_angle;
824    let r = m * z / 2.0;
825    let r_b = r * alpha.cos();
826    let r_a = r - (gear.addendum - gear.profile_shift) * m; // inner (tip) circle
827    let r_f = r + (gear.dedendum + gear.profile_shift) * m; // outer (root) circle
828    let rho = gear.root_fillet * m;
829    let half_pitch = PI / z;
830    let tolerance = GEAR_FIT_TOLERANCE * m;
831    if r_a <= r_b + 1e-9 * m {
832        return Err(refuse(
833            "tip_inside_base",
834            format!(
835                "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.",
836                2.0 * r_a,
837                2.0 * r_b
838            ),
839        ));
840    }
841    // Half the SPACE angle at a radius: the space is shaped as an external tooth.
842    let space = PI * m / 2.0 + 2.0 * gear.profile_shift * m * alpha.tan() + gear.backlash;
843    let involute = |angle: f64| angle.tan() - angle;
844    let half_space = |radius: f64| space / (2.0 * r) + involute(alpha) - involute((r_b / radius).min(1.0).acos());
845    let flank = |radius: f64| {
846        let angle = half_space(radius);
847        [radius * angle.cos(), radius * angle.sin()]
848    };
849    if half_space(r_a) >= half_pitch - 1e-6 * m / r_a {
850        return Err(refuse(
851            "pointed_tip",
852            "The ring teeth come to a point at the tip circle: reduce the profile shift, the backlash or the addendum.".into(),
853        ));
854    }
855    // The spaces narrow outward: one that closes before the root circle has
856    // crossed flanks (read unwrapped, from the closed form).
857    if half_space(r_f) <= 1e-6 * m / r_f {
858        let (mut lo, mut hi) = (r_a, r_f);
859        for _ in 0..200 {
860            let mid = 0.5 * (lo + hi);
861            if half_space(mid) > 0.0 { lo = mid } else { hi = mid }
862        }
863        return Err(refuse(
864            "teeth_overlap",
865            format!(
866                "The tooth spaces close at d = {:.4}, inside the root circle (d = {:.4}); reduce the dedendum or the profile shift.",
867                2.0 * lo,
868                2.0 * r_f
869            ),
870        ));
871    }
872    // The fillet: a circle of radius rho tangent to the flank (left side of
873    // space 0, at T) and inside the root circle. Its centre is T moved by rho
874    // along the flank's normal into the space; solve |centre| = r_f - rho for T.
875    let normal_into_space = |radius: f64| {
876        let h = 1e-6 * m;
877        let (a, b) = (flank(radius - h), flank(radius + h));
878        let (tx, ty) = (b[0] - a[0], b[1] - a[1]);
879        let length = tx.hypot(ty);
880        // The space lies at smaller angles than its left flank: the normal turned clockwise from the outward tangent.
881        [ty / length, -tx / length]
882    };
883    let centre_at = |radius: f64| {
884        let point = flank(radius);
885        let n = normal_into_space(radius);
886        [point[0] + rho * n[0], point[1] + rho * n[1]]
887    };
888    let (join_radius, centre) = if rho == 0.0 {
889        (r_f, flank(r_f))
890    } else {
891        let target = r_f - rho;
892        let (mut lo, mut hi) = (r_a, r_f);
893        if radius_of(centre_at(lo)) > target {
894            return Err(refuse("root_fillet_too_large", "The root fillet is too large for the tooth depth; lower it.".into()));
895        }
896        for _ in 0..200 {
897            let mid = 0.5 * (lo + hi);
898            if radius_of(centre_at(mid)) < target { lo = mid } else { hi = mid }
899        }
900        let radius = 0.5 * (lo + hi);
901        (radius, centre_at(radius))
902    };
903    let root_angle = polar_angle(centre);
904    if rho > 0.0 && root_angle <= 1e-9 {
905        return Err(refuse(
906            "root_fillet_too_large",
907            "The root fillet is larger than fits the tooth space; lower it.".into(),
908        ));
909    }
910    let tip_angle = half_space(r_a);
911    // Left flank of space 0 from its root end (join) in to the tip circle.
912    let flank_fit = fit_planar(&|radius| flank(radius), r_a, join_radius, tolerance)?; // tip -> join
913    let mut space: Vec<(&'static str, NurbsCurve)> = Vec::new();
914    // Clockwise side (negative angles), outward: mirrored left flank (tip -> join), fillet, land, fillet, flank.
915    space.push(("R", mirrored(&flank_fit)));
916    if rho > 0.0 {
917        // The left fillet runs counter-clockwise about its centre from the root
918        // tangent point (straight out from the centre) round to the flank join.
919        let join = flank(join_radius);
920        let from = root_angle;
921        let mut to = (join[1] - centre[1]).atan2(join[0] - centre[0]);
922        while to <= from {
923            to += TAU;
924        }
925        let left = centred_arc(centre, rho, from, to)?; // root -> join
926        space.push(("V", mirrored(&left).reversed().map_err(|e| refuse("gear_arc", e))?));
927        space.push(("G", arc(r_f, -root_angle, root_angle)?));
928        space.push(("W", left));
929    } else {
930        space.push(("G", arc(r_f, -root_angle, root_angle)?));
931    }
932    space.push(("L", flank_fit.reversed().map_err(|e| refuse("gear_fit", e))?));
933    space.push(("K", arc(r_a, tip_angle, 2.0 * half_pitch - tip_angle)?));
934    let mut curves = Vec::with_capacity(space.len() * gear.teeth);
935    for index in 0..gear.teeth {
936        let angle = TAU * index as f64 / z;
937        for (role, curve) in &space {
938            curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
939        }
940    }
941    snap_junctions(&mut curves);
942    let data = GearData {
943        pitch_diameter: 2.0 * r,
944        base_diameter: 2.0 * r_b,
945        tip_diameter: 2.0 * r_a,
946        root_diameter: 2.0 * r_f,
947        form_diameter: 2.0 * join_radius,
948        tooth_thickness: 2.0 * r * (half_pitch - half_space(r)),
949        tip_thickness: 2.0 * r_a * (half_pitch - tip_angle),
950        undercut: false,
951        min_shift_without_undercut: 0.0,
952    };
953    Ok(GearSection { curves, data })
954}
955
956/// A ring gear solid: a cylinder of radius root + rim with the toothed loop
957/// cut through it. Its faces carry their role names (`R3`, `K0`, …, `OD` the
958/// outside, `F` at z = 0, `B` at z = width) in `face.name`.
959pub fn ring_solid(gear: &RingGear) -> Result<(BrepSolid, GearData), KernelRefusal> {
960    let section = ring_section(gear)?;
961    let outer = section.data.root_diameter / 2.0 + gear.rim;
962    let axis = Vec3::new(0.0, 0.0, 1.0);
963    let mut blank = crate::make_cylinder_brep(Vec3::new(0.0, 0.0, 0.0), axis, outer, gear.face_width)
964        .map_err(|error| refuse("gear_blank", error))?;
965    for (face, name) in blank.shells[0].faces.iter_mut().zip(["OD", "F", "B"]) {
966        face.name = Some(name.into());
967    }
968    // The tool runs past both faces so no face of it lies on the blank's.
969    let reach = gear.face_width * 0.1 + gear.module;
970    let shifted: Vec<SectionCurve> = section
971        .curves
972        .iter()
973        .map(|piece| SectionCurve { curve: translated(&piece.curve, -reach), role: piece.role, tooth: piece.tooth })
974        .collect();
975    let mut tool = extrude_section(&GearSection { curves: shifted.clone(), data: section.data.clone() }, gear.face_width + 2.0 * reach)?;
976    for (face, piece) in tool.shells[0].faces.iter_mut().zip(&shifted) {
977        face.name = Some(piece.suffix());
978    }
979    let ring = crate::boolean_operation_nary(&[blank, tool], crate::BooleanOperation::Subtract)?;
980    Ok((ring, section.data))
981}
982
983/// A helical (or double helical) ring gear: `gear` in the normal section,
984/// its transverse section screwed through the blank. Names as [`ring_solid`].
985pub fn ring_solid_helical(gear: &RingGear, helix_angle: f64, hand: Hand, herringbone: bool) -> Result<(BrepSolid, GearData), KernelRefusal> {
986    let beta = helix_angle;
987    if !(beta.to_degrees() >= 0.5 - 1e-9 && beta.to_degrees() <= 45.0 + 1e-9) {
988        return Err(refuse("bad_helix", format!("The helix angle must be between 0.5° and 45° (it is {:.4}°).", beta.to_degrees())));
989    }
990    let normal = gear.pressure_angle.to_degrees();
991    if !(10.0 - 1e-9..=35.0 + 1e-9).contains(&normal) {
992        return Err(refuse("gear_input", format!("The normal pressure angle must be between 10° and 35° (it is {normal}°).")));
993    }
994    let c = beta.cos();
995    let transverse = RingGear {
996        module: gear.module / c,
997        pressure_angle: (gear.pressure_angle.tan() / c).atan(),
998        profile_shift: gear.profile_shift * c,
999        addendum: gear.addendum * c,
1000        dedendum: gear.dedendum * c,
1001        root_fillet: gear.root_fillet * c,
1002        ..gear.clone()
1003    };
1004    let section = ring_section_checked(&transverse, 60.0)?;
1005    let r = transverse.module * transverse.teeth as f64 / 2.0;
1006    let sign = if hand == Hand::Right { 1.0 } else { -1.0 };
1007    let rate = sign * beta.tan() / r; // turn per unit height
1008    let outer = section.data.root_diameter / 2.0 + gear.rim;
1009    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)
1010        .map_err(|error| refuse("gear_blank", error))?;
1011    for (face, name) in blank.shells[0].faces.iter_mut().zip(["OD", "F", "B"]) {
1012        face.name = Some(name.into());
1013    }
1014    // The tool runs past both faces, turned so that it reads the nominal section at z = 0.
1015    let reach = gear.face_width * 0.1 + transverse.module;
1016    let height = gear.face_width + 2.0 * reach;
1017    let start: Vec<SectionCurve> = section
1018        .curves
1019        .iter()
1020        .map(|piece| SectionCurve { curve: rotated(&piece.curve, -rate * reach), role: piece.role, tooth: piece.tooth })
1021        .collect();
1022    let twist = if herringbone { Twist::Herringbone { turn: rate * height } } else { Twist::Helical { turn: rate * height } };
1023    let tool = twisted_prism(&GearSection { curves: start.clone(), data: section.data.clone() }, height, twist, GEAR_FIT_TOLERANCE * transverse.module)?;
1024    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])
1025        .map_err(|e| refuse("gear_transform", e))?;
1026    let mut tool = crate::transform_brep(&tool, shift, false).map_err(|e| refuse("gear_transform", e))?;
1027    for (face, piece) in tool.shells[0].faces.iter_mut().zip(&start) {
1028        face.name = Some(piece.suffix());
1029    }
1030    let ring = crate::boolean_operation_nary(&[blank, tool], crate::BooleanOperation::Subtract)?;
1031    Ok((ring, section.data))
1032}
1033
1034fn translated(curve: &NurbsCurve, dz: f64) -> NurbsCurve {
1035    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();
1036    NurbsCurve::new(curve.degree, curve.knots.clone(), points).expect("a translated curve is a valid curve")
1037}
1038
1039/// Which ISO 606 tooth form a sprocket is cut to.
1040#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1041pub enum SprocketForm {
1042    /// Smallest seating radius, largest flank radius, largest seating angle.
1043    Minimum,
1044    /// Largest seating radius, smallest flank radius, smallest seating angle.
1045    Maximum,
1046    /// The mean of the two.
1047    Mean,
1048}
1049
1050/// A roller-chain sprocket (ISO 606 tooth form; ANSI chains are its A series).
1051#[derive(Clone, Debug)]
1052pub struct Sprocket {
1053    pub pitch: f64,
1054    pub roller_diameter: f64,
1055    pub teeth: usize,
1056    pub form: SprocketForm,
1057    /// Tooth width across the sprocket (the extrusion).
1058    pub width: f64,
1059}
1060
1061/// The section of a roller-chain sprocket, counter-clockwise; every curve is a
1062/// circular arc. Tooth k is centred on angle 2 pi k / z (tooth 0 on +x); gap k
1063/// follows it. Roles: `A<k>` the flank into gap k, `S<k>` its roller seating,
1064/// `C<k>` the flank out of it, `K<k>` the tip land of the tooth after gap k
1065/// (absent when the flanks meet below the tip circle).
1066pub fn sprocket_section(sprocket: &Sprocket) -> Result<GearSection, KernelRefusal> {
1067    let p = sprocket.pitch;
1068    let d1 = sprocket.roller_diameter;
1069    if !(p > 0.0 && d1 > 0.0 && d1 < p && sprocket.width > 0.0) {
1070        return Err(refuse(
1071            "gear_input",
1072            format!("The chain pitch ({p}), the roller diameter ({d1}, less than the pitch) and the width must be positive."),
1073        ));
1074    }
1075    if sprocket.teeth < 6 || sprocket.teeth > 300 {
1076        return Err(refuse("gear_input", format!("A sprocket needs from 6 to 300 teeth (it has {}).", sprocket.teeth)));
1077    }
1078    let z = sprocket.teeth as f64;
1079    let tau = TAU / z;
1080    let d = p / (PI / z).sin();
1081    // ISO 606 tooth form limits.
1082    let ri_min = 0.505 * d1;
1083    let ri_max = 0.505 * d1 + 0.069 * d1.cbrt();
1084    let re_min = 0.008 * d1 * (z * z + 180.0);
1085    let re_max = 0.12 * d1 * (z + 2.0);
1086    let a_min = (120.0 - 90.0 / z).to_radians();
1087    let a_max = (140.0 - 90.0 / z).to_radians();
1088    let da_min = d + p * (1.0 - 1.6 / z) - d1;
1089    let da_max = d + 1.25 * p - d1;
1090    let (ri, re, alpha, da) = match sprocket.form {
1091        SprocketForm::Minimum => (ri_min, re_max, a_max, da_min),
1092        SprocketForm::Maximum => (ri_max, re_min, a_min, da_max),
1093        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)),
1094    };
1095    let ra = da / 2.0;
1096    // Gap 0 centred on angle tau / 2 is built centred on +x, then turned.
1097    let c = [d / 2.0, 0.0];
1098    let u = [-(alpha / 2.0).cos(), (alpha / 2.0).sin()]; // roller centre -> upper seating end
1099    let t_up = [c[0] + ri * u[0], c[1] + ri * u[1]];
1100    let f = [c[0] + (ri + re) * u[0], c[1] + (ri + re) * u[1]]; // the upper flank's centre
1101    // The upper flank: circle (f, re) from t_up outward. The tooth after the gap
1102    // is centred on the line at angle tau / 2 (built frame).
1103    let half = tau / 2.0;
1104    let a_t = (t_up[1] - f[1]).atan2(t_up[0] - f[0]);
1105    // Walk the flank circle from t_up in the sense that moves away from the axis.
1106    let on_flank = |angle: f64| [f[0] + re * angle.cos(), f[1] + re * angle.sin()];
1107    let step = 1e-4;
1108    let sense = if radius_of(on_flank(a_t + step)) > radius_of(on_flank(a_t - step)) { 1.0 } else { -1.0 };
1109    // Find where the flank reaches the tip circle or the tooth centre line, whichever first.
1110    let reach = |angle: f64| {
1111        let q = on_flank(angle);
1112        (radius_of(q) >= ra, polar_angle(q) >= half)
1113    };
1114    let (mut lo, mut hi) = (0.0, PI / 2.0);
1115    if !(reach(a_t + sense * hi).0 || reach(a_t + sense * hi).1) {
1116        return Err(refuse("gear_input", "The sprocket flank does not reach the tip circle.".into()));
1117    }
1118    for _ in 0..200 {
1119        let mid = 0.5 * (lo + hi);
1120        let (tip, centre) = reach(a_t + sense * mid);
1121        if tip || centre { hi = mid } else { lo = mid }
1122    }
1123    let a_end = a_t + sense * hi;
1124    let end = on_flank(a_end);
1125    let pointed = polar_angle(end) >= half - 1e-12 || radius_of(end) < ra - 1e-9 * p;
1126    let (a_end, end) = if pointed {
1127        // Land exactly on the tooth centre line.
1128        let (mut lo, mut hi) = (0.0, hi);
1129        for _ in 0..200 {
1130            let mid = 0.5 * (lo + hi);
1131            if polar_angle(on_flank(a_t + sense * mid)) >= half { hi = mid } else { lo = mid }
1132        }
1133        let a = a_t + sense * hi;
1134        (a, on_flank(a))
1135    } else {
1136        (a_end, end)
1137    };
1138    let flank_arc = |from: f64, to: f64| -> Result<NurbsCurve, KernelRefusal> {
1139        if to > from { centred_arc(f, re, from, to) } else { centred_arc(f, re, to, from)?.reversed().map_err(|e| refuse("gear_arc", e)) }
1140    };
1141    let upper = flank_arc(a_t, a_end)?; // t_up -> end
1142    let seat = centred_arc(c, ri, PI - alpha / 2.0, PI + alpha / 2.0)?.reversed().map_err(|e| refuse("gear_arc", e))?; // t_down -> t_up
1143    let lower = mirrored(&upper).reversed().map_err(|e| refuse("gear_arc", e))?; // end' -> t_down
1144    let mut gap: Vec<(&'static str, NurbsCurve)> = vec![("A", lower), ("S", seat), ("C", upper)];
1145    let tip_angle = polar_angle(end);
1146    if !pointed {
1147        gap.push(("K", arc(ra, tip_angle, tau - tip_angle)?));
1148    }
1149    let mut curves = Vec::with_capacity(gap.len() * sprocket.teeth);
1150    for index in 0..sprocket.teeth {
1151        let angle = tau * index as f64 + half;
1152        for (role, curve) in &gap {
1153            curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
1154        }
1155    }
1156    snap_junctions(&mut curves);
1157    let data = GearData {
1158        pitch_diameter: d,
1159        tip_diameter: if pointed { 2.0 * radius_of(end) } else { da },
1160        root_diameter: d - 2.0 * ri,
1161        ..GearData::default()
1162    };
1163    Ok(GearSection { curves, data })
1164}
1165
1166/// A sprocket solid: the section extruded along +z by the width; names as
1167/// [`sprocket_section`], then `F` and `B`.
1168pub fn sprocket_solid(sprocket: &Sprocket) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
1169    let section = sprocket_section(sprocket)?;
1170    let solid = extrude_section(&section, sprocket.width)?;
1171    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
1172    names.push("F".into());
1173    names.push("B".into());
1174    Ok((solid, names, section.data))
1175}
1176
1177/// The turn of a twisted prism's section along its height: `theta(t)` at
1178/// `t = z / width` in [0, 1], with an optional crease at `t = 1/2` (a
1179/// herringbone's apex).
1180#[derive(Clone, Copy, Debug)]
1181pub enum Twist {
1182    /// theta = turn · t (a helical gear: a screw motion).
1183    Helical { turn: f64 },
1184    /// theta = turn · (1/2 − |t − 1/2|): out by `turn / 2` to the middle and back.
1185    Herringbone { turn: f64 },
1186}
1187
1188impl Twist {
1189    fn angle(&self, t: f64) -> f64 {
1190        match *self {
1191            Twist::Helical { turn } => turn * t,
1192            Twist::Herringbone { turn } => turn * (0.5 - (t - 0.5).abs()),
1193        }
1194    }
1195
1196    fn rate(&self, t: f64, after_crease: bool) -> f64 {
1197        match *self {
1198            Twist::Helical { turn } => turn,
1199            Twist::Herringbone { turn } => {
1200                if t < 0.5 || (t == 0.5 && !after_crease) { turn } else { -turn }
1201            }
1202        }
1203    }
1204
1205    fn total_turn(&self) -> f64 {
1206        match *self {
1207            Twist::Helical { turn } => turn.abs(),
1208            Twist::Herringbone { turn } => turn.abs(),
1209        }
1210    }
1211}
1212
1213/// The axial basis of a twisted prism: cubic Hermite spans in t carrying
1214/// (cos theta, sin theta, t), with doubled interior knots (C1) and a tripled
1215/// knot at a crease. Returns (knots, per control point (cos, sin, t)).
1216fn twist_basis(twist: Twist, reach: f64, tolerance: f64) -> Result<(Vec<f64>, Vec<[f64; 3]>), KernelRefusal> {
1217    let crease = matches!(twist, Twist::Herringbone { .. });
1218    // Hermite cubic error of cos/sin over a span of turn d: about reach · d^4 / 384.
1219    let per = (384.0 * tolerance / reach.max(1e-12)).powf(0.25);
1220    let needed = twist.total_turn() / per;
1221    if !(needed <= 4096.0) {
1222        return Err(refuse(
1223            "twist_too_long",
1224            format!(
1225                "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).",
1226                twist.total_turn() / TAU,
1227                4096.0 * per / TAU
1228            ),
1229        ));
1230    }
1231    let mut spans = (needed.ceil() as usize).max(1);
1232    if crease && spans % 2 == 1 {
1233        spans += 1;
1234    }
1235    let value = |t: f64| {
1236        let a = twist.angle(t);
1237        [a.cos(), a.sin(), t]
1238    };
1239    let slope = |t: f64, after: bool| {
1240        let a = twist.angle(t);
1241        let r = twist.rate(t, after);
1242        [-a.sin() * r, a.cos() * r, 1.0]
1243    };
1244    let mut knots = vec![0.0; 4];
1245    let mut points = vec![value(0.0)];
1246    for index in 0..spans {
1247        let (t0, t1) = (index as f64 / spans as f64, (index + 1) as f64 / spans as f64);
1248        let h = (t1 - t0) / 3.0;
1249        let (p0, p1) = (value(t0), value(t1));
1250        let (d0, d1) = (slope(t0, true), slope(t1, false));
1251        points.push([p0[0] + d0[0] * h, p0[1] + d0[1] * h, p0[2] + d0[2] * h]);
1252        points.push([p1[0] - d1[0] * h, p1[1] - d1[1] * h, p1[2] - d1[2] * h]);
1253        let last = index + 1 == spans;
1254        let at_crease = crease && 2 * (index + 1) == spans;
1255        if last {
1256            points.push(p1);
1257        } else if at_crease {
1258            points.push(p1);
1259            knots.extend([t1, t1, t1]);
1260        } else {
1261            knots.extend([t1, t1]);
1262        }
1263    }
1264    knots.extend([1.0; 4]);
1265    Ok((knots, points))
1266}
1267
1268/// Carry a section curve along the twist: the curve turned by theta and lifted
1269/// by t · width, as a surface (u along the curve, v = t).
1270fn twisted_surface(curve: &NurbsCurve, width: f64, knots_v: &[f64], basis: &[[f64; 3]]) -> Result<NurbsSurface, KernelRefusal> {
1271    let rows = curve
1272        .control_points
1273        .iter()
1274        .map(|p| {
1275            basis
1276                .iter()
1277                .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 })
1278                .collect()
1279        })
1280        .collect();
1281    NurbsSurface::new(curve.degree, 3, curve.knots.clone(), knots_v.to_vec(), rows).map_err(|e| refuse("gear_surface", e))
1282}
1283
1284/// The axial edge through a section point.
1285fn twisted_edge(point: Vec4, width: f64, knots_v: &[f64], basis: &[[f64; 3]]) -> Result<NurbsCurve, KernelRefusal> {
1286    let (x, y) = (point.x / point.w, point.y / point.w);
1287    let points = basis
1288        .iter()
1289        .map(|[c, s, t]| Vec4 { x: c * x - s * y, y: s * x + c * y, z: t * width, w: 1.0 })
1290        .collect();
1291    NurbsCurve::new(3, knots_v.to_vec(), points).map_err(|e| refuse("gear_edge", e))
1292}
1293
1294/// A counter-clockwise section (z = 0) carried up to z = width while turning
1295/// by `twist`: side faces in section order, then the face at z = 0, then the
1296/// face at z = width (exactly the section turned by the end angle).
1297pub fn twisted_prism(section: &GearSection, width: f64, twist: Twist, tolerance: f64) -> Result<BrepSolid, KernelRefusal> {
1298    use crate::sweep_topology::{curve_to_plane_parameters, make_plane, parameter_line, CoedgeRecord, EdgeRecord, FaceRecord, LoopRecord, ShellRecord, VertexRecord};
1299    if !(width > 0.0) {
1300        return Err(refuse("gear_input", format!("The face width must be greater than zero (it is {width}).")));
1301    }
1302    let curves: Vec<NurbsCurve> = section.curves.iter().map(|piece| piece.curve.clone()).collect();
1303    let count = curves.len();
1304    let reach = curves
1305        .iter()
1306        .flat_map(|c| c.control_points.iter())
1307        .map(|p| (p.x / p.w).hypot(p.y / p.w))
1308        .fold(0.0, f64::max);
1309    let (knots_v, basis) = twist_basis(twist, reach, tolerance)?;
1310    let end_angle = twist.angle(1.0);
1311    let lift = |curve: &NurbsCurve| -> NurbsCurve {
1312        let mut top = rotated(curve, end_angle);
1313        for point in &mut top.control_points {
1314            point.z += point.w * width;
1315        }
1316        top
1317    };
1318    let starts: Vec<Vec4> = curves.iter().map(|c| c.control_points[0]).collect();
1319    let point_of = |p: Vec4| Vec3::new(p.x / p.w, p.y / p.w, p.z / p.w);
1320    let mut vertices = Vec::with_capacity(2 * count);
1321    for (index, start) in starts.iter().enumerate() {
1322        vertices.push(VertexRecord { id: index as u64 + 1, point: point_of(*start) });
1323    }
1324    let (se, ce) = end_angle.sin_cos();
1325    for (index, start) in starts.iter().enumerate() {
1326        let p = point_of(*start);
1327        vertices.push(VertexRecord {
1328            id: (count + index) as u64 + 1,
1329            point: Vec3::new(ce * p.x - se * p.y, se * p.x + ce * p.y, width),
1330        });
1331    }
1332    // Ids: edges from 10, coedges/loops/faces past every edge id.
1333    let edge_id = |kind: usize, index: usize| 10 + (kind * count + index) as u64;
1334    let mut edges = Vec::with_capacity(3 * count);
1335    for (index, curve) in curves.iter().enumerate() {
1336        let [start, end] = curve.domain().map_err(|e| refuse("gear_domain", e))?;
1337        let next = (index + 1) % count;
1338        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 });
1339        edges.push(EdgeRecord { id: edge_id(1, index), curve: lift(curve), t0: start, t1: end, start_vertex_id: (count + index) as u64 + 1, end_vertex_id: (count + next) as u64 + 1, degenerate: false, name: None });
1340        edges.push(EdgeRecord { id: edge_id(2, index), curve: twisted_edge(starts[index], width, &knots_v, &basis)?, 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 });
1341    }
1342    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));
1343    let mut next_id = 10 + 3 * count as u64 + 1000;
1344    let mut faces = Vec::with_capacity(count + 2);
1345    for (index, curve) in curves.iter().enumerate() {
1346        let [start, end] = curve.domain().map_err(|e| refuse("gear_domain", e))?;
1347        let next = (index + 1) % count;
1348        let coedges = vec![
1349            CoedgeRecord { id: next_id, edge_id: edge_id(0, index), forward: true, pcurve: line([start, 0.0], [end, 0.0])? },
1350            CoedgeRecord { id: next_id + 1, edge_id: edge_id(2, next), forward: true, pcurve: line([end, 0.0], [end, 1.0])? },
1351            CoedgeRecord { id: next_id + 2, edge_id: edge_id(1, index), forward: false, pcurve: line([end, 1.0], [start, 1.0])? },
1352            CoedgeRecord { id: next_id + 3, edge_id: edge_id(2, index), forward: false, pcurve: line([start, 1.0], [start, 0.0])? },
1353        ];
1354        next_id += 4;
1355        faces.push(FaceRecord {
1356            id: next_id + 1,
1357            surface: twisted_surface(curve, width, &knots_v, &basis)?,
1358            same_sense: true,
1359            loops: vec![LoopRecord { id: next_id, coedges }],
1360            name: None,
1361        });
1362        next_id += 2;
1363    }
1364    let pad = reach * 1.1 + 1.0;
1365    let x_axis = Vec3::new(1.0, 0.0, 0.0);
1366    let y_axis = Vec3::new(0.0, 1.0, 0.0);
1367    let bottom_origin = Vec3::new(-pad, -pad, 0.0);
1368    let mut bottom = Vec::with_capacity(count);
1369    for index in (0..count).rev() {
1370        bottom.push(CoedgeRecord {
1371            id: next_id,
1372            edge_id: edge_id(0, index),
1373            forward: false,
1374            pcurve: curve_to_plane_parameters(&curves[index], bottom_origin, x_axis, y_axis)
1375                .and_then(|c| c.reversed())
1376                .map_err(|e| refuse("gear_pcurve", e))?,
1377        });
1378        next_id += 1;
1379    }
1380    faces.push(FaceRecord {
1381        id: next_id + 1,
1382        surface: make_plane(bottom_origin, x_axis, y_axis, 2.0 * pad, 2.0 * pad).map_err(|e| refuse("gear_plane", e))?,
1383        same_sense: false,
1384        loops: vec![LoopRecord { id: next_id, coedges: bottom }],
1385        name: None,
1386    });
1387    next_id += 2;
1388    let top_origin = Vec3::new(-pad, -pad, width);
1389    let mut top = Vec::with_capacity(count);
1390    for (index, curve) in curves.iter().enumerate() {
1391        top.push(CoedgeRecord {
1392            id: next_id,
1393            edge_id: edge_id(1, index),
1394            forward: true,
1395            pcurve: curve_to_plane_parameters(&lift(curve), top_origin, x_axis, y_axis).map_err(|e| refuse("gear_pcurve", e))?,
1396        });
1397        next_id += 1;
1398    }
1399    faces.push(FaceRecord {
1400        id: next_id + 1,
1401        surface: make_plane(top_origin, x_axis, y_axis, 2.0 * pad, 2.0 * pad).map_err(|e| refuse("gear_plane", e))?,
1402        same_sense: true,
1403        loops: vec![LoopRecord { id: next_id, coedges: top }],
1404        name: None,
1405    });
1406    next_id += 2;
1407    let solid = BrepSolid {
1408        mass_properties_cache: Default::default(),
1409        cells: Default::default(),
1410        id: next_id + 1,
1411        vertices,
1412        edges,
1413        shells: vec![ShellRecord { id: next_id, faces }],
1414        genus: 0,
1415        kind: crate::BodyKind::Solid,
1416    };
1417    let issues = solid.validate();
1418    if issues.is_empty() {
1419        Ok(solid)
1420    } else {
1421        Err(KernelRefusal::internal(KernelStage::Validate, "validate", format!("twisted gear prism is not valid: {issues:?}")))
1422    }
1423}
1424
1425/// Hand of a helical gear's teeth.
1426#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1427pub enum Hand {
1428    Right,
1429    Left,
1430}
1431
1432/// A helical (or, with `herringbone`, double helical) external gear given by
1433/// its normal-section values; `spur` carries them (module = normal module,
1434/// pressure angle = normal pressure angle, coefficients × normal module).
1435#[derive(Clone, Debug)]
1436pub struct HelicalGear {
1437    pub spur: SpurGear,
1438    pub helix_angle: f64,
1439    pub hand: Hand,
1440    pub herringbone: bool,
1441}
1442
1443/// The transverse spur gear a helical gear's every section is (turned).
1444pub fn helical_transverse(gear: &HelicalGear) -> Result<SpurGear, KernelRefusal> {
1445    let beta = gear.helix_angle;
1446    // The pressure angle limits apply to the normal section (the cutter's).
1447    let normal = gear.spur.pressure_angle.to_degrees();
1448    if !(10.0 - 1e-9..=35.0 + 1e-9).contains(&normal) {
1449        return Err(refuse("gear_input", format!("The normal pressure angle must be between 10° and 35° (it is {normal}°).")));
1450    }
1451    if !(beta.to_degrees() >= 0.5 - 1e-9 && beta.to_degrees() <= 45.0 + 1e-9) {
1452        return Err(refuse("bad_helix", format!("The helix angle must be between 0.5° and 45° (it is {:.4}°).", beta.to_degrees())));
1453    }
1454    let n = &gear.spur;
1455    let c = beta.cos();
1456    Ok(SpurGear {
1457        module: n.module / c,
1458        teeth: n.teeth,
1459        pressure_angle: (n.pressure_angle.tan() / c).atan(),
1460        profile_shift: n.profile_shift * c,
1461        addendum: n.addendum * c,
1462        dedendum: n.dedendum * c,
1463        // The cutter's tip radius in the transverse section is taken as the
1464        // normal one (the true section of the round is a slightly longer ellipse).
1465        root_fillet: n.root_fillet * c,
1466        backlash: n.backlash,
1467        face_width: n.face_width,
1468    })
1469}
1470
1471/// A helical or herringbone gear solid; names as [`spur_solid`].
1472pub fn helical_solid(gear: &HelicalGear) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
1473    let transverse = helical_transverse(gear)?;
1474    let section = transverse_section(&transverse)?;
1475    let r = transverse.module * transverse.teeth as f64 / 2.0;
1476    let width = transverse.face_width;
1477    let sign = if gear.hand == Hand::Right { 1.0 } else { -1.0 };
1478    let twist = if gear.herringbone {
1479        // Each half advances by its own half width.
1480        Twist::Herringbone { turn: sign * width * gear.helix_angle.tan() / r }
1481    } else {
1482        Twist::Helical { turn: sign * width * gear.helix_angle.tan() / r }
1483    };
1484    let solid = twisted_prism(&section, width, twist, 0.1 * GEAR_FIT_TOLERANCE * transverse.module)?;
1485    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
1486    names.push("F".into());
1487    names.push("B".into());
1488    Ok((solid, names, section.data))
1489}
1490
1491/// A straight-sided spline (ISO 14 form: `teeth` keys of width `key_width`
1492/// between the minor diameter `minor` and the major diameter `major`).
1493#[derive(Clone, Debug)]
1494pub struct StraightSpline {
1495    pub teeth: usize,
1496    pub minor: f64,
1497    pub major: f64,
1498    pub key_width: f64,
1499    pub length: f64,
1500}
1501
1502fn check_straight_spline(spline: &StraightSpline) -> Result<(), KernelRefusal> {
1503    let StraightSpline { teeth, minor, major, key_width, length } = *spline;
1504    if !(minor > 0.0 && major > minor && key_width > 0.0 && length > 0.0) {
1505        return Err(refuse(
1506            "gear_input",
1507            format!("A spline needs 0 < minor diameter ({minor}) < major diameter ({major}), a positive key width ({key_width}) and length ({length})."),
1508        ));
1509    }
1510    if teeth < 2 || teeth > 100 {
1511        return Err(refuse("gear_input", format!("A spline needs from 2 to 100 keys (it has {teeth}).")));
1512    }
1513    // The keys must not meet on the minor circle.
1514    let half_root = (key_width / minor).asin();
1515    if !(key_width < minor) || 2.0 * half_root >= TAU / teeth as f64 - 1e-9 {
1516        return Err(refuse("keys_overlap", format!("{teeth} keys {key_width} wide do not fit round a {minor} minor diameter.")));
1517    }
1518    Ok(())
1519}
1520
1521/// The section of a straight-sided spline shaft, counter-clockwise; exact
1522/// lines and arcs. Key k is centred on angle 2 pi k / N. Roles: `R<k>`/`L<k>`
1523/// its flanks, `K<k>` its top on the major circle, `G<k>` the root land after it.
1524pub fn straight_spline_section(spline: &StraightSpline) -> Result<GearSection, KernelRefusal> {
1525    check_straight_spline(spline)?;
1526    let (rr, ra, h) = (spline.minor / 2.0, spline.major / 2.0, spline.key_width / 2.0);
1527    let n = spline.teeth as f64;
1528    let foot = [(rr * rr - h * h).sqrt(), h];
1529    let top = [(ra * ra - h * h).sqrt(), h];
1530    let top_angle = (h / ra).asin();
1531    let foot_angle = (h / rr).asin();
1532    let key: Vec<(&'static str, NurbsCurve)> = vec![
1533        ("R", line([foot[0], -h], [top[0], -h])?),
1534        ("K", arc(ra, -top_angle, top_angle)?),
1535        ("L", line(top, foot)?),
1536        ("G", arc(rr, foot_angle, TAU / n - foot_angle)?),
1537    ];
1538    let mut curves = Vec::with_capacity(4 * spline.teeth);
1539    for index in 0..spline.teeth {
1540        let angle = TAU * index as f64 / n;
1541        for (role, curve) in &key {
1542            curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
1543        }
1544    }
1545    snap_junctions(&mut curves);
1546    Ok(GearSection { curves, data: GearData { tip_diameter: spline.major, root_diameter: spline.minor, ..GearData::default() } })
1547}
1548
1549/// A spline shaft: the section extruded along +z by the length; names as the
1550/// section's roles, then `F` and `B`.
1551pub fn straight_spline_shaft(spline: &StraightSpline) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
1552    let section = straight_spline_section(spline)?;
1553    let solid = extrude_section(&section, spline.length)?;
1554    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
1555    names.push("F".into());
1556    names.push("B".into());
1557    Ok((solid, names, section.data))
1558}
1559
1560/// Cut a counter-clockwise section through a cylinder of `outside` diameter
1561/// and `length`: a hub. The section's faces keep their role names, the
1562/// cylinder's are `OD`, `F` and `B` (all in `face.name`).
1563pub fn hub_from_section(section: &GearSection, outside: f64, length: f64) -> Result<BrepSolid, KernelRefusal> {
1564    // The section's true outer radius, read off the curves (a rational arc's
1565    // middle control point lies outside the arc).
1566    let mut reach: f64 = 0.0;
1567    for piece in &section.curves {
1568        let [t0, t1] = piece.curve.domain().map_err(|e| refuse("gear_domain", e))?;
1569        for i in 0..=32 {
1570            let p = piece.curve.evaluate(t0 + (t1 - t0) * i as f64 / 32.0).map_err(|e| refuse("gear_eval", e))?;
1571            reach = reach.max(p.x.hypot(p.y));
1572        }
1573    }
1574    if !(outside / 2.0 > reach + 1e-9) {
1575        return Err(refuse(
1576            "hub_too_small",
1577            format!("The hub's outside diameter ({outside}) must be larger than its spline's major diameter ({:.4}).", 2.0 * reach),
1578        ));
1579    }
1580    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)
1581        .map_err(|error| refuse("gear_blank", error))?;
1582    for (face, name) in blank.shells[0].faces.iter_mut().zip(["OD", "F", "B"]) {
1583        face.name = Some(name.into());
1584    }
1585    let extra = 0.1 * length + 0.1 * reach;
1586    let shifted: Vec<SectionCurve> = section
1587        .curves
1588        .iter()
1589        .map(|piece| SectionCurve { curve: translated(&piece.curve, -extra), role: piece.role, tooth: piece.tooth })
1590        .collect();
1591    let mut tool = extrude_section(&GearSection { curves: shifted.clone(), data: section.data.clone() }, length + 2.0 * extra)?;
1592    for (face, piece) in tool.shells[0].faces.iter_mut().zip(&shifted) {
1593        face.name = Some(piece.suffix());
1594    }
1595    crate::boolean_operation_nary(&[blank, tool], crate::BooleanOperation::Subtract)
1596}
1597
1598/// A spline hub: the shaft's section (nominal size) cut through a cylinder.
1599pub fn straight_spline_hub(spline: &StraightSpline, outside: f64) -> Result<(BrepSolid, GearData), KernelRefusal> {
1600    let section = straight_spline_section(spline)?;
1601    let hub = hub_from_section(&section, outside, spline.length)?;
1602    Ok((hub, section.data))
1603}
1604
1605/// A timing-belt pulley with straight-sided grooves (ISO 5294 Table 2 form;
1606/// the metric trapezoidal profiles the same way): every curve a line or an arc.
1607#[derive(Clone, Debug)]
1608pub struct TimingPulley {
1609    /// Belt pitch.
1610    pub pitch: f64,
1611    pub teeth: usize,
1612    /// Pitch line differential 2a: outside diameter = pitch z / pi - 2a.
1613    pub pld: f64,
1614    /// Groove bottom width bw.
1615    pub bottom_width: f64,
1616    /// Groove depth hg (from the outside diameter).
1617    pub depth: f64,
1618    /// Groove side angle to the radial direction, each side (half of 2 beta).
1619    pub side_angle: f64,
1620    /// Bottom (root) corner radius rb.
1621    pub bottom_radius: f64,
1622    /// Top (tip) corner radius rt.
1623    pub top_radius: f64,
1624    pub width: f64,
1625}
1626
1627/// An arc about `centre` from `from` to `to` (both on it), counter-clockwise
1628/// when `ccw`, else clockwise.
1629fn arc_through(centre: [f64; 2], from: [f64; 2], to: [f64; 2], ccw: bool) -> Result<NurbsCurve, KernelRefusal> {
1630    let radius = (from[0] - centre[0]).hypot(from[1] - centre[1]);
1631    let a0 = (from[1] - centre[1]).atan2(from[0] - centre[0]);
1632    let a1 = (to[1] - centre[1]).atan2(to[0] - centre[0]);
1633    if ccw {
1634        let mut end = a1;
1635        while end <= a0 {
1636            end += TAU;
1637        }
1638        centred_arc(centre, radius, a0, end)
1639    } else {
1640        let mut start = a1;
1641        while start <= a0 - TAU {
1642            start += TAU;
1643        }
1644        while start >= a0 {
1645            start -= TAU;
1646        }
1647        centred_arc(centre, radius, start, a0)?.reversed().map_err(|e| refuse("gear_arc", e))
1648    }
1649}
1650
1651/// The pulley section, counter-clockwise. Groove k is centred on angle
1652/// 2 pi (k + 1/2) / z (tooth k on angle 2 pi k / z). Roles per groove k, in
1653/// order: `Q<k>` the top corner arc into it, `A<k>` its first side, `U<k>`
1654/// the bottom corner arc, `S<k>` the bottom, `D<k>` the other bottom corner
1655/// arc, `C<k>` the other side, `P<k>` the top corner arc out of it, `K<k>`
1656/// the land of the next tooth on the outside diameter.
1657pub fn timing_pulley_section(pulley: &TimingPulley) -> Result<GearSection, KernelRefusal> {
1658    let TimingPulley { pitch, teeth, pld, bottom_width, depth, side_angle, bottom_radius, top_radius, width } = pulley.clone();
1659    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) {
1660        return Err(refuse("gear_input", "The pulley's pitch, groove sizes and width must be positive.".into()));
1661    }
1662    if !(0.0..60f64.to_radians()).contains(&side_angle) {
1663        return Err(refuse("gear_input", "The groove side angle must be between 0° and 60°.".into()));
1664    }
1665    if teeth < 6 || teeth > 400 {
1666        return Err(refuse("gear_input", format!("A pulley needs from 6 to 400 teeth (it has {teeth}).")));
1667    }
1668    let z = teeth as f64;
1669    let ro = pitch * z / PI / 2.0 - pld / 2.0;
1670    let x_bottom = ro - depth;
1671    if !(x_bottom > 0.0) {
1672        return Err(refuse("gear_input", "The groove is deeper than the pulley's radius.".into()));
1673    }
1674    let tau = TAU / z;
1675    let (s, c) = side_angle.sin_cos();
1676    let side = [c, s]; // outward along the upper side
1677    let normal = [-s, c]; // from the upper side into the material
1678    let corner = [x_bottom, bottom_width / 2.0];
1679    // The upper side meets the outside circle at |corner + t side| = ro.
1680    let b = corner[0] * side[0] + corner[1] * side[1];
1681    let t_top = -b + (b * b - (corner[0] * corner[0] + corner[1] * corner[1] - ro * ro)).sqrt();
1682    let top = [corner[0] + t_top * side[0], corner[1] + t_top * side[1]];
1683    // Bottom corner fillet: between the bottom (direction +y) and the side; the
1684    // path turns right there (clockwise arc). Interior turn angle phi = 90° - beta.
1685    let turn = PI / 2.0 - side_angle;
1686    let reach_b = bottom_radius * (turn / 2.0).tan();
1687    let t1 = [corner[0], corner[1] - reach_b];
1688    let t2 = [corner[0] + reach_b * side[0], corner[1] + reach_b * side[1]];
1689    let centre_b = [t1[0] + bottom_radius, t1[1]];
1690    // Top corner fillet: tangent to the side (offset into the material) and
1691    // inside the outside circle (centre at ro - rt).
1692    let rt = top_radius;
1693    let base = [corner[0] + rt * normal[0], corner[1] + rt * normal[1]];
1694    let bb = base[0] * side[0] + base[1] * side[1];
1695    let disc = bb * bb - (base[0] * base[0] + base[1] * base[1] - (ro - rt) * (ro - rt));
1696    if disc < 0.0 {
1697        return Err(refuse("gear_input", "The groove's top radius does not fit.".into()));
1698    }
1699    let t_c = -bb + disc.sqrt();
1700    let centre_t = [base[0] + t_c * side[0], base[1] + t_c * side[1]];
1701    let t3 = [corner[0] + t_c * side[0], corner[1] + t_c * side[1]];
1702    let scale = ro / (centre_t[0].hypot(centre_t[1]));
1703    let t4 = [centre_t[0] * scale, centre_t[1] * scale];
1704    let land_start = polar_angle(t4);
1705    if land_start >= tau / 2.0 - 1e-9 || reach_b > t_c + 1e-12 || t1[1] < 0.0 {
1706        return Err(refuse(
1707            "groove_too_wide",
1708            format!("The grooves and their corner radii do not fit the pitch at {teeth} teeth; add teeth or reduce the radii."),
1709        ));
1710    }
1711    let _ = top;
1712    // The upper half of groove 0, outward: bottom half line, D, C, P.
1713    let mut upper: Vec<(&'static str, NurbsCurve)> = Vec::new();
1714    if bottom_radius > 0.0 {
1715        upper.push(("D", arc_through(centre_b, t1, t2, false)?));
1716    }
1717    upper.push(("C", line(t2, t3)?));
1718    if rt > 0.0 {
1719        upper.push(("P", arc_through(centre_t, t3, t4, true)?));
1720    }
1721    let mut groove: Vec<(&'static str, NurbsCurve)> = Vec::new();
1722    let lower_roles = |role: &'static str| match role {
1723        "D" => "U",
1724        "C" => "A",
1725        _ => "Q",
1726    };
1727    for (role, curve) in upper.iter().rev() {
1728        groove.push((lower_roles(role), mirrored(curve).reversed().map_err(|e| refuse("gear_arc", e))?));
1729    }
1730    groove.push(("S", line([t1[0], -t1[1]], t1)?));
1731    groove.extend(upper.into_iter());
1732    groove.push(("K", arc(ro, land_start, tau - land_start)?));
1733    let mut curves = Vec::with_capacity(groove.len() * teeth);
1734    for index in 0..teeth {
1735        let angle = tau * index as f64 + tau / 2.0;
1736        for (role, curve) in &groove {
1737            curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
1738        }
1739    }
1740    snap_junctions(&mut curves);
1741    let data = GearData { pitch_diameter: pitch * z / PI, tip_diameter: 2.0 * ro, root_diameter: 2.0 * x_bottom, ..GearData::default() };
1742    Ok(GearSection { curves, data })
1743}
1744
1745/// A pulley solid: the section extruded along +z by the width; names as the
1746/// section's roles, then `F` and `B`.
1747pub fn timing_pulley_solid(pulley: &TimingPulley) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
1748    let section = timing_pulley_section(pulley)?;
1749    let solid = extrude_section(&section, pulley.width)?;
1750    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
1751    names.push("F".into());
1752    names.push("B".into());
1753    Ok((solid, names, section.data))
1754}
1755
1756/// A ratchet wheel: `teeth` teeth on `outside` diameter, `depth` deep. A saw
1757/// tooth has a locking face (leaning `lean` back from radial, so a pawl is drawn
1758/// in under load) and a straight back; a symmetric tooth leans both faces
1759/// equally (for a reversible pawl). Teeth lock against counter-clockwise turning
1760/// when `clockwise_locks` is false.
1761#[derive(Clone, Debug)]
1762pub struct Ratchet {
1763    pub teeth: usize,
1764    pub outside: f64,
1765    pub depth: f64,
1766    pub lean: f64,
1767    pub symmetric: bool,
1768    pub clockwise_locks: bool,
1769    pub width: f64,
1770}
1771
1772/// The ratchet section, counter-clockwise; straight lines only. Roles per
1773/// tooth k (tip k on angle 2 pi k / z): `LK<k>` the locking face below its
1774/// tip, `BK<k>` the back running up to it.
1775pub fn ratchet_section(ratchet: &Ratchet) -> Result<GearSection, KernelRefusal> {
1776    let Ratchet { teeth, outside, depth, lean, symmetric, clockwise_locks, width } = ratchet.clone();
1777    if !(outside > 0.0 && depth > 0.0 && depth < outside / 2.0 && width > 0.0) {
1778        return Err(refuse("gear_input", format!("A ratchet needs a positive outside diameter ({outside}), a depth ({depth}) under its radius and a positive width.")));
1779    }
1780    if teeth < 3 || teeth > 360 {
1781        return Err(refuse("gear_input", format!("A ratchet needs from 3 to 360 teeth (it has {teeth}).")));
1782    }
1783    if !(lean >= 0.0 && lean.to_degrees() <= 30.0) {
1784        return Err(refuse("gear_input", "The locking face lean must be between 0° and 30°.".into()));
1785    }
1786    let z = teeth as f64;
1787    let tau = TAU / z;
1788    let ra = outside / 2.0;
1789    let rf = ra - depth;
1790    // Tooth 0's tip on +x. The locking face runs from the tip down to the root
1791    // at a polar angle `foot` ahead of the tip (counter-clockwise), leaning back.
1792    // A radial face has foot = 0; leaning back by `lean` moves the root point
1793    // forward along the face's direction: solve |tip + t d| = rf.
1794    let tip = [ra, 0.0];
1795    let face_angle = PI + lean; // pointing inward, tilted to +y by `lean`
1796    let d = [face_angle.cos(), face_angle.sin()];
1797    let b = tip[0] * d[0] + tip[1] * d[1];
1798    let t = -b - (b * b - (ra * ra - rf * rf)).sqrt();
1799    let root = [tip[0] + t * d[0], tip[1] + t * d[1]];
1800    let foot = polar_angle(root);
1801    let (lock, back) = if symmetric {
1802        // Both faces meet at the root halfway between tips, each leaning equally.
1803        let mid = [rf * (tau / 2.0).cos(), rf * (tau / 2.0).sin()];
1804        let lock = line(tip, mid)?;
1805        let next = [ra * tau.cos(), ra * tau.sin()];
1806        (lock, line(mid, next)?)
1807    } else {
1808        if foot >= tau - 1e-9 {
1809            return Err(refuse("gear_input", "The locking faces overlap: fewer teeth, less depth or less lean.".into()));
1810        }
1811        let next = [ra * tau.cos(), ra * tau.sin()];
1812        (line(tip, root)?, line(root, next)?)
1813    };
1814    // Counter-clockwise traversal from tip k: locking face down, back up to tip k + 1.
1815    let mut curves = Vec::with_capacity(2 * teeth);
1816    for index in 0..teeth {
1817        let angle = tau * index as f64;
1818        curves.push(SectionCurve { curve: rotated(&lock, angle), role: "LK", tooth: index });
1819        curves.push(SectionCurve { curve: rotated(&back, angle), role: "BK", tooth: index });
1820    }
1821    if clockwise_locks {
1822        // The mirror image locks the other way; mirror, then restore the
1823        // counter-clockwise order.
1824        let mut mirrored_curves: Vec<SectionCurve> = curves
1825            .iter()
1826            .map(|piece| SectionCurve { curve: mirrored(&piece.curve).reversed().expect("a line reverses"), role: piece.role, tooth: piece.tooth })
1827            .collect();
1828        mirrored_curves.reverse();
1829        curves = mirrored_curves;
1830    }
1831    snap_junctions(&mut curves);
1832    Ok(GearSection { curves, data: GearData { tip_diameter: outside, root_diameter: 2.0 * rf, ..GearData::default() } })
1833}
1834
1835/// A ratchet solid: the section extruded along +z; names as the section's roles, then `F` and `B`.
1836pub fn ratchet_solid(ratchet: &Ratchet) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
1837    let section = ratchet_section(ratchet)?;
1838    let solid = extrude_section(&section, ratchet.width)?;
1839    let mut names: Vec<String> = section.curves.iter().map(|c| c.suffix()).collect();
1840    names.push("F".into());
1841    names.push("B".into());
1842    Ok((solid, names, section.data))
1843}
1844
1845/// An external Geneva wheel of `slots` slots for a driver at `centre_distance`
1846/// whose pin of `pin_diameter` runs on the crank radius a sin(pi / n); the
1847/// wheel's radius is a cos(pi / n) (the pin enters the slot tangentially). The
1848/// rim between slots is cut by the concave locking arc of radius
1849/// `lock_radius + clearance / 2` about the driver's centre.
1850#[derive(Clone, Debug)]
1851pub struct GenevaWheel {
1852    pub slots: usize,
1853    pub centre_distance: f64,
1854    pub pin_diameter: f64,
1855    pub clearance: f64,
1856    /// The driver's locking disc radius; 0 = crank radius − pin diameter.
1857    pub lock_radius: f64,
1858    pub width: f64,
1859}
1860
1861/// Derived Geneva sizes: (crank radius, wheel radius, slot inner centre radius, locking disc radius).
1862pub fn geneva_sizes(wheel: &GenevaWheel) -> (f64, f64, f64, f64) {
1863    let n = wheel.slots as f64;
1864    let a = wheel.centre_distance;
1865    let crank = a * (PI / n).sin();
1866    let radius = a * (PI / n).cos();
1867    let lock = if wheel.lock_radius > 0.0 { wheel.lock_radius } else { crank - wheel.pin_diameter };
1868    (crank, radius, a - crank, lock)
1869}
1870
1871/// The Geneva wheel section, counter-clockwise; lines and arcs. Slot k on
1872/// angle 2 pi k / n. Roles: `SL<k>`/`SU<k>` its sides, `SE<k>` its end arc,
1873/// `RA<k>`/`RB<k>` the rim arcs either side of the locking arc `LA<k>` that
1874/// follows slot k.
1875pub fn geneva_section(wheel: &GenevaWheel) -> Result<GearSection, KernelRefusal> {
1876    let GenevaWheel { slots, centre_distance: a, pin_diameter: dp, clearance: c, width, .. } = wheel.clone();
1877    if !(3..=12).contains(&slots) {
1878        return Err(refuse("gear_input", format!("A Geneva wheel has from 3 to 12 slots (it has {slots}).")));
1879    }
1880    if !(a > 0.0 && dp > 0.0 && c >= 0.0 && width > 0.0) {
1881        return Err(refuse("gear_input", "The centre distance, pin diameter and width must be positive (the clearance not negative).".into()));
1882    }
1883    let n = slots as f64;
1884    let (crank, rw, end_centre, lock) = geneva_sizes(wheel);
1885    let half = (dp + c) / 2.0; // half the slot width
1886    let rl = lock + c / 2.0;
1887    if !(lock > 0.0 && lock < a - rw + 1e-9 + rw) || !(half < end_centre) || !(half < rw * (PI / n).sin()) {
1888        return Err(refuse("gear_input", format!("The pin ({dp}) is too large for {slots} slots at centre distance {a}.")));
1889    }
1890    // Adjacent slots must not meet: their ends (and sides) stay apart only
1891    // while the end centres are more than a slot width apart.
1892    if end_centre * (PI / n).sin() <= half * (1.0 + 1e-9) {
1893        return Err(refuse(
1894            "gear_input",
1895            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),
1896        ));
1897    }
1898    let x_top = (rw * rw - half * half).sqrt();
1899    let p1 = [x_top, half];
1900    let beta = PI / n;
1901    let centre = [a * beta.cos(), a * beta.sin()];
1902    // Rim circle (O, rw) meets the locking circle (centre, rl).
1903    let along = (rw * rw - rl * rl + a * a) / (2.0 * a);
1904    let h2 = rw * rw - along * along;
1905    if h2 <= 0.0 {
1906        return Err(refuse("gear_input", "The locking arc does not reach the wheel's rim: increase the locking disc radius.".into()));
1907    }
1908    let h = h2.sqrt();
1909    let e = [beta.cos(), beta.sin()];
1910    let perp = [-beta.sin(), beta.cos()];
1911    let q1 = [along * e[0] - h * perp[0], along * e[1] - h * perp[1]];
1912    let q2 = [along * e[0] + h * perp[0], along * e[1] + h * perp[1]];
1913    let a1 = polar_angle(p1);
1914    if polar_angle(q1) <= a1 + 1e-9 {
1915        return Err(refuse("gear_input", "The locking arc cuts into the slots: reduce the locking disc radius or the pin.".into()));
1916    }
1917    let tau = TAU / n;
1918    let slot: Vec<(&'static str, NurbsCurve)> = vec![
1919        ("SL", line([x_top, -half], [end_centre, -half])?),
1920        ("SE", arc_through([end_centre, 0.0], [end_centre, -half], [end_centre, half], false)?),
1921        ("SU", line([end_centre, half], p1)?),
1922        ("RA", arc(rw, a1, polar_angle(q1))?),
1923        ("LA", arc_through(centre, q1, q2, false)?),
1924        ("RB", arc(rw, polar_angle(q2), tau - a1)?),
1925    ];
1926    let mut curves = Vec::with_capacity(6 * slots);
1927    for index in 0..slots {
1928        let angle = tau * index as f64;
1929        for (role, curve) in &slot {
1930            curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
1931        }
1932    }
1933    snap_junctions(&mut curves);
1934    let _ = crank;
1935    Ok(GearSection { curves, data: GearData { tip_diameter: 2.0 * rw, ..GearData::default() } })
1936}
1937
1938/// A Geneva wheel solid: the section extruded along +z; names as the
1939/// section's roles, then `F` and `B`.
1940pub fn geneva_solid(wheel: &GenevaWheel) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
1941    let section = geneva_section(wheel)?;
1942    let solid = extrude_section(&section, wheel.width)?;
1943    let mut names: Vec<String> = section.curves.iter().map(|c| c.suffix()).collect();
1944    names.push("F".into());
1945    names.push("B".into());
1946    Ok((solid, names, section.data))
1947}
1948
1949/// A cylindrical worm with an Archimedean (ZA) thread: straight flanks in the
1950/// axial section at the axial pressure angle. Lengths in model units.
1951#[derive(Clone, Debug)]
1952pub struct Worm {
1953    pub axial_module: f64,
1954    pub starts: usize,
1955    /// Reference (pitch) diameter d1 = q × axial module.
1956    pub reference_diameter: f64,
1957    pub pressure_angle: f64,
1958    pub addendum: f64,
1959    pub dedendum: f64,
1960    pub length: f64,
1961    pub hand: Hand,
1962}
1963
1964impl Worm {
1965    /// The lead: starts × axial pitch.
1966    pub fn lead(&self) -> f64 {
1967        self.starts as f64 * PI * self.axial_module
1968    }
1969
1970    /// The axial thread thickness at a radius (ZA: straight axial flanks).
1971    pub fn axial_thickness(&self, radius: f64) -> f64 {
1972        PI * self.axial_module / 2.0 - 2.0 * (radius - self.reference_diameter / 2.0) * self.pressure_angle.tan()
1973    }
1974}
1975
1976/// The worm's transverse section (z = 0), counter-clockwise: per start j (its
1977/// thread centred on angle 2 pi j / n) `R<j>` the flank on its clockwise side,
1978/// `K<j>` the thread's tip, `L<j>` the other flank, `G<j>` the root after it.
1979/// The flanks are Archimedean spirals (fitted), tip and root exact arcs.
1980pub fn worm_section(worm: &Worm) -> Result<GearSection, KernelRefusal> {
1981    let m = worm.axial_module;
1982    if !(m > 0.0 && worm.reference_diameter > 0.0 && worm.length > 0.0 && worm.addendum > 0.0 && worm.dedendum > 0.0) {
1983        return Err(refuse("gear_input", "The worm's module, diameter, length, addendum and dedendum must be positive.".into()));
1984    }
1985    if worm.starts < 1 || worm.starts > 8 {
1986        return Err(refuse("gear_input", format!("A worm has from 1 to 8 starts (it has {}).", worm.starts)));
1987    }
1988    let degrees = worm.pressure_angle.to_degrees();
1989    if !(10.0 - 1e-9..=35.0 + 1e-9).contains(&degrees) {
1990        return Err(refuse("gear_input", format!("The axial pressure angle must be between 10° and 35° (it is {degrees}°).")));
1991    }
1992    let r1 = worm.reference_diameter / 2.0;
1993    let ra = r1 + worm.addendum * m;
1994    let rf = r1 - worm.dedendum * m;
1995    if !(rf > 0.0) {
1996        return Err(refuse("gear_input", format!("The worm's root diameter is not positive ({:.4}): raise the diameter quotient.", 2.0 * rf)));
1997    }
1998    let lead = worm.lead();
1999    let gamma = (lead / (PI * worm.reference_diameter)).atan();
2000    if gamma.to_degrees() > 45.0 {
2001        return Err(refuse("bad_lead", format!("The lead angle {:.3}° is over 45°: fewer starts or a larger diameter.", gamma.to_degrees())));
2002    }
2003    if worm.axial_thickness(ra) <= 1e-6 * m {
2004        return Err(refuse("pointed_tip", "The worm thread comes to a point below its tip: lower the addendum or the pressure angle.".into()));
2005    }
2006    let n = worm.starts as f64;
2007    let pitch = PI * m;
2008    if worm.axial_thickness(rf) >= pitch - 1e-6 * m {
2009        return Err(refuse("teeth_overlap", "The worm's threads meet at the root: lower the dedendum or the pressure angle.".into()));
2010    }
2011    // Half the angular width of a thread at radius r in the transverse plane.
2012    let half = |r: f64| PI * worm.axial_thickness(r) / lead;
2013    let flank = |r: f64| {
2014        let t = half(r);
2015        [r * t.cos(), r * t.sin()]
2016    };
2017    let tolerance = GEAR_FIT_TOLERANCE * m;
2018    let upper = fit_planar(&|r| flank(r), rf, ra, tolerance)?; // root -> tip on the +angle side
2019    let tau = TAU / n;
2020    let thread: Vec<(&'static str, NurbsCurve)> = vec![
2021        ("R", mirrored(&upper)),
2022        ("K", arc(ra, -half(ra), half(ra))?),
2023        ("L", upper.reversed().map_err(|e| refuse("gear_fit", e))?),
2024        ("G", arc(rf, half(rf), tau - half(rf))?),
2025    ];
2026    let mut curves = Vec::with_capacity(4 * worm.starts);
2027    for index in 0..worm.starts {
2028        let angle = tau * index as f64;
2029        for (role, curve) in &thread {
2030            curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
2031        }
2032    }
2033    snap_junctions(&mut curves);
2034    let data = GearData { pitch_diameter: worm.reference_diameter, tip_diameter: 2.0 * ra, root_diameter: 2.0 * rf, ..GearData::default() };
2035    Ok(GearSection { curves, data })
2036}
2037
2038/// A worm solid: the transverse section screwed along +z by the length (one
2039/// lead per turn); names as the section's roles, then `F` and `B`.
2040pub fn worm_solid(worm: &Worm) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
2041    let section = worm_section(worm)?;
2042    let sign = if worm.hand == Hand::Right { 1.0 } else { -1.0 };
2043    let turn = sign * TAU * worm.length / worm.lead();
2044    let solid = twisted_prism(&section, worm.length, Twist::Helical { turn }, GEAR_FIT_TOLERANCE * worm.axial_module)?;
2045    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
2046    names.push("F".into());
2047    names.push("B".into());
2048    Ok((solid, names, section.data))
2049}
2050
2051/// A cycloidal-drive disc: `pins` housing pins of diameter `pin_diameter` on a
2052/// circle of `pin_circle_diameter`, the disc running at `eccentricity`; the disc
2053/// has pins − 1 lobes. Its profile is the equidistant (by the pin radius plus
2054/// half the clearance) of the epitrochoid the pin centres trace relative to it.
2055#[derive(Clone, Debug)]
2056pub struct CycloidalDisc {
2057    pub pins: usize,
2058    pub pin_circle_diameter: f64,
2059    pub pin_diameter: f64,
2060    pub eccentricity: f64,
2061    /// Running clearance (diametral): the profile stands clearance / 2 further off the pins.
2062    pub clearance: f64,
2063    pub width: f64,
2064}
2065
2066impl CycloidalDisc {
2067    /// The epitrochoid of the pin centres relative to the disc, and its derivative.
2068    fn trochoid(&self, t: f64) -> ([f64; 2], [f64; 2]) {
2069        let r = self.pin_circle_diameter / 2.0;
2070        let e = self.eccentricity;
2071        let n = self.pins as f64;
2072        (
2073            [r * t.cos() - e * (n * t).cos(), -r * t.sin() + e * (n * t).sin()],
2074            [-r * t.sin() + e * n * (n * t).sin(), -r * t.cos() + e * n * (n * t).cos()],
2075        )
2076    }
2077
2078    /// The disc profile point at parameter t: the trochoid moved by the offset
2079    /// along its normal towards the disc's centre.
2080    pub fn profile(&self, t: f64) -> [f64; 2] {
2081        let (q, d) = self.trochoid(t);
2082        let length = d[0].hypot(d[1]);
2083        let offset = self.pin_diameter / 2.0 + self.clearance / 2.0;
2084        // The trochoid runs clockwise (y = -r sin t ...); its right-hand normal points inward.
2085        let n = [d[1] / length, -d[0] / length];
2086        [q[0] + offset * n[0], q[1] + offset * n[1]]
2087    }
2088}
2089
2090/// The disc's section, counter-clockwise: one fitted piece per lobe, `LB<k>`.
2091pub fn cycloidal_disc_section(disc: &CycloidalDisc) -> Result<GearSection, KernelRefusal> {
2092    let CycloidalDisc { pins, pin_circle_diameter: dc, pin_diameter: dp, eccentricity: e, clearance, width } = disc.clone();
2093    if !(4..=200).contains(&pins) {
2094        return Err(refuse("gear_input", format!("A cycloidal drive has from 4 to 200 pins (it has {pins}).")));
2095    }
2096    if !(dc > 0.0 && dp > 0.0 && e > 0.0 && clearance >= 0.0 && width > 0.0) {
2097        return Err(refuse("gear_input", "The pin circle, pin diameter, eccentricity and width must be positive.".into()));
2098    }
2099    let n = pins as f64;
2100    let r = dc / 2.0;
2101    // The trochoid loops back on itself once e >= r / n.
2102    if e >= r / n * (1.0 - 1e-9) {
2103        return Err(refuse(
2104            "gear_input",
2105            format!("The eccentricity must be under the pin circle radius / pins = {:.4} (it is {e}).", r / n),
2106        ));
2107    }
2108    // The offset must stay under the trochoid's smallest radius of curvature (else the lobes cusp).
2109    let offset = dp / 2.0 + clearance / 2.0;
2110    // An inward offset can cusp only where the (clockwise) curve turns
2111    // clockwise, its centre of curvature inside. Radius of curvature there,
2112    // from the closed-form first and second derivatives.
2113    let (rr, ee) = (dc / 2.0, e);
2114    let radius = |t: f64| -> f64 {
2115        let d = [-rr * t.sin() + ee * n * (n * t).sin(), -rr * t.cos() + ee * n * (n * t).cos()];
2116        let dd = [-rr * t.cos() + ee * n * n * (n * t).cos(), rr * t.sin() - ee * n * n * (n * t).sin()];
2117        let cross = d[0] * dd[1] - d[1] * dd[0];
2118        let speed = d[0].hypot(d[1]);
2119        if cross < 0.0 { speed * speed * speed / -cross } else { f64::INFINITY }
2120    };
2121    // The curve repeats every 2 pi / (n - 1): sample one period densely, then
2122    // refine every local minimum by golden-section search.
2123    let period = TAU / (n - 1.0);
2124    let samples = 2000;
2125    let values: Vec<f64> = (0..=samples).map(|i| radius(period * i as f64 / samples as f64)).collect();
2126    let mut least = f64::INFINITY;
2127    for i in 0..=samples {
2128        let previous = values[if i == 0 { samples - 1 } else { i - 1 }];
2129        let next = values[if i == samples { 1 } else { i + 1 }];
2130        if values[i] <= previous && values[i] <= next && values[i].is_finite() {
2131            let (mut lo, mut hi) = (period * (i as f64 - 1.0) / samples as f64, period * (i as f64 + 1.0) / samples as f64);
2132            for _ in 0..100 {
2133                let a = lo + (hi - lo) * 0.381966;
2134                let b = hi - (hi - lo) * 0.381966;
2135                if radius(a) < radius(b) { hi = b } else { lo = a }
2136            }
2137            least = least.min(radius(0.5 * (lo + hi)));
2138        }
2139    }
2140    if offset >= least * (1.0 - 1e-6) {
2141        return Err(refuse(
2142            "undercut",
2143            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})."),
2144        ));
2145    }
2146    let lobes = pins - 1;
2147    let step = TAU / lobes as f64;
2148    let tolerance = GEAR_FIT_TOLERANCE * dp.min(e * 4.0);
2149    // The trochoid runs clockwise in t: walk t downwards for a counter-clockwise section.
2150    let mut curves = Vec::with_capacity(lobes);
2151    for k in 0..lobes {
2152        let (a, b) = (step * k as f64, step * (k + 1) as f64);
2153        let piece = fit_planar(&|u| disc.profile(-u), a, b, tolerance)?;
2154        curves.push(SectionCurve { curve: piece, role: "LB", tooth: k });
2155    }
2156    snap_junctions(&mut curves);
2157    Ok(GearSection { curves, data: GearData { pitch_diameter: dc, ..GearData::default() } })
2158}
2159
2160/// A cycloidal disc solid: the section extruded along +z; names `LB<k>`, `F`, `B`.
2161pub fn cycloidal_disc_solid(disc: &CycloidalDisc) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
2162    let section = cycloidal_disc_section(disc)?;
2163    let solid = extrude_section(&section, disc.width)?;
2164    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
2165    names.push("F".into());
2166    names.push("B".into());
2167    Ok((solid, names, section.data))
2168}
2169
2170/// The pin ring of a cycloidal drive: a ring of `outside` diameter whose bore
2171/// is the pin circle, with `pins` pins of `pin_diameter` centred on it (half
2172/// standing into the bore). Exact arcs. Faces: `P<k>` the pins' exposed halves,
2173/// `G<k>` the bore between pins, `OD`, `F`, `B`.
2174pub fn cycloidal_pin_ring(pins: usize, pin_circle_diameter: f64, pin_diameter: f64, outside: f64, width: f64) -> Result<(BrepSolid, GearData), KernelRefusal> {
2175    if !(4..=200).contains(&pins) || !(pin_diameter > 0.0 && pin_circle_diameter > pin_diameter && width > 0.0) {
2176        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()));
2177    }
2178    let r = pin_circle_diameter / 2.0;
2179    let rp = pin_diameter / 2.0;
2180    let n = pins as f64;
2181    let tau = TAU / n;
2182    // Where a pin's circle crosses the bore circle (radius r): half-angle delta about the origin.
2183    let delta = 2.0 * (rp / (2.0 * r)).asin();
2184    if 2.0 * delta >= tau - 1e-9 || 2.0 * r * (PI / n).sin() <= pin_diameter * (1.0 + 1e-9) {
2185        return Err(refuse("gear_input", format!("{pins} pins of diameter {pin_diameter} overlap on a {pin_circle_diameter} pin circle.")));
2186    }
2187    let centre = [r, 0.0];
2188    let a = [r * (-delta).cos(), r * (-delta).sin()];
2189    let b = [r * delta.cos(), r * delta.sin()];
2190    // The pin bulges into the bore: its arc from a to b passes through (r - rp, 0).
2191    let cw = arc_through(centre, a, b, false)?;
2192    let pin_arc = {
2193        let [t0, t1] = cw.domain().map_err(|e| refuse("gear_domain", e))?;
2194        let mid = cw.evaluate(0.5 * (t0 + t1)).map_err(|e| refuse("gear_eval", e))?;
2195        if mid.x < r { cw } else { arc_through(centre, a, b, true)? }
2196    };
2197    let space: Vec<(&'static str, NurbsCurve)> = vec![("P", pin_arc), ("G", arc(r, delta, tau - delta)?)];
2198    let mut curves = Vec::with_capacity(2 * pins);
2199    for k in 0..pins {
2200        for (role, curve) in &space {
2201            curves.push(SectionCurve { curve: rotated(curve, tau * k as f64), role, tooth: k });
2202        }
2203    }
2204    snap_junctions(&mut curves);
2205    let section = GearSection { curves, data: GearData { pitch_diameter: pin_circle_diameter, ..GearData::default() } };
2206    let ring = hub_from_section(&section, outside, width)?;
2207    Ok((ring, section.data))
2208}
2209
2210/// A cycloidal (clock-style) gear: teeth whose addenda are epicycloids rolled
2211/// by a circle of `generating_radius` on the pitch circle and whose dedenda are
2212/// radial lines (the hypocycloid of a circle of half the mate's pitch radius).
2213#[derive(Clone, Debug)]
2214pub struct CycloidalGear {
2215    pub module: f64,
2216    pub teeth: usize,
2217    /// Radius of the rolling circle (usually half the mating gear's pitch radius).
2218    pub generating_radius: f64,
2219    /// Tooth thickness on the pitch circle as a fraction of the circular pitch.
2220    pub tooth_fraction: f64,
2221    /// Addendum limit × module (the tip is pointed if the flanks meet first).
2222    pub addendum: f64,
2223    /// Dedendum × module.
2224    pub dedendum: f64,
2225    pub width: f64,
2226}
2227
2228/// The cycloidal gear's section, counter-clockwise. Per tooth k: `R<k>`/`L<k>`
2229/// the radial dedendum flanks, `ER<k>`/`EL<k>` the epicycloidal addenda, `K<k>`
2230/// the tip land (absent when pointed), `G<k>` the root land.
2231pub fn cycloidal_gear_section(gear: &CycloidalGear) -> Result<GearSection, KernelRefusal> {
2232    let m = gear.module;
2233    if !(m > 0.0 && gear.generating_radius > 0.0 && gear.addendum > 0.0 && gear.dedendum > 0.0 && gear.width > 0.0) {
2234        return Err(refuse("gear_input", "The module, rolling circle, addendum, dedendum and width must be positive.".into()));
2235    }
2236    if !(gear.tooth_fraction > 0.1 && gear.tooth_fraction < 0.9) {
2237        return Err(refuse("gear_input", "The tooth thickness must be between 0.1 and 0.9 of the pitch.".into()));
2238    }
2239    if gear.teeth < 6 || gear.teeth > 1000 {
2240        return Err(refuse("gear_input", format!("A cycloidal gear needs from 6 to 1000 teeth (it has {}).", gear.teeth)));
2241    }
2242    let z = gear.teeth as f64;
2243    let r = m * z / 2.0;
2244    let rho = gear.generating_radius;
2245    let rf = r - gear.dedendum * m;
2246    if !(rf > 0.0) {
2247        return Err(refuse("root_below_centre", "The root circle is not positive: fewer dedendum or more teeth.".into()));
2248    }
2249    let tau = TAU / z;
2250    let psi = PI * gear.tooth_fraction / z; // half the tooth angle on the pitch circle
2251    // The right flank's epicycloid, from the pitch circle at angle -psi.
2252    let k = (r + rho) / rho;
2253    let epi = |phi: f64| {
2254        let p = [(r + rho) * phi.cos() - rho * (k * phi).cos(), (r + rho) * phi.sin() - rho * (k * phi).sin()];
2255        rotate(p, -psi)
2256    };
2257    let ra = r + gear.addendum * m;
2258    // Run phi up until the curve reaches the tip circle or the tooth centre line (angle 0).
2259    let reach = |phi: f64| radius_of(epi(phi)) >= ra || polar_angle(epi(phi)) >= 0.0;
2260    let mut hi = 1e-3;
2261    while !reach(hi) {
2262        hi *= 1.5;
2263        if hi > PI {
2264            return Err(refuse("gear_input", "The addendum curve does not close.".into()));
2265        }
2266    }
2267    let mut lo = 0.0;
2268    for _ in 0..200 {
2269        let mid = 0.5 * (lo + hi);
2270        if reach(mid) { hi = mid } else { lo = mid }
2271    }
2272    let end = epi(hi);
2273    // Pointed when the flank reaches the tooth centre line no later than the
2274    // tip circle (a tip land narrower than 1e-9 counts as pointed).
2275    let pointed = polar_angle(end) >= -1e-9;
2276    let phi_end = if pointed {
2277        let (mut lo, mut hi) = (0.0, hi);
2278        for _ in 0..200 {
2279            let mid = 0.5 * (lo + hi);
2280            if polar_angle(epi(mid)) >= 0.0 { hi = mid } else { lo = mid }
2281        }
2282        hi
2283    } else {
2284        hi
2285    };
2286    let tolerance = GEAR_FIT_TOLERANCE * m;
2287    let right_add = fit_planar(&|phi| epi(phi), 0.0, phi_end, tolerance)?; // pitch -> tip, right side
2288    let foot = [rf * (-psi).cos(), rf * (-psi).sin()];
2289    let pitch_point = [r * (-psi).cos(), r * (-psi).sin()];
2290    let mut tooth: Vec<(&'static str, NurbsCurve)> = vec![("R", line(foot, pitch_point)?), ("ER", right_add.clone())];
2291    let tip_angle = -polar_angle(epi(phi_end));
2292    if !pointed {
2293        tooth.push(("K", arc(ra, -tip_angle, tip_angle)?));
2294    }
2295    tooth.push(("EL", mirrored(&right_add).reversed().map_err(|e| refuse("gear_fit", e))?));
2296    tooth.push(("L", line([pitch_point[0], -pitch_point[1]], [foot[0], -foot[1]])?));
2297    tooth.push(("G", arc(rf, psi, tau - psi)?));
2298    let mut curves = Vec::with_capacity(tooth.len() * gear.teeth);
2299    for index in 0..gear.teeth {
2300        let angle = tau * index as f64;
2301        for (role, curve) in &tooth {
2302            curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
2303        }
2304    }
2305    snap_junctions(&mut curves);
2306    let data = GearData {
2307        pitch_diameter: 2.0 * r,
2308        tip_diameter: 2.0 * radius_of(epi(phi_end)),
2309        root_diameter: 2.0 * rf,
2310        tooth_thickness: 2.0 * psi * r,
2311        ..GearData::default()
2312    };
2313    Ok(GearSection { curves, data })
2314}
2315
2316/// A cycloidal gear solid; names as the section's roles, then `F` and `B`.
2317pub fn cycloidal_gear_solid(gear: &CycloidalGear) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
2318    let section = cycloidal_gear_section(gear)?;
2319    let solid = extrude_section(&section, gear.width)?;
2320    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
2321    names.push("F".into());
2322    names.push("B".into());
2323    Ok((solid, names, section.data))
2324}
2325