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/// An intermittent (mutilated) spur gear: only teeth 0 .. `kept` of the full gear, the rest of the rim an exact
513/// arc. Without `locking` the gap is the root circle; with it, past one root land after the last tooth and before
514/// the first (room for the driven gear's tooth to leave and enter), the rim rises radially to an arc on the tip
515/// circle that locks the driven gear between steps. Names: the kept teeth as the spur gear's, `S` the gap's arc,
516/// `E0`/`E1` the locking arc's radial ends, then `F`, `B`.
517pub fn spur_sector_solid(gear: &SpurGear, kept: usize, locking: bool) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
518    let full = spur_section(gear)?;
519    let z = gear.teeth;
520    if !(1..z).contains(&kept) {
521        return Err(refuse("gear_input", format!("A sector keeps from 1 to {} of the {z} teeth (not {kept}).", z - 1)));
522    }
523    if locking && kept + 2 > z {
524        return Err(refuse("gear_input", "A locking arc needs at least two teeth left out (a root land each side).".into()));
525    }
526    let point = |curve: &NurbsCurve, end: bool| -> Result<[f64; 2], KernelRefusal> {
527        let [a, b] = curve.domain().map_err(|e| refuse("gear_domain", e))?;
528        let p = curve.evaluate(if end { b } else { a }).map_err(|e| refuse("gear_eval", e))?;
529        Ok([p.x, p.y])
530    };
531    let unwrap_ccw = |from: f64, to: f64| from + (to - from).rem_euclid(TAU);
532    let mut curves: Vec<SectionCurve> = full.curves.iter().filter(|c| c.tooth < kept).cloned().collect();
533    let first = full.curves.iter().find(|c| c.tooth == 0).expect("tooth 0").curve.clone();
534    let start = point(&first, false)?; // tooth 0's first piece: where the rim comes back
535    let root_r = radius_of(start);
536    if locking {
537        // Keep the root land after the last tooth and the one before tooth 0; between them the locking arc.
538        let after = full.curves.iter().filter(|c| c.tooth == kept).next().expect("the next tooth").curve.clone();
539        let rise = point(&after, false)?; // where tooth `kept` would start
540        let before_land = full.curves.iter().filter(|c| c.tooth == z - 1 && c.role == "G").last().map(|c| c.curve.clone());
541        let Some(before_land) = before_land else {
542            return Err(refuse("gear_input", "This gear has no root land for a locking arc.".into()));
543        };
544        let fall = point(&before_land, false)?; // where the land before tooth 0 starts
545        let tip_r = full.data.tip_diameter / 2.0;
546        let (a0, a1) = (polar_angle(rise), polar_angle(fall));
547        let a1 = unwrap_ccw(a0, a1);
548        let up = [tip_r * a0.cos(), tip_r * a0.sin()];
549        let down = [tip_r * a1.cos(), tip_r * a1.sin()];
550        curves.push(SectionCurve { curve: line(rise, up)?, role: "E", tooth: 0 });
551        curves.push(SectionCurve { curve: arc(tip_r, a0, a1)?, role: "S", tooth: 0 });
552        curves.push(SectionCurve { curve: line(down, fall)?, role: "E", tooth: 1 });
553        curves.push(SectionCurve { curve: before_land, role: "G", tooth: z - 1 });
554    } else {
555        // Drop the last kept tooth's root land: the root circle runs on to tooth 0.
556        if curves.last().is_some_and(|c| c.role == "G") {
557            curves.pop();
558        }
559        let end = point(&curves.last().expect("a kept tooth").curve, true)?;
560        let (a0, a1) = (polar_angle(end), polar_angle(start));
561        curves.push(SectionCurve { curve: arc(root_r, a0, unwrap_ccw(a0, a1))?, role: "S", tooth: 0 });
562    }
563    snap_junctions(&mut curves);
564    let section = GearSection { curves, data: full.data };
565    let solid = extrude_section(&section, gear.face_width)?;
566    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
567    names.push("F".into());
568    names.push("B".into());
569    Ok((solid, names, section.data))
570}
571
572/// Extrude a counter-clockwise gear section along +z.
573pub fn extrude_section(section: &GearSection, width: f64) -> Result<BrepSolid, KernelRefusal> {
574    let curves: Vec<NurbsCurve> = section.curves.iter().map(|piece| piece.curve.clone()).collect();
575    extrude_profile_brep(&curves, Vec3::new(0.0, 0.0, 1.0), width)
576}
577
578/// A straight-toothed rack: the basic rack profile of `teeth` teeth along +x
579/// from x = 0, the pitch line on y = 0, teeth pointing +y, extruded along +z.
580/// Each end stops in the middle of a tooth space.
581#[derive(Clone, Debug)]
582pub struct Rack {
583    pub module: f64,
584    pub teeth: usize,
585    pub pressure_angle: f64,
586    pub addendum: f64,
587    pub dedendum: f64,
588    /// Root fillet radius coefficient (× module).
589    pub root_fillet: f64,
590    /// Circumferential backlash taken off the tooth thickness on the pitch line.
591    pub backlash: f64,
592    pub face_width: f64,
593    /// Distance from the pitch line down to the rack's back face.
594    pub height: f64,
595    /// Helix angle of a helical rack (0: straight teeth); the module, pressure
596    /// angle and coefficients are then those of the normal section. Positive
597    /// leans the teeth one way (right hand), negative the other.
598    pub helix_angle: f64,
599}
600
601impl Default for Rack {
602    fn default() -> Self {
603        Self {
604            module: 2.0,
605            teeth: 10,
606            pressure_angle: 20f64.to_radians(),
607            addendum: 1.0,
608            dedendum: 1.25,
609            root_fillet: 0.38,
610            backlash: 0.0,
611            face_width: 10.0,
612            height: 6.0,
613            helix_angle: 0.0,
614        }
615    }
616}
617
618fn line(a: [f64; 2], b: [f64; 2]) -> Result<NurbsCurve, KernelRefusal> {
619    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))
620}
621
622fn centred_arc(centre: [f64; 2], radius: f64, from: f64, to: f64) -> Result<NurbsCurve, KernelRefusal> {
623    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)
624        .map_err(|error| refuse("gear_arc", error))
625}
626
627/// The section of a straight rack (exact: lines and arcs), counter-clockwise.
628/// Roles: `G<k>` the root land before tooth k (`G<teeth>` the last one),
629/// `W<k>`/`V<k>` the root fillets left/right of tooth k, `L<k>`/`R<k>` its
630/// left (low x) and right flanks, `K<k>` its tip, `BASE` the back face, `E0`
631/// and `E1` the ends at x = 0 and x = length.
632pub fn rack_section(rack: &Rack) -> Result<GearSection, KernelRefusal> {
633    rack_section_checked(rack, 35.0)
634}
635
636fn rack_section_checked(rack: &Rack, max_pressure_degrees: f64) -> Result<GearSection, KernelRefusal> {
637    let m = rack.module;
638    let positive = |value: f64, what: &str| {
639        if value.is_finite() && value > 0.0 {
640            Ok(())
641        } else {
642            Err(refuse("gear_input", format!("The {what} must be greater than zero (it is {value}).")))
643        }
644    };
645    positive(m, "module")?;
646    positive(rack.face_width, "face width")?;
647    positive(rack.addendum, "addendum coefficient")?;
648    positive(rack.dedendum, "dedendum coefficient")?;
649    if rack.teeth < 1 {
650        return Err(refuse("gear_input", "A rack needs at least one tooth.".into()));
651    }
652    let degrees = rack.pressure_angle.to_degrees();
653    if !(10.0 - 1e-9..=max_pressure_degrees + 1e-9).contains(&degrees) {
654        return Err(refuse("gear_input", format!("The pressure angle must be between 10° and {max_pressure_degrees}° (it is {degrees}°).")));
655    }
656    if !(rack.root_fillet >= 0.0) || !(rack.backlash >= 0.0) {
657        return Err(refuse("gear_input", "The root fillet and the backlash cannot be negative.".into()));
658    }
659    let alpha = rack.pressure_angle;
660    let (ha, hf) = (rack.addendum * m, rack.dedendum * m);
661    if rack.height <= hf + 1e-9 * m {
662        return Err(refuse(
663            "rack_too_thin",
664            format!("The rack height below the pitch line ({:.4}) must exceed the dedendum ({:.4}).", rack.height, hf),
665        ));
666    }
667    let p = PI * m;
668    let w = p / 4.0 - rack.backlash / 2.0; // half the tooth thickness on the pitch line
669    let tip_half = w - ha * alpha.tan();
670    if tip_half <= 1e-6 * m {
671        return Err(refuse(
672            "pointed_tip",
673            "The rack teeth come to a point below their tip line; reduce the addendum, the pressure angle or the backlash.".into(),
674        ));
675    }
676    let rho = rack.root_fillet * m;
677    // Right-hand fillet of the tooth centred on x = 0: centre, flank tangent point, root tangent x.
678    let y_p = -hf + rho - rho * alpha.sin();
679    let flank_x = |y: f64| w - y * alpha.tan();
680    let centre = [flank_x(y_p) + rho * alpha.cos(), -hf + rho];
681    let root_half = centre[0]; // the root tangent point's x (right of the tooth centre)
682    if y_p >= ha - 1e-9 * m {
683        return Err(refuse(
684            "root_fillet_too_large",
685            format!(
686                "The root fillet (coefficient {:.4}) reaches above the tooth tip; lower it or raise the addendum.",
687                rack.root_fillet
688            ),
689        ));
690    }
691    if root_half > p / 2.0 + 1e-9 * m {
692        let max = (p / 2.0 - w - hf * alpha.tan()) * alpha.cos() / (1.0 - alpha.sin());
693        return Err(refuse(
694            "root_fillet_too_large",
695            format!("The root fillet coefficient {:.4} is larger than the {:.4} that fits this tooth space; lower it.", rack.root_fillet, max / m),
696        ));
697    }
698    let length = p * rack.teeth as f64;
699    let mut curves: Vec<SectionCurve> = Vec::new();
700    let mut push = |curve: NurbsCurve, role: &'static str, tooth: usize| curves.push(SectionCurve { curve, role, tooth });
701    let base = -rack.height;
702    push(line([0.0, base], [length, base])?, "BASE", 0);
703    push(line([length, base], [length, -hf])?, "E1", 0);
704    // Teeth from the right end leftwards (counter-clockwise along the top).
705    let mut x_prev_root = length; // where the current root land starts (right end)
706    for k in (0..rack.teeth).rev() {
707        let c = (k as f64 + 0.5) * p;
708        let right_root = [c + root_half, -hf];
709        if x_prev_root - right_root[0] > 1e-9 * m {
710            push(line([x_prev_root, -hf], right_root)?, "G", k + 1);
711        }
712        // Right fillet: from the root tangent (angle 270°) back to the flank tangent (180° + alpha).
713        let right_centre = [c + centre[0], centre[1]];
714        let right_flank_low = [c + flank_x(y_p), y_p];
715        if rho > 0.0 {
716            push(centred_arc(right_centre, rho, PI + alpha, 1.5 * PI)?.reversed().map_err(|e| refuse("gear_arc", e))?, "V", k);
717        }
718        let right_tip = [c + tip_half, ha];
719        let left_tip = [c - tip_half, ha];
720        let left_flank_low = [c - flank_x(y_p), y_p];
721        push(line(if rho > 0.0 { right_flank_low } else { right_root }, right_tip)?, "R", k);
722        push(line(right_tip, left_tip)?, "K", k);
723        let left_root = [c - root_half, -hf];
724        push(line(left_tip, if rho > 0.0 { left_flank_low } else { left_root })?, "L", k);
725        if rho > 0.0 {
726            let left_centre = [c - centre[0], centre[1]];
727            push(centred_arc(left_centre, rho, 1.5 * PI, 2.0 * PI - alpha)?.reversed().map_err(|e| refuse("gear_arc", e))?, "W", k);
728        }
729        x_prev_root = left_root[0];
730    }
731    if x_prev_root > 1e-9 * m {
732        push(line([x_prev_root, -hf], [0.0, -hf])?, "G", 0);
733    }
734    push(line([0.0, -hf], [0.0, base])?, "E0", 0);
735    // Share every junction exactly.
736    snap_junctions(&mut curves);
737    let data = GearData {
738        pitch_diameter: f64::INFINITY,
739        tooth_thickness: 2.0 * w,
740        tip_thickness: 2.0 * tip_half,
741        ..GearData::default()
742    };
743    Ok(GearSection { curves, data })
744}
745
746/// A rack solid: the section extruded along +z by the face width; names as
747/// [`rack_section`], then `F` (z = 0) and `B` (z = width).
748pub fn rack_solid(rack: &Rack) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
749    let beta = rack.helix_angle;
750    if !(beta.abs().to_degrees() <= 45.0 + 1e-9) {
751        return Err(refuse("bad_helix", format!("The rack's helix angle must be between −45° and 45° (it is {:.4}°).", beta.to_degrees())));
752    }
753    // A helical rack's transverse section (the plane z = const) is the rack of
754    // the transverse module and pressure angle; the teeth run along (tan beta, 0, 1).
755    let degrees = rack.pressure_angle.to_degrees();
756    if !(10.0 - 1e-9..=35.0 + 1e-9).contains(&degrees) {
757        return Err(refuse("gear_input", format!("The pressure angle must be between 10° and 35° (it is {degrees}°).")));
758    }
759    if beta == 0.0 {
760        // Straight teeth: the rack exactly as given (no transverse conversion).
761        let section = rack_section(rack)?;
762        let solid = extrude_section(&section, rack.face_width)?;
763        let mut names: Vec<String> = section.curves.iter().map(rack_suffix).collect();
764        names.push("F".into());
765        names.push("B".into());
766        return Ok((solid, names, section.data));
767    }
768    // A helical rack's teeth are straight prisms along (tan beta, 0, 1). Its
769    // normal section (across the teeth) is the basic rack; the transverse
770    // section (z = const) is that section stretched along the rack by
771    // 1 / cos beta, exactly: lines stay lines, the root rounds become ellipses
772    // (still rational quadratic arcs).
773    let c = beta.cos();
774    let mut section = rack_section(rack)?;
775    for piece in &mut section.curves {
776        for point in &mut piece.curve.control_points {
777            point.x /= c;
778        }
779    }
780    // The recorded thicknesses are read along the rack (transverse), as the section is.
781    section.data.tooth_thickness /= c;
782    section.data.tip_thickness /= c;
783    let curves: Vec<NurbsCurve> = section.curves.iter().map(|piece| piece.curve.clone()).collect();
784    let direction = Vec3::new(beta.tan(), 0.0, 1.0);
785    let solid = extrude_profile_brep(&curves, direction, rack.face_width / c)?;
786    let mut names: Vec<String> = section.curves.iter().map(rack_suffix).collect();
787    names.push("F".into());
788    names.push("B".into());
789    Ok((solid, names, section.data))
790}
791
792fn rack_suffix(piece: &SectionCurve) -> String {
793    match piece.role {
794        "BASE" | "E0" | "E1" => piece.role.to_string(),
795        _ => piece.suffix(),
796    }
797}
798
799/// Share every junction of a closed loop exactly: each curve ends on the next one's first point.
800fn snap_junctions(curves: &mut [SectionCurve]) {
801    let count = curves.len();
802    for index in 0..count {
803        let start = curves[(index + 1) % count].curve.control_points[0];
804        let curve = &mut curves[index].curve;
805        let last = curve.control_points.len() - 1;
806        let w = curve.control_points[last].w;
807        curve.control_points[last] = Vec4 { x: start.x / start.w * w, y: start.y / start.w * w, z: start.z / start.w * w, w };
808    }
809}
810
811/// An internal (ring) gear: involute tooth spaces cut into the inside of a
812/// ring. Lengths in model units, angles in radians, coefficients × module.
813#[derive(Clone, Debug)]
814pub struct RingGear {
815    pub module: f64,
816    pub teeth: usize,
817    pub pressure_angle: f64,
818    /// Profile shift: the cutter moved outward by x · module (tip and root
819    /// circles grow by x · module, the spaces widen by 2 x m tan alpha).
820    pub profile_shift: f64,
821    pub addendum: f64,
822    pub dedendum: f64,
823    /// Radius of the root fillet (× module): an exact arc tangent to the
824    /// flank and the root circle.
825    pub root_fillet: f64,
826    /// Circumferential backlash added to each tooth space on the reference circle.
827    pub backlash: f64,
828    pub face_width: f64,
829    /// Radial wall beyond the root circle.
830    pub rim: f64,
831}
832
833impl Default for RingGear {
834    fn default() -> Self {
835        Self {
836            module: 2.0,
837            teeth: 60,
838            pressure_angle: 20f64.to_radians(),
839            profile_shift: 0.0,
840            addendum: 1.0,
841            dedendum: 1.25,
842            root_fillet: 0.38,
843            backlash: 0.0,
844            face_width: 10.0,
845            rim: 6.0,
846        }
847    }
848}
849
850/// The inner (toothed) loop of a ring gear, counter-clockwise about +z, and its data.
851/// Roles per tooth space k: `R<k>` flank on its clockwise side, `V<k>` its
852/// fillet, `G<k>` the root land, `W<k>`, `L<k>`, then `K<k>` the tip land of
853/// the ring tooth after the space.
854pub fn ring_section(gear: &RingGear) -> Result<GearSection, KernelRefusal> {
855    ring_section_checked(gear, 35.0)
856}
857
858fn ring_section_checked(gear: &RingGear, max_pressure_degrees: f64) -> Result<GearSection, KernelRefusal> {
859    let m = gear.module;
860    let positive = |value: f64, what: &str| {
861        if value.is_finite() && value > 0.0 {
862            Ok(())
863        } else {
864            Err(refuse("gear_input", format!("The {what} must be greater than zero (it is {value}).")))
865        }
866    };
867    positive(m, "module")?;
868    positive(gear.face_width, "face width")?;
869    positive(gear.addendum, "addendum coefficient")?;
870    positive(gear.dedendum, "dedendum coefficient")?;
871    positive(gear.rim, "rim thickness")?;
872    if gear.teeth < 6 {
873        return Err(refuse("gear_input", format!("An internal gear needs at least 6 teeth (it has {}).", gear.teeth)));
874    }
875    let degrees = gear.pressure_angle.to_degrees();
876    if !(10.0 - 1e-9..=max_pressure_degrees + 1e-9).contains(&degrees) {
877        return Err(refuse("gear_input", format!("The pressure angle must be between 10° and {max_pressure_degrees}° (it is {degrees}°).")));
878    }
879    if !(gear.root_fillet >= 0.0) || !(gear.backlash >= 0.0) || !gear.profile_shift.is_finite() {
880        return Err(refuse("gear_input", "The root fillet and the backlash cannot be negative.".into()));
881    }
882    let z = gear.teeth as f64;
883    let alpha = gear.pressure_angle;
884    let r = m * z / 2.0;
885    let r_b = r * alpha.cos();
886    let r_a = r - (gear.addendum - gear.profile_shift) * m; // inner (tip) circle
887    let r_f = r + (gear.dedendum + gear.profile_shift) * m; // outer (root) circle
888    let rho = gear.root_fillet * m;
889    let half_pitch = PI / z;
890    let tolerance = GEAR_FIT_TOLERANCE * m;
891    if r_a <= r_b + 1e-9 * m {
892        return Err(refuse(
893            "tip_inside_base",
894            format!(
895                "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.",
896                2.0 * r_a,
897                2.0 * r_b
898            ),
899        ));
900    }
901    // Half the SPACE angle at a radius: the space is shaped as an external tooth.
902    let space = PI * m / 2.0 + 2.0 * gear.profile_shift * m * alpha.tan() + gear.backlash;
903    let involute = |angle: f64| angle.tan() - angle;
904    let half_space = |radius: f64| space / (2.0 * r) + involute(alpha) - involute((r_b / radius).min(1.0).acos());
905    let flank = |radius: f64| {
906        let angle = half_space(radius);
907        [radius * angle.cos(), radius * angle.sin()]
908    };
909    if half_space(r_a) >= half_pitch - 1e-6 * m / r_a {
910        return Err(refuse(
911            "pointed_tip",
912            "The ring teeth come to a point at the tip circle: reduce the profile shift, the backlash or the addendum.".into(),
913        ));
914    }
915    // The spaces narrow outward: one that closes before the root circle has
916    // crossed flanks (read unwrapped, from the closed form).
917    if half_space(r_f) <= 1e-6 * m / r_f {
918        let (mut lo, mut hi) = (r_a, r_f);
919        for _ in 0..200 {
920            let mid = 0.5 * (lo + hi);
921            if half_space(mid) > 0.0 { lo = mid } else { hi = mid }
922        }
923        return Err(refuse(
924            "teeth_overlap",
925            format!(
926                "The tooth spaces close at d = {:.4}, inside the root circle (d = {:.4}); reduce the dedendum or the profile shift.",
927                2.0 * lo,
928                2.0 * r_f
929            ),
930        ));
931    }
932    // The fillet: a circle of radius rho tangent to the flank (left side of
933    // space 0, at T) and inside the root circle. Its centre is T moved by rho
934    // along the flank's normal into the space; solve |centre| = r_f - rho for T.
935    let normal_into_space = |radius: f64| {
936        let h = 1e-6 * m;
937        let (a, b) = (flank(radius - h), flank(radius + h));
938        let (tx, ty) = (b[0] - a[0], b[1] - a[1]);
939        let length = tx.hypot(ty);
940        // The space lies at smaller angles than its left flank: the normal turned clockwise from the outward tangent.
941        [ty / length, -tx / length]
942    };
943    let centre_at = |radius: f64| {
944        let point = flank(radius);
945        let n = normal_into_space(radius);
946        [point[0] + rho * n[0], point[1] + rho * n[1]]
947    };
948    let (join_radius, centre) = if rho == 0.0 {
949        (r_f, flank(r_f))
950    } else {
951        let target = r_f - rho;
952        let (mut lo, mut hi) = (r_a, r_f);
953        if radius_of(centre_at(lo)) > target {
954            return Err(refuse("root_fillet_too_large", "The root fillet is too large for the tooth depth; lower it.".into()));
955        }
956        for _ in 0..200 {
957            let mid = 0.5 * (lo + hi);
958            if radius_of(centre_at(mid)) < target { lo = mid } else { hi = mid }
959        }
960        let radius = 0.5 * (lo + hi);
961        (radius, centre_at(radius))
962    };
963    let root_angle = polar_angle(centre);
964    if rho > 0.0 && root_angle <= 1e-9 {
965        return Err(refuse(
966            "root_fillet_too_large",
967            "The root fillet is larger than fits the tooth space; lower it.".into(),
968        ));
969    }
970    let tip_angle = half_space(r_a);
971    // Left flank of space 0 from its root end (join) in to the tip circle.
972    let flank_fit = fit_planar(&|radius| flank(radius), r_a, join_radius, tolerance)?; // tip -> join
973    let mut space: Vec<(&'static str, NurbsCurve)> = Vec::new();
974    // Clockwise side (negative angles), outward: mirrored left flank (tip -> join), fillet, land, fillet, flank.
975    space.push(("R", mirrored(&flank_fit)));
976    if rho > 0.0 {
977        // The left fillet runs counter-clockwise about its centre from the root
978        // tangent point (straight out from the centre) round to the flank join.
979        let join = flank(join_radius);
980        let from = root_angle;
981        let mut to = (join[1] - centre[1]).atan2(join[0] - centre[0]);
982        while to <= from {
983            to += TAU;
984        }
985        let left = centred_arc(centre, rho, from, to)?; // root -> join
986        space.push(("V", mirrored(&left).reversed().map_err(|e| refuse("gear_arc", e))?));
987        space.push(("G", arc(r_f, -root_angle, root_angle)?));
988        space.push(("W", left));
989    } else {
990        space.push(("G", arc(r_f, -root_angle, root_angle)?));
991    }
992    space.push(("L", flank_fit.reversed().map_err(|e| refuse("gear_fit", e))?));
993    space.push(("K", arc(r_a, tip_angle, 2.0 * half_pitch - tip_angle)?));
994    let mut curves = Vec::with_capacity(space.len() * gear.teeth);
995    for index in 0..gear.teeth {
996        let angle = TAU * index as f64 / z;
997        for (role, curve) in &space {
998            curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
999        }
1000    }
1001    snap_junctions(&mut curves);
1002    let data = GearData {
1003        pitch_diameter: 2.0 * r,
1004        base_diameter: 2.0 * r_b,
1005        tip_diameter: 2.0 * r_a,
1006        root_diameter: 2.0 * r_f,
1007        form_diameter: 2.0 * join_radius,
1008        tooth_thickness: 2.0 * r * (half_pitch - half_space(r)),
1009        tip_thickness: 2.0 * r_a * (half_pitch - tip_angle),
1010        undercut: false,
1011        min_shift_without_undercut: 0.0,
1012    };
1013    Ok(GearSection { curves, data })
1014}
1015
1016/// A ring gear solid: a cylinder of radius root + rim with the toothed loop
1017/// cut through it. Its faces carry their role names (`R3`, `K0`, …, `OD` the
1018/// outside, `F` at z = 0, `B` at z = width) in `face.name`.
1019pub fn ring_solid(gear: &RingGear) -> Result<(BrepSolid, GearData), KernelRefusal> {
1020    let section = ring_section(gear)?;
1021    let outer = section.data.root_diameter / 2.0 + gear.rim;
1022    let width = gear.face_width;
1023    let rows = |p: Vec4| vec![p, Vec4 { x: p.x, y: p.y, z: p.z + p.w * width, w: p.w }];
1024    let ring = hollow_prism(&section, outer, width, 1, &[0.0, 0.0, 1.0, 1.0], &rows)?;
1025    Ok((ring, section.data))
1026}
1027
1028/// A helical (or double helical) ring gear: `gear` in the normal section,
1029/// its transverse section screwed through the blank. Names as [`ring_solid`].
1030pub fn ring_solid_helical(gear: &RingGear, helix_angle: f64, hand: Hand, herringbone: bool) -> Result<(BrepSolid, GearData), KernelRefusal> {
1031    let beta = helix_angle;
1032    if !(beta.to_degrees() >= 0.5 - 1e-9 && beta.to_degrees() <= 45.0 + 1e-9) {
1033        return Err(refuse("bad_helix", format!("The helix angle must be between 0.5° and 45° (it is {:.4}°).", beta.to_degrees())));
1034    }
1035    let normal = gear.pressure_angle.to_degrees();
1036    if !(10.0 - 1e-9..=35.0 + 1e-9).contains(&normal) {
1037        return Err(refuse("gear_input", format!("The normal pressure angle must be between 10° and 35° (it is {normal}°).")));
1038    }
1039    let c = beta.cos();
1040    let transverse = RingGear {
1041        module: gear.module / c,
1042        pressure_angle: (gear.pressure_angle.tan() / c).atan(),
1043        profile_shift: gear.profile_shift * c,
1044        addendum: gear.addendum * c,
1045        dedendum: gear.dedendum * c,
1046        root_fillet: gear.root_fillet * c,
1047        ..gear.clone()
1048    };
1049    let section = ring_section_checked(&transverse, 60.0)?;
1050    let r = transverse.module * transverse.teeth as f64 / 2.0;
1051    let sign = if hand == Hand::Right { 1.0 } else { -1.0 };
1052    let rate = sign * beta.tan() / r; // turn per unit height
1053    let outer = section.data.root_diameter / 2.0 + gear.rim;
1054    // The section carried up the face width turning at the helix's rate (out and back for double helical).
1055    let width = gear.face_width;
1056    let turn = rate * width;
1057    let twist = if herringbone { Twist::Herringbone { turn } } else { Twist::Helical { turn } };
1058    let reach = section.curves.iter().flat_map(|c| c.curve.control_points.iter()).map(|p| (p.x / p.w).hypot(p.y / p.w)).fold(0.0, f64::max);
1059    let (knots_v, basis) = twist_basis(twist, reach, GEAR_FIT_TOLERANCE * transverse.module)?;
1060    let rows = |p: Vec4| -> Vec<Vec4> { basis.iter().map(|[c, s, t]| Vec4 { x: c * p.x - s * p.y, y: s * p.x + c * p.y, z: p.z + p.w * t * width, w: p.w }).collect() };
1061    let ring = hollow_prism(&section, outer, width, 3, &knots_v, &rows)?;
1062    Ok((ring, section.data))
1063}
1064
1065fn translated(curve: &NurbsCurve, dz: f64) -> NurbsCurve {
1066    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();
1067    NurbsCurve::new(curve.degree, curve.knots.clone(), points).expect("a translated curve is a valid curve")
1068}
1069
1070/// Which ISO 606 tooth form a sprocket is cut to.
1071#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1072pub enum SprocketForm {
1073    /// Smallest seating radius, largest flank radius, largest seating angle.
1074    Minimum,
1075    /// Largest seating radius, smallest flank radius, smallest seating angle.
1076    Maximum,
1077    /// The mean of the two.
1078    Mean,
1079}
1080
1081/// A roller-chain sprocket (ISO 606 tooth form; ANSI chains are its A series).
1082#[derive(Clone, Debug)]
1083pub struct Sprocket {
1084    pub pitch: f64,
1085    pub roller_diameter: f64,
1086    pub teeth: usize,
1087    pub form: SprocketForm,
1088    /// Tooth width across the sprocket (the extrusion).
1089    pub width: f64,
1090}
1091
1092/// The section of a roller-chain sprocket, counter-clockwise; every curve is a
1093/// circular arc. Tooth k is centred on angle 2 pi k / z (tooth 0 on +x); gap k
1094/// follows it. Roles: `A<k>` the flank into gap k, `S<k>` its roller seating,
1095/// `C<k>` the flank out of it, `K<k>` the tip land of the tooth after gap k
1096/// (absent when the flanks meet below the tip circle).
1097pub fn sprocket_section(sprocket: &Sprocket) -> Result<GearSection, KernelRefusal> {
1098    let p = sprocket.pitch;
1099    let d1 = sprocket.roller_diameter;
1100    if !(p > 0.0 && d1 > 0.0 && d1 < p && sprocket.width > 0.0) {
1101        return Err(refuse(
1102            "gear_input",
1103            format!("The chain pitch ({p}), the roller diameter ({d1}, less than the pitch) and the width must be positive."),
1104        ));
1105    }
1106    if sprocket.teeth < 6 || sprocket.teeth > 300 {
1107        return Err(refuse("gear_input", format!("A sprocket needs from 6 to 300 teeth (it has {}).", sprocket.teeth)));
1108    }
1109    let z = sprocket.teeth as f64;
1110    let tau = TAU / z;
1111    let d = p / (PI / z).sin();
1112    // ISO 606 tooth form limits.
1113    let ri_min = 0.505 * d1;
1114    let ri_max = 0.505 * d1 + 0.069 * d1.cbrt();
1115    let re_min = 0.008 * d1 * (z * z + 180.0);
1116    let re_max = 0.12 * d1 * (z + 2.0);
1117    let a_min = (120.0 - 90.0 / z).to_radians();
1118    let a_max = (140.0 - 90.0 / z).to_radians();
1119    let da_min = d + p * (1.0 - 1.6 / z) - d1;
1120    let da_max = d + 1.25 * p - d1;
1121    let (ri, re, alpha, da) = match sprocket.form {
1122        SprocketForm::Minimum => (ri_min, re_max, a_max, da_min),
1123        SprocketForm::Maximum => (ri_max, re_min, a_min, da_max),
1124        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)),
1125    };
1126    let ra = da / 2.0;
1127    // Gap 0 centred on angle tau / 2 is built centred on +x, then turned.
1128    let c = [d / 2.0, 0.0];
1129    let u = [-(alpha / 2.0).cos(), (alpha / 2.0).sin()]; // roller centre -> upper seating end
1130    let t_up = [c[0] + ri * u[0], c[1] + ri * u[1]];
1131    let f = [c[0] + (ri + re) * u[0], c[1] + (ri + re) * u[1]]; // the upper flank's centre
1132    // The upper flank: circle (f, re) from t_up outward. The tooth after the gap
1133    // is centred on the line at angle tau / 2 (built frame).
1134    let half = tau / 2.0;
1135    let a_t = (t_up[1] - f[1]).atan2(t_up[0] - f[0]);
1136    // Walk the flank circle from t_up in the sense that moves away from the axis.
1137    let on_flank = |angle: f64| [f[0] + re * angle.cos(), f[1] + re * angle.sin()];
1138    let step = 1e-4;
1139    let sense = if radius_of(on_flank(a_t + step)) > radius_of(on_flank(a_t - step)) { 1.0 } else { -1.0 };
1140    // Find where the flank reaches the tip circle or the tooth centre line, whichever first.
1141    let reach = |angle: f64| {
1142        let q = on_flank(angle);
1143        (radius_of(q) >= ra, polar_angle(q) >= half)
1144    };
1145    let (mut lo, mut hi) = (0.0, PI / 2.0);
1146    if !(reach(a_t + sense * hi).0 || reach(a_t + sense * hi).1) {
1147        return Err(refuse("gear_input", "The sprocket flank does not reach the tip circle.".into()));
1148    }
1149    for _ in 0..200 {
1150        let mid = 0.5 * (lo + hi);
1151        let (tip, centre) = reach(a_t + sense * mid);
1152        if tip || centre { hi = mid } else { lo = mid }
1153    }
1154    let a_end = a_t + sense * hi;
1155    let end = on_flank(a_end);
1156    let pointed = polar_angle(end) >= half - 1e-12 || radius_of(end) < ra - 1e-9 * p;
1157    let (a_end, end) = if pointed {
1158        // Land exactly on the tooth centre line.
1159        let (mut lo, mut hi) = (0.0, hi);
1160        for _ in 0..200 {
1161            let mid = 0.5 * (lo + hi);
1162            if polar_angle(on_flank(a_t + sense * mid)) >= half { hi = mid } else { lo = mid }
1163        }
1164        let a = a_t + sense * hi;
1165        (a, on_flank(a))
1166    } else {
1167        (a_end, end)
1168    };
1169    let flank_arc = |from: f64, to: f64| -> Result<NurbsCurve, KernelRefusal> {
1170        if to > from { centred_arc(f, re, from, to) } else { centred_arc(f, re, to, from)?.reversed().map_err(|e| refuse("gear_arc", e)) }
1171    };
1172    let upper = flank_arc(a_t, a_end)?; // t_up -> end
1173    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
1174    let lower = mirrored(&upper).reversed().map_err(|e| refuse("gear_arc", e))?; // end' -> t_down
1175    let mut gap: Vec<(&'static str, NurbsCurve)> = vec![("A", lower), ("S", seat), ("C", upper)];
1176    let tip_angle = polar_angle(end);
1177    if !pointed {
1178        gap.push(("K", arc(ra, tip_angle, tau - tip_angle)?));
1179    }
1180    let mut curves = Vec::with_capacity(gap.len() * sprocket.teeth);
1181    for index in 0..sprocket.teeth {
1182        let angle = tau * index as f64 + half;
1183        for (role, curve) in &gap {
1184            curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
1185        }
1186    }
1187    snap_junctions(&mut curves);
1188    let data = GearData {
1189        pitch_diameter: d,
1190        tip_diameter: if pointed { 2.0 * radius_of(end) } else { da },
1191        root_diameter: d - 2.0 * ri,
1192        ..GearData::default()
1193    };
1194    Ok(GearSection { curves, data })
1195}
1196
1197/// A sprocket solid: the section extruded along +z by the width; names as
1198/// [`sprocket_section`], then `F` and `B`.
1199pub fn sprocket_solid(sprocket: &Sprocket) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
1200    let section = sprocket_section(sprocket)?;
1201    let solid = extrude_section(&section, sprocket.width)?;
1202    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
1203    names.push("F".into());
1204    names.push("B".into());
1205    Ok((solid, names, section.data))
1206}
1207
1208/// The turn of a twisted prism's section along its height: `theta(t)` at
1209/// `t = z / width` in [0, 1], with an optional crease at `t = 1/2` (a
1210/// herringbone's apex).
1211#[derive(Clone, Copy, Debug)]
1212pub enum Twist {
1213    /// theta = turn · t (a helical gear: a screw motion).
1214    Helical { turn: f64 },
1215    /// theta = turn · (1/2 − |t − 1/2|): out by `turn / 2` to the middle and back.
1216    Herringbone { turn: f64 },
1217}
1218
1219impl Twist {
1220    fn angle(&self, t: f64) -> f64 {
1221        match *self {
1222            Twist::Helical { turn } => turn * t,
1223            Twist::Herringbone { turn } => turn * (0.5 - (t - 0.5).abs()),
1224        }
1225    }
1226
1227    fn rate(&self, t: f64, after_crease: bool) -> f64 {
1228        match *self {
1229            Twist::Helical { turn } => turn,
1230            Twist::Herringbone { turn } => {
1231                if t < 0.5 || (t == 0.5 && !after_crease) { turn } else { -turn }
1232            }
1233        }
1234    }
1235
1236    fn total_turn(&self) -> f64 {
1237        match *self {
1238            Twist::Helical { turn } => turn.abs(),
1239            Twist::Herringbone { turn } => turn.abs(),
1240        }
1241    }
1242}
1243
1244/// The axial basis of a twisted prism: cubic Hermite spans in t carrying
1245/// (cos theta, sin theta, t), with doubled interior knots (C1) and a tripled
1246/// knot at a crease. Returns (knots, per control point (cos, sin, t)).
1247fn twist_basis(twist: Twist, reach: f64, tolerance: f64) -> Result<(Vec<f64>, Vec<[f64; 3]>), KernelRefusal> {
1248    let crease = matches!(twist, Twist::Herringbone { .. });
1249    // Hermite cubic error of cos/sin over a span of turn d: about reach · d^4 / 384.
1250    let per = (384.0 * tolerance / reach.max(1e-12)).powf(0.25);
1251    let needed = twist.total_turn() / per;
1252    if !(needed <= 4096.0) {
1253        return Err(refuse(
1254            "twist_too_long",
1255            format!(
1256                "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).",
1257                twist.total_turn() / TAU,
1258                4096.0 * per / TAU
1259            ),
1260        ));
1261    }
1262    let mut spans = (needed.ceil() as usize).max(1);
1263    if crease && spans % 2 == 1 {
1264        spans += 1;
1265    }
1266    let value = |t: f64| {
1267        let a = twist.angle(t);
1268        [a.cos(), a.sin(), t]
1269    };
1270    let slope = |t: f64, after: bool| {
1271        let a = twist.angle(t);
1272        let r = twist.rate(t, after);
1273        [-a.sin() * r, a.cos() * r, 1.0]
1274    };
1275    let mut knots = vec![0.0; 4];
1276    let mut points = vec![value(0.0)];
1277    for index in 0..spans {
1278        let (t0, t1) = (index as f64 / spans as f64, (index + 1) as f64 / spans as f64);
1279        let h = (t1 - t0) / 3.0;
1280        let (p0, p1) = (value(t0), value(t1));
1281        let (d0, d1) = (slope(t0, true), slope(t1, false));
1282        points.push([p0[0] + d0[0] * h, p0[1] + d0[1] * h, p0[2] + d0[2] * h]);
1283        points.push([p1[0] - d1[0] * h, p1[1] - d1[1] * h, p1[2] - d1[2] * h]);
1284        let last = index + 1 == spans;
1285        let at_crease = crease && 2 * (index + 1) == spans;
1286        if last {
1287            points.push(p1);
1288        } else if at_crease {
1289            points.push(p1);
1290            knots.extend([t1, t1, t1]);
1291        } else {
1292            knots.extend([t1, t1]);
1293        }
1294    }
1295    knots.extend([1.0; 4]);
1296    Ok((knots, points))
1297}
1298
1299/// Carry a section curve along the twist: the curve turned by theta and lifted
1300
1301
1302/// A counter-clockwise section (z = 0) carried up to z = width while turning
1303/// by `twist`: side faces in section order, then the face at z = 0, then the
1304/// face at z = width (exactly the section turned by the end angle).
1305pub fn twisted_prism(section: &GearSection, width: f64, twist: Twist, tolerance: f64) -> Result<BrepSolid, KernelRefusal> {
1306    if !(width > 0.0) {
1307        return Err(refuse("gear_input", format!("The face width must be greater than zero (it is {width}).")));
1308    }
1309    let reach = section
1310        .curves
1311        .iter()
1312        .flat_map(|c| c.curve.control_points.iter())
1313        .map(|p| (p.x / p.w).hypot(p.y / p.w))
1314        .fold(0.0, f64::max);
1315    let (knots_v, basis) = twist_basis(twist, reach, tolerance)?;
1316    let rows = |p: Vec4| -> Vec<Vec4> {
1317        basis.iter().map(|[c, s, t]| Vec4 { x: c * p.x - s * p.y, y: s * p.x + c * p.y, z: p.z + p.w * t * width, w: p.w }).collect()
1318    };
1319    prism_by_rows(section, 3, &knots_v, &rows)
1320}
1321
1322/// The section's largest distance from the z axis, read off the curves (a rational arc's middle control
1323/// point lies outside the arc).
1324fn section_reach(section: &GearSection) -> Result<f64, KernelRefusal> {
1325    let mut reach: f64 = 0.0;
1326    for piece in &section.curves {
1327        let [t0, t1] = piece.curve.domain().map_err(|e| refuse("gear_domain", e))?;
1328        for i in 0..=32 {
1329            let p = piece.curve.evaluate(t0 + (t1 - t0) * i as f64 / 32.0).map_err(|e| refuse("gear_eval", e))?;
1330            reach = reach.max(p.x.hypot(p.y));
1331        }
1332    }
1333    Ok(reach)
1334}
1335
1336/// A cylinder of `radius` and `height` with the counter-clockwise planar section (in z = z0, read off the
1337/// section) carried through it by `rows` (as [`prism_by_rows`] carries it; the last row planar at z0 + `height`)
1338/// taken out:
1339/// a ring gear or a spline hub, built directly rather than as a boolean. The section's faces are named by
1340/// their role (`R3`, `G0`, …), the cylinder `OD`, the face at z = 0 `F` and the face at z = `height` `B`.
1341pub fn hollow_prism(section: &GearSection, radius: f64, height: f64, degree_v: usize, knots_v: &[f64], rows: &dyn Fn(Vec4) -> Vec<Vec4>) -> Result<BrepSolid, KernelRefusal> {
1342    use crate::sweep_topology::{curve_to_plane_parameters, make_plane, parameter_line};
1343    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));
1344    let point_of = |p: Vec4| Vec3::new(p.x / p.w, p.y / p.w, p.z / p.w);
1345    if !(height > 0.0 && radius.is_finite() && radius > section_reach(section)? * (1.0 + 1e-9)) {
1346        return Err(refuse("gear_input", format!("The ring's outside radius ({radius}) must clear its section and its height ({height}) be positive.")));
1347    }
1348    let count = section.curves.len();
1349    let z0 = section.curves.first().map(|c| c.curve.control_points[0]).map(|p| p.z / p.w).unwrap_or(0.0);
1350    let mut shell = ShellBuilder { vertices: Vec::new(), edges: Vec::new(), faces: Vec::new(), next: 0 };
1351    // The walls: junction j starts curve j at the bottom and the top, joined by its v-curve.
1352    let mut bottom_v = Vec::with_capacity(count);
1353    let mut top_v = Vec::with_capacity(count);
1354    let mut axial = Vec::with_capacity(count);
1355    for piece in &section.curves {
1356        let start = piece.curve.control_points[0];
1357        let unit = Vec4 { x: start.x / start.w, y: start.y / start.w, z: start.z / start.w, w: 1.0 };
1358        let row = rows(unit);
1359        let (b, t) = (shell.vertex(point_of(start)), shell.vertex(point_of(*row.last().expect("a row"))));
1360        let curve = NurbsCurve::new(degree_v, knots_v.to_vec(), row).map_err(|e| refuse("gear_edge", e))?;
1361        axial.push(shell.edge(curve, b, t)?);
1362        bottom_v.push(b);
1363        top_v.push(t);
1364    }
1365    let mut bottom_e = Vec::with_capacity(count);
1366    let mut top_e = Vec::with_capacity(count);
1367    for (index, piece) in section.curves.iter().enumerate() {
1368        let next = (index + 1) % count;
1369        let top = NurbsCurve::new(piece.curve.degree, piece.curve.knots.clone(), piece.curve.control_points.iter().map(|p| *rows(*p).last().expect("a row")).collect()).map_err(|e| refuse("gear_curve", e))?;
1370        bottom_e.push(shell.edge(piece.curve.clone(), bottom_v[index], bottom_v[next])?);
1371        top_e.push(shell.edge(top, top_v[index], top_v[next])?);
1372    }
1373    for (index, piece) in section.curves.iter().enumerate() {
1374        let next = (index + 1) % count;
1375        let [u0, u1] = piece.curve.domain().map_err(|e| refuse("gear_domain", e))?;
1376        let grid: Vec<Vec<Vec4>> = piece.curve.control_points.iter().map(|p| rows(*p)).collect();
1377        let surface = NurbsSurface::new(piece.curve.degree, degree_v, piece.curve.knots.clone(), knots_v.to_vec(), grid).map_err(|e| refuse("gear_surface", e))?;
1378        let loops = vec![vec![
1379            (bottom_e[index], true, line([u0, 0.0], [u1, 0.0])?),
1380            (axial[next], true, line([u1, 0.0], [u1, 1.0])?),
1381            (top_e[index], false, line([u0, 1.0], [u1, 1.0])?),
1382            (axial[index], false, line([u0, 0.0], [u0, 1.0])?),
1383        ]];
1384        // The section's outward normal points into the hole: the solid lies outside it.
1385        shell.face(surface, false, loops, piece.suffix())?;
1386    }
1387    // The outside cylinder, one face with a seam at angle 0.
1388    let circle = crate::make_arc(Vec3::new(0.0, 0.0, z0), Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0), radius, 0.0, TAU).map_err(|e| refuse("gear_arc", e))?;
1389    let lifted = translated(&circle, height);
1390    let (b0, t0) = (shell.vertex(Vec3::new(radius, 0.0, z0)), shell.vertex(Vec3::new(radius, 0.0, z0 + height)));
1391    let bottom_circle = shell.edge(circle.clone(), b0, b0)?;
1392    let top_circle = shell.edge(lifted.clone(), t0, t0)?;
1393    let seam = shell.edge(crate::make_line(Vec3::new(radius, 0.0, z0), Vec3::new(radius, 0.0, z0 + height)).map_err(|e| refuse("gear_edge", e))?, b0, t0)?;
1394    let side = crate::make_extrusion(&circle, Vec3::new(0.0, 0.0, height)).map_err(|e| refuse("gear_surface", e))?;
1395    let [c0, c1] = circle.domain().map_err(|e| refuse("gear_domain", e))?;
1396    let loops = vec![vec![
1397        (bottom_circle, true, line([c0, 0.0], [c1, 0.0])?),
1398        (seam, true, line([c1, 0.0], [c1, 1.0])?),
1399        (top_circle, false, line([c0, 1.0], [c1, 1.0])?),
1400        (seam, false, line([c0, 0.0], [c0, 1.0])?),
1401    ]];
1402    shell.face(side, true, loops, "OD".into())?;
1403    // The two ends: the outer circle round the section's hole.
1404    let pad = radius * 1.1 + 1.0;
1405    let x_axis = Vec3::new(1.0, 0.0, 0.0);
1406    let y_axis = Vec3::new(0.0, 1.0, 0.0);
1407    for (z, name, ring_edge, hole) in [(z0, "F", bottom_circle, &bottom_e), (z0 + height, "B", top_circle, &top_e)] {
1408        let origin = Vec3::new(-pad, -pad, z);
1409        let on_plane = |curve: &NurbsCurve| curve_to_plane_parameters(curve, origin, x_axis, y_axis).map_err(|e| refuse("gear_pcurve", e));
1410        let outer = vec![(ring_edge, true, on_plane(shell.curve(ring_edge))?)];
1411        let mut inner = Vec::with_capacity(count);
1412        for &edge in hole.iter() {
1413            inner.push((edge, true, on_plane(shell.curve(edge))?));
1414        }
1415        let plane = make_plane(origin, x_axis, y_axis, 2.0 * pad, 2.0 * pad).map_err(|e| refuse("gear_plane", e))?;
1416        shell.face(plane, name == "B", vec![outer, inner], name.into())?;
1417    }
1418    let id = shell.id();
1419    let shell_id = shell.id();
1420    let solid = BrepSolid {
1421        mass_properties_cache: Default::default(),
1422        cells: Default::default(),
1423        id,
1424        vertices: shell.vertices,
1425        edges: shell.edges,
1426        shells: vec![crate::sweep_topology::ShellRecord { id: shell_id, faces: shell.faces }],
1427        genus: 1,
1428        kind: crate::BodyKind::Solid,
1429    };
1430    let issues = solid.validate();
1431    if !issues.is_empty() {
1432        return Err(KernelRefusal::internal(KernelStage::Validate, "validate", format!("hollow gear prism is not valid: {issues:?}")));
1433    }
1434    Ok(solid)
1435}
1436
1437/// A planar counter-clockwise section (in a plane z = const) carried along
1438/// v in [0, 1] by `rows`, which maps each homogeneous control point to the
1439/// control points of its v-curve (degree `degree_v` on `knots_v`); the last
1440/// row must again be planar at a constant z (the top cap). Side faces in
1441/// section order, then the face at v = 0, then the face at v = 1.
1442pub fn prism_by_rows(section: &GearSection, degree_v: usize, knots_v: &[f64], rows: &dyn Fn(Vec4) -> Vec<Vec4>) -> Result<BrepSolid, KernelRefusal> {
1443    use crate::sweep_topology::{curve_to_plane_parameters, make_plane, parameter_line, CoedgeRecord, EdgeRecord, FaceRecord, LoopRecord, ShellRecord, VertexRecord};
1444    let curves: Vec<NurbsCurve> = section.curves.iter().map(|piece| piece.curve.clone()).collect();
1445    let count = curves.len();
1446    let top_of = |curve: &NurbsCurve| -> Result<NurbsCurve, KernelRefusal> {
1447        let points = curve.control_points.iter().map(|p| *rows(*p).last().expect("a row")).collect();
1448        NurbsCurve::new(curve.degree, curve.knots.clone(), points).map_err(|e| refuse("gear_curve", e))
1449    };
1450    let point_of = |p: Vec4| Vec3::new(p.x / p.w, p.y / p.w, p.z / p.w);
1451    let unit = |p: Vec4| Vec4 { x: p.x / p.w, y: p.y / p.w, z: p.z / p.w, w: 1.0 };
1452    let starts: Vec<Vec4> = curves.iter().map(|c| c.control_points[0]).collect();
1453    let mut vertices = Vec::with_capacity(2 * count);
1454    for (index, start) in starts.iter().enumerate() {
1455        vertices.push(VertexRecord { id: index as u64 + 1, point: point_of(*start) });
1456    }
1457    for (index, start) in starts.iter().enumerate() {
1458        vertices.push(VertexRecord { id: (count + index) as u64 + 1, point: point_of(*rows(unit(*start)).last().expect("a row")) });
1459    }
1460    let edge_id = |kind: usize, index: usize| 10 + (kind * count + index) as u64;
1461    let mut edges = Vec::with_capacity(3 * count);
1462    let mut tops = Vec::with_capacity(count);
1463    for (index, curve) in curves.iter().enumerate() {
1464        let [start, end] = curve.domain().map_err(|e| refuse("gear_domain", e))?;
1465        let next = (index + 1) % count;
1466        let top = top_of(curve)?;
1467        let axial = NurbsCurve::new(degree_v, knots_v.to_vec(), rows(unit(starts[index]))).map_err(|e| refuse("gear_edge", e))?;
1468        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 });
1469        edges.push(EdgeRecord { id: edge_id(1, index), curve: top.clone(), t0: start, t1: end, start_vertex_id: (count + index) as u64 + 1, end_vertex_id: (count + next) as u64 + 1, degenerate: false, name: None });
1470        edges.push(EdgeRecord { id: edge_id(2, index), curve: axial, t0: 0.0, t1: 1.0, start_vertex_id: index as u64 + 1, end_vertex_id: (count + index) as u64 + 1, degenerate: false, name: None });
1471        tops.push(top);
1472    }
1473    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));
1474    let mut next_id = 10 + 3 * count as u64 + 1000;
1475    let mut faces = Vec::with_capacity(count + 2);
1476    for (index, curve) in curves.iter().enumerate() {
1477        let [start, end] = curve.domain().map_err(|e| refuse("gear_domain", e))?;
1478        let next = (index + 1) % count;
1479        let coedges = vec![
1480            CoedgeRecord { id: next_id, edge_id: edge_id(0, index), forward: true, pcurve: line([start, 0.0], [end, 0.0])? },
1481            CoedgeRecord { id: next_id + 1, edge_id: edge_id(2, next), forward: true, pcurve: line([end, 0.0], [end, 1.0])? },
1482            CoedgeRecord { id: next_id + 2, edge_id: edge_id(1, index), forward: false, pcurve: line([end, 1.0], [start, 1.0])? },
1483            CoedgeRecord { id: next_id + 3, edge_id: edge_id(2, index), forward: false, pcurve: line([start, 1.0], [start, 0.0])? },
1484        ];
1485        next_id += 4;
1486        let surface_rows: Vec<Vec<Vec4>> = curve.control_points.iter().map(|p| rows(*p)).collect();
1487        let surface = NurbsSurface::new(curve.degree, degree_v, curve.knots.clone(), knots_v.to_vec(), surface_rows).map_err(|e| refuse("gear_surface", e))?;
1488        faces.push(FaceRecord { id: next_id + 1, surface, same_sense: true, loops: vec![LoopRecord { id: next_id, coedges }], name: None });
1489        next_id += 2;
1490    }
1491    let reach = curves.iter().chain(tops.iter()).flat_map(|c| c.control_points.iter()).map(|p| (p.x / p.w).hypot(p.y / p.w)).fold(0.0, f64::max);
1492    let pad = reach * 1.1 + 1.0;
1493    let x_axis = Vec3::new(1.0, 0.0, 0.0);
1494    let y_axis = Vec3::new(0.0, 1.0, 0.0);
1495    let z0 = vertices[0].point.z;
1496    let z1 = vertices[count].point.z;
1497    let bottom_origin = Vec3::new(-pad, -pad, z0);
1498    let mut bottom = Vec::with_capacity(count);
1499    for index in (0..count).rev() {
1500        bottom.push(CoedgeRecord {
1501            id: next_id,
1502            edge_id: edge_id(0, index),
1503            forward: false,
1504            pcurve: curve_to_plane_parameters(&curves[index], bottom_origin, x_axis, y_axis).and_then(|c| c.reversed()).map_err(|e| refuse("gear_pcurve", e))?,
1505        });
1506        next_id += 1;
1507    }
1508    faces.push(FaceRecord {
1509        id: next_id + 1,
1510        surface: make_plane(bottom_origin, x_axis, y_axis, 2.0 * pad, 2.0 * pad).map_err(|e| refuse("gear_plane", e))?,
1511        same_sense: false,
1512        loops: vec![LoopRecord { id: next_id, coedges: bottom }],
1513        name: None,
1514    });
1515    next_id += 2;
1516    let top_origin = Vec3::new(-pad, -pad, z1);
1517    let mut top = Vec::with_capacity(count);
1518    for (index, curve) in tops.iter().enumerate() {
1519        top.push(CoedgeRecord {
1520            id: next_id,
1521            edge_id: edge_id(1, index),
1522            forward: true,
1523            pcurve: curve_to_plane_parameters(curve, top_origin, x_axis, y_axis).map_err(|e| refuse("gear_pcurve", e))?,
1524        });
1525        next_id += 1;
1526    }
1527    faces.push(FaceRecord {
1528        id: next_id + 1,
1529        surface: make_plane(top_origin, x_axis, y_axis, 2.0 * pad, 2.0 * pad).map_err(|e| refuse("gear_plane", e))?,
1530        same_sense: true,
1531        loops: vec![LoopRecord { id: next_id, coedges: top }],
1532        name: None,
1533    });
1534    next_id += 2;
1535    let solid = BrepSolid {
1536        mass_properties_cache: Default::default(),
1537        cells: Default::default(),
1538        id: next_id + 1,
1539        vertices,
1540        edges,
1541        shells: vec![ShellRecord { id: next_id, faces }],
1542        genus: 0,
1543        kind: crate::BodyKind::Solid,
1544    };
1545    let issues = solid.validate();
1546    if issues.is_empty() {
1547        Ok(solid)
1548    } else {
1549        Err(KernelRefusal::internal(KernelStage::Validate, "validate", format!("gear prism is not valid: {issues:?}")))
1550    }
1551}
1552
1553/// Hand of a helical gear's teeth.
1554#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1555pub enum Hand {
1556    Right,
1557    Left,
1558}
1559
1560/// A helical (or, with `herringbone`, double helical) external gear given by
1561/// its normal-section values; `spur` carries them (module = normal module,
1562/// pressure angle = normal pressure angle, coefficients × normal module).
1563#[derive(Clone, Debug)]
1564pub struct HelicalGear {
1565    pub spur: SpurGear,
1566    pub helix_angle: f64,
1567    pub hand: Hand,
1568    pub herringbone: bool,
1569}
1570
1571/// The transverse spur gear a helical gear's every section is (turned).
1572pub fn helical_transverse(gear: &HelicalGear) -> Result<SpurGear, KernelRefusal> {
1573    let beta = gear.helix_angle;
1574    // The pressure angle limits apply to the normal section (the cutter's).
1575    let normal = gear.spur.pressure_angle.to_degrees();
1576    if !(10.0 - 1e-9..=35.0 + 1e-9).contains(&normal) {
1577        return Err(refuse("gear_input", format!("The normal pressure angle must be between 10° and 35° (it is {normal}°).")));
1578    }
1579    if !(beta.to_degrees() >= 0.5 - 1e-9 && beta.to_degrees() <= 45.0 + 1e-9) {
1580        return Err(refuse("bad_helix", format!("The helix angle must be between 0.5° and 45° (it is {:.4}°).", beta.to_degrees())));
1581    }
1582    let n = &gear.spur;
1583    let c = beta.cos();
1584    Ok(SpurGear {
1585        module: n.module / c,
1586        teeth: n.teeth,
1587        pressure_angle: (n.pressure_angle.tan() / c).atan(),
1588        profile_shift: n.profile_shift * c,
1589        addendum: n.addendum * c,
1590        dedendum: n.dedendum * c,
1591        // The cutter's tip radius in the transverse section is taken as the
1592        // normal one (the true section of the round is a slightly longer ellipse).
1593        root_fillet: n.root_fillet * c,
1594        backlash: n.backlash,
1595        face_width: n.face_width,
1596    })
1597}
1598
1599/// A helical or herringbone gear solid; names as [`spur_solid`].
1600pub fn helical_solid(gear: &HelicalGear) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
1601    let transverse = helical_transverse(gear)?;
1602    let section = transverse_section(&transverse)?;
1603    let r = transverse.module * transverse.teeth as f64 / 2.0;
1604    let width = transverse.face_width;
1605    let sign = if gear.hand == Hand::Right { 1.0 } else { -1.0 };
1606    let twist = if gear.herringbone {
1607        // Each half advances by its own half width.
1608        Twist::Herringbone { turn: sign * width * gear.helix_angle.tan() / r }
1609    } else {
1610        Twist::Helical { turn: sign * width * gear.helix_angle.tan() / r }
1611    };
1612    let solid = twisted_prism(&section, width, twist, 0.1 * GEAR_FIT_TOLERANCE * transverse.module)?;
1613    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
1614    names.push("F".into());
1615    names.push("B".into());
1616    Ok((solid, names, section.data))
1617}
1618
1619/// A straight-sided spline (ISO 14 form: `teeth` keys of width `key_width`
1620/// between the minor diameter `minor` and the major diameter `major`).
1621#[derive(Clone, Debug)]
1622pub struct StraightSpline {
1623    pub teeth: usize,
1624    pub minor: f64,
1625    pub major: f64,
1626    pub key_width: f64,
1627    pub length: f64,
1628}
1629
1630fn check_straight_spline(spline: &StraightSpline) -> Result<(), KernelRefusal> {
1631    let StraightSpline { teeth, minor, major, key_width, length } = *spline;
1632    if !(minor > 0.0 && major > minor && key_width > 0.0 && length > 0.0) {
1633        return Err(refuse(
1634            "gear_input",
1635            format!("A spline needs 0 < minor diameter ({minor}) < major diameter ({major}), a positive key width ({key_width}) and length ({length})."),
1636        ));
1637    }
1638    if teeth < 2 || teeth > 100 {
1639        return Err(refuse("gear_input", format!("A spline needs from 2 to 100 keys (it has {teeth}).")));
1640    }
1641    // The keys must not meet on the minor circle.
1642    let half_root = (key_width / minor).asin();
1643    if !(key_width < minor) || 2.0 * half_root >= TAU / teeth as f64 - 1e-9 {
1644        return Err(refuse("keys_overlap", format!("{teeth} keys {key_width} wide do not fit round a {minor} minor diameter.")));
1645    }
1646    Ok(())
1647}
1648
1649/// The section of a straight-sided spline shaft, counter-clockwise; exact
1650/// lines and arcs. Key k is centred on angle 2 pi k / N. Roles: `R<k>`/`L<k>`
1651/// its flanks, `K<k>` its top on the major circle, `G<k>` the root land after it.
1652pub fn straight_spline_section(spline: &StraightSpline) -> Result<GearSection, KernelRefusal> {
1653    check_straight_spline(spline)?;
1654    let (rr, ra, h) = (spline.minor / 2.0, spline.major / 2.0, spline.key_width / 2.0);
1655    let n = spline.teeth as f64;
1656    let foot = [(rr * rr - h * h).sqrt(), h];
1657    let top = [(ra * ra - h * h).sqrt(), h];
1658    let top_angle = (h / ra).asin();
1659    let foot_angle = (h / rr).asin();
1660    let key: Vec<(&'static str, NurbsCurve)> = vec![
1661        ("R", line([foot[0], -h], [top[0], -h])?),
1662        ("K", arc(ra, -top_angle, top_angle)?),
1663        ("L", line(top, foot)?),
1664        ("G", arc(rr, foot_angle, TAU / n - foot_angle)?),
1665    ];
1666    let mut curves = Vec::with_capacity(4 * spline.teeth);
1667    for index in 0..spline.teeth {
1668        let angle = TAU * index as f64 / n;
1669        for (role, curve) in &key {
1670            curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
1671        }
1672    }
1673    snap_junctions(&mut curves);
1674    Ok(GearSection { curves, data: GearData { tip_diameter: spline.major, root_diameter: spline.minor, ..GearData::default() } })
1675}
1676
1677/// A spline shaft: the section extruded along +z by the length; names as the
1678/// section's roles, then `F` and `B`.
1679pub fn straight_spline_shaft(spline: &StraightSpline) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
1680    let section = straight_spline_section(spline)?;
1681    let solid = extrude_section(&section, spline.length)?;
1682    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
1683    names.push("F".into());
1684    names.push("B".into());
1685    Ok((solid, names, section.data))
1686}
1687
1688/// Cut a counter-clockwise section through a cylinder of `outside` diameter
1689/// and `length`: a hub. The section's faces keep their role names, the
1690/// cylinder's are `OD`, `F` and `B` (all in `face.name`).
1691pub fn hub_from_section(section: &GearSection, outside: f64, length: f64) -> Result<BrepSolid, KernelRefusal> {
1692    // The section's true outer radius, read off the curves (a rational arc's
1693    // middle control point lies outside the arc).
1694    let mut reach: f64 = 0.0;
1695    for piece in &section.curves {
1696        let [t0, t1] = piece.curve.domain().map_err(|e| refuse("gear_domain", e))?;
1697        for i in 0..=32 {
1698            let p = piece.curve.evaluate(t0 + (t1 - t0) * i as f64 / 32.0).map_err(|e| refuse("gear_eval", e))?;
1699            reach = reach.max(p.x.hypot(p.y));
1700        }
1701    }
1702    if !(outside / 2.0 > reach + 1e-9) {
1703        return Err(refuse(
1704            "hub_too_small",
1705            format!("The hub's outside diameter ({outside}) must be larger than its spline's major diameter ({:.4}).", 2.0 * reach),
1706        ));
1707    }
1708    let rows = |p: Vec4| vec![p, Vec4 { x: p.x, y: p.y, z: p.z + p.w * length, w: p.w }];
1709    hollow_prism(section, outside / 2.0, length, 1, &[0.0, 0.0, 1.0, 1.0], &rows)
1710}
1711
1712/// A spline hub: the shaft's section (nominal size) cut through a cylinder.
1713pub fn straight_spline_hub(spline: &StraightSpline, outside: f64) -> Result<(BrepSolid, GearData), KernelRefusal> {
1714    let section = straight_spline_section(spline)?;
1715    let hub = hub_from_section(&section, outside, spline.length)?;
1716    Ok((hub, section.data))
1717}
1718
1719/// A timing-belt pulley with straight-sided grooves (ISO 5294 Table 2 form;
1720/// the metric trapezoidal profiles the same way): every curve a line or an arc.
1721#[derive(Clone, Debug)]
1722pub struct TimingPulley {
1723    /// Belt pitch.
1724    pub pitch: f64,
1725    pub teeth: usize,
1726    /// Pitch line differential 2a: outside diameter = pitch z / pi - 2a.
1727    pub pld: f64,
1728    /// Groove bottom width bw.
1729    pub bottom_width: f64,
1730    /// Groove depth hg (from the outside diameter).
1731    pub depth: f64,
1732    /// Groove side angle to the radial direction, each side (half of 2 beta).
1733    pub side_angle: f64,
1734    /// Bottom (root) corner radius rb.
1735    pub bottom_radius: f64,
1736    /// Top (tip) corner radius rt.
1737    pub top_radius: f64,
1738    pub width: f64,
1739}
1740
1741/// An arc about `centre` from `from` to `to` (both on it), counter-clockwise
1742/// when `ccw`, else clockwise.
1743fn arc_through(centre: [f64; 2], from: [f64; 2], to: [f64; 2], ccw: bool) -> Result<NurbsCurve, KernelRefusal> {
1744    let radius = (from[0] - centre[0]).hypot(from[1] - centre[1]);
1745    let a0 = (from[1] - centre[1]).atan2(from[0] - centre[0]);
1746    let a1 = (to[1] - centre[1]).atan2(to[0] - centre[0]);
1747    if ccw {
1748        let mut end = a1;
1749        while end <= a0 {
1750            end += TAU;
1751        }
1752        centred_arc(centre, radius, a0, end)
1753    } else {
1754        let mut start = a1;
1755        while start <= a0 - TAU {
1756            start += TAU;
1757        }
1758        while start >= a0 {
1759            start -= TAU;
1760        }
1761        centred_arc(centre, radius, start, a0)?.reversed().map_err(|e| refuse("gear_arc", e))
1762    }
1763}
1764
1765/// The pulley section, counter-clockwise. Groove k is centred on angle
1766/// 2 pi (k + 1/2) / z (tooth k on angle 2 pi k / z). Roles per groove k, in
1767/// order: `Q<k>` the top corner arc into it, `A<k>` its first side, `U<k>`
1768/// the bottom corner arc, `S<k>` the bottom, `D<k>` the other bottom corner
1769/// arc, `C<k>` the other side, `P<k>` the top corner arc out of it, `K<k>`
1770/// the land of the next tooth on the outside diameter.
1771pub fn timing_pulley_section(pulley: &TimingPulley) -> Result<GearSection, KernelRefusal> {
1772    let TimingPulley { pitch, teeth, pld, bottom_width, depth, side_angle, bottom_radius, top_radius, width } = pulley.clone();
1773    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) {
1774        return Err(refuse("gear_input", "The pulley's pitch, groove sizes and width must be positive.".into()));
1775    }
1776    if !(0.0..60f64.to_radians()).contains(&side_angle) {
1777        return Err(refuse("gear_input", "The groove side angle must be between 0° and 60°.".into()));
1778    }
1779    if teeth < 6 || teeth > 400 {
1780        return Err(refuse("gear_input", format!("A pulley needs from 6 to 400 teeth (it has {teeth}).")));
1781    }
1782    let z = teeth as f64;
1783    let ro = pitch * z / PI / 2.0 - pld / 2.0;
1784    let x_bottom = ro - depth;
1785    if !(x_bottom > 0.0) {
1786        return Err(refuse("gear_input", "The groove is deeper than the pulley's radius.".into()));
1787    }
1788    let tau = TAU / z;
1789    let (s, c) = side_angle.sin_cos();
1790    let side = [c, s]; // outward along the upper side
1791    let normal = [-s, c]; // from the upper side into the material
1792    let corner = [x_bottom, bottom_width / 2.0];
1793    // The upper side meets the outside circle at |corner + t side| = ro.
1794    let b = corner[0] * side[0] + corner[1] * side[1];
1795    let t_top = -b + (b * b - (corner[0] * corner[0] + corner[1] * corner[1] - ro * ro)).sqrt();
1796    let top = [corner[0] + t_top * side[0], corner[1] + t_top * side[1]];
1797    // Bottom corner fillet: between the bottom (direction +y) and the side; the
1798    // path turns right there (clockwise arc). Interior turn angle phi = 90° - beta.
1799    let turn = PI / 2.0 - side_angle;
1800    let reach_b = bottom_radius * (turn / 2.0).tan();
1801    let t1 = [corner[0], corner[1] - reach_b];
1802    let t2 = [corner[0] + reach_b * side[0], corner[1] + reach_b * side[1]];
1803    let centre_b = [t1[0] + bottom_radius, t1[1]];
1804    // Top corner fillet: tangent to the side (offset into the material) and
1805    // inside the outside circle (centre at ro - rt).
1806    let rt = top_radius;
1807    let base = [corner[0] + rt * normal[0], corner[1] + rt * normal[1]];
1808    let bb = base[0] * side[0] + base[1] * side[1];
1809    let disc = bb * bb - (base[0] * base[0] + base[1] * base[1] - (ro - rt) * (ro - rt));
1810    if disc < 0.0 {
1811        return Err(refuse("gear_input", "The groove's top radius does not fit.".into()));
1812    }
1813    let t_c = -bb + disc.sqrt();
1814    let centre_t = [base[0] + t_c * side[0], base[1] + t_c * side[1]];
1815    let t3 = [corner[0] + t_c * side[0], corner[1] + t_c * side[1]];
1816    let scale = ro / (centre_t[0].hypot(centre_t[1]));
1817    let t4 = [centre_t[0] * scale, centre_t[1] * scale];
1818    let land_start = polar_angle(t4);
1819    if land_start >= tau / 2.0 - 1e-9 || reach_b > t_c + 1e-12 || t1[1] < 0.0 {
1820        return Err(refuse(
1821            "groove_too_wide",
1822            format!("The grooves and their corner radii do not fit the pitch at {teeth} teeth; add teeth or reduce the radii."),
1823        ));
1824    }
1825    let _ = top;
1826    // The upper half of groove 0, outward: bottom half line, D, C, P.
1827    let mut upper: Vec<(&'static str, NurbsCurve)> = Vec::new();
1828    if bottom_radius > 0.0 {
1829        upper.push(("D", arc_through(centre_b, t1, t2, false)?));
1830    }
1831    upper.push(("C", line(t2, t3)?));
1832    if rt > 0.0 {
1833        upper.push(("P", arc_through(centre_t, t3, t4, true)?));
1834    }
1835    let mut groove: Vec<(&'static str, NurbsCurve)> = Vec::new();
1836    let lower_roles = |role: &'static str| match role {
1837        "D" => "U",
1838        "C" => "A",
1839        _ => "Q",
1840    };
1841    for (role, curve) in upper.iter().rev() {
1842        groove.push((lower_roles(role), mirrored(curve).reversed().map_err(|e| refuse("gear_arc", e))?));
1843    }
1844    groove.push(("S", line([t1[0], -t1[1]], t1)?));
1845    groove.extend(upper.into_iter());
1846    groove.push(("K", arc(ro, land_start, tau - land_start)?));
1847    let mut curves = Vec::with_capacity(groove.len() * teeth);
1848    for index in 0..teeth {
1849        let angle = tau * index as f64 + tau / 2.0;
1850        for (role, curve) in &groove {
1851            curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
1852        }
1853    }
1854    snap_junctions(&mut curves);
1855    let data = GearData { pitch_diameter: pitch * z / PI, tip_diameter: 2.0 * ro, root_diameter: 2.0 * x_bottom, ..GearData::default() };
1856    Ok(GearSection { curves, data })
1857}
1858
1859/// A straight beveloid (conical involute) gear: a spur gear whose profile shift grows linearly across the
1860/// face, `cone_angle` the angle its tip and root cones make with the axis. Every plane square to the axis is the
1861/// spur gear the standard rack generates at that plane's shift, so the flanks are involute helicoids (turning
1862/// opposite ways on the two sides) and the tip and root are cones; it meshes with spur, helical or beveloid
1863/// gears on parallel, crossed or skew axes and takes up backlash by sliding along its axis. `spur` is the gear
1864/// at z = 0 (its profile shift there) and its face width.
1865#[derive(Clone, Debug)]
1866pub struct BeveloidGear {
1867    pub spur: SpurGear,
1868    pub cone_angle: f64,
1869}
1870
1871/// A beveloid gear solid: plane sections skinned (planes added until the skin holds 1e-5 × module halfway
1872/// between them). Names as the spur gear's per tooth, then `F` (z = 0) and `B`.
1873pub fn beveloid_solid(gear: &BeveloidGear) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
1874    let base = &gear.spur;
1875    let m = base.module;
1876    let width = base.face_width;
1877    let degrees = gear.cone_angle.to_degrees();
1878    if !(degrees > 0.0 && degrees <= 20.0 + 1e-9) {
1879        return Err(refuse("gear_input", format!("The cone angle must be over 0° and at most 20° (it is {degrees}°).")));
1880    }
1881    if !(width > 0.0) {
1882        return Err(refuse("gear_input", "The face width must be positive.".into()));
1883    }
1884    let slope = gear.cone_angle.tan() / m;
1885    let at = |z: f64| -> Result<GearSection, KernelRefusal> { spur_section(&SpurGear { profile_shift: base.profile_shift + slope * z, ..base.clone() }) };
1886    let first = at(0.0)?;
1887    let roles: Vec<&'static str> = first.curves.iter().filter(|c| c.tooth == 0).map(|c| c.role).collect();
1888    let count = roles.len();
1889    // Tooth 0's pieces in a plane, each as a function of its normalised parameter.
1890    let pieces = |section: &GearSection| -> Result<Vec<NurbsCurve>, KernelRefusal> {
1891        let tooth: Vec<NurbsCurve> = section.curves.iter().filter(|c| c.tooth == 0).map(|c| c.curve.clone()).collect();
1892        let same: Vec<&'static str> = section.curves.iter().filter(|c| c.tooth == 0).map(|c| c.role).collect();
1893        if same != roles {
1894            return Err(refuse(
1895                "section_changes",
1896                "The tooth's form changes across the face (undercut or a pointed tip appears partway): lower the cone angle or narrow the face.".into(),
1897            ));
1898        }
1899        Ok(tooth)
1900    };
1901    let evaluate = |curve: &NurbsCurve, t: f64| -> [f64; 2] {
1902        let [a, b] = curve.domain().unwrap_or([0.0, 1.0]);
1903        let p = curve.evaluate_extended(a + (b - a) * t).unwrap_or(Vec3::new(f64::NAN, f64::NAN, 0.0));
1904        [p.x, p.y]
1905    };
1906    let tolerance = GEAR_FIT_TOLERANCE * m;
1907    let skin_tolerance = 1e-5 * m;
1908    let probes: Vec<Vec<NurbsCurve>> = [0.0, 0.5 * width, width].iter().map(|&z| at(z).and_then(|s| pieces(&s))).collect::<Result<_, _>>()?;
1909    let mut breaks: Vec<Vec<f64>> = Vec::with_capacity(count);
1910    for role in 0..count {
1911        let mut all: Vec<f64> = Vec::new();
1912        for probe in &probes {
1913            all.extend(adaptive_breaks(&|t| evaluate(&probe[role], t), tolerance)?);
1914        }
1915        all.sort_by(f64::total_cmp);
1916        all.dedup_by(|x, y| (*x - *y).abs() < 1e-12);
1917        breaks.push(all);
1918    }
1919    // Tooth 0's curves in the plane at height z, refitted on the shared breaks (so every plane's control points pair up).
1920    let refit = |z: f64| -> Result<(Vec<NurbsCurve>, f64), KernelRefusal> {
1921        let tooth = pieces(&at(z)?)?;
1922        let mut curves = Vec::with_capacity(count);
1923        let mut worst = 0.0_f64;
1924        for (role, role_breaks) in breaks.iter().enumerate() {
1925            let (mut curve, error) = fit_on_breaks(&|t| evaluate(&tooth[role], t), role_breaks)?;
1926            worst = worst.max(error);
1927            for p in &mut curve.control_points {
1928                p.z = z * p.w;
1929            }
1930            curves.push(curve);
1931        }
1932        Ok((curves, worst))
1933    };
1934    let teeth = base.teeth;
1935    let tau = TAU / teeth as f64;
1936    let mut planes = 4usize;
1937    loop {
1938        let step = width / planes as f64;
1939        let delta = 1e-3 * step.min(m);
1940        let mut rows: Vec<Vec<NurbsCurve>> = Vec::with_capacity(planes + 1);
1941        let mut slopes: Vec<Vec<Vec<[f64; 2]>>> = Vec::with_capacity(planes + 1);
1942        for j in 0..=planes {
1943            let z = step * j as f64;
1944            let (tooth, worst) = refit(z)?;
1945            if worst > 2.0 * tolerance {
1946                return Err(refuse("gear_fit", format!("The beveloid's sections could not be fitted on shared breaks ({worst:.2e}).")));
1947            }
1948            let lo = refit(z - delta)?.0;
1949            let hi = refit(z + delta)?.0;
1950            let slope: Vec<Vec<[f64; 2]>> = lo
1951                .iter()
1952                .zip(&hi)
1953                .map(|(l, h)| l.control_points.iter().zip(&h.control_points).map(|(p, q)| [(q.x - p.x) / (2.0 * delta), (q.y - p.y) / (2.0 * delta)]).collect())
1954                .collect();
1955            rows.push(tooth);
1956            slopes.push(slope);
1957        }
1958        let mut worst = 0.0_f64;
1959        for j in 0..planes {
1960            let exact = refit(step * (j as f64 + 0.5))?.0;
1961            for role in 0..count {
1962                for (k, p) in exact[role].control_points.iter().enumerate() {
1963                    let (p0, p1) = (rows[j][role].control_points[k], rows[j + 1][role].control_points[k]);
1964                    let (d0, d1) = (slopes[j][role][k], slopes[j + 1][role][k]);
1965                    let x = 0.5 * (p0.x + p1.x) + step * (d0[0] - d1[0]) / 8.0;
1966                    let y = 0.5 * (p0.y + p1.y) + step * (d0[1] - d1[1]) / 8.0;
1967                    worst = worst.max((x - p.x).hypot(y - p.y));
1968                }
1969            }
1970        }
1971        if worst > skin_tolerance {
1972            if planes >= 256 {
1973                return Err(refuse("gear_fit", format!("The beveloid's flanks could not be skinned within {skin_tolerance:.2e} ({worst:.2e}).")));
1974            }
1975            let factor = (1.15 * (worst / skin_tolerance).powf(0.25)).max(2.0);
1976            planes = (planes as f64 * factor).ceil().min(256.0) as usize;
1977            continue;
1978        }
1979        // The full section from tooth 0's curves at z = 0, junctions shared; every tooth's rows tooth 0's turned.
1980        let mut section_curves: Vec<SectionCurve> = Vec::with_capacity(count * teeth);
1981        for index in 0..teeth {
1982            for (role, curve) in rows[0].iter().enumerate() {
1983                section_curves.push(SectionCurve { curve: rotated(curve, tau * index as f64), role: roles[role], tooth: index });
1984            }
1985        }
1986        snap_junctions(&mut section_curves);
1987        let mut table: std::collections::HashMap<[u64; 4], Vec<Vec4>> = std::collections::HashMap::new();
1988        let h = 1.0 / planes as f64;
1989        for (index, piece) in section_curves.iter().enumerate() {
1990            let (role, tooth) = (index % count, index / count);
1991            let (s, cs) = (tau * tooth as f64).sin_cos();
1992            for (k, p) in piece.curve.control_points.iter().enumerate() {
1993                let mut row = Vec::with_capacity(2 * planes + 2);
1994                for j in 0..=planes {
1995                    let q = if j == 0 { *p } else { let r = rows[j][role].control_points[k]; Vec4 { x: cs * r.x - s * r.y, y: s * r.x + cs * r.y, z: r.z, w: r.w } };
1996                    let d = slopes[j][role][k];
1997                    let dv = [width * (cs * d[0] - s * d[1]), width * (s * d[0] + cs * d[1]), width];
1998                    let point = Vec3::new(q.x, q.y, q.z);
1999                    if j > 0 {
2000                        row.push(Vec4::from_point(Vec3::new(point.x - dv[0] * h / 3.0, point.y - dv[1] * h / 3.0, point.z - dv[2] * h / 3.0), 1.0));
2001                    }
2002                    if j == 0 || j == planes {
2003                        row.push(Vec4::from_point(point, 1.0));
2004                    }
2005                    if j < planes {
2006                        row.push(Vec4::from_point(Vec3::new(point.x + dv[0] * h / 3.0, point.y + dv[1] * h / 3.0, point.z + dv[2] * h / 3.0), 1.0));
2007                    }
2008                }
2009                table.insert([p.x.to_bits(), p.y.to_bits(), p.z.to_bits(), p.w.to_bits()], row);
2010            }
2011        }
2012        let mut knots_v = vec![0.0; 4];
2013        for j in 1..planes {
2014            let v = j as f64 * h;
2015            knots_v.extend([v, v]);
2016        }
2017        knots_v.extend([1.0; 4]);
2018        let section = GearSection { curves: section_curves, data: GearData::default() };
2019        let solid = prism_by_rows(&section, 3, &knots_v, &|p: Vec4| {
2020            table.get(&[p.x.to_bits(), p.y.to_bits(), p.z.to_bits(), p.w.to_bits()]).cloned().expect("a row for every section control point")
2021        })?;
2022        let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
2023        names.push("F".into());
2024        names.push("B".into());
2025        return Ok((solid, names, first.data));
2026    }
2027}
2028
2029/// A star (pin) wheel: the wheel that drives a lantern pinion, as in clocks and mills. Its teeth are cut
2030/// for the pinion's round pins: above the pitch circle each flank is the curve parallel, at the pin radius, to
2031/// the epicycloid the pin's centre traces relative to the wheel (the pinion's pitch circle rolling on the
2032/// wheel's), so the pins roll on the flanks; below it the tooth space has straight walls the pin's width apart
2033/// and a round root clear of the pins. Module m: wheel pitch radius m × teeth / 2, the pinion's m × pins / 2.
2034/// Tooth space 0 is centred on +x.
2035#[derive(Clone, Debug)]
2036pub struct StarWheel {
2037    pub module: f64,
2038    pub teeth: usize,
2039    /// Pins of the mating lantern pinion.
2040    pub pinion_pins: usize,
2041    pub pin_diameter: f64,
2042    /// Tip height above the pitch circle × module; 0 takes 92% of the height where the flanks meet.
2043    pub addendum: f64,
2044    /// Root clearance below the pins, × module.
2045    pub clearance: f64,
2046    pub backlash: f64,
2047    pub face_width: f64,
2048}
2049
2050/// The star wheel's section (counter-clockwise; per tooth `V` the +θ space wall, `R` its flank, `K` the tip,
2051/// `L`/`W` the next space's flank and wall, `G` that space's root).
2052pub fn star_wheel_section(wheel: &StarWheel) -> Result<GearSection, KernelRefusal> {
2053    let m = wheel.module;
2054    if !(m > 0.0 && wheel.pin_diameter > 0.0 && wheel.face_width > 0.0 && wheel.addendum >= 0.0 && wheel.clearance >= 0.0 && wheel.backlash >= 0.0) {
2055        return Err(refuse("gear_input", "The module, pin diameter and face width must be positive; the addendum, clearance and backlash not negative.".into()));
2056    }
2057    if !(6..=1000).contains(&wheel.teeth) || !(3..=200).contains(&wheel.pinion_pins) {
2058        return Err(refuse("gear_input", format!("A star wheel needs 6 to 1000 teeth and a pinion of 3 to 200 pins (it has {} and {}).", wheel.teeth, wheel.pinion_pins)));
2059    }
2060    let r2 = m * wheel.teeth as f64 / 2.0;
2061    let r1 = m * wheel.pinion_pins as f64 / 2.0;
2062    let rho = wheel.pin_diameter / 2.0;
2063    let half = rho + wheel.backlash / 2.0; // the space's half width
2064    let tau = TAU / wheel.teeth as f64;
2065    if !(2.0 * half < PI * m * 0.9) {
2066        return Err(refuse("pins_too_thick", format!("The pins ({}) fill the pitch ({:.4}): a star wheel needs pins under 0.9 of the pitch.", wheel.pin_diameter, PI * m)));
2067    }
2068    // The pin centre's path in the wheel's frame: the epicycloid with its cusp at (r2, 0), and its normal.
2069    let k = (r1 + r2) / r1;
2070    let path = |a: f64| {
2071        let t = PI + a * k;
2072        [(r2 + r1) * a.cos() + r1 * t.cos(), (r2 + r1) * a.sin() + r1 * t.sin()]
2073    };
2074    let path_tangent = |a: f64| {
2075        let t = PI + a * k;
2076        let d = [-(r2 + r1) * a.sin() - r1 * k * t.sin(), (r2 + r1) * a.cos() + r1 * k * t.cos()];
2077        let l = d[0].hypot(d[1]);
2078        [d[0] / l, d[1] / l]
2079    };
2080    // The flank: the path offset by the space's half width to the tooth's side (left of the outgoing branch).
2081    let flank = |a: f64| {
2082        let (p, t) = (path(a), path_tangent(a));
2083        [p[0] - half * t[1], p[1] + half * t[0]]
2084    };
2085    // Near the cusp the offset curve first runs back below the pitch circle (a swallowtail: the pin's centre
2086    // leaves the cusp sideways before it rises), so the space's boundary there is the offset curve only from its
2087    // own cusp (where its x stops falling) out; below that point the wall is straight at that point's height.
2088    let slope_x = |a: f64| {
2089        let h = 1e-7 * a.max(1e-9);
2090        flank(a + h)[0] - flank(a - h)[0]
2091    };
2092    let mut hi = 1e-6;
2093    while slope_x(hi) < 0.0 {
2094        hi *= 1.5;
2095        if hi > 1.0 {
2096            return Err(refuse("gear_fit", "The star wheel's flank never turns outward.".into()));
2097        }
2098    }
2099    let (mut lo, mut top) = (hi / 1.5, hi);
2100    for _ in 0..200 {
2101        let mid = 0.5 * (lo + top);
2102        if !(mid > lo && mid < top) {
2103            break;
2104        }
2105        if slope_x(mid) < 0.0 { lo = mid } else { top = mid }
2106    }
2107    let cusp = 0.5 * (lo + top);
2108    // Below that the swept pins (the cusp's disc and the swallowtail inside it) stay under the line at the half
2109    // width, so the space's wall is straight at the half width up to where the outer branch rises to it.
2110    let outside = |a: f64| flank(a)[1] - half;
2111    let mut hi = cusp * 1.5;
2112    while outside(hi) < 0.0 {
2113        hi *= 1.5;
2114        if hi > PI {
2115            return Err(refuse("gear_fit", "The star wheel's flank never rises past the pin's width.".into()));
2116        }
2117    }
2118    let (mut lo, mut top) = (cusp, hi);
2119    for _ in 0..200 {
2120        let mid = 0.5 * (lo + top);
2121        if !(mid > lo && mid < top) {
2122            break;
2123        }
2124        if outside(mid) < 0.0 { lo = mid } else { top = mid }
2125    }
2126    let start = 0.5 * (lo + top);
2127    // Where the flank reaches the tooth's middle (the flanks of neighbouring spaces meet): the pointed tip.
2128    let reach = |a: f64| polar_angle(flank(a)) - tau / 2.0;
2129    let mut hi = 1e-3;
2130    while reach(hi) < 0.0 {
2131        hi *= 1.5;
2132        if hi > PI {
2133            return Err(refuse("gear_fit", "The star wheel's flanks never meet.".into()));
2134        }
2135    }
2136    let (mut lo, mut top) = (start, hi);
2137    for _ in 0..200 {
2138        let mid = 0.5 * (lo + top);
2139        if !(mid > lo && mid < top) {
2140            break;
2141        }
2142        if reach(mid) < 0.0 { lo = mid } else { top = mid }
2143    }
2144    let pointed = radius_of(flank(0.5 * (lo + top)));
2145    let base = radius_of(flank(start));
2146    let tip_r = if wheel.addendum > 0.0 { r2 + wheel.addendum * m } else { base + 0.92 * (pointed - base) };
2147    if !(tip_r < pointed - 1e-6 * m) {
2148        return Err(refuse("pointed_tip", format!("The teeth come to a point at radius {pointed:.4}, below the tip ({tip_r:.4}): lower the addendum.")));
2149    }
2150    if !(tip_r > base) {
2151        return Err(refuse("gear_input", "The tip must lie above the pitch circle.".into()));
2152    }
2153    // The flank's parameter at the tip circle.
2154    let (mut lo, mut top) = (start, 0.5 * (lo + top));
2155    for _ in 0..200 {
2156        let mid = 0.5 * (lo + top);
2157        if !(mid > lo && mid < top) {
2158            break;
2159        }
2160        if radius_of(flank(mid)) < tip_r { lo = mid } else { top = mid }
2161    }
2162    let end = 0.5 * (lo + top);
2163    let root_r = r2 - half - wheel.clearance * m;
2164    if !(root_r > half * 1.01) {
2165        return Err(refuse("root_below_centre", "The root circle falls inside the space's width: more teeth or thinner pins.".into()));
2166    }
2167    let wall_foot = [(root_r * root_r - half * half).sqrt(), half];
2168    let wall_top = flank(start);
2169    let tolerance = GEAR_FIT_TOLERANCE * m;
2170    let right_flank = fit_planar(&flank, start, end, tolerance)?;
2171    let tip_from = polar_angle(flank(end));
2172    let mirror_into_next = |curve: &NurbsCurve| -> Result<NurbsCurve, KernelRefusal> {
2173        // Space 1's -θ side: space 0's +θ side mirrored about the x axis, turned by tau, run backwards.
2174        rotated(&mirrored(curve), tau).reversed().map_err(|e| refuse("gear_fit", e))
2175    };
2176    let wall = line(wall_foot, wall_top)?;
2177    let beta = (half / root_r).asin();
2178    let tooth: Vec<(&'static str, NurbsCurve)> = vec![
2179        ("V", wall.clone()),
2180        ("R", right_flank.clone()),
2181        ("K", arc(tip_r, tip_from, tau - tip_from)?),
2182        ("L", mirror_into_next(&right_flank)?),
2183        ("W", mirror_into_next(&wall)?),
2184        ("G", arc(root_r, tau - beta, tau + beta)?),
2185    ];
2186    let mut curves = Vec::with_capacity(6 * wheel.teeth);
2187    for index in 0..wheel.teeth {
2188        for (role, curve) in &tooth {
2189            curves.push(SectionCurve { curve: rotated(curve, tau * index as f64), role, tooth: index });
2190        }
2191    }
2192    snap_junctions(&mut curves);
2193    let data = GearData {
2194        pitch_diameter: 2.0 * r2,
2195        tip_diameter: 2.0 * tip_r,
2196        root_diameter: 2.0 * root_r,
2197        ..GearData::default()
2198    };
2199    Ok(GearSection { curves, data })
2200}
2201
2202/// A star wheel solid (the section extruded by the face width) with its face names and data.
2203pub fn star_wheel_solid(wheel: &StarWheel) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
2204    let section = star_wheel_section(wheel)?;
2205    let solid = extrude_section(&section, wheel.face_width)?;
2206    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
2207    names.push("F".into());
2208    names.push("B".into());
2209    Ok((solid, names, section.data))
2210}
2211
2212/// A lantern pinion: two discs joined by `pins` round pins on a circle, as a clock's or a mill's pinion,
2213/// driven by a star wheel's cycloidal teeth. Exact: pins and disc rims are cylinders, the disc faces planes.
2214/// The first disc spans z = -thickness..0, the pins z = 0..length, the second disc length..length + thickness;
2215/// pin 0 is centred on +x.
2216#[derive(Clone, Debug)]
2217pub struct LanternPinion {
2218    pub pins: usize,
2219    pub pin_circle_diameter: f64,
2220    pub pin_diameter: f64,
2221    pub disc_diameter: f64,
2222    pub disc_thickness: f64,
2223    /// The pins' length between the discs.
2224    pub length: f64,
2225}
2226
2227/// A lantern pinion solid and its data. Faces are named `P<k>` (pin walls), `FL1_OD`, `FL1_F` (the first
2228/// disc's outer face), `FL1_B` (its inner face round the pins), `FL2_F` (the second disc's inner face),
2229/// `FL2_OD` and `FL2_B`.
2230pub fn lantern_solid(lantern: &LanternPinion) -> Result<(BrepSolid, GearData), KernelRefusal> {
2231    use crate::sweep_topology::{curve_to_plane_parameters, make_plane, parameter_line};
2232    let n = lantern.pins;
2233    let (r, d, t, length) = (lantern.pin_circle_diameter / 2.0, lantern.pin_diameter, lantern.disc_thickness, lantern.length);
2234    let radius = lantern.disc_diameter / 2.0;
2235    if !(3..=200).contains(&n) {
2236        return Err(refuse("gear_input", format!("A lantern pinion needs from 3 to 200 pins (it has {n}).")));
2237    }
2238    if !(r > 0.0 && d > 0.0 && t > 0.0 && length > 0.0 && [r, d, t, length, radius].iter().all(|v| v.is_finite())) {
2239        return Err(refuse("gear_input", "The pin circle, pin diameter, disc thickness and length must be positive.".into()));
2240    }
2241    if !(2.0 * r * (PI / n as f64).sin() > d * (1.0 + 1e-9)) {
2242        return Err(refuse("pins_overlap", format!("The {n} pins of diameter {d} overlap on a pin circle of diameter {}: enlarge the circle or thin the pins.", 2.0 * r)));
2243    }
2244    if !(radius > r + d / 2.0) {
2245        return Err(refuse("disc_too_small", format!("The discs (diameter {}) must reach past the pins (to {:.4}).", 2.0 * radius, 2.0 * r + d)));
2246    }
2247    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));
2248    let x_axis = Vec3::new(1.0, 0.0, 0.0);
2249    let y_axis = Vec3::new(0.0, 1.0, 0.0);
2250    let circle = |cx: f64, cy: f64, z: f64, rad: f64| crate::make_arc(Vec3::new(cx, cy, z), x_axis, y_axis, rad, 0.0, TAU).map_err(|e| refuse("gear_arc", e));
2251    let mut shell = ShellBuilder { vertices: Vec::new(), edges: Vec::new(), faces: Vec::new(), next: 0 };
2252    // A cylinder from z = `low` up by `height` round (cx, cy): its circles, its seam and its face; returns the circles.
2253    let cylinder = |shell: &mut ShellBuilder, cx: f64, cy: f64, rad: f64, low: f64, height: f64, name: String| -> Result<(u64, u64), KernelRefusal> {
2254        let base = circle(cx, cy, low, rad)?;
2255        let (a, b) = (shell.vertex(Vec3::new(cx + rad, cy, low)), shell.vertex(Vec3::new(cx + rad, cy, low + height)));
2256        let lower = shell.edge(base.clone(), a, a)?;
2257        let upper = shell.edge(translated(&base, height), b, b)?;
2258        let seam = shell.edge(crate::make_line(Vec3::new(cx + rad, cy, low), Vec3::new(cx + rad, cy, low + height)).map_err(|e| refuse("gear_edge", e))?, a, b)?;
2259        let side = crate::make_extrusion(&base, Vec3::new(0.0, 0.0, height)).map_err(|e| refuse("gear_surface", e))?;
2260        let [c0, c1] = base.domain().map_err(|e| refuse("gear_domain", e))?;
2261        let loops = vec![vec![
2262            (lower, true, line([c0, 0.0], [c1, 0.0])?),
2263            (seam, true, line([c1, 0.0], [c1, 1.0])?),
2264            (upper, false, line([c0, 1.0], [c1, 1.0])?),
2265            (seam, false, line([c0, 0.0], [c0, 1.0])?),
2266        ]];
2267        shell.face(side, true, loops, name)?;
2268        Ok((lower, upper))
2269    };
2270    let mut pin_bottoms = Vec::with_capacity(n);
2271    let mut pin_tops = Vec::with_capacity(n);
2272    for k in 0..n {
2273        let (s, c) = (TAU * k as f64 / n as f64).sin_cos();
2274        let (lower, upper) = cylinder(&mut shell, r * c, r * s, d / 2.0, 0.0, length, format!("P{k}"))?;
2275        pin_bottoms.push(lower);
2276        pin_tops.push(upper);
2277    }
2278    let (outer1, inner1) = cylinder(&mut shell, 0.0, 0.0, radius, -t, t, "FL1_OD".into())?;
2279    let (inner2, outer2) = cylinder(&mut shell, 0.0, 0.0, radius, length, t, "FL2_OD".into())?;
2280    let pad = radius * 1.1 + 1.0;
2281    let plane_at = |z: f64| make_plane(Vec3::new(-pad, -pad, z), x_axis, y_axis, 2.0 * pad, 2.0 * pad).map_err(|e| refuse("gear_plane", e));
2282    let on_plane = |curve: &NurbsCurve, z: f64| curve_to_plane_parameters(curve, Vec3::new(-pad, -pad, z), x_axis, y_axis).map_err(|e| refuse("gear_pcurve", e));
2283    // The discs' outer faces, then their inner faces round the pins.
2284    let face = vec![vec![(outer1, true, on_plane(shell.curve(outer1), -t)?)]];
2285    shell.face(plane_at(-t)?, false, face, "FL1_F".into())?;
2286    let face = vec![vec![(outer2, true, on_plane(shell.curve(outer2), length + t)?)]];
2287    shell.face(plane_at(length + t)?, true, face, "FL2_B".into())?;
2288    for (z, rim, pins, same_sense, name) in [(0.0, inner1, &pin_bottoms, true, "FL1_B"), (length, inner2, &pin_tops, false, "FL2_F")] {
2289        let mut loops = vec![vec![(rim, true, on_plane(shell.curve(rim), z)?)]];
2290        for &pin in pins.iter() {
2291            loops.push(vec![(pin, true, on_plane(shell.curve(pin), z)?)]);
2292        }
2293        shell.face(plane_at(z)?, same_sense, loops, name.into())?;
2294    }
2295    let id = shell.id();
2296    let shell_id = shell.id();
2297    let solid = BrepSolid {
2298        mass_properties_cache: Default::default(),
2299        cells: Default::default(),
2300        id,
2301        vertices: shell.vertices,
2302        edges: shell.edges,
2303        shells: vec![crate::sweep_topology::ShellRecord { id: shell_id, faces: shell.faces }],
2304        genus: (n - 1) as _,
2305        kind: crate::BodyKind::Solid,
2306    };
2307    let issues = solid.validate();
2308    if !issues.is_empty() {
2309        return Err(KernelRefusal::internal(KernelStage::Validate, "validate", format!("lantern pinion is not valid: {issues:?}")));
2310    }
2311    let data = GearData { pitch_diameter: 2.0 * r, tip_diameter: 2.0 * r + d, root_diameter: 2.0 * r - d, ..GearData::default() };
2312    Ok((solid, data))
2313}
2314
2315/// A pulley solid: the section extruded along +z by the width; names as the
2316/// section's roles, then `F` and `B`.
2317/// The counter-clockwise section (z = 0) extruded to z = `width` with a flange disc of `radius` and
2318/// `thickness` under it (and, with `both`, another over it), built directly rather than as a union. Faces
2319/// are named: the section's walls by role, the flanges `FL1_OD`/`FL1_F` (its outer face)/`FL1_B` (the
2320/// annulus round the section) and `FL2_F` (the annulus)/`FL2_OD`/`FL2_B`, and without a second flange the
2321/// section's own end `B`.
2322pub fn flanged_prism(section: &GearSection, width: f64, radius: f64, thickness: f64, both: bool) -> Result<BrepSolid, KernelRefusal> {
2323    use crate::sweep_topology::{curve_to_plane_parameters, make_plane, parameter_line};
2324    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));
2325    let point_of = |p: Vec4| Vec3::new(p.x / p.w, p.y / p.w, p.z / p.w);
2326    if !(width > 0.0 && thickness > 0.0 && radius.is_finite() && radius > section_reach(section)? * (1.0 + 1e-9)) {
2327        return Err(refuse(
2328            "gear_input",
2329            format!("The flange radius ({radius}) must clear the section, and the width ({width}) and flange thickness ({thickness}) be positive."),
2330        ));
2331    }
2332    let up = Vec3::new(0.0, 0.0, width);
2333    let count = section.curves.len();
2334    let mut shell = ShellBuilder { vertices: Vec::new(), edges: Vec::new(), faces: Vec::new(), next: 0 };
2335    let mut bottom_v = Vec::with_capacity(count);
2336    let mut top_v = Vec::with_capacity(count);
2337    let mut axial = Vec::with_capacity(count);
2338    for piece in &section.curves {
2339        let p = point_of(piece.curve.control_points[0]);
2340        let (b, t) = (shell.vertex(p), shell.vertex(p.add(up)));
2341        axial.push(shell.edge(crate::make_line(p, p.add(up)).map_err(|e| refuse("gear_edge", e))?, b, t)?);
2342        bottom_v.push(b);
2343        top_v.push(t);
2344    }
2345    let mut bottom_e = Vec::with_capacity(count);
2346    let mut top_e = Vec::with_capacity(count);
2347    for (index, piece) in section.curves.iter().enumerate() {
2348        let next = (index + 1) % count;
2349        bottom_e.push(shell.edge(piece.curve.clone(), bottom_v[index], bottom_v[next])?);
2350        top_e.push(shell.edge(translated(&piece.curve, width), top_v[index], top_v[next])?);
2351    }
2352    for (index, piece) in section.curves.iter().enumerate() {
2353        let next = (index + 1) % count;
2354        let [u0, u1] = piece.curve.domain().map_err(|e| refuse("gear_domain", e))?;
2355        let surface = crate::make_extrusion(&piece.curve, up).map_err(|e| refuse("gear_surface", e))?;
2356        let loops = vec![vec![
2357            (bottom_e[index], true, line([u0, 0.0], [u1, 0.0])?),
2358            (axial[next], true, line([u1, 0.0], [u1, 1.0])?),
2359            (top_e[index], false, line([u0, 1.0], [u1, 1.0])?),
2360            (axial[index], false, line([u0, 0.0], [u0, 1.0])?),
2361        ]];
2362        shell.face(surface, true, loops, piece.suffix())?;
2363    }
2364    let pad = radius * 1.1 + 1.0;
2365    let x_axis = Vec3::new(1.0, 0.0, 0.0);
2366    let y_axis = Vec3::new(0.0, 1.0, 0.0);
2367    let plane_at = |z: f64| make_plane(Vec3::new(-pad, -pad, z), x_axis, y_axis, 2.0 * pad, 2.0 * pad).map_err(|e| refuse("gear_plane", e));
2368    let on_plane = |curve: &NurbsCurve, z: f64| curve_to_plane_parameters(curve, Vec3::new(-pad, -pad, z), x_axis, y_axis).map_err(|e| refuse("gear_pcurve", e));
2369    // A flange from z = `low` to `low` + thickness: its circles, seam and outside cylinder; returns the circles.
2370    let flange = |shell: &mut ShellBuilder, low: f64, name: &str| -> Result<(u64, u64), KernelRefusal> {
2371        let circle = crate::make_arc(Vec3::new(0.0, 0.0, low), x_axis, y_axis, radius, 0.0, TAU).map_err(|e| refuse("gear_arc", e))?;
2372        let lifted = translated(&circle, thickness);
2373        let (a, b) = (shell.vertex(Vec3::new(radius, 0.0, low)), shell.vertex(Vec3::new(radius, 0.0, low + thickness)));
2374        let lower = shell.edge(circle.clone(), a, a)?;
2375        let upper = shell.edge(lifted, b, b)?;
2376        let seam = shell.edge(crate::make_line(Vec3::new(radius, 0.0, low), Vec3::new(radius, 0.0, low + thickness)).map_err(|e| refuse("gear_edge", e))?, a, b)?;
2377        let side = crate::make_extrusion(&circle, Vec3::new(0.0, 0.0, thickness)).map_err(|e| refuse("gear_surface", e))?;
2378        let [c0, c1] = circle.domain().map_err(|e| refuse("gear_domain", e))?;
2379        let loops = vec![vec![
2380            (lower, true, line([c0, 0.0], [c1, 0.0])?),
2381            (seam, true, line([c1, 0.0], [c1, 1.0])?),
2382            (upper, false, line([c0, 1.0], [c1, 1.0])?),
2383            (seam, false, line([c0, 0.0], [c0, 1.0])?),
2384        ]];
2385        shell.face(side, true, loops, format!("{name}OD"))?;
2386        Ok((lower, upper))
2387    };
2388    // Flange 1 under the section: its outer face at z = -thickness, the annulus at z = 0 round the section.
2389    let (outer1, inner1) = flange(&mut shell, -thickness, "FL1_")?;
2390    let face = vec![(outer1, true, on_plane(shell.curve(outer1), -thickness)?)];
2391    shell.face(plane_at(-thickness)?, false, vec![face], "FL1_F".into())?;
2392    let mut annulus = vec![vec![(inner1, true, on_plane(shell.curve(inner1), 0.0)?)], Vec::with_capacity(count)];
2393    for &edge in &bottom_e {
2394        annulus[1].push((edge, true, on_plane(shell.curve(edge), 0.0)?));
2395    }
2396    shell.face(plane_at(0.0)?, true, annulus, "FL1_B".into())?;
2397    if both {
2398        let (inner2, outer2) = flange(&mut shell, width, "FL2_")?;
2399        let mut annulus = vec![vec![(inner2, true, on_plane(shell.curve(inner2), width)?)], Vec::with_capacity(count)];
2400        for &edge in &top_e {
2401            annulus[1].push((edge, true, on_plane(shell.curve(edge), width)?));
2402        }
2403        shell.face(plane_at(width)?, false, annulus, "FL2_F".into())?;
2404        let face = vec![(outer2, true, on_plane(shell.curve(outer2), width + thickness)?)];
2405        shell.face(plane_at(width + thickness)?, true, vec![face], "FL2_B".into())?;
2406    } else {
2407        let mut end = Vec::with_capacity(count);
2408        for &edge in &top_e {
2409            end.push((edge, true, on_plane(shell.curve(edge), width)?));
2410        }
2411        shell.face(plane_at(width)?, true, vec![end], "B".into())?;
2412    }
2413    let id = shell.id();
2414    let shell_id = shell.id();
2415    let solid = BrepSolid {
2416        mass_properties_cache: Default::default(),
2417        cells: Default::default(),
2418        id,
2419        vertices: shell.vertices,
2420        edges: shell.edges,
2421        shells: vec![crate::sweep_topology::ShellRecord { id: shell_id, faces: shell.faces }],
2422        genus: 0,
2423        kind: crate::BodyKind::Solid,
2424    };
2425    let issues = solid.validate();
2426    if !issues.is_empty() {
2427        return Err(KernelRefusal::internal(KernelStage::Validate, "validate", format!("flanged prism is not valid: {issues:?}")));
2428    }
2429    Ok(solid)
2430}
2431
2432pub fn timing_pulley_solid(pulley: &TimingPulley) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
2433    let section = timing_pulley_section(pulley)?;
2434    let solid = extrude_section(&section, pulley.width)?;
2435    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
2436    names.push("F".into());
2437    names.push("B".into());
2438    Ok((solid, names, section.data))
2439}
2440
2441/// A ratchet wheel: `teeth` teeth on `outside` diameter, `depth` deep. A saw
2442/// tooth has a locking face (leaning `lean` back from radial, so a pawl is drawn
2443/// in under load) and a straight back; a symmetric tooth leans both faces
2444/// equally (for a reversible pawl). Teeth lock against counter-clockwise turning
2445/// when `clockwise_locks` is false.
2446#[derive(Clone, Debug)]
2447pub struct Ratchet {
2448    pub teeth: usize,
2449    pub outside: f64,
2450    pub depth: f64,
2451    pub lean: f64,
2452    pub symmetric: bool,
2453    pub clockwise_locks: bool,
2454    pub width: f64,
2455}
2456
2457/// The ratchet section, counter-clockwise; straight lines only. Roles per
2458/// tooth k (tip k on angle 2 pi k / z): `LK<k>` the locking face below its
2459/// tip, `BK<k>` the back running up to it.
2460pub fn ratchet_section(ratchet: &Ratchet) -> Result<GearSection, KernelRefusal> {
2461    let Ratchet { teeth, outside, depth, lean, symmetric, clockwise_locks, width } = ratchet.clone();
2462    if !(outside > 0.0 && depth > 0.0 && depth < outside / 2.0 && width > 0.0) {
2463        return Err(refuse("gear_input", format!("A ratchet needs a positive outside diameter ({outside}), a depth ({depth}) under its radius and a positive width.")));
2464    }
2465    if teeth < 3 || teeth > 360 {
2466        return Err(refuse("gear_input", format!("A ratchet needs from 3 to 360 teeth (it has {teeth}).")));
2467    }
2468    if !(lean >= 0.0 && lean.to_degrees() <= 30.0) {
2469        return Err(refuse("gear_input", "The locking face lean must be between 0° and 30°.".into()));
2470    }
2471    let z = teeth as f64;
2472    let tau = TAU / z;
2473    let ra = outside / 2.0;
2474    let rf = ra - depth;
2475    // Tooth 0's tip on +x. The locking face runs from the tip down to the root
2476    // at a polar angle `foot` ahead of the tip (counter-clockwise), leaning back.
2477    // A radial face has foot = 0; leaning back by `lean` moves the root point
2478    // forward along the face's direction: solve |tip + t d| = rf.
2479    let tip = [ra, 0.0];
2480    let face_angle = PI + lean; // pointing inward, tilted to +y by `lean`
2481    let d = [face_angle.cos(), face_angle.sin()];
2482    let b = tip[0] * d[0] + tip[1] * d[1];
2483    let t = -b - (b * b - (ra * ra - rf * rf)).sqrt();
2484    let root = [tip[0] + t * d[0], tip[1] + t * d[1]];
2485    let foot = polar_angle(root);
2486    let (lock, back) = if symmetric {
2487        // Both faces meet at the root halfway between tips, each leaning equally.
2488        let mid = [rf * (tau / 2.0).cos(), rf * (tau / 2.0).sin()];
2489        let lock = line(tip, mid)?;
2490        let next = [ra * tau.cos(), ra * tau.sin()];
2491        (lock, line(mid, next)?)
2492    } else {
2493        if foot >= tau - 1e-9 {
2494            return Err(refuse("gear_input", "The locking faces overlap: fewer teeth, less depth or less lean.".into()));
2495        }
2496        let next = [ra * tau.cos(), ra * tau.sin()];
2497        (line(tip, root)?, line(root, next)?)
2498    };
2499    // Counter-clockwise traversal from tip k: locking face down, back up to tip k + 1.
2500    let mut curves = Vec::with_capacity(2 * teeth);
2501    for index in 0..teeth {
2502        let angle = tau * index as f64;
2503        curves.push(SectionCurve { curve: rotated(&lock, angle), role: "LK", tooth: index });
2504        curves.push(SectionCurve { curve: rotated(&back, angle), role: "BK", tooth: index });
2505    }
2506    if clockwise_locks {
2507        // The mirror image locks the other way; mirror, then restore the
2508        // counter-clockwise order.
2509        let mut mirrored_curves: Vec<SectionCurve> = curves
2510            .iter()
2511            .map(|piece| SectionCurve { curve: mirrored(&piece.curve).reversed().expect("a line reverses"), role: piece.role, tooth: piece.tooth })
2512            .collect();
2513        mirrored_curves.reverse();
2514        curves = mirrored_curves;
2515    }
2516    snap_junctions(&mut curves);
2517    Ok(GearSection { curves, data: GearData { tip_diameter: outside, root_diameter: 2.0 * rf, ..GearData::default() } })
2518}
2519
2520/// A ratchet solid: the section extruded along +z; names as the section's roles, then `F` and `B`.
2521pub fn ratchet_solid(ratchet: &Ratchet) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
2522    let section = ratchet_section(ratchet)?;
2523    let solid = extrude_section(&section, ratchet.width)?;
2524    let mut names: Vec<String> = section.curves.iter().map(|c| c.suffix()).collect();
2525    names.push("F".into());
2526    names.push("B".into());
2527    Ok((solid, names, section.data))
2528}
2529
2530/// An external Geneva wheel of `slots` slots for a driver at `centre_distance`
2531/// whose pin of `pin_diameter` runs on the crank radius a sin(pi / n); the
2532/// wheel's radius is a cos(pi / n) (the pin enters the slot tangentially). The
2533/// rim between slots is cut by the concave locking arc of radius
2534/// `lock_radius + clearance / 2` about the driver's centre.
2535#[derive(Clone, Debug)]
2536pub struct GenevaWheel {
2537    pub slots: usize,
2538    pub centre_distance: f64,
2539    pub pin_diameter: f64,
2540    pub clearance: f64,
2541    /// The driver's locking disc radius; 0 = crank radius − pin diameter.
2542    pub lock_radius: f64,
2543    pub width: f64,
2544}
2545
2546/// Derived Geneva sizes: (crank radius, wheel radius, slot inner centre radius, locking disc radius).
2547pub fn geneva_sizes(wheel: &GenevaWheel) -> (f64, f64, f64, f64) {
2548    let n = wheel.slots as f64;
2549    let a = wheel.centre_distance;
2550    let crank = a * (PI / n).sin();
2551    let radius = a * (PI / n).cos();
2552    let lock = if wheel.lock_radius > 0.0 { wheel.lock_radius } else { crank - wheel.pin_diameter };
2553    (crank, radius, a - crank, lock)
2554}
2555
2556/// The Geneva wheel section, counter-clockwise; lines and arcs. Slot k on
2557/// angle 2 pi k / n. Roles: `SL<k>`/`SU<k>` its sides, `SE<k>` its end arc,
2558/// `RA<k>`/`RB<k>` the rim arcs either side of the locking arc `LA<k>` that
2559/// follows slot k.
2560pub fn geneva_section(wheel: &GenevaWheel) -> Result<GearSection, KernelRefusal> {
2561    let GenevaWheel { slots, centre_distance: a, pin_diameter: dp, clearance: c, width, .. } = wheel.clone();
2562    if !(3..=12).contains(&slots) {
2563        return Err(refuse("gear_input", format!("A Geneva wheel has from 3 to 12 slots (it has {slots}).")));
2564    }
2565    if !(a > 0.0 && dp > 0.0 && c >= 0.0 && width > 0.0) {
2566        return Err(refuse("gear_input", "The centre distance, pin diameter and width must be positive (the clearance not negative).".into()));
2567    }
2568    let n = slots as f64;
2569    let (crank, rw, end_centre, lock) = geneva_sizes(wheel);
2570    let half = (dp + c) / 2.0; // half the slot width
2571    let rl = lock + c / 2.0;
2572    if !(lock > 0.0 && lock < a - rw + 1e-9 + rw) || !(half < end_centre) || !(half < rw * (PI / n).sin()) {
2573        return Err(refuse("gear_input", format!("The pin ({dp}) is too large for {slots} slots at centre distance {a}.")));
2574    }
2575    // Adjacent slots must not meet: their ends (and sides) stay apart only
2576    // while the end centres are more than a slot width apart.
2577    if end_centre * (PI / n).sin() <= half * (1.0 + 1e-9) {
2578        return Err(refuse(
2579            "gear_input",
2580            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),
2581        ));
2582    }
2583    let x_top = (rw * rw - half * half).sqrt();
2584    let p1 = [x_top, half];
2585    let beta = PI / n;
2586    let centre = [a * beta.cos(), a * beta.sin()];
2587    // Rim circle (O, rw) meets the locking circle (centre, rl).
2588    let along = (rw * rw - rl * rl + a * a) / (2.0 * a);
2589    let h2 = rw * rw - along * along;
2590    if h2 <= 0.0 {
2591        return Err(refuse("gear_input", "The locking arc does not reach the wheel's rim: increase the locking disc radius.".into()));
2592    }
2593    let h = h2.sqrt();
2594    let e = [beta.cos(), beta.sin()];
2595    let perp = [-beta.sin(), beta.cos()];
2596    let q1 = [along * e[0] - h * perp[0], along * e[1] - h * perp[1]];
2597    let q2 = [along * e[0] + h * perp[0], along * e[1] + h * perp[1]];
2598    let a1 = polar_angle(p1);
2599    if polar_angle(q1) <= a1 + 1e-9 {
2600        return Err(refuse("gear_input", "The locking arc cuts into the slots: reduce the locking disc radius or the pin.".into()));
2601    }
2602    let tau = TAU / n;
2603    let slot: Vec<(&'static str, NurbsCurve)> = vec![
2604        ("SL", line([x_top, -half], [end_centre, -half])?),
2605        ("SE", arc_through([end_centre, 0.0], [end_centre, -half], [end_centre, half], false)?),
2606        ("SU", line([end_centre, half], p1)?),
2607        ("RA", arc(rw, a1, polar_angle(q1))?),
2608        ("LA", arc_through(centre, q1, q2, false)?),
2609        ("RB", arc(rw, polar_angle(q2), tau - a1)?),
2610    ];
2611    let mut curves = Vec::with_capacity(6 * slots);
2612    for index in 0..slots {
2613        let angle = tau * index as f64;
2614        for (role, curve) in &slot {
2615            curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
2616        }
2617    }
2618    snap_junctions(&mut curves);
2619    let _ = crank;
2620    Ok(GearSection { curves, data: GearData { tip_diameter: 2.0 * rw, ..GearData::default() } })
2621}
2622
2623/// A Geneva wheel solid: the section extruded along +z; names as the
2624/// section's roles, then `F` and `B`.
2625pub fn geneva_solid(wheel: &GenevaWheel) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
2626    let section = geneva_section(wheel)?;
2627    let solid = extrude_section(&section, wheel.width)?;
2628    let mut names: Vec<String> = section.curves.iter().map(|c| c.suffix()).collect();
2629    names.push("F".into());
2630    names.push("B".into());
2631    Ok((solid, names, section.data))
2632}
2633
2634/// A cylindrical worm with an Archimedean (ZA) thread: straight flanks in the
2635/// axial section at the axial pressure angle. Lengths in model units.
2636#[derive(Clone, Debug)]
2637pub struct Worm {
2638    pub axial_module: f64,
2639    pub starts: usize,
2640    /// Reference (pitch) diameter d1 = q × axial module.
2641    pub reference_diameter: f64,
2642    pub pressure_angle: f64,
2643    pub addendum: f64,
2644    pub dedendum: f64,
2645    pub length: f64,
2646    pub hand: Hand,
2647}
2648
2649impl Worm {
2650    /// The lead: starts × axial pitch.
2651    pub fn lead(&self) -> f64 {
2652        self.starts as f64 * PI * self.axial_module
2653    }
2654
2655    /// The axial thread thickness at a radius (ZA: straight axial flanks).
2656    pub fn axial_thickness(&self, radius: f64) -> f64 {
2657        PI * self.axial_module / 2.0 - 2.0 * (radius - self.reference_diameter / 2.0) * self.pressure_angle.tan()
2658    }
2659}
2660
2661/// The worm's transverse section (z = 0), counter-clockwise: per start j (its
2662/// thread centred on angle 2 pi j / n) `R<j>` the flank on its clockwise side,
2663/// `K<j>` the thread's tip, `L<j>` the other flank, `G<j>` the root after it.
2664/// The flanks are Archimedean spirals (fitted), tip and root exact arcs.
2665pub fn worm_section(worm: &Worm) -> Result<GearSection, KernelRefusal> {
2666    let m = worm.axial_module;
2667    if !(m > 0.0 && worm.reference_diameter > 0.0 && worm.length > 0.0 && worm.addendum > 0.0 && worm.dedendum > 0.0) {
2668        return Err(refuse("gear_input", "The worm's module, diameter, length, addendum and dedendum must be positive.".into()));
2669    }
2670    if worm.starts < 1 || worm.starts > 8 {
2671        return Err(refuse("gear_input", format!("A worm has from 1 to 8 starts (it has {}).", worm.starts)));
2672    }
2673    let degrees = worm.pressure_angle.to_degrees();
2674    if !(10.0 - 1e-9..=35.0 + 1e-9).contains(&degrees) {
2675        return Err(refuse("gear_input", format!("The axial pressure angle must be between 10° and 35° (it is {degrees}°).")));
2676    }
2677    let r1 = worm.reference_diameter / 2.0;
2678    let ra = r1 + worm.addendum * m;
2679    let rf = r1 - worm.dedendum * m;
2680    if !(rf > 0.0) {
2681        return Err(refuse("gear_input", format!("The worm's root diameter is not positive ({:.4}): raise the diameter quotient.", 2.0 * rf)));
2682    }
2683    let lead = worm.lead();
2684    let gamma = (lead / (PI * worm.reference_diameter)).atan();
2685    if gamma.to_degrees() > 45.0 {
2686        return Err(refuse("bad_lead", format!("The lead angle {:.3}° is over 45°: fewer starts or a larger diameter.", gamma.to_degrees())));
2687    }
2688    if worm.axial_thickness(ra) <= 1e-6 * m {
2689        return Err(refuse("pointed_tip", "The worm thread comes to a point below its tip: lower the addendum or the pressure angle.".into()));
2690    }
2691    let n = worm.starts as f64;
2692    let pitch = PI * m;
2693    if worm.axial_thickness(rf) >= pitch - 1e-6 * m {
2694        return Err(refuse("teeth_overlap", "The worm's threads meet at the root: lower the dedendum or the pressure angle.".into()));
2695    }
2696    // Half the angular width of a thread at radius r in the transverse plane.
2697    let half = |r: f64| PI * worm.axial_thickness(r) / lead;
2698    let flank = |r: f64| {
2699        let t = half(r);
2700        [r * t.cos(), r * t.sin()]
2701    };
2702    let tolerance = GEAR_FIT_TOLERANCE * m;
2703    let upper = fit_planar(&|r| flank(r), rf, ra, tolerance)?; // root -> tip on the +angle side
2704    let tau = TAU / n;
2705    let thread: Vec<(&'static str, NurbsCurve)> = vec![
2706        ("R", mirrored(&upper)),
2707        ("K", arc(ra, -half(ra), half(ra))?),
2708        ("L", upper.reversed().map_err(|e| refuse("gear_fit", e))?),
2709        ("G", arc(rf, half(rf), tau - half(rf))?),
2710    ];
2711    let mut curves = Vec::with_capacity(4 * worm.starts);
2712    for index in 0..worm.starts {
2713        let angle = tau * index as f64;
2714        for (role, curve) in &thread {
2715            curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
2716        }
2717    }
2718    snap_junctions(&mut curves);
2719    let data = GearData { pitch_diameter: worm.reference_diameter, tip_diameter: 2.0 * ra, root_diameter: 2.0 * rf, ..GearData::default() };
2720    Ok(GearSection { curves, data })
2721}
2722
2723/// A worm solid: the transverse section screwed along +z by the length (one
2724/// lead per turn); names as the section's roles, then `F` and `B`.
2725pub fn worm_solid(worm: &Worm) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
2726    let section = worm_section(worm)?;
2727    let sign = if worm.hand == Hand::Right { 1.0 } else { -1.0 };
2728    let turn = sign * TAU * worm.length / worm.lead();
2729    let solid = twisted_prism(&section, worm.length, Twist::Helical { turn }, GEAR_FIT_TOLERANCE * worm.axial_module)?;
2730    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
2731    names.push("F".into());
2732    names.push("B".into());
2733    Ok((solid, names, section.data))
2734}
2735
2736/// A cycloidal-drive disc: `pins` housing pins of diameter `pin_diameter` on a
2737/// circle of `pin_circle_diameter`, the disc running at `eccentricity`; the disc
2738/// has pins − 1 lobes. Its profile is the equidistant (by the pin radius plus
2739/// half the clearance) of the epitrochoid the pin centres trace relative to it.
2740#[derive(Clone, Debug)]
2741pub struct CycloidalDisc {
2742    pub pins: usize,
2743    pub pin_circle_diameter: f64,
2744    pub pin_diameter: f64,
2745    pub eccentricity: f64,
2746    /// Running clearance (diametral): the profile stands clearance / 2 further off the pins.
2747    pub clearance: f64,
2748    pub width: f64,
2749}
2750
2751impl CycloidalDisc {
2752    /// The epitrochoid of the pin centres relative to the disc, and its derivative.
2753    fn trochoid(&self, t: f64) -> ([f64; 2], [f64; 2]) {
2754        let r = self.pin_circle_diameter / 2.0;
2755        let e = self.eccentricity;
2756        let n = self.pins as f64;
2757        (
2758            [r * t.cos() - e * (n * t).cos(), -r * t.sin() + e * (n * t).sin()],
2759            [-r * t.sin() + e * n * (n * t).sin(), -r * t.cos() + e * n * (n * t).cos()],
2760        )
2761    }
2762
2763    /// The disc profile point at parameter t: the trochoid moved by the offset
2764    /// along its normal towards the disc's centre.
2765    pub fn profile(&self, t: f64) -> [f64; 2] {
2766        let (q, d) = self.trochoid(t);
2767        let length = d[0].hypot(d[1]);
2768        let offset = self.pin_diameter / 2.0 + self.clearance / 2.0;
2769        // The trochoid runs clockwise (y = -r sin t ...); its right-hand normal points inward.
2770        let n = [d[1] / length, -d[0] / length];
2771        [q[0] + offset * n[0], q[1] + offset * n[1]]
2772    }
2773}
2774
2775/// The disc's section, counter-clockwise: one fitted piece per lobe, `LB<k>`.
2776pub fn cycloidal_disc_section(disc: &CycloidalDisc) -> Result<GearSection, KernelRefusal> {
2777    let CycloidalDisc { pins, pin_circle_diameter: dc, pin_diameter: dp, eccentricity: e, clearance, width } = disc.clone();
2778    if !(4..=200).contains(&pins) {
2779        return Err(refuse("gear_input", format!("A cycloidal drive has from 4 to 200 pins (it has {pins}).")));
2780    }
2781    if !(dc > 0.0 && dp > 0.0 && e > 0.0 && clearance >= 0.0 && width > 0.0) {
2782        return Err(refuse("gear_input", "The pin circle, pin diameter, eccentricity and width must be positive.".into()));
2783    }
2784    let n = pins as f64;
2785    let r = dc / 2.0;
2786    // The trochoid loops back on itself once e >= r / n.
2787    if e >= r / n * (1.0 - 1e-9) {
2788        return Err(refuse(
2789            "gear_input",
2790            format!("The eccentricity must be under the pin circle radius / pins = {:.4} (it is {e}).", r / n),
2791        ));
2792    }
2793    // The offset must stay under the trochoid's smallest radius of curvature (else the lobes cusp).
2794    let offset = dp / 2.0 + clearance / 2.0;
2795    // An inward offset can cusp only where the (clockwise) curve turns
2796    // clockwise, its centre of curvature inside. Radius of curvature there,
2797    // from the closed-form first and second derivatives.
2798    let (rr, ee) = (dc / 2.0, e);
2799    let radius = |t: f64| -> f64 {
2800        let d = [-rr * t.sin() + ee * n * (n * t).sin(), -rr * t.cos() + ee * n * (n * t).cos()];
2801        let dd = [-rr * t.cos() + ee * n * n * (n * t).cos(), rr * t.sin() - ee * n * n * (n * t).sin()];
2802        let cross = d[0] * dd[1] - d[1] * dd[0];
2803        let speed = d[0].hypot(d[1]);
2804        if cross < 0.0 { speed * speed * speed / -cross } else { f64::INFINITY }
2805    };
2806    // The curve repeats every 2 pi / (n - 1): sample one period densely, then
2807    // refine every local minimum by golden-section search.
2808    let period = TAU / (n - 1.0);
2809    let samples = 2000;
2810    let values: Vec<f64> = (0..=samples).map(|i| radius(period * i as f64 / samples as f64)).collect();
2811    let mut least = f64::INFINITY;
2812    for i in 0..=samples {
2813        let previous = values[if i == 0 { samples - 1 } else { i - 1 }];
2814        let next = values[if i == samples { 1 } else { i + 1 }];
2815        if values[i] <= previous && values[i] <= next && values[i].is_finite() {
2816            let (mut lo, mut hi) = (period * (i as f64 - 1.0) / samples as f64, period * (i as f64 + 1.0) / samples as f64);
2817            for _ in 0..100 {
2818                let a = lo + (hi - lo) * 0.381966;
2819                let b = hi - (hi - lo) * 0.381966;
2820                if radius(a) < radius(b) { hi = b } else { lo = a }
2821            }
2822            least = least.min(radius(0.5 * (lo + hi)));
2823        }
2824    }
2825    if offset >= least * (1.0 - 1e-6) {
2826        return Err(refuse(
2827            "undercut",
2828            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})."),
2829        ));
2830    }
2831    let lobes = pins - 1;
2832    let step = TAU / lobes as f64;
2833    let tolerance = GEAR_FIT_TOLERANCE * dp.min(e * 4.0);
2834    // The trochoid runs clockwise in t: walk t downwards for a counter-clockwise section.
2835    let mut curves = Vec::with_capacity(lobes);
2836    for k in 0..lobes {
2837        let (a, b) = (step * k as f64, step * (k + 1) as f64);
2838        let piece = fit_planar(&|u| disc.profile(-u), a, b, tolerance)?;
2839        curves.push(SectionCurve { curve: piece, role: "LB", tooth: k });
2840    }
2841    snap_junctions(&mut curves);
2842    Ok(GearSection { curves, data: GearData { pitch_diameter: dc, ..GearData::default() } })
2843}
2844
2845/// A cycloidal disc solid: the section extruded along +z; names `LB<k>`, `F`, `B`.
2846pub fn cycloidal_disc_solid(disc: &CycloidalDisc) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
2847    let section = cycloidal_disc_section(disc)?;
2848    let solid = extrude_section(&section, disc.width)?;
2849    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
2850    names.push("F".into());
2851    names.push("B".into());
2852    Ok((solid, names, section.data))
2853}
2854
2855/// The pin ring of a cycloidal drive: a ring of `outside` diameter whose bore
2856/// is the pin circle, with `pins` pins of `pin_diameter` centred on it (half
2857/// standing into the bore). Exact arcs. Faces: `P<k>` the pins' exposed halves,
2858/// `G<k>` the bore between pins, `OD`, `F`, `B`.
2859pub fn cycloidal_pin_ring(pins: usize, pin_circle_diameter: f64, pin_diameter: f64, outside: f64, width: f64) -> Result<(BrepSolid, GearData), KernelRefusal> {
2860    if !(4..=200).contains(&pins) || !(pin_diameter > 0.0 && pin_circle_diameter > pin_diameter && width > 0.0) {
2861        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()));
2862    }
2863    let r = pin_circle_diameter / 2.0;
2864    let rp = pin_diameter / 2.0;
2865    let n = pins as f64;
2866    let tau = TAU / n;
2867    // Where a pin's circle crosses the bore circle (radius r): half-angle delta about the origin.
2868    let delta = 2.0 * (rp / (2.0 * r)).asin();
2869    if 2.0 * delta >= tau - 1e-9 || 2.0 * r * (PI / n).sin() <= pin_diameter * (1.0 + 1e-9) {
2870        return Err(refuse("gear_input", format!("{pins} pins of diameter {pin_diameter} overlap on a {pin_circle_diameter} pin circle.")));
2871    }
2872    let centre = [r, 0.0];
2873    let a = [r * (-delta).cos(), r * (-delta).sin()];
2874    let b = [r * delta.cos(), r * delta.sin()];
2875    // The pin bulges into the bore: its arc from a to b passes through (r - rp, 0).
2876    let cw = arc_through(centre, a, b, false)?;
2877    let pin_arc = {
2878        let [t0, t1] = cw.domain().map_err(|e| refuse("gear_domain", e))?;
2879        let mid = cw.evaluate(0.5 * (t0 + t1)).map_err(|e| refuse("gear_eval", e))?;
2880        if mid.x < r { cw } else { arc_through(centre, a, b, true)? }
2881    };
2882    let space: Vec<(&'static str, NurbsCurve)> = vec![("P", pin_arc), ("G", arc(r, delta, tau - delta)?)];
2883    let mut curves = Vec::with_capacity(2 * pins);
2884    for k in 0..pins {
2885        for (role, curve) in &space {
2886            curves.push(SectionCurve { curve: rotated(curve, tau * k as f64), role, tooth: k });
2887        }
2888    }
2889    snap_junctions(&mut curves);
2890    let section = GearSection { curves, data: GearData { pitch_diameter: pin_circle_diameter, ..GearData::default() } };
2891    let ring = hub_from_section(&section, outside, width)?;
2892    Ok((ring, section.data))
2893}
2894
2895/// A cycloidal (clock-style) gear: teeth whose addenda are epicycloids rolled
2896/// by a circle of `generating_radius` on the pitch circle and whose dedenda are
2897/// radial lines (the hypocycloid of a circle of half the mate's pitch radius).
2898#[derive(Clone, Debug)]
2899pub struct CycloidalGear {
2900    pub module: f64,
2901    pub teeth: usize,
2902    /// Radius of the rolling circle (usually half the mating gear's pitch radius).
2903    pub generating_radius: f64,
2904    /// Tooth thickness on the pitch circle as a fraction of the circular pitch.
2905    pub tooth_fraction: f64,
2906    /// Addendum limit × module (the tip is pointed if the flanks meet first).
2907    pub addendum: f64,
2908    /// Dedendum × module.
2909    pub dedendum: f64,
2910    pub width: f64,
2911}
2912
2913/// The cycloidal gear's section, counter-clockwise. Per tooth k: `R<k>`/`L<k>`
2914/// the radial dedendum flanks, `ER<k>`/`EL<k>` the epicycloidal addenda, `K<k>`
2915/// the tip land (absent when pointed), `G<k>` the root land.
2916pub fn cycloidal_gear_section(gear: &CycloidalGear) -> Result<GearSection, KernelRefusal> {
2917    let m = gear.module;
2918    if !(m > 0.0 && gear.generating_radius > 0.0 && gear.addendum > 0.0 && gear.dedendum > 0.0 && gear.width > 0.0) {
2919        return Err(refuse("gear_input", "The module, rolling circle, addendum, dedendum and width must be positive.".into()));
2920    }
2921    if !(gear.tooth_fraction > 0.1 && gear.tooth_fraction < 0.9) {
2922        return Err(refuse("gear_input", "The tooth thickness must be between 0.1 and 0.9 of the pitch.".into()));
2923    }
2924    if gear.teeth < 6 || gear.teeth > 1000 {
2925        return Err(refuse("gear_input", format!("A cycloidal gear needs from 6 to 1000 teeth (it has {}).", gear.teeth)));
2926    }
2927    let z = gear.teeth as f64;
2928    let r = m * z / 2.0;
2929    let rho = gear.generating_radius;
2930    let rf = r - gear.dedendum * m;
2931    if !(rf > 0.0) {
2932        return Err(refuse("root_below_centre", "The root circle is not positive: fewer dedendum or more teeth.".into()));
2933    }
2934    let tau = TAU / z;
2935    let psi = PI * gear.tooth_fraction / z; // half the tooth angle on the pitch circle
2936    // The right flank's epicycloid, from the pitch circle at angle -psi.
2937    let k = (r + rho) / rho;
2938    let epi = |phi: f64| {
2939        let p = [(r + rho) * phi.cos() - rho * (k * phi).cos(), (r + rho) * phi.sin() - rho * (k * phi).sin()];
2940        rotate(p, -psi)
2941    };
2942    let ra = r + gear.addendum * m;
2943    // Run phi up until the curve reaches the tip circle or the tooth centre line (angle 0).
2944    let reach = |phi: f64| radius_of(epi(phi)) >= ra || polar_angle(epi(phi)) >= 0.0;
2945    let mut hi = 1e-3;
2946    while !reach(hi) {
2947        hi *= 1.5;
2948        if hi > PI {
2949            return Err(refuse("gear_input", "The addendum curve does not close.".into()));
2950        }
2951    }
2952    let mut lo = 0.0;
2953    for _ in 0..200 {
2954        let mid = 0.5 * (lo + hi);
2955        if reach(mid) { hi = mid } else { lo = mid }
2956    }
2957    let end = epi(hi);
2958    // Pointed when the flank reaches the tooth centre line no later than the
2959    // tip circle (a tip land narrower than 1e-9 counts as pointed).
2960    let pointed = polar_angle(end) >= -1e-9;
2961    let phi_end = if pointed {
2962        let (mut lo, mut hi) = (0.0, hi);
2963        for _ in 0..200 {
2964            let mid = 0.5 * (lo + hi);
2965            if polar_angle(epi(mid)) >= 0.0 { hi = mid } else { lo = mid }
2966        }
2967        hi
2968    } else {
2969        hi
2970    };
2971    let tolerance = GEAR_FIT_TOLERANCE * m;
2972    let right_add = fit_planar(&|phi| epi(phi), 0.0, phi_end, tolerance)?; // pitch -> tip, right side
2973    let foot = [rf * (-psi).cos(), rf * (-psi).sin()];
2974    let pitch_point = [r * (-psi).cos(), r * (-psi).sin()];
2975    let mut tooth: Vec<(&'static str, NurbsCurve)> = vec![("R", line(foot, pitch_point)?), ("ER", right_add.clone())];
2976    let tip_angle = -polar_angle(epi(phi_end));
2977    if !pointed {
2978        tooth.push(("K", arc(ra, -tip_angle, tip_angle)?));
2979    }
2980    tooth.push(("EL", mirrored(&right_add).reversed().map_err(|e| refuse("gear_fit", e))?));
2981    tooth.push(("L", line([pitch_point[0], -pitch_point[1]], [foot[0], -foot[1]])?));
2982    tooth.push(("G", arc(rf, psi, tau - psi)?));
2983    let mut curves = Vec::with_capacity(tooth.len() * gear.teeth);
2984    for index in 0..gear.teeth {
2985        let angle = tau * index as f64;
2986        for (role, curve) in &tooth {
2987            curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
2988        }
2989    }
2990    snap_junctions(&mut curves);
2991    let data = GearData {
2992        pitch_diameter: 2.0 * r,
2993        tip_diameter: 2.0 * radius_of(epi(phi_end)),
2994        root_diameter: 2.0 * rf,
2995        tooth_thickness: 2.0 * psi * r,
2996        ..GearData::default()
2997    };
2998    Ok(GearSection { curves, data })
2999}
3000
3001/// A cycloidal gear solid; names as the section's roles, then `F` and `B`.
3002pub fn cycloidal_gear_solid(gear: &CycloidalGear) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
3003    let section = cycloidal_gear_section(gear)?;
3004    let solid = extrude_section(&section, gear.width)?;
3005    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
3006    names.push("F".into());
3007    names.push("B".into());
3008    Ok((solid, names, section.data))
3009}
3010
3011/// A straight bevel gear with spherical-involute teeth (the true conjugate
3012/// form; not Tredgold's back-cone approximation). Module at the heel, shaft
3013/// angle 90°, pitch cone angle atan(z / z_mate). Apex at the origin, axis +z,
3014/// the teeth between cone distances R − face width and R; back and front
3015/// faces are the back and front cones (perpendicular to the pitch cone).
3016#[derive(Clone, Debug)]
3017pub struct BevelGear {
3018    pub module: f64,
3019    pub teeth: usize,
3020    pub mate_teeth: usize,
3021    pub pressure_angle: f64,
3022    pub addendum: f64,
3023    pub dedendum: f64,
3024    pub face_width: f64,
3025    pub backlash: f64,
3026}
3027
3028/// Derived bevel sizes: (pitch cone angle, cone distance, base cone angle).
3029pub fn bevel_cones(gear: &BevelGear) -> (f64, f64, f64) {
3030    let delta = (gear.teeth as f64).atan2(gear.mate_teeth as f64);
3031    let cone = gear.module * gear.teeth as f64 / (2.0 * delta.sin());
3032    let base = (delta.sin() * gear.pressure_angle.cos()).asin();
3033    (delta, cone, base)
3034}
3035
3036/// A point of the spherical involute of the base cone (half angle `base`) on
3037/// the sphere of radius `r`, unwrapped by `phi` from the base circle at azimuth 0.
3038fn spherical_involute(r: f64, base: f64, phi: f64) -> [f64; 3] {
3039    let (s, c) = base.sin_cos();
3040    let t = phi * s;
3041    [
3042        r * (t.cos() * s * phi.cos() + t.sin() * phi.sin()),
3043        r * (t.cos() * s * phi.sin() - t.sin() * phi.cos()),
3044        r * t.cos() * c,
3045    ]
3046}
3047
3048/// The polar angle from the axis (the cone angle) of a point.
3049fn cone_angle(p: [f64; 3]) -> f64 {
3050    p[0].hypot(p[1]).atan2(p[2])
3051}
3052
3053/// Central projection from the apex onto the plane z = h.
3054fn project(p: [f64; 3], h: f64) -> [f64; 2] {
3055    [p[0] * h / p[2], p[1] * h / p[2]]
3056}
3057
3058/// The bevel gear section: the spherical tooth outline on the sphere through
3059/// the heel, centrally projected onto the plane z = h (so every surface the
3060/// apex sees edge-on — tooth flanks, root and tip cones — becomes a planar
3061/// curve; the cones' circles project to exact arcs). Counter-clockwise; roles
3062/// as the spur gear's: `V/R/K/L/W/G` with `V/W` the radial (meridian) root
3063/// extension below the base cone when the root lies under it.
3064pub fn bevel_section(gear: &BevelGear, h: f64) -> Result<GearSection, KernelRefusal> {
3065    let m = gear.module;
3066    if !(m > 0.0 && gear.face_width > 0.0 && gear.addendum > 0.0 && gear.dedendum > 0.0 && gear.backlash >= 0.0) {
3067        return Err(refuse("gear_input", "The module, face width, addendum and dedendum must be positive.".into()));
3068    }
3069    if gear.teeth < 6 || gear.mate_teeth < 6 {
3070        return Err(refuse("gear_input", "A bevel pair needs at least 6 teeth on each gear.".into()));
3071    }
3072    let degrees = gear.pressure_angle.to_degrees();
3073    if !(10.0 - 1e-9..=35.0 + 1e-9).contains(&degrees) {
3074        return Err(refuse("gear_input", format!("The pressure angle must be between 10° and 35° (it is {degrees}°).")));
3075    }
3076    let (delta, r, base) = bevel_cones(gear);
3077    if gear.face_width > r / 3.0 + 1e-9 {
3078        return Err(refuse(
3079            "face_too_wide",
3080            format!("The face width ({}) is over a third of the cone distance ({:.4}): the teeth would be too small at the toe.", gear.face_width, r),
3081        ));
3082    }
3083    let z = gear.teeth as f64;
3084    let tip = delta + gear.addendum * m / r;
3085    let root = delta - gear.dedendum * m / r;
3086    if !(root > 0.0) {
3087        return Err(refuse("root_below_centre", "The root cone passes the axis: fewer dedendum or more teeth.".into()));
3088    }
3089    // The unwrap angle where the involute reaches a cone angle theta: cos(phi sin b) cos b = cos theta.
3090    let phi_at = |theta: f64| ((theta.cos() / base.cos()).clamp(-1.0, 1.0)).acos() / base.sin();
3091    let azimuth = |p: [f64; 3]| p[1].atan2(p[0]);
3092    // Position the left flank: half the tooth thickness (arc on the pitch circle of radius r sin delta) at the pitch cone.
3093    let half = (PI * m / 2.0 - gear.backlash) / (2.0 * r * delta.sin());
3094    let p_pitch = spherical_involute(r, base, phi_at(delta));
3095    // The involute (unwrapping counter-clockwise) leans to positive azimuth as it rises: the left flank
3096    // is it mirrored, turned so its pitch point sits at +half.
3097    let shift = half + azimuth(p_pitch);
3098    let left = |phi: f64| {
3099        let p = spherical_involute(r, base, phi);
3100        let q = [p[0], -p[1], p[2]];
3101        let (s, c) = shift.sin_cos();
3102        [c * q[0] - s * q[1], s * q[0] + c * q[1], q[2]]
3103    };
3104    let tip_phi = phi_at(tip);
3105    if azimuth(left(tip_phi)) <= 1e-6 * m / r {
3106        return Err(refuse("pointed_tip", "The teeth come to a point below the tip cone: reduce the addendum.".into()));
3107    }
3108    // At the base cone the involute leaves with zero speed (a cusp in phi):
3109    // when the root lies under it, the flank starts a little above (2% of the
3110    // unwrap) and the radial root extension runs up to that point.
3111    let extend = !(root > base); // the root lies on or under the base cone: a radial extension
3112    let start_phi = if extend { 0.02 * tip_phi } else { phi_at(root) };
3113    let tolerance = GEAR_FIT_TOLERANCE * m;
3114    let flank = fit_planar(&|phi| project(left(phi), h), start_phi, tip_phi, tolerance)?; // root side -> tip
3115    let tau = TAU / z;
3116    let base_point = project(left(start_phi), h);
3117    let root_r = h * root.tan();
3118    let tip_r = h * tip.tan();
3119    let foot_angle = base_point[1].atan2(base_point[0]);
3120    let mut tooth: Vec<(&'static str, NurbsCurve)> = Vec::new();
3121    let tip_angle = {
3122        let p = project(left(tip_phi), h);
3123        p[1].atan2(p[0])
3124    };
3125    // Right side (mirror), going up: [V radial] + R; tip K; then L down + [W radial]; G root land.
3126    let radial_foot = [root_r * foot_angle.cos(), root_r * foot_angle.sin()];
3127    if extend {
3128        tooth.push(("V", line([radial_foot[0], -radial_foot[1]], [base_point[0], -base_point[1]])?));
3129    }
3130    tooth.push(("R", mirrored(&flank)));
3131    tooth.push(("K", arc(tip_r, -tip_angle, tip_angle)?));
3132    tooth.push(("L", flank.reversed().map_err(|e| refuse("gear_fit", e))?));
3133    if extend {
3134        tooth.push(("W", line(base_point, radial_foot)?));
3135    }
3136    if foot_angle >= tau / 2.0 - 1e-9 {
3137        return Err(refuse("teeth_overlap", "The tooth roots meet: fewer teeth or a smaller pressure angle.".into()));
3138    }
3139    tooth.push(("G", arc(root_r, foot_angle, tau - foot_angle)?));
3140    let mut curves = Vec::with_capacity(tooth.len() * gear.teeth);
3141    for index in 0..gear.teeth {
3142        let angle = tau * index as f64;
3143        for (role, curve) in &tooth {
3144            curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
3145        }
3146    }
3147    // Lift the section into the plane z = h.
3148    for piece in &mut curves {
3149        for p in &mut piece.curve.control_points {
3150            p.z = p.w * h;
3151        }
3152    }
3153    snap_junctions(&mut curves);
3154    // Diameters at the heel: where each cone meets the back cone (perpendicular
3155    // to the pitch cone at cone distance r).
3156    let heel = |angle: f64| 2.0 * r * angle.sin() / (angle - delta).cos();
3157    let data = GearData {
3158        pitch_diameter: 2.0 * r * delta.sin(),
3159        tip_diameter: heel(tip),
3160        root_diameter: heel(root),
3161        ..GearData::default()
3162    };
3163    Ok(GearSection { curves, data })
3164}
3165
3166/// A straight bevel gear solid: the section's cone (every flank exactly the cone from the apex over the
3167/// spherical involute) between the front and back cones. Built directly, without booleans: the back cone
3168/// cuts every generator at the cone distance r, so each face of the tooth outline is its back curve (the
3169/// outline's trace on the back cone) scaled towards the apex down to the front cone, a ruled face whose
3170/// edges are all iso-lines. Faces carry their roles in `face.name` (`R3`, `K0`, …, `BACK`, `FRONT`).
3171pub fn bevel_solid(gear: &BevelGear) -> Result<(BrepSolid, GearData), KernelRefusal> {
3172    use crate::sweep_topology::parameter_line;
3173    let (delta, r, base) = bevel_cones(gear);
3174    // The section's own checks and data (diameters at the heel).
3175    let data = bevel_section(gear, r * delta.cos())?.data;
3176    let m = gear.module;
3177    let teeth = gear.teeth;
3178    let tau = TAU / teeth as f64;
3179    let tip = delta + gear.addendum * m / r;
3180    let root = delta - gear.dedendum * m / r;
3181    // The left flank on the sphere of radius r, as `bevel_section` positions it.
3182    let phi_at = |theta: f64| ((theta.cos() / base.cos()).clamp(-1.0, 1.0)).acos() / base.sin();
3183    let azimuth = |p: [f64; 3]| p[1].atan2(p[0]);
3184    let half = (PI * m / 2.0 - gear.backlash) / (2.0 * r * delta.sin());
3185    let shift = half + azimuth(spherical_involute(r, base, phi_at(delta)));
3186    let left = |phi: f64| {
3187        let p = spherical_involute(r, base, phi);
3188        let q = [p[0], -p[1], p[2]];
3189        let (s, c) = shift.sin_cos();
3190        [c * q[0] - s * q[1], s * q[0] + c * q[1], q[2]]
3191    };
3192    let tip_phi = phi_at(tip);
3193    let extend = !(root > base);
3194    let start_phi = if extend { 0.02 * tip_phi } else { phi_at(root) };
3195    let foot_angle = azimuth(left(start_phi));
3196    let tip_angle = azimuth(left(tip_phi));
3197    // Along the ray through p, the point on the back cone (rho sin delta + z cos delta = r).
3198    let (sd, cd) = delta.sin_cos();
3199    let back = |p: [f64; 3]| {
3200        let s = r / (p[0].hypot(p[1]) * sd + p[2] * cd);
3201        [p[0] * s, p[1] * s, p[2] * s]
3202    };
3203    // The back cone's circle at cone angle theta: (radius, height).
3204    let circle_at = |theta: f64| {
3205        let k = r / (theta - delta).cos();
3206        (k * theta.sin(), k * theta.cos())
3207    };
3208    let at = |theta: f64, angle: f64| {
3209        let (rho, z) = circle_at(theta);
3210        Vec3::new(rho * angle.cos(), rho * angle.sin(), z)
3211    };
3212    let v3 = |p: [f64; 3]| Vec3::new(p[0], p[1], p[2]);
3213    let mirror = |curve: &NurbsCurve| -> Result<NurbsCurve, KernelRefusal> {
3214        NurbsCurve::new(curve.degree, curve.knots.clone(), curve.control_points.iter().map(|p| Vec4 { x: p.x, y: -p.y, z: p.z, w: p.w }).collect()).map_err(|e| refuse("gear_fit", e))
3215    };
3216    let arc_on = |theta: f64, from: f64, to: f64| -> Result<NurbsCurve, KernelRefusal> {
3217        let (rho, z) = circle_at(theta);
3218        crate::make_arc(Vec3::new(0.0, 0.0, z), Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0), rho, from, to).map_err(|e| refuse("gear_arc", e))
3219    };
3220    let segment = |a: Vec3, b: Vec3| crate::make_line(a, b).map_err(|e| refuse("gear_edge", e));
3221    // The left flank's back curve, fitted from the exact involute (tip -> foot); the right flank mirrors it.
3222    let tolerance = 0.2 * GEAR_FIT_TOLERANCE * m;
3223    let flank = |t: f64| back(left(tip_phi - t * (tip_phi - start_phi)));
3224    let (left_back, _) = fit_on_breaks3(&flank, &adaptive_breaks3(&flank, tolerance)?)?;
3225    let right_back = mirror(&left_back)?.reversed().map_err(|e| refuse("gear_fit", e))?;
3226    let foot = v3(back(left(start_phi)));
3227    let mirrored = |p: Vec3| Vec3::new(p.x, -p.y, p.z);
3228    // Tooth 0's back curves in section order (counter-clockwise about +z).
3229    let mut tooth: Vec<(&'static str, NurbsCurve)> = Vec::new();
3230    if extend {
3231        tooth.push(("V", segment(at(root, -foot_angle), mirrored(foot))?));
3232    }
3233    tooth.push(("R", right_back));
3234    tooth.push(("K", arc_on(tip, -tip_angle, tip_angle)?));
3235    tooth.push(("L", left_back));
3236    if extend {
3237        tooth.push(("W", segment(foot, at(root, foot_angle))?));
3238    }
3239    tooth.push(("G", arc_on(root, foot_angle, tau - foot_angle)?));
3240    let mut curves: Vec<SectionCurve> = Vec::with_capacity(tooth.len() * teeth);
3241    for index in 0..teeth {
3242        for (role, curve) in &tooth {
3243            curves.push(SectionCurve { curve: rotated(curve, tau * index as f64), role, tooth: index });
3244        }
3245    }
3246    snap_junctions(&mut curves);
3247    let count = curves.len();
3248    let lambda = (r - gear.face_width) / r;
3249    let scaled = |curve: &NurbsCurve| -> Result<NurbsCurve, KernelRefusal> {
3250        NurbsCurve::new(curve.degree, curve.knots.clone(), curve.control_points.iter().map(|p| Vec4 { x: p.x * lambda, y: p.y * lambda, z: p.z * lambda, w: p.w }).collect()).map_err(|e| refuse("gear_fit", e))
3251    };
3252    let point_of = |p: Vec4| Vec3::new(p.x / p.w, p.y / p.w, p.z / p.w);
3253    let mut shell = ShellBuilder { vertices: Vec::new(), edges: Vec::new(), faces: Vec::new(), next: 0 };
3254    // Junction j starts curve j: its back and front vertices and the generator between them.
3255    let mut back_v = Vec::with_capacity(count);
3256    let mut front_v = Vec::with_capacity(count);
3257    let mut generators = Vec::with_capacity(count);
3258    for piece in &curves {
3259        let b = point_of(piece.curve.control_points[0]);
3260        let f = b.scale(lambda);
3261        let (vb, vf) = (shell.vertex(b), shell.vertex(f));
3262        generators.push(shell.edge(segment(f, b)?, vf, vb)?);
3263        back_v.push(vb);
3264        front_v.push(vf);
3265    }
3266    let mut back_e = Vec::with_capacity(count);
3267    let mut front_e = Vec::with_capacity(count);
3268    for (index, piece) in curves.iter().enumerate() {
3269        let next = (index + 1) % count;
3270        back_e.push(shell.edge(piece.curve.clone(), back_v[index], back_v[next])?);
3271        front_e.push(shell.edge(scaled(&piece.curve)?, front_v[index], front_v[next])?);
3272    }
3273    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));
3274    for (index, piece) in curves.iter().enumerate() {
3275        let next = (index + 1) % count;
3276        let rows: Vec<Vec<Vec4>> = piece.curve.control_points.iter().map(|p| vec![Vec4 { x: p.x * lambda, y: p.y * lambda, z: p.z * lambda, w: p.w }, *p]).collect();
3277        let surface = NurbsSurface::new(piece.curve.degree, 1, piece.curve.knots.clone(), vec![0.0, 0.0, 1.0, 1.0], rows).map_err(|e| refuse("gear_surface", e))?;
3278        let [u0, u1] = piece.curve.domain().map_err(|e| refuse("gear_domain", e))?;
3279        let loops = vec![vec![
3280            (front_e[index], true, line([u0, 0.0], [u1, 0.0])?),
3281            (generators[next], true, line([u1, 0.0], [u1, 1.0])?),
3282            (back_e[index], false, line([u0, 1.0], [u1, 1.0])?),
3283            (generators[index], false, line([u0, 0.0], [u0, 1.0])?),
3284        ]];
3285        shell.face(surface, true, loops, piece.suffix())?;
3286    }
3287    // The back and front cones, each one face round its apex (a pole edge there) with a seam through
3288    // junction 0. u follows the rational circle from junction 0's azimuth, v runs out from the apex.
3289    let seam = {
3290        let p = point_of(curves[0].curve.control_points[0]);
3291        p.y.atan2(p.x)
3292    };
3293    let reach = curves.iter().flat_map(|c| c.curve.control_points.iter()).map(|p| (p.x / p.w).hypot(p.y / p.w)).fold(0.0, f64::max) * 1.1 + m;
3294    let circle = crate::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), 1.0, seam, seam + TAU).map_err(|e| refuse("gear_arc", e))?;
3295    let segments = (circle.knots.len() - 6) / 2 + 1;
3296    let quarter = TAU / segments as f64;
3297    let cone = |scale: f64| -> Result<NurbsSurface, KernelRefusal> {
3298        let (apex, rim) = (scale * r / cd, scale * (r - reach * sd) / cd);
3299        let rows = circle.control_points.iter().map(|c| vec![Vec4 { x: 0.0, y: 0.0, z: apex * c.w, w: c.w }, Vec4 { x: scale * reach * c.x, y: scale * reach * c.y, z: rim * c.w, w: c.w }]).collect();
3300        NurbsSurface::new(circle.degree, 1, circle.knots.clone(), vec![0.0, 0.0, 1.0, 1.0], rows).map_err(|e| refuse("gear_surface", e))
3301    };
3302    // The circle's parameter at an angle from the seam: each span a rational quadratic arc of `quarter`, on
3303    // which tan(beta / 2) = (2 s - 1) tan(quarter / 4) about the span's middle.
3304    let parameter = |angle: f64| {
3305        let k = ((angle / quarter).floor().max(0.0) as usize).min(segments - 1);
3306        let beta = angle - (k as f64 + 0.5) * quarter;
3307        let s = ((beta / 2.0).tan() / (quarter / 4.0).tan() + 1.0) / 2.0;
3308        (k as f64 + s) / segments as f64
3309    };
3310    // Back-cone pcurves of the back curves (the front cone is the back scaled to the apex: the same pcurves).
3311    let mut cone_pcurves = Vec::with_capacity(count);
3312    for piece in &curves {
3313        let curve = &piece.curve;
3314        let [t0, t1] = curve.domain().map_err(|e| refuse("gear_domain", e))?;
3315        let mid = curve.evaluate(0.5 * (t0 + t1)).map_err(|e| refuse("gear_curve", e))?;
3316        let middle = (mid.y.atan2(mid.x) - seam).rem_euclid(TAU);
3317        // (Extended past the ends: the fit's end slopes look a step outside the edge.)
3318        let uv = |t: f64| {
3319            let p = curve.evaluate_extended(t0 + (t1 - t0) * t).unwrap_or(mid);
3320            let angle = middle + ((p.y.atan2(p.x) - seam - middle + PI).rem_euclid(TAU) - PI);
3321            [parameter(angle), p.x.hypot(p.y) / reach]
3322        };
3323        let breaks = adaptive_breaks(&uv, 1e-11)?;
3324        let (mut pcurve, _) = fit_on_breaks(&uv, &breaks)?;
3325        // On the edge's own parameter range.
3326        pcurve.knots.iter_mut().for_each(|k| *k = t0 + (t1 - t0) * *k);
3327        cone_pcurves.push(NurbsCurve::new(pcurve.degree, pcurve.knots.clone(), pcurve.control_points.clone()).map_err(|e| refuse("gear_pcurve", e))?);
3328    }
3329    let seam_v = point_of(curves[0].curve.control_points[0]).x.hypot(point_of(curves[0].curve.control_points[0]).y) / reach;
3330    for (scale, name, outline, junction) in [(1.0, "BACK", &back_e, &back_v), (lambda, "FRONT", &front_e, &front_v)] {
3331        let surface = cone(scale)?;
3332        let apex_point = Vec3::new(0.0, 0.0, scale * r / cd);
3333        let apex = shell.vertex(apex_point);
3334        let pole_curve = NurbsCurve::new(surface.degree_u, surface.knots_u.clone(), surface.control_points.iter().map(|row| row[0]).collect()).map_err(|e| refuse("gear_edge", e))?;
3335        let pole = shell.degenerate_edge(pole_curve, apex)?;
3336        let seam_point = shell.vertices.iter().find(|v| v.id == junction[0]).expect("junction 0").point;
3337        let seam_edge = shell.edge(segment(apex_point, seam_point)?, apex, junction[0])?;
3338        let mut coedges = vec![(pole, true, line([0.0, 0.0], [1.0, 0.0])?), (seam_edge, true, line([1.0, 0.0], [1.0, seam_v])?)];
3339        for index in (0..count).rev() {
3340            coedges.push((outline[index], false, cone_pcurves[index].clone()));
3341        }
3342        coedges.push((seam_edge, false, line([0.0, 0.0], [0.0, seam_v])?));
3343        // The surface's normal points to the apex side: outward for the front, inward for the back.
3344        shell.face(surface, name == "FRONT", vec![coedges], name.into())?;
3345    }
3346    let id = shell.id();
3347    let shell_id = shell.id();
3348    let solid = BrepSolid {
3349        mass_properties_cache: Default::default(),
3350        cells: Default::default(),
3351        id,
3352        vertices: shell.vertices,
3353        edges: shell.edges,
3354        shells: vec![crate::sweep_topology::ShellRecord { id: shell_id, faces: shell.faces }],
3355        genus: 0,
3356        kind: crate::BodyKind::Solid,
3357    };
3358    let issues = solid.validate();
3359    if !issues.is_empty() {
3360        return Err(KernelRefusal::internal(KernelStage::Validate, "validate", format!("bevel gear is not valid: {issues:?}")));
3361    }
3362    Ok((solid, data))
3363}
3364
3365/// The cubic Hermite span of a space curve (numeric end derivatives) as Bézier points.
3366fn hermite_span3(f: &dyn Fn(f64) -> [f64; 3], t0: f64, t1: f64) -> [[f64; 3]; 4] {
3367    let derivative = |t: f64| {
3368        let h = 1e-6;
3369        let (p, q) = (f(t + h), f(t - h));
3370        [(p[0] - q[0]) / (2.0 * h), (p[1] - q[1]) / (2.0 * h), (p[2] - q[2]) / (2.0 * h)]
3371    };
3372    let (p0, p1) = (f(t0), f(t1));
3373    let (d0, d1) = (derivative(t0), derivative(t1));
3374    let k = (t1 - t0) / 3.0;
3375    let ahead = |p: [f64; 3], d: [f64; 3], s: f64| [p[0] + s * d[0], p[1] + s * d[1], p[2] + s * d[2]];
3376    [p0, ahead(p0, d0, k), ahead(p1, d1, -k), p1]
3377}
3378
3379fn hermite_span3_error(f: &dyn Fn(f64) -> [f64; 3], t0: f64, t1: f64) -> f64 {
3380    let c = hermite_span3(f, t0, t1);
3381    [0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875]
3382        .iter()
3383        .map(|&u| {
3384            let exact = f(t0 + (t1 - t0) * u);
3385            let v = 1.0 - u;
3386            let w = [v * v * v, 3.0 * v * v * u, 3.0 * v * u * u, u * u * u];
3387            let mut d = 0.0;
3388            for axis in 0..3 {
3389                let x = w[0] * c[0][axis] + w[1] * c[1][axis] + w[2] * c[2][axis] + w[3] * c[3][axis];
3390                d += (exact[axis] - x).powi(2);
3391            }
3392            d.sqrt()
3393        })
3394        .fold(0.0, f64::max)
3395}
3396
3397fn adaptive_breaks3(f: &dyn Fn(f64) -> [f64; 3], tolerance: f64) -> Result<Vec<f64>, KernelRefusal> {
3398    let mut breaks = vec![0.0];
3399    let mut pending: Vec<(f64, f64, usize)> = (0..4).rev().map(|i| (i as f64 / 4.0, (i + 1) as f64 / 4.0, 0)).collect();
3400    while let Some((t0, t1, depth)) = pending.pop() {
3401        if hermite_span3_error(f, t0, t1) > tolerance {
3402            if depth >= 16 {
3403                return Err(refuse("gear_fit", format!("gear curve fit did not converge on [{t0}, {t1}]")));
3404            }
3405            let mid = 0.5 * (t0 + t1);
3406            pending.push((mid, t1, depth + 1));
3407            pending.push((t0, mid, depth + 1));
3408        } else {
3409            breaks.push(t1);
3410        }
3411    }
3412    Ok(breaks)
3413}
3414
3415/// A space curve on [0, 1] as C1 cubic Hermite spans at the given breaks, and its worst error.
3416fn fit_on_breaks3(f: &dyn Fn(f64) -> [f64; 3], breaks: &[f64]) -> Result<(NurbsCurve, f64), KernelRefusal> {
3417    let to_point = |p: [f64; 3]| Vec4::from_point(Vec3::new(p[0], p[1], p[2]), 1.0);
3418    let mut knots = vec![0.0; 4];
3419    let mut points = Vec::with_capacity(2 * breaks.len() + 2);
3420    let mut worst = 0.0_f64;
3421    let spans = breaks.len() - 1;
3422    for index in 0..spans {
3423        let (t0, t1) = (breaks[index], breaks[index + 1]);
3424        let c = hermite_span3(f, t0, t1);
3425        worst = worst.max(hermite_span3_error(f, t0, t1));
3426        if index == 0 {
3427            points.push(to_point(c[0]));
3428        }
3429        points.push(to_point(c[1]));
3430        points.push(to_point(c[2]));
3431        if index + 1 < spans {
3432            knots.extend([t1, t1]);
3433        } else {
3434            points.push(to_point(c[3]));
3435        }
3436    }
3437    knots.extend([1.0; 4]);
3438    Ok((NurbsCurve::new(3, knots, points).map_err(|error| refuse("gear_fit", error))?, worst))
3439}
3440
3441/// Builds a closed shell from faces whose loops are given in any direction: each loop is turned to run
3442/// counter-clockwise about the outward normal (its pcurves' area sign against `same_sense`). A face's first
3443/// loop is its outer loop.
3444pub(crate) struct ShellBuilder {
3445    pub(crate) vertices: Vec<crate::sweep_topology::VertexRecord>,
3446    pub(crate) edges: Vec<crate::sweep_topology::EdgeRecord>,
3447    pub(crate) faces: Vec<crate::sweep_topology::FaceRecord>,
3448    pub(crate) next: u64,
3449}
3450
3451impl ShellBuilder {
3452    pub(crate) fn id(&mut self) -> u64 {
3453        self.next += 1;
3454        self.next
3455    }
3456
3457    pub(crate) fn vertex(&mut self, p: Vec3) -> u64 {
3458        let id = self.id();
3459        self.vertices.push(crate::sweep_topology::VertexRecord { id, point: p });
3460        id
3461    }
3462
3463    pub(crate) fn edge(&mut self, curve: NurbsCurve, start: u64, end: u64) -> Result<u64, KernelRefusal> {
3464        let [t0, t1] = curve.domain().map_err(|e| refuse("gear_domain", e))?;
3465        let id = self.id();
3466        self.edges.push(crate::sweep_topology::EdgeRecord { id, curve, t0, t1, start_vertex_id: start, end_vertex_id: end, degenerate: false, name: None });
3467        Ok(id)
3468    }
3469
3470    /// A pole: an edge collapsed to the vertex `at` (its curve the surface's iso-curve there).
3471    pub(crate) fn degenerate_edge(&mut self, curve: NurbsCurve, at: u64) -> Result<u64, KernelRefusal> {
3472        let [t0, t1] = curve.domain().map_err(|e| refuse("gear_domain", e))?;
3473        let id = self.id();
3474        self.edges.push(crate::sweep_topology::EdgeRecord { id, curve, t0, t1, start_vertex_id: at, end_vertex_id: at, degenerate: true, name: None });
3475        Ok(id)
3476    }
3477
3478    #[allow(dead_code)]
3479    pub(crate) fn curve(&self, edge: u64) -> &NurbsCurve {
3480        &self.edges.iter().find(|e| e.id == edge).expect("a known edge").curve
3481    }
3482
3483    /// `loops`: (edge, forward, pcurve along the edge's own direction).
3484    pub(crate) fn face(&mut self, surface: NurbsSurface, same_sense: bool, loops: Vec<Vec<(u64, bool, NurbsCurve)>>, name: String) -> Result<(), KernelRefusal> {
3485        use crate::sweep_topology::{CoedgeRecord, FaceRecord, LoopRecord};
3486        let area = |coedges: &[(u64, bool, NurbsCurve)]| -> Result<f64, KernelRefusal> {
3487            let mut points = Vec::new();
3488            for (_, forward, pcurve) in coedges {
3489                let [a, b] = pcurve.domain().map_err(|e| refuse("gear_pcurve", e))?;
3490                for i in 0..16 {
3491                    let f = i as f64 / 16.0;
3492                    let t = if *forward { a + (b - a) * f } else { b - (b - a) * f };
3493                    points.push(pcurve.evaluate(t).map_err(|e| refuse("gear_pcurve", e))?);
3494                }
3495            }
3496            Ok((0..points.len()).map(|i| {
3497                let (p, q) = (points[i], points[(i + 1) % points.len()]);
3498                p.x * q.y - q.x * p.y
3499            }).sum::<f64>() / 2.0)
3500        };
3501        // The first loop is the outer one (a sampled area cannot tell: a hole of many short edges can out-measure
3502        // an outer circle of one).
3503        let areas: Vec<f64> = loops.iter().map(|l| area(l)).collect::<Result<_, _>>()?;
3504        let outer = 0;
3505        let mut records = Vec::with_capacity(loops.len());
3506        for (index, coedges) in loops.into_iter().enumerate() {
3507            let want = (index == outer) == same_sense;
3508            let mut coedges = coedges;
3509            if (areas[index] > 0.0) != want {
3510                coedges.reverse();
3511                for coedge in &mut coedges {
3512                    coedge.1 = !coedge.1;
3513                }
3514            }
3515            let mut out = Vec::with_capacity(coedges.len());
3516            for (edge, forward, pcurve) in coedges {
3517                let pcurve = if forward { pcurve } else { pcurve.reversed().map_err(|e| refuse("gear_pcurve", e))? };
3518                out.push(CoedgeRecord { id: self.id(), edge_id: edge, forward, pcurve });
3519            }
3520            records.push(LoopRecord { id: self.id(), coedges: out });
3521        }
3522        let id = self.id();
3523        self.faces.push(FaceRecord { id, surface, same_sense, loops: records, name: Some(name) });
3524        Ok(())
3525    }
3526}
3527
3528/// An elliptical gear: the pitch curve is an ellipse turning about one of its
3529/// foci, and the teeth are generated by rolling the standard basic rack round
3530/// it without slip (the rack's pitch line tangent to the ellipse, the contact
3531/// normal through the touching point), as a spur gear is generated round its
3532/// pitch circle. Two identical elliptical gears with an odd tooth count mesh
3533/// at a centre distance of the major axis (see [`elliptical_sizes`]).
3534///
3535/// The ellipse is sized so its perimeter is exactly `teeth` circular pitches
3536/// (π · module), so the teeth close. Tooth 0 is centred on the near vertex
3537/// (on +x, closest to the pivot).
3538#[derive(Clone, Debug)]
3539pub struct EllipticalGear {
3540    pub module: f64,
3541    pub teeth: usize,
3542    /// Eccentricity of the pitch ellipse (0 is a spur gear turning about its centre).
3543    pub eccentricity: f64,
3544    pub pressure_angle: f64,
3545    /// Addendum coefficient × module, measured normal to the pitch curve.
3546    pub addendum: f64,
3547    /// Dedendum coefficient × module, normal to the pitch curve.
3548    pub dedendum: f64,
3549    /// Tip radius of the generating rack × module.
3550    pub root_fillet: f64,
3551    /// Arc length added to each tooth space along the pitch curve.
3552    pub backlash: f64,
3553    pub face_width: f64,
3554}
3555
3556/// The pitch ellipse about its focus, by arc length.
3557struct PitchEllipse {
3558    /// Semi-latus rectum: r(θ) = p / (1 + e cos nθ) about the focus (n = 1, an ellipse) or the centre (n lobes).
3559    latus: f64,
3560    e: f64,
3561    lobes: f64,
3562    segments: usize,
3563    /// Cumulative arc length at θ = 2π i / SEGMENTS.
3564    table: Vec<f64>,
3565}
3566
3567impl PitchEllipse {
3568    const SEGMENTS: usize = 1024;
3569
3570    fn new(latus: f64, e: f64) -> Self {
3571        Self::lobed(latus, e, 1)
3572    }
3573
3574    fn lobed(latus: f64, e: f64, lobes: usize) -> Self {
3575        let segments = Self::SEGMENTS * lobes.max(1);
3576        let mut curve = Self { latus, e, lobes: lobes.max(1) as f64, segments, table: Vec::with_capacity(segments + 1) };
3577        // Five-point Gauss-Legendre per segment.
3578        let nodes = [0.0, -0.538_469_310_105_683_1, 0.538_469_310_105_683_1, -0.906_179_845_938_664, 0.906_179_845_938_664];
3579        let weights = [0.568_888_888_888_888_9, 0.478_628_670_499_366_5, 0.478_628_670_499_366_5, 0.236_926_885_056_189_1, 0.236_926_885_056_189_1];
3580        let step = TAU / segments as f64;
3581        let mut total = 0.0;
3582        curve.table.push(0.0);
3583        for i in 0..segments {
3584            let mid = (i as f64 + 0.5) * step;
3585            let sum: f64 = nodes.iter().zip(&weights).map(|(x, w)| w * curve.speed(mid + 0.5 * step * x)).sum();
3586            total += 0.5 * step * sum;
3587            curve.table.push(total);
3588        }
3589        curve
3590    }
3591
3592    fn length(&self) -> f64 {
3593        self.table[self.segments]
3594    }
3595
3596    /// Point, first and second derivatives in θ.
3597    fn derivatives(&self, theta: f64) -> ([f64; 2], [f64; 2], [f64; 2]) {
3598        let n = self.lobes;
3599        let (s, c) = theta.sin_cos();
3600        let (sn, cn) = (n * theta).sin_cos();
3601        let d = 1.0 + self.e * cn;
3602        let d1 = -self.e * n * sn;
3603        let d2 = -self.e * n * n * cn;
3604        let r = self.latus / d;
3605        let r1 = -self.latus * d1 / (d * d);
3606        let r2 = -self.latus * (d2 * d - 2.0 * d1 * d1) / (d * d * d);
3607        (
3608            [r * c, r * s],
3609            [r1 * c - r * s, r1 * s + r * c],
3610            [r2 * c - 2.0 * r1 * s - r * c, r2 * s + 2.0 * r1 * c - r * s],
3611        )
3612    }
3613
3614    fn speed(&self, theta: f64) -> f64 {
3615        let (_, d1, _) = self.derivatives(theta);
3616        d1[0].hypot(d1[1])
3617    }
3618
3619    /// The polar angle at arc length `s` (any real; the curve is periodic).
3620    fn theta_at(&self, s: f64) -> f64 {
3621        let length = self.length();
3622        let turns = (s / length).floor();
3623        let local = s - turns * length;
3624        let index = self.table.partition_point(|&value| value <= local).clamp(1, self.segments) - 1;
3625        let step = TAU / self.segments as f64;
3626        let (lo, hi) = (index as f64 * step, (index + 1) as f64 * step);
3627        let span = self.table[index + 1] - self.table[index];
3628        let mut theta = lo + step * (local - self.table[index]) / span;
3629        // Newton on the segment's arc length, measured from its start by Gauss-Legendre.
3630        let nodes = [0.0, -0.538_469_310_105_683_1, 0.538_469_310_105_683_1, -0.906_179_845_938_664, 0.906_179_845_938_664];
3631        let weights = [0.568_888_888_888_888_9, 0.478_628_670_499_366_5, 0.478_628_670_499_366_5, 0.236_926_885_056_189_1, 0.236_926_885_056_189_1];
3632        for _ in 0..8 {
3633            let half = 0.5 * (theta - lo);
3634            let arc: f64 = half * nodes.iter().zip(&weights).map(|(x, w)| w * self.speed(lo + half * (1.0 + x))).sum::<f64>();
3635            let error = self.table[index] + arc - local;
3636            theta = (theta - error / self.speed(theta)).clamp(lo, hi);
3637            if error.abs() < 1e-15 * length {
3638                break;
3639            }
3640        }
3641        theta + turns * TAU
3642    }
3643
3644    /// Point, unit tangent (counter-clockwise), outward unit normal and signed curvature at arc length `s`.
3645    fn frame(&self, s: f64) -> ([f64; 2], [f64; 2], [f64; 2], f64) {
3646        let (p, d1, d2) = self.derivatives(self.theta_at(s));
3647        let speed = d1[0].hypot(d1[1]);
3648        let t = [d1[0] / speed, d1[1] / speed];
3649        let curvature = (d1[0] * d2[1] - d1[1] * d2[0]) / speed.powi(3);
3650        (p, t, [t[1], -t[0]], curvature)
3651    }
3652}
3653
3654/// The derived sizes of an elliptical gear: (semi-major axis, eccentricity,
3655/// perimeter, centre distance to an identical mate = 2 × semi-major axis).
3656pub fn elliptical_sizes(gear: &EllipticalGear) -> (f64, f64, f64, f64) {
3657    lobed_sizes(gear, 1)
3658}
3659
3660/// [`elliptical_sizes`] for a pitch curve of `lobes` lobes, r(θ) = a (1 − e²) / (1 + e cos(lobes · θ)) about its
3661/// centre (one lobe: the ellipse about its focus). Two equal gears roll on it at the same centre distance 2a.
3662pub fn lobed_sizes(gear: &EllipticalGear, lobes: usize) -> (f64, f64, f64, f64) {
3663    let e = gear.eccentricity;
3664    let unit = PitchEllipse::lobed(1.0 - e * e, e, lobes); // a = 1
3665    let a = PI * gear.module * gear.teeth as f64 / unit.length();
3666    (a, e, PI * gear.module * gear.teeth as f64, 2.0 * a)
3667}
3668
3669/// The rack, pitch line on y = 0 with +y away from the gear, rolled to arc
3670/// length `s`: rack point (x, y) lies at P(s) + (x − s) T(s) + y N(s).
3671struct RollingRack<'a> {
3672    pitch: &'a PitchEllipse,
3673}
3674
3675impl RollingRack<'_> {
3676    /// The gear point generated by the rack point `q` with normal direction `n`
3677    /// (either sense): the normal through q meets the pitch line at the rolling position.
3678    fn envelope(&self, q: [f64; 2], n: [f64; 2]) -> [f64; 2] {
3679        let s = q[0] - q[1] * n[0] / n[1];
3680        self.place(q, s)
3681    }
3682
3683    fn place(&self, q: [f64; 2], s: f64) -> [f64; 2] {
3684        let (p, t, n, _) = self.pitch.frame(s);
3685        let u = q[0] - s;
3686        [p[0] + u * t[0] + q[1] * n[0], p[1] + u * t[1] + q[1] * n[1]]
3687    }
3688
3689    /// The arc length of the foot of the normal from `g` to the pitch curve
3690    /// (starting near `guess`) and the signed distance along the outward normal.
3691    fn foot(&self, g: [f64; 2], guess: f64) -> (f64, f64) {
3692        let mut sigma = guess;
3693        for _ in 0..40 {
3694            let (p, t, n, curvature) = self.pitch.frame(sigma);
3695            let v = [g[0] - p[0], g[1] - p[1]];
3696            let along = v[0] * t[0] + v[1] * t[1];
3697            let distance = v[0] * n[0] + v[1] * n[1];
3698            let step = along / (1.0 + curvature * distance);
3699            sigma += step;
3700            if step.abs() < 1e-15 * self.pitch.length() {
3701                break;
3702            }
3703        }
3704        let (p, _, n, _) = self.pitch.frame(sigma);
3705        (sigma, (g[0] - p[0]) * n[0] + (g[1] - p[1]) * n[1])
3706    }
3707}
3708
3709/// The elliptical gear section, counter-clockwise about the pivot (the focus,
3710/// at the origin). Roles per tooth k, as the spur gear's: `V<k>` root fillet,
3711/// `R<k>` flank rising to `K<k>` the tip land (normal offset of the pitch
3712/// curve), `L<k>` the falling flank, `W<k>` root fillet, `G<k>` the root land
3713/// (inward offset) of the space after tooth k.
3714pub fn elliptical_section(gear: &EllipticalGear) -> Result<GearSection, KernelRefusal> {
3715    lobed_section(gear, 1)
3716}
3717
3718/// [`elliptical_section`] on a pitch curve of `lobes` lobes about its centre ([`lobed_sizes`]); tooth 0 is
3719/// centred on +x, where the curve is nearest its axis.
3720pub fn lobed_section(gear: &EllipticalGear, lobes: usize) -> Result<GearSection, KernelRefusal> {
3721    if !(1..=8).contains(&lobes) {
3722        return Err(refuse("gear_input", format!("A lobed pitch curve has 1 to 8 lobes (not {lobes}).")));
3723    }
3724    let m = gear.module;
3725    if !(m > 0.0 && gear.face_width > 0.0 && gear.addendum > 0.0 && gear.dedendum > 0.0) {
3726        return Err(refuse("gear_input", "The module, face width, addendum and dedendum must be positive.".into()));
3727    }
3728    if !(gear.root_fillet >= 0.0 && gear.backlash >= 0.0) {
3729        return Err(refuse("gear_input", "The root fillet and the backlash cannot be negative.".into()));
3730    }
3731    if !(0.0..=0.8).contains(&gear.eccentricity) {
3732        return Err(refuse("gear_input", format!("The eccentricity must be from 0 to 0.8 (it is {}).", gear.eccentricity)));
3733    }
3734    if gear.teeth < 8 || gear.teeth > 1000 {
3735        return Err(refuse("gear_input", format!("An elliptical gear needs from 8 to 1000 teeth (it has {}).", gear.teeth)));
3736    }
3737    let degrees = gear.pressure_angle.to_degrees();
3738    if !(10.0 - 1e-9..=35.0 + 1e-9).contains(&degrees) {
3739        return Err(refuse("gear_input", format!("The pressure angle must be between 10° and 35° (it is {degrees}°).")));
3740    }
3741    let (a, e, perimeter, _) = lobed_sizes(gear, lobes);
3742    let pitch_curve = PitchEllipse::lobed(a * (1.0 - e * e), e, lobes);
3743    let rack = RollingRack { pitch: &pitch_curve };
3744    let z = gear.teeth as f64;
3745    let p = perimeter / z;
3746    let alpha = gear.pressure_angle;
3747    let (sin_a, cos_a, tan_a) = (alpha.sin(), alpha.cos(), alpha.tan());
3748    let h_a = gear.addendum * m;
3749    let h_f = gear.dedendum * m;
3750    let rho = gear.root_fillet * m;
3751    let tolerance = GEAR_FIT_TOLERANCE * m;
3752    // The sharpest point of the ellipse is its major vertex: radius b²/a.
3753    // The sharpest point's radius of curvature: the ellipse's major vertex b²/a; with lobes, read off the curve
3754    // (which must be convex for a rack to roll round it).
3755    let min_radius = if lobes == 1 {
3756        a * (1.0 - e * e)
3757    } else {
3758        let mut least = f64::INFINITY;
3759        for i in 0..4096 {
3760            let (_, d1, d2) = pitch_curve.derivatives(TAU * i as f64 / 4096.0);
3761            let cross = d1[0] * d2[1] - d1[1] * d2[0];
3762            if !(cross > 0.0) {
3763                return Err(refuse("not_convex", format!("The {lobes}-lobe pitch curve is not convex at this eccentricity ({e}): a rack cannot roll round it; lower the eccentricity.")));
3764            }
3765            least = least.min(d1[0].hypot(d1[1]).powi(3) / cross);
3766        }
3767        least
3768    };
3769    if h_f >= min_radius {
3770        return Err(refuse(
3771            "undercut",
3772            format!("The root would fold at the ellipse's ends (radius of curvature {min_radius:.4} there): add teeth or lower the eccentricity."),
3773        ));
3774    }
3775    // Cutter tooth centred on x = 0 (it cuts the space there): half width at height y is w0 + y tan α.
3776    let w0 = p / 4.0 + gear.backlash / 2.0;
3777    let centre_y = -h_f + rho;
3778    let centre_x = -w0 - (centre_y - rho * sin_a) * tan_a + rho * cos_a; // low-side fillet centre
3779    if centre_x >= 0.0 {
3780        return Err(refuse("root_fillet_too_large", "The root fillet is larger than fits the tooth space; lower it.".into()));
3781    }
3782    let y_join = centre_y - rho * sin_a;
3783    let low_flank = |c: f64, y: f64| rack.envelope([c - w0 - y * tan_a, y], [cos_a, sin_a]);
3784    let high_flank = |c: f64, y: f64| rack.envelope([c + w0 + y * tan_a, y], [-cos_a, sin_a]);
3785    // ψ ∈ [0, 1]: from the flank tangency (0) to the tip line (1).
3786    let fillet_normal = |t: f64| {
3787        let psi = -PI + alpha + t * (PI / 2.0 - alpha);
3788        [psi.cos(), psi.sin()]
3789    };
3790    let low_fillet = |c: f64, t: f64| {
3791        let n = fillet_normal(t);
3792        if rho == 0.0 {
3793            return rack.envelope([c + centre_x, centre_y], n);
3794        }
3795        rack.envelope([c + centre_x + rho * n[0], centre_y + rho * n[1]], n)
3796    };
3797    let high_fillet = |c: f64, t: f64| {
3798        let n = fillet_normal(t);
3799        if rho == 0.0 {
3800            return rack.envelope([c - centre_x, centre_y], [-n[0], n[1]]);
3801        }
3802        rack.envelope([c - centre_x - rho * n[0], centre_y + rho * n[1]], [-n[0], n[1]])
3803    };
3804    let root = |x: f64| rack.place([x, -h_f], x);
3805    let tip = |sigma: f64| {
3806        let (q, _, n, _) = pitch_curve.frame(sigma);
3807        [q[0] + h_a * n[0], q[1] + h_a * n[1]]
3808    };
3809    // The generated flank is regular while sin²α + y κ > 0 down to its foot (it cusps
3810    // where the rack flank passes the point of interference); κ is largest, 1 / min_radius,
3811    // at the major vertices.
3812    if sin_a * sin_a + y_join / min_radius <= 1e-9 {
3813        return Err(refuse(
3814            "undercut",
3815            format!(
3816                "The teeth would be undercut where the ellipse is sharpest (radius of curvature {min_radius:.4}): add teeth, lower the eccentricity or raise the pressure angle."
3817            ),
3818        ));
3819    }
3820    // The flank height where a generated flank reaches the tip offset (offset distance h_a).
3821    let top_of = |flank: &dyn Fn(f64) -> [f64; 2], guess: f64| -> Result<(f64, f64), KernelRefusal> {
3822        let offset = |y: f64| rack.foot(flank(y), guess).1 - h_a;
3823        let (mut lo, mut hi) = (y_join, h_a + 2.0 * m);
3824        if !(offset(lo) < 0.0 && offset(hi) > 0.0) {
3825            return Err(refuse("gear_fit", "The generated flank does not reach the tip curve.".into()));
3826        }
3827        // Until the interval stops shrinking (about 55 halvings), not a fixed 200 evaluations.
3828        for _ in 0..200 {
3829            let mid = 0.5 * (lo + hi);
3830            if !(mid > lo && mid < hi) {
3831                break;
3832            }
3833            if offset(mid) < 0.0 { lo = mid } else { hi = mid }
3834        }
3835        let y = 0.5 * (lo + hi);
3836        Ok((y, rack.foot(flank(y), guess).0))
3837    };
3838    let mut curves = Vec::with_capacity(6 * gear.teeth);
3839    let reversed = |curve: NurbsCurve| curve.reversed().map_err(|error| refuse("gear_fit", error));
3840    for k in 0..gear.teeth {
3841        let before = (k as f64 - 0.5) * p; // the space before tooth k
3842        let after = (k as f64 + 0.5) * p;
3843        let rising = |y: f64| high_flank(before, y);
3844        let falling = |y: f64| low_flank(after, y);
3845        let (y_rise, sigma_rise) = top_of(&rising, k as f64 * p - w0)?;
3846        let (y_fall, sigma_fall) = top_of(&falling, k as f64 * p + w0)?;
3847        if sigma_fall - sigma_rise <= 1e-6 * m {
3848            return Err(refuse("pointed_tip", "The teeth come to a point below the tip curve: reduce the addendum or the backlash.".into()));
3849        }
3850        curves.push(SectionCurve { curve: reversed(fit_planar(&|t| high_fillet(before, t), 0.0, 1.0, tolerance)?)?, role: "V", tooth: k });
3851        curves.push(SectionCurve { curve: fit_planar(&rising, y_join, y_rise, tolerance)?, role: "R", tooth: k });
3852        curves.push(SectionCurve { curve: fit_planar(&tip, sigma_rise, sigma_fall, tolerance)?, role: "K", tooth: k });
3853        curves.push(SectionCurve { curve: reversed(fit_planar(&falling, y_join, y_fall, tolerance)?)?, role: "L", tooth: k });
3854        curves.push(SectionCurve { curve: fit_planar(&|t| low_fillet(after, t), 0.0, 1.0, tolerance)?, role: "W", tooth: k });
3855        if centre_x < -1e-9 * m {
3856            curves.push(SectionCurve { curve: fit_planar(&root, after + centre_x, after - centre_x, tolerance)?, role: "G", tooth: k });
3857        }
3858    }
3859    snap_junctions(&mut curves);
3860    let samples = 4096;
3861    let (mut tip_max, mut root_min) = (0.0_f64, f64::INFINITY);
3862    for i in 0..samples {
3863        let s = perimeter * i as f64 / samples as f64;
3864        tip_max = tip_max.max(radius_of(tip(s)));
3865        root_min = root_min.min(radius_of(rack.place([s, -h_f], s)));
3866    }
3867    let data = GearData {
3868        pitch_diameter: perimeter / PI,
3869        tip_diameter: 2.0 * tip_max,
3870        root_diameter: 2.0 * root_min,
3871        tooth_thickness: p / 2.0 - gear.backlash,
3872        ..GearData::default()
3873    };
3874    Ok(GearSection { curves, data })
3875}
3876
3877/// An elliptical gear solid: the section extruded along +z by the face width;
3878/// names as the section's roles, then `F` and `B`.
3879pub fn elliptical_solid(gear: &EllipticalGear) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
3880    lobed_solid(gear, 1)
3881}
3882
3883/// A lobed non-circular gear solid ([`lobed_section`] extruded by the face width), names as the elliptical gear's.
3884pub fn lobed_solid(gear: &EllipticalGear, lobes: usize) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
3885    let section = lobed_section(gear, lobes)?;
3886    let solid = extrude_section(&section, gear.face_width)?;
3887    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
3888    names.push("F".into());
3889    names.push("B".into());
3890    Ok((solid, names, section.data))
3891}
3892
3893/// The parameter breaks (normalised to [0, 1]) at which [`fit_planar`] would
3894/// split `f` on `[a, b]` to fit it within `tolerance`.
3895fn adaptive_breaks(f: &dyn Fn(f64) -> [f64; 2], tolerance: f64) -> Result<Vec<f64>, KernelRefusal> {
3896    let mut breaks = vec![0.0];
3897    let mut pending: Vec<(f64, f64, usize)> = (0..4).rev().map(|i| (i as f64 / 4.0, (i + 1) as f64 / 4.0, 0)).collect();
3898    while let Some((t0, t1, depth)) = pending.pop() {
3899        if hermite_span_error(f, t0, t1) > tolerance {
3900            if depth >= 16 {
3901                return Err(refuse("gear_fit", format!("gear curve fit did not converge on [{t0}, {t1}]")));
3902            }
3903            let mid = 0.5 * (t0 + t1);
3904            pending.push((mid, t1, depth + 1));
3905            pending.push((t0, mid, depth + 1));
3906        } else {
3907            breaks.push(t1);
3908        }
3909    }
3910    Ok(breaks)
3911}
3912
3913/// The cubic Hermite span of `f` on `[t0, t1]` (numeric end derivatives) as Bézier points.
3914fn hermite_span(f: &dyn Fn(f64) -> [f64; 2], t0: f64, t1: f64) -> [[f64; 2]; 4] {
3915    let derivative = |t: f64| {
3916        let h = 1e-6;
3917        let (p, q) = (f(t + h), f(t - h));
3918        [(p[0] - q[0]) / (2.0 * h), (p[1] - q[1]) / (2.0 * h)]
3919    };
3920    let (p0, p1) = (f(t0), f(t1));
3921    let (d0, d1) = (derivative(t0), derivative(t1));
3922    let k = (t1 - t0) / 3.0;
3923    [p0, [p0[0] + d0[0] * k, p0[1] + d0[1] * k], [p1[0] - d1[0] * k, p1[1] - d1[1] * k], p1]
3924}
3925
3926fn hermite_span_error(f: &dyn Fn(f64) -> [f64; 2], t0: f64, t1: f64) -> f64 {
3927    let c = hermite_span(f, t0, t1);
3928    [0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875]
3929        .iter()
3930        .map(|&u| {
3931            let exact = f(t0 + (t1 - t0) * u);
3932            let v = 1.0 - u;
3933            let w = [v * v * v, 3.0 * v * v * u, 3.0 * v * u * u, u * u * u];
3934            let x = w[0] * c[0][0] + w[1] * c[1][0] + w[2] * c[2][0] + w[3] * c[3][0];
3935            let y = w[0] * c[0][1] + w[1] * c[1][1] + w[2] * c[2][1] + w[3] * c[3][1];
3936            (exact[0] - x).hypot(exact[1] - y)
3937        })
3938        .fold(0.0, f64::max)
3939}
3940
3941/// `f` on [0, 1] as C1 cubic Hermite spans at the given breaks (as
3942/// [`fit_planar`] lays them out), and its worst error over the spans.
3943fn fit_on_breaks(f: &dyn Fn(f64) -> [f64; 2], breaks: &[f64]) -> Result<(NurbsCurve, f64), KernelRefusal> {
3944    let to_point = |p: [f64; 2]| Vec4::from_point(Vec3::new(p[0], p[1], 0.0), 1.0);
3945    let mut knots = vec![0.0; 4];
3946    let mut points = Vec::with_capacity(2 * breaks.len() + 2);
3947    let mut worst = 0.0_f64;
3948    let spans = breaks.len() - 1;
3949    for index in 0..spans {
3950        let (t0, t1) = (breaks[index], breaks[index + 1]);
3951        let c = hermite_span(f, t0, t1);
3952        worst = worst.max(hermite_span_error(f, t0, t1));
3953        if index == 0 {
3954            points.push(to_point(c[0]));
3955        }
3956        points.push(to_point(c[1]));
3957        points.push(to_point(c[2]));
3958        if index + 1 < spans {
3959            knots.extend([t1, t1]);
3960        } else {
3961            points.push(to_point(c[3]));
3962        }
3963    }
3964    knots.extend([1.0; 4]);
3965    Ok((NurbsCurve::new(3, knots, points).map_err(|error| refuse("gear_fit", error))?, worst))
3966}
3967
3968/// A throated (single-enveloping) worm wheel: the teeth are cut as a hob of
3969/// the mating ZA worm cuts them, the worm's thread swept by the generating
3970/// motion (the worm turning, the wheel turning with it at the gear ratio).
3971/// In every plane across the face width the worm's thread section moves as a
3972/// rack and the wheel section is its envelope; the flanks, tips (the throat,
3973/// a torus about the worm's axis) and roots are skinned through those
3974/// sections. Front face on z = 0, back face on z = face width; the worm's
3975/// axis runs along +y at x = centre distance, z = face width / 2.
3976#[derive(Clone, Debug)]
3977pub struct WormWheel {
3978    /// The mating worm (its length is not used).
3979    pub worm: Worm,
3980    pub teeth: usize,
3981    /// Wheel addendum × module, in the mid-plane (the throat).
3982    pub addendum: f64,
3983    /// Wheel dedendum × module, in the mid-plane: the hob's tip (the worm's tip plus the clearance).
3984    pub dedendum: f64,
3985    pub face_width: f64,
3986    /// Axial backlash: the hob's thread is that much thicker than the worm's.
3987    pub backlash: f64,
3988}
3989
3990/// The worm wheel's sizes: (pitch radius, centre distance, throat radius in the mid-plane, outside radius at the faces).
3991pub fn worm_wheel_sizes(wheel: &WormWheel) -> (f64, f64, f64, f64) {
3992    let m = wheel.worm.axial_module;
3993    let r2 = m * wheel.teeth as f64 / 2.0;
3994    let a = r2 + wheel.worm.reference_diameter / 2.0;
3995    let throat = r2 + wheel.addendum * m;
3996    let tube = a - throat;
3997    let half = wheel.face_width / 2.0;
3998    (r2, a, throat, a - (tube * tube - half * half).max(0.0).sqrt())
3999}
4000
4001/// One plane z = c (from the mid-plane) of the wheel: the hob section as a rack.
4002struct WheelPlane<'a> {
4003    wheel: &'a WormWheel,
4004    c: f64,
4005    r2: f64,
4006    a: f64,
4007    /// The hob's tip radius about the worm axis.
4008    rho_tip: f64,
4009    /// The wheel's tip (throat) radius in this plane.
4010    r_tip: f64,
4011    /// Flank parameters (radius about the worm axis) where each flank reaches the tip: [- side, + side].
4012    rho_clip: [f64; 2],
4013}
4014
4015impl<'a> WheelPlane<'a> {
4016    fn new(wheel: &'a WormWheel, c: f64) -> Result<Self, KernelRefusal> {
4017        let m = wheel.worm.axial_module;
4018        let (r2, a, throat, _) = worm_wheel_sizes(wheel);
4019        let rho_tip = a - (r2 - wheel.dedendum * m);
4020        let tube = a - throat;
4021        let r_tip = a - (tube * tube - c * c).sqrt();
4022        let mut plane = Self { wheel, c, r2, a, rho_tip, r_tip, rho_clip: [0.0; 2] };
4023        for (index, side) in [-1.0, 1.0].into_iter().enumerate() {
4024            // The generated flank falls from above the tip to the root. A hob point with rho under the throat's
4025            // tube radius sits beyond the throat (x = a - sqrt(rho^2 - c^2) > r_tip), and so does its envelope.
4026            let (mut lo, mut hi) = (0.5 * (c.abs() + tube), rho_tip);
4027            if !(radius_of(plane.flank(side, lo)) > r_tip && radius_of(plane.flank(side, hi)) < r_tip) {
4028                return Err(refuse("gear_fit", "A worm wheel flank does not reach its throat.".into()));
4029            }
4030            for _ in 0..200 {
4031                let mid = 0.5 * (lo + hi);
4032                if !(mid > lo && mid < hi) {
4033                    break;
4034                }
4035                if radius_of(plane.flank(side, mid)) > r_tip { lo = mid } else { hi = mid }
4036            }
4037            plane.rho_clip[index] = 0.5 * (lo + hi);
4038        }
4039        Ok(plane)
4040    }
4041
4042    /// The hob flank point (radial x from the wheel axis, y along the worm axis) at radius `rho`
4043    /// about the worm axis, on the `side` (±1) of the thread centred on y = 0.
4044    fn hob(&self, side: f64, rho: f64) -> [f64; 2] {
4045        let worm = &self.wheel.worm;
4046        let hand = if worm.hand == Hand::Right { 1.0 } else { -1.0 };
4047        let thickness = worm.axial_thickness(rho) + self.wheel.backlash;
4048        let angle = (self.c / rho).clamp(-1.0, 1.0).asin();
4049        [self.a - (rho * rho - self.c * self.c).max(0.0).sqrt(), side * thickness / 2.0 + hand * worm.lead() * angle / TAU]
4050    }
4051
4052    fn hob_normal(&self, side: f64, rho: f64) -> [f64; 2] {
4053        // d/drho of hob(): x = a - sqrt(rho^2 - c^2), y = side t(rho) / 2 + hand L asin(c / rho) / 2 pi (exact:
4054        // a difference quotient's rounding noise is magnified by the fits' own derivative steps).
4055        let worm = &self.wheel.worm;
4056        let hand = if worm.hand == Hand::Right { 1.0 } else { -1.0 };
4057        let root = (rho * rho - self.c * self.c).max(1e-300).sqrt();
4058        let t = [-rho / root, -side * worm.pressure_angle.tan() - hand * worm.lead() * self.c / (TAU * rho * root)];
4059        let length = t[0].hypot(t[1]);
4060        // Outward of the thread: +y on the + side.
4061        let n = [-t[1] / length, t[0] / length];
4062        if n[1] * side >= 0.0 { n } else { [-n[0], -n[1]] }
4063    }
4064
4065    /// The wheel point generated by the hob point `q` with normal `n` (rolling at the pitch radius).
4066    fn envelope(&self, q: [f64; 2], n: [f64; 2]) -> [f64; 2] {
4067        let s = (q[0] - self.r2) * n[1] / n[0] - q[1];
4068        rotate([q[0], q[1] + s], -s / self.r2)
4069    }
4070
4071    fn flank(&self, side: f64, rho: f64) -> [f64; 2] {
4072        self.envelope(self.hob(side, rho), self.hob_normal(side, rho))
4073    }
4074
4075    /// The root fillet the hob's sharp tip corner traces, `t` from the flank (0) to the tip land (1).
4076    fn fillet(&self, side: f64, t: f64) -> [f64; 2] {
4077        let n = self.hob_normal(side, self.rho_tip);
4078        let from = n[1].atan2(n[0]);
4079        let psi = from + t * (side * PI - from);
4080        self.envelope(self.hob(side, self.rho_tip), [psi.cos(), psi.sin()])
4081    }
4082
4083    /// The six pieces of tooth 0 on normalised parameters, in section order V, R, K, L, W, G.
4084    fn piece(&self, role: usize, t: f64) -> [f64; 2] {
4085        let tau = TAU / self.wheel.teeth as f64;
4086        let half = tau / 2.0;
4087        let turn = |p: [f64; 2], angle: f64| rotate(p, angle);
4088        let root_r = self.a - (self.rho_tip * self.rho_tip - self.c * self.c).sqrt();
4089        match role {
4090            0 => turn(self.fillet(1.0, 1.0 - t), -half),
4091            1 => turn(self.flank(1.0, self.rho_tip + t * (self.rho_clip[1] - self.rho_tip)), -half),
4092            2 => {
4093                let from = polar_angle(self.flank(1.0, self.rho_clip[1]));
4094                let to = tau + polar_angle(self.flank(-1.0, self.rho_clip[0]));
4095                let angle = from + t * (to - from) - half;
4096                [self.r_tip * angle.cos(), self.r_tip * angle.sin()]
4097            }
4098            3 => turn(self.flank(-1.0, self.rho_clip[0] + t * (self.rho_tip - self.rho_clip[0])), half),
4099            4 => turn(self.fillet(-1.0, t), half),
4100            _ => {
4101                // The root land of the space after the tooth (the base space turned by tau, then by -half).
4102                let from = polar_angle(self.fillet(-1.0, 1.0));
4103                let to = polar_angle(self.fillet(1.0, 1.0));
4104                let angle = from + t * (to - from) + half;
4105                [root_r * angle.cos(), root_r * angle.sin()]
4106            }
4107        }
4108    }
4109
4110    /// Refuse a plane whose teeth are pointed, whose roots meet, or whose flanks are undercut.
4111    fn check(&self) -> Result<(), KernelRefusal> {
4112        let m = self.wheel.worm.axial_module;
4113        let tau = TAU / self.wheel.teeth as f64;
4114        let tip_span = tau + polar_angle(self.flank(-1.0, self.rho_clip[0])) - polar_angle(self.flank(1.0, self.rho_clip[1]));
4115        if tip_span * self.r_tip <= 1e-6 * m {
4116            return Err(refuse("pointed_tip", format!("The wheel teeth come to a point below the throat {:.4} from the mid-plane: lower the addendum or the face width.", self.c)));
4117        }
4118        let root_span = polar_angle(self.fillet(1.0, 1.0)) - polar_angle(self.fillet(-1.0, 1.0));
4119        if root_span <= 1e-9 {
4120            return Err(refuse("teeth_overlap", "The worm thread is wider than the wheel's tooth space at the root: lower the dedendum.".into()));
4121        }
4122        // Each flank must fall steadily from its tip to its root, and the corner's trace must not cross it.
4123        for side in [-1.0, 1.0] {
4124            let index = if side < 0.0 { 0 } else { 1 };
4125            let flank: Vec<[f64; 2]> = (0..=96).map(|i| self.flank(side, self.rho_clip[index] + (self.rho_tip - self.rho_clip[index]) * i as f64 / 96.0)).collect();
4126            let fillet: Vec<[f64; 2]> = (0..=48).map(|i| self.fillet(side, i as f64 / 48.0)).collect();
4127            let falling = flank.windows(2).all(|pair| radius_of(pair[1]) < radius_of(pair[0]));
4128            let crosses = flank[..flank.len() - 2].windows(2).any(|f| fillet[1..].windows(2).any(|g| segments_cross(f[0], f[1], g[0], g[1])));
4129            if !falling || crosses {
4130                return Err(refuse(
4131                    "undercut",
4132                    format!("The worm undercuts the wheel teeth {:.4} from the mid-plane: add wheel teeth, narrow the face width or raise the pressure angle.", self.c),
4133                ));
4134            }
4135        }
4136        Ok(())
4137    }
4138}
4139
4140fn segments_cross(a: [f64; 2], b: [f64; 2], c: [f64; 2], d: [f64; 2]) -> bool {
4141    let cross = |o: [f64; 2], p: [f64; 2], q: [f64; 2]| (p[0] - o[0]) * (q[1] - o[1]) - (p[1] - o[1]) * (q[0] - o[0]);
4142    let (d1, d2) = (cross(c, d, a), cross(c, d, b));
4143    let (d3, d4) = (cross(a, b, c), cross(a, b, d));
4144    d1 * d2 < 0.0 && d3 * d4 < 0.0
4145}
4146
4147const WHEEL_ROLES: [&str; 6] = ["V", "R", "K", "L", "W", "G"];
4148
4149/// Tooth 0's six curves in the plane `c`, fitted on the shared breaks, at height z.
4150fn wheel_tooth(plane: &WheelPlane, breaks: &[Vec<f64>], z: f64) -> Result<(Vec<NurbsCurve>, f64), KernelRefusal> {
4151    let mut curves = Vec::with_capacity(6);
4152    let mut worst = 0.0_f64;
4153    for (role, role_breaks) in breaks.iter().enumerate() {
4154        let (mut curve, error) = fit_on_breaks(&|t| plane.piece(role, t), role_breaks)?;
4155        worst = worst.max(error);
4156        for p in &mut curve.control_points {
4157            p.z = z * p.w;
4158        }
4159        curves.push(curve);
4160    }
4161    Ok((curves, worst))
4162}
4163
4164/// The full section (every tooth) from tooth 0's curves, junctions shared.
4165fn wheel_section(tooth: &[NurbsCurve], teeth: usize) -> Vec<SectionCurve> {
4166    let tau = TAU / teeth as f64;
4167    let mut curves = Vec::with_capacity(6 * teeth);
4168    for index in 0..teeth {
4169        for (role, curve) in tooth.iter().enumerate() {
4170            curves.push(SectionCurve { curve: rotated(curve, tau * index as f64), role: WHEEL_ROLES[role], tooth: index });
4171        }
4172    }
4173    snap_junctions(&mut curves);
4174    curves
4175}
4176
4177/// A throated worm wheel solid and its data; face names as the spur gear's
4178/// per tooth (`V/R/K/L/W/G<n>`, the `K` faces making the throat), then `F` (z = 0) and `B`.
4179pub fn worm_wheel_solid(wheel: &WormWheel) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
4180    let worm = &wheel.worm;
4181    let m = worm.axial_module;
4182    worm_section(worm)?; // the worm's own checks
4183    if wheel.teeth < 12 || wheel.teeth > 400 {
4184        return Err(refuse("gear_input", format!("A worm wheel needs from 12 to 400 teeth (it has {}).", wheel.teeth)));
4185    }
4186    if !(wheel.addendum > 0.0 && wheel.dedendum > 0.0 && wheel.face_width > 0.0 && wheel.backlash >= 0.0) {
4187        return Err(refuse("gear_input", "The wheel's addendum, dedendum and face width must be positive, the backlash not negative.".into()));
4188    }
4189    let (r2, a, throat, _) = worm_wheel_sizes(wheel);
4190    let tube = a - throat;
4191    let limit = 0.9 * tube;
4192    if wheel.face_width / 2.0 > limit {
4193        return Err(refuse(
4194            "face_too_wide",
4195            format!("The face width ({}) must stay inside the throat: at most {:.4} for this worm.", wheel.face_width, 2.0 * limit),
4196        ));
4197    }
4198    // The hob's thread at the wheel's tip (in the mid-plane) must leave a tooth in the axial pitch. Checked
4199    // here, before any polar angle: a thread a whole pitch wider wraps round to the same teeth.
4200    if worm.axial_thickness(tube) + wheel.backlash >= PI * m - 1e-6 * m {
4201        return Err(refuse("pointed_tip", format!("The backlash ({}) leaves no wheel tooth: the hob's thread fills the whole axial pitch at the throat.", wheel.backlash)));
4202    }
4203    if worm.axial_thickness(a - (r2 - wheel.dedendum * m)) + wheel.backlash <= 1e-6 * m {
4204        return Err(refuse("pointed_tip", "The hob's thread (the worm's, grown to the wheel's root) comes to a point: lower the wheel dedendum.".into()));
4205    }
4206    let half = wheel.face_width / 2.0;
4207    let tolerance = GEAR_FIT_TOLERANCE * m;
4208    let skin_tolerance = 1e-5 * m;
4209    // Shared breaks per role from the mid-plane and both faces.
4210    let probe: Vec<WheelPlane> = [-half, 0.0, half].iter().map(|&c| WheelPlane::new(wheel, c)).collect::<Result<_, _>>()?;
4211    for plane in &probe {
4212        plane.check()?;
4213    }
4214    let mut breaks: Vec<Vec<f64>> = Vec::with_capacity(6);
4215    for role in 0..6 {
4216        let mut all: Vec<f64> = Vec::new();
4217        for plane in &probe {
4218            all.extend(adaptive_breaks(&|t| plane.piece(role, t), tolerance)?);
4219        }
4220        all.sort_by(f64::total_cmp);
4221        all.dedup_by(|x, y| (*x - *y).abs() < 1e-12);
4222        breaks.push(all);
4223    }
4224    // Planes across the face; each plane's control points carried along v by
4225    // cubic Hermite spans (derivatives from planes a step either side).
4226    let mut planes = 8usize;
4227    loop {
4228        let step = wheel.face_width / planes as f64;
4229        let delta = 1e-3 * step;
4230        let mut rows: Vec<Vec<NurbsCurve>> = Vec::with_capacity(planes + 1); // tooth 0 per plane
4231        let mut slopes: Vec<Vec<Vec<[f64; 2]>>> = Vec::with_capacity(planes + 1);
4232        let mut refit = false;
4233        for j in 0..=planes {
4234            let c = -half + step * j as f64;
4235            let plane = WheelPlane::new(wheel, c)?;
4236            plane.check()?;
4237            let (tooth, worst) = wheel_tooth(&plane, &breaks, c + half)?;
4238            if worst > tolerance {
4239                refit = true;
4240                break;
4241            }
4242            let lo = wheel_tooth(&WheelPlane::new(wheel, c - delta)?, &breaks, 0.0)?.0;
4243            let hi = wheel_tooth(&WheelPlane::new(wheel, c + delta)?, &breaks, 0.0)?.0;
4244            let slope: Vec<Vec<[f64; 2]>> = lo
4245                .iter()
4246                .zip(&hi)
4247                .map(|(l, h)| l.control_points.iter().zip(&h.control_points).map(|(p, q)| [(q.x - p.x) / (2.0 * delta), (q.y - p.y) / (2.0 * delta)]).collect())
4248                .collect();
4249            rows.push(tooth);
4250            slopes.push(slope);
4251        }
4252        if refit {
4253            // A plane the shared breaks fit too loosely: halve every span and start over.
4254            for role_breaks in &mut breaks {
4255                let mut finer = Vec::with_capacity(2 * role_breaks.len());
4256                for pair in role_breaks.windows(2) {
4257                    finer.push(pair[0]);
4258                    finer.push(0.5 * (pair[0] + pair[1]));
4259                }
4260                finer.push(1.0);
4261                *role_breaks = finer;
4262            }
4263            continue;
4264        }
4265        // Check the skin halfway between planes against the exact plane there.
4266        let mut worst = 0.0_f64;
4267        for j in 0..planes {
4268            let c = -half + step * (j as f64 + 0.5);
4269            let exact = wheel_tooth(&WheelPlane::new(wheel, c)?, &breaks, 0.0)?.0;
4270            for role in 0..6 {
4271                for (k, p) in exact[role].control_points.iter().enumerate() {
4272                    let (p0, p1) = (rows[j][role].control_points[k], rows[j + 1][role].control_points[k]);
4273                    let (d0, d1) = (slopes[j][role][k], slopes[j + 1][role][k]);
4274                    let x = 0.5 * (p0.x + p1.x) + step * (d0[0] - d1[0]) / 8.0;
4275                    let y = 0.5 * (p0.y + p1.y) + step * (d0[1] - d1[1]) / 8.0;
4276                    worst = worst.max((x - p.x).hypot(y - p.y));
4277                }
4278            }
4279        }
4280        if worst > skin_tolerance {
4281            if planes >= 256 {
4282                return Err(refuse("gear_fit", format!("The worm wheel's flanks could not be skinned within {skin_tolerance:.2e} ({worst:.2e}).")));
4283            }
4284            // The skin's error falls as the fourth power of the plane spacing: go straight to the count that
4285            // reading predicts (with a margin), not plane-count doubling by doubling.
4286            let factor = (1.15 * (worst / skin_tolerance).powf(0.25)).max(2.0);
4287            planes = (planes as f64 * factor).ceil().min(256.0) as usize;
4288            continue;
4289        }
4290        // Rows along v for every control point of the full bottom section, keyed by its bits.
4291        // Tooth 0's section with its junctions shared; every tooth's rows are tooth 0's turned.
4292        let first = wheel_section(&rows[0], wheel.teeth);
4293        let tau = TAU / wheel.teeth as f64;
4294        let mut table: std::collections::HashMap<[u64; 4], Vec<Vec4>> = std::collections::HashMap::new();
4295        let h = 1.0 / planes as f64;
4296        for (index, piece) in first.iter().enumerate() {
4297            let (role, tooth) = (index % 6, index / 6);
4298            let (s, cs) = (tau * tooth as f64).sin_cos();
4299            for (k, p) in piece.curve.control_points.iter().enumerate() {
4300                let mut row = Vec::with_capacity(3 * planes + 1);
4301                for j in 0..=planes {
4302                    let q = if j == 0 { piece.curve.control_points[k] } else { let p = rows[j][role].control_points[k]; Vec4 { x: cs * p.x - s * p.y, y: s * p.x + cs * p.y, z: p.z, w: p.w } };
4303                    let d = slopes[j][role][k];
4304                    // The slope in v (per unit v: face width per unit c), turned with the tooth.
4305                    let dv = [wheel.face_width * (cs * d[0] - s * d[1]), wheel.face_width * (s * d[0] + cs * d[1]), wheel.face_width];
4306                    let point = Vec3::new(q.x, q.y, q.z);
4307                    if j > 0 {
4308                        row.push(Vec4::from_point(Vec3::new(point.x - dv[0] * h / 3.0, point.y - dv[1] * h / 3.0, point.z - dv[2] * h / 3.0), 1.0));
4309                    }
4310                    if j == 0 || j == planes {
4311                        row.push(Vec4::from_point(point, 1.0));
4312                    }
4313                    if j < planes {
4314                        row.push(Vec4::from_point(Vec3::new(point.x + dv[0] * h / 3.0, point.y + dv[1] * h / 3.0, point.z + dv[2] * h / 3.0), 1.0));
4315                    }
4316                }
4317                table.insert([p.x.to_bits(), p.y.to_bits(), p.z.to_bits(), p.w.to_bits()], row);
4318            }
4319        }
4320        let mut knots_v = vec![0.0; 4];
4321        for j in 1..planes {
4322            let v = j as f64 * h;
4323            knots_v.extend([v, v]);
4324        }
4325        knots_v.extend([1.0; 4]);
4326        let section = GearSection { curves: first.clone(), data: GearData::default() };
4327        let solid = prism_by_rows(&section, 3, &knots_v, &|p: Vec4| {
4328            table.get(&[p.x.to_bits(), p.y.to_bits(), p.z.to_bits(), p.w.to_bits()]).cloned().expect("a row for every section control point")
4329        })?;
4330        let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
4331        names.push("F".into());
4332        names.push("B".into());
4333        let data = GearData {
4334            pitch_diameter: 2.0 * r2,
4335            tip_diameter: 2.0 * throat,
4336            root_diameter: 2.0 * (r2 - wheel.dedendum * m),
4337            tip_thickness: 0.0,
4338            ..GearData::default()
4339        };
4340        return Ok((solid, names, data));
4341    }
4342}
4343
4344/// A crown (face) gear: teeth on the flat face of a disc, for a spur pinion
4345/// whose axis lies parallel to that face and meets the crown's axis (90°
4346/// shaft angle). The teeth are cut as a shaper cuts them: a spur shaper with
4347/// `shaper_extra` more teeth than the pinion turns about the pinion's axis
4348/// while the crown turns with it at the tooth ratio, and the tooth spaces are
4349/// the volume its teeth sweep. The shaper's flanks are involutes and its tips
4350/// are rounded (0.2 × module, less on a thin tooth) and flat between the rounds, so every
4351/// face of a tooth space (root land, fillets, flanks) is the envelope of one
4352/// smooth piece of the shaper's outline. A shaper with more teeth than the
4353/// pinion touches it at a point rather than along a line, which keeps the
4354/// pair's contact clear of the tooth ends.
4355///
4356/// The crown's axis is +z; its back face is z = 0, the root plane z = `rim`,
4357/// the pitch plane z = `rim` + dedendum × module and the tips the plane
4358/// above by the addendum. The pinion's axis runs along +x (through the crown
4359/// axis, so radially) at the pitch plane + the pinion's pitch radius; tooth
4360/// space 0 is centred on +x.
4361#[derive(Clone, Debug)]
4362pub struct CrownGear {
4363    pub module: f64,
4364    pub teeth: usize,
4365    /// Teeth of the mating spur pinion.
4366    pub pinion_teeth: usize,
4367    /// The shaper's teeth over the pinion's (1 to 3).
4368    pub shaper_extra: usize,
4369    pub pressure_angle: f64,
4370    /// Crown addendum × module above the pitch plane (the pinion's dedendum less the clearance).
4371    pub addendum: f64,
4372    /// Crown dedendum × module below the pitch plane: the shaper's addendum (the pinion's plus the clearance).
4373    pub dedendum: f64,
4374    /// Inner radius of the toothed ring; 0 takes the undercut limit ([`crown_limits`]).
4375    pub inner_radius: f64,
4376    /// Outer radius of the toothed ring; 0 takes the pointed-tooth limit.
4377    pub outer_radius: f64,
4378    /// Blank thickness under the root plane.
4379    pub rim: f64,
4380}
4381
4382/// The shaper's tip round, × module.
4383const CROWN_TIP_ROUND: f64 = 0.2;
4384/// The narrowest tip land the outer radius may leave, × module.
4385const CROWN_TIP_LAND: f64 = 0.05;
4386
4387/// The generating shaper in its transverse plane: (Y, H), H up from the
4388/// shaper's axis, tooth 0 pointing down (to the crown), polar angle from −H
4389/// towards +Y. Its +Y side generates the +Y wall of tooth space 0.
4390struct CrownShaper {
4391    /// Pitch, base and tip radii.
4392    rs: f64,
4393    rb: f64,
4394    ra: f64,
4395    /// Crown turn per shaper turn (shaper teeth / crown teeth).
4396    k: f64,
4397    /// Half the tooth's angle at the pitch circle plus inv(α): the flank at roll u sits at c0 − inv(α(u)).
4398    c0: f64,
4399    /// Tip round radius, its centre and the roll where it meets the involute.
4400    rr: f64,
4401    centre: [f64; 2],
4402    uj: f64,
4403    /// Polar angle of the round's centre (half the tip land's angle).
4404    bc: f64,
4405    /// Normal angles (CCW from +Y) of the round where it meets the land and the involute.
4406    psi_land: f64,
4407    psi_flank: f64,
4408}
4409
4410/// A point of the shaper's outline with its outward unit normal and its
4411/// moment about the shaper's axis (point × normal), which the generating
4412/// motion leaves unchanged.
4413#[derive(Clone, Copy)]
4414struct OutlinePoint {
4415    q: [f64; 2],
4416    n: [f64; 2],
4417    moment: f64,
4418}
4419
4420impl CrownShaper {
4421    fn new(gear: &CrownGear) -> Result<Self, KernelRefusal> {
4422        let m = gear.module;
4423        let ns = (gear.pinion_teeth + gear.shaper_extra) as f64;
4424        let alpha = gear.pressure_angle;
4425        let rs = m * ns / 2.0;
4426        let rb = rs * alpha.cos();
4427        let ra = rs + gear.dedendum * m;
4428        let c0 = PI / (2.0 * ns) + alpha.tan() - alpha;
4429        // The tip round: 0.2 × module, smaller on a thin tooth so a tip land of at least 0.02 × module stays.
4430        let mut rr = CROWN_TIP_ROUND * m;
4431        for _ in 0..12 {
4432            let shaper = Self::rounded(rs, rb, ra, ns / gear.teeth as f64, c0, rr)?;
4433            if shaper.bc * ra >= 0.01 * m {
4434                return Ok(shaper);
4435            }
4436            rr *= 0.7;
4437        }
4438        Err(refuse("shaper_tip", "The shaper's teeth come to a point before its tip: lower the dedendum or raise the shaper's teeth.".into()))
4439    }
4440
4441    fn rounded(rs: f64, rb: f64, ra: f64, k: f64, c0: f64, rr: f64) -> Result<Self, KernelRefusal> {
4442        let mut shaper = Self { rs, rb, ra, k, c0, rr, centre: [0.0; 2], uj: 0.0, bc: 0.0, psi_land: 0.0, psi_flank: 0.0 };
4443        // The round touches the tip circle (its centre on ra − rr) and the involute.
4444        let reach = |u: f64| {
4445            let p = shaper.involute(u);
4446            radius_of([p.q[0] - rr * p.n[0], p.q[1] - rr * p.n[1]])
4447        };
4448        let u_tip = ((ra / rb).powi(2) - 1.0).sqrt();
4449        let (mut lo, mut hi) = (0.0, u_tip);
4450        if !(reach(lo) < ra - rr && reach(hi) > ra - rr) {
4451            return Err(refuse("shaper_tip", "The shaper's tip round does not fit its tooth: lower the dedendum or the pressure angle.".into()));
4452        }
4453        for _ in 0..200 {
4454            let mid = 0.5 * (lo + hi);
4455            if reach(mid) < ra - rr { lo = mid } else { hi = mid }
4456        }
4457        shaper.uj = 0.5 * (lo + hi);
4458        let p = shaper.involute(shaper.uj);
4459        shaper.centre = [p.q[0] - rr * p.n[0], p.q[1] - rr * p.n[1]];
4460        shaper.bc = shaper.centre[0].atan2(-shaper.centre[1]);
4461        shaper.psi_land = shaper.centre[1].atan2(shaper.centre[0]);
4462        shaper.psi_flank = p.n[1].atan2(p.n[0]);
4463        Ok(shaper)
4464    }
4465
4466    /// The +Y flank (an involute of the base circle) at roll `u`.
4467    fn involute(&self, u: f64) -> OutlinePoint {
4468        let s = (1.0 + u * u).sqrt();
4469        let rho = self.rb * s;
4470        let beta = self.c0 - u + u.atan();
4471        let (sb, cb) = beta.sin_cos();
4472        let (e, de) = ([sb, -cb], [cb, sb]);
4473        OutlinePoint { q: [rho * e[0], rho * e[1]], n: [(u * e[0] + de[0]) / s, (u * e[1] + de[1]) / s], moment: self.rb }
4474    }
4475
4476    /// The +Y tip round at normal angle `psi`.
4477    fn round(&self, psi: f64) -> OutlinePoint {
4478        let n = [psi.cos(), psi.sin()];
4479        let c = self.centre;
4480        OutlinePoint { q: [c[0] + self.rr * n[0], c[1] + self.rr * n[1]], n, moment: c[0] * n[1] - c[1] * n[0] }
4481    }
4482
4483    /// The crown point (crown frame: X along tooth space 0, Y, height h above the pitch plane) that
4484    /// the outline point generates where the shaper's line of it crosses x (from the crown axis).
4485    fn generate(&self, p: OutlinePoint, x: f64) -> Option<[f64; 3]> {
4486        // Contact where the normal is square to the relative velocity: n·v = 0 with
4487        // v = (k y, rs − h − k x, y) gives (n rotated by φ)_Y · k x = moment.
4488        let c = p.moment / (self.k * x);
4489        if !(c.abs() <= 1.0) {
4490            return None;
4491        }
4492        let mut phi = -c.acos() - p.n[1].atan2(p.n[0]);
4493        phi = (phi + PI).rem_euclid(TAU) - PI;
4494        let q = rotate(p.q, phi);
4495        let (s, co) = (self.k * phi).sin_cos();
4496        Some([x * co + q[0] * s, -x * s + q[0] * co, self.rs + q[1]])
4497    }
4498
4499    /// The point `p` generates on the cylinder of `radius` about the crown axis: (polar angle, h).
4500    fn on_cylinder(&self, p: OutlinePoint, radius: f64) -> Option<[f64; 2]> {
4501        // The crown's turn keeps the radius: it is hypot(x, y) of the shaper's contact point.
4502        let radius_at = |x: f64| self.generate(p, x).map(|g| (g[0].hypot(g[1]), g));
4503        let mut x = radius;
4504        for _ in 0..60 {
4505            let (r, g) = radius_at(x)?;
4506            let error = r - radius;
4507            if error.abs() <= 1e-13 * radius {
4508                return Some([g[1].atan2(g[0]), g[2]]);
4509            }
4510            let dx = 1e-7 * radius;
4511            let slope = (radius_at(x + dx)?.0 - r) / dx;
4512            // Damped: a full step may leave the range where the contact exists (x < moment / k).
4513            let mut step = error / slope;
4514            let mut halvings = 0;
4515            while !(step.is_finite() && radius_at(x - step).is_some()) {
4516                step *= 0.5;
4517                halvings += 1;
4518                if !step.is_finite() || halvings > 60 {
4519                    return None;
4520                }
4521            }
4522            x -= step;
4523        }
4524        None
4525    }
4526}
4527
4528fn check_crown_input(gear: &CrownGear) -> Result<(), KernelRefusal> {
4529    let m = gear.module;
4530    if !(m > 0.0 && gear.addendum > 0.0 && gear.dedendum > 0.0 && gear.rim > 0.0) {
4531        return Err(refuse("gear_input", "The module, addendum, dedendum and rim must be positive.".into()));
4532    }
4533    // The limits search out to 4 × the pitch radius: keep every size well inside the floating-point range.
4534    let sizes = [m, gear.addendum * m, gear.dedendum * m, gear.rim, gear.inner_radius, gear.outer_radius, 4.0 * m * gear.teeth as f64];
4535    if sizes.iter().any(|v| !(v.is_finite() && v.abs() < 1e12)) {
4536        return Err(refuse("gear_input", "The crown gear's sizes must be finite and under 1e12.".into()));
4537    }
4538    if !(gear.inner_radius >= 0.0 && gear.outer_radius >= 0.0) {
4539        return Err(refuse("gear_input", "The inner and outer radii must not be negative (0 takes the limits).".into()));
4540    }
4541    if gear.pinion_teeth < 10 || gear.pinion_teeth > 100 {
4542        return Err(refuse("gear_input", format!("The pinion needs from 10 to 100 teeth (it has {}).", gear.pinion_teeth)));
4543    }
4544    if !(1..=3).contains(&gear.shaper_extra) {
4545        return Err(refuse("gear_input", format!("The shaper has 1 to 3 teeth more than the pinion (not {}).", gear.shaper_extra)));
4546    }
4547    let shaper = gear.pinion_teeth + gear.shaper_extra;
4548    if gear.teeth < 2 * shaper || gear.teeth > 600 {
4549        return Err(refuse("gear_input", format!("A crown gear needs from twice the shaper's teeth ({}) to 600 teeth (it has {}).", 2 * shaper, gear.teeth)));
4550    }
4551    let degrees = gear.pressure_angle.to_degrees();
4552    if !(14.5 - 1e-9..=30.0 + 1e-9).contains(&degrees) {
4553        return Err(refuse("gear_input", format!("The pressure angle must be from 14.5° to 30° (it is {degrees}°).")));
4554    }
4555    Ok(())
4556}
4557
4558/// One cylinder about the crown axis: tooth space 0's walls where they cross it.
4559struct CrownRing<'a> {
4560    shaper: &'a CrownShaper,
4561    radius: f64,
4562    /// The roll where the flank reaches the tips.
4563    u_tip: f64,
4564    /// Heights above the pitch plane of the tips and the root, and of the pitch plane above z = 0.
4565    tip: f64,
4566    root: f64,
4567    lift: f64,
4568}
4569
4570impl<'a> CrownRing<'a> {
4571    fn new(gear: &CrownGear, shaper: &'a CrownShaper, radius: f64, lift: f64) -> Result<Self, KernelRefusal> {
4572        let tip = gear.addendum * gear.module;
4573        let undercut = || refuse("undercut", format!("The crown's teeth are undercut at radius {radius:.4}: raise the inner radius."));
4574        let height = |u: f64| shaper.on_cylinder(shaper.involute(u), radius).map(|p| p[1]);
4575        let (Some(h0), Some(h1)) = (height(0.0), height(shaper.uj)) else {
4576            return Err(undercut());
4577        };
4578        // The flank falls from the base circle (u = 0) to the round (u = uj); the tips need it from above them.
4579        if !(h0 >= tip && h1 < tip) {
4580            return Err(undercut());
4581        }
4582        let (mut lo, mut hi) = (0.0, shaper.uj);
4583        for _ in 0..200 {
4584            let mid = 0.5 * (lo + hi);
4585            match height(mid) {
4586                Some(h) if h >= tip => lo = mid,
4587                Some(_) => hi = mid,
4588                None => return Err(undercut()),
4589            }
4590        }
4591        Ok(Self { shaper, radius, u_tip: 0.5 * (lo + hi), tip, root: shaper.rs - shaper.ra, lift })
4592    }
4593
4594    /// The five walls of tooth space 0 as (polar angle, h), in order across the space from the −θ tip to the +θ
4595    /// tip: L the −θ flank (down), W its fillet, G the root land, V the +θ fillet, R the +θ flank (up).
4596    fn polar(&self, role: usize, t: f64) -> [f64; 2] {
4597        let s = self.shaper;
4598        let at = |p: OutlinePoint| s.on_cylinder(p, self.radius).unwrap_or([f64::NAN, f64::NAN]);
4599        let fillet = |t: f64| at(s.round(s.psi_land + t * (s.psi_flank - s.psi_land)));
4600        let flank = |t: f64| at(s.involute(s.uj + t * (self.u_tip - s.uj)));
4601        let mirror = |p: [f64; 2]| [-p[0], p[1]];
4602        match role {
4603            0 => mirror(flank(1.0 - t)),
4604            1 => mirror(fillet(1.0 - t)),
4605            // The land, turned about the crown axis by k × its angle: the root land between two radial lines.
4606            2 => [s.k * s.bc * (2.0 * t - 1.0), self.root],
4607            3 => fillet(t),
4608            _ => flank(t),
4609        }
4610    }
4611
4612    fn piece(&self, role: usize, t: f64) -> [f64; 3] {
4613        let [angle, h] = self.polar(role, t);
4614        [self.radius * angle.cos(), self.radius * angle.sin(), h + self.lift]
4615    }
4616
4617    /// Refuse a ring whose walls do not rise steadily from the root to the tips.
4618    fn check(&self) -> Result<(), KernelRefusal> {
4619        for role in [3, 4] {
4620            let points: Vec<[f64; 2]> = (0..=64).map(|i| self.polar(role, i as f64 / 64.0)).collect();
4621            if points.iter().any(|p| !p[0].is_finite()) || !points.windows(2).all(|w| w[1][1] > w[0][1]) {
4622                return Err(refuse("undercut", format!("The crown's tooth space does not rise steadily at radius {:.4}: raise the inner radius.", self.radius)));
4623            }
4624        }
4625        Ok(())
4626    }
4627}
4628
4629/// The crown gear's limits: (undercut limit, pointed-tooth limit). The first is the smallest inner radius at
4630/// which the shaper's flank reaches the tips from above its base circle and every wall of the tooth space
4631/// reaches the cylinder (the flank's foot, by the round, the last); the second is the largest outer radius
4632/// that leaves a tip land of 0.05 × module.
4633pub fn crown_limits(gear: &CrownGear) -> Result<(f64, f64), KernelRefusal> {
4634    check_crown_input(gear)?;
4635    let shaper = CrownShaper::new(gear)?;
4636    let m = gear.module;
4637    let tip = gear.addendum * m;
4638    let r2 = m * gear.teeth as f64 / 2.0;
4639    let base_free = |r: f64| shaper.on_cylinder(shaper.involute(0.0), r).is_some_and(|p| p[1] >= tip);
4640    let (mut lo, mut hi) = (shaper.rb / shaper.k * (1.0 + 1e-9), 4.0 * r2);
4641    if !base_free(hi) {
4642        return Err(refuse("undercut", "The crown's tips would need the shaper's flank below its base circle at every radius: lower the addendum.".into()));
4643    }
4644    for _ in 0..200 {
4645        let mid = 0.5 * (lo + hi);
4646        if base_free(mid) { hi = mid } else { lo = mid }
4647    }
4648    // Then every wall must reach the cylinder: the flank's foot, by the round, is the last to.
4649    let walls_reach = |r: f64| base_free(r) && CrownRing::new(gear, &shaper, r, 0.0).and_then(|ring| ring.check()).is_ok();
4650    if !walls_reach(hi) {
4651        let step = 0.02 * m;
4652        let mut found = None;
4653        let mut r = hi;
4654        while r < 2.0 * r2 {
4655            r += step;
4656            if walls_reach(r) {
4657                found = Some(r);
4658                break;
4659            }
4660        }
4661        let Some(good) = found else {
4662            return Err(refuse("undercut", "The crown's tooth spaces do not reach from the root to the tips at any radius: lower the addendum or raise the pressure angle.".into()));
4663        };
4664        let (mut lo, mut top) = (good - step, good);
4665        for _ in 0..100 {
4666            let mid = 0.5 * (lo + top);
4667            if walls_reach(mid) { top = mid } else { lo = mid }
4668        }
4669        hi = top;
4670    }
4671    // A little inside, so the skin's slopes may look a step past the ring's ends.
4672    let inner = hi + 2e-3 * m;
4673    let tau = TAU / gear.teeth as f64;
4674    let land = |r: f64| -> Result<bool, KernelRefusal> {
4675        let ring = CrownRing::new(gear, &shaper, r, 0.0)?;
4676        Ok((tau - 2.0 * ring.polar(4, 1.0)[0]) * r >= CROWN_TIP_LAND * m)
4677    };
4678    let (mut lo, mut hi) = (inner, 4.0 * r2);
4679    if !land(lo)? {
4680        return Err(refuse("pointed_tip", "The crown's teeth come to a point at the undercut limit: add crown teeth or lower the addendum.".into()));
4681    }
4682    if land(hi).unwrap_or(false) {
4683        return Err(refuse("gear_input", "The crown's teeth never come to a point: check the module and tooth counts.".into()));
4684    }
4685    for _ in 0..100 {
4686        let mid = 0.5 * (lo + hi);
4687        if land(mid).unwrap_or(false) { lo = mid } else { hi = mid }
4688    }
4689    Ok((inner, lo - 2e-3 * m))
4690}
4691
4692/// The crown gear's sizes: [pitch radius, inner radius, outer radius, z of the pitch plane, z of the tips,
4693/// z of the pinion's axis], the radii resolved from the limits where 0.
4694pub fn crown_sizes(gear: &CrownGear) -> Result<[f64; 6], KernelRefusal> {
4695    let m = gear.module;
4696    let (limit_in, limit_out) = crown_limits(gear)?;
4697    let inner = if gear.inner_radius > 0.0 { gear.inner_radius } else { limit_in };
4698    let outer = if gear.outer_radius > 0.0 { gear.outer_radius } else { limit_out };
4699    if inner < limit_in - 1e-9 * m {
4700        return Err(refuse("undercut", format!("The inner radius ({inner}) is inside the undercut limit {limit_in:.4}: raise it.")));
4701    }
4702    if outer > limit_out + 1e-9 * m {
4703        return Err(refuse("pointed_tip", format!("The outer radius ({outer}) is past the pointed-tooth limit {limit_out:.4}: lower it.")));
4704    }
4705    if !(outer > inner + 0.1 * m) {
4706        return Err(refuse("gear_input", format!("The outer radius ({outer:.4}) must be beyond the inner radius ({inner:.4}).")));
4707    }
4708    let pitch = gear.rim + gear.dedendum * m;
4709    Ok([m * gear.teeth as f64 / 2.0, inner, outer, pitch, pitch + gear.addendum * m, pitch + m * gear.pinion_teeth as f64 / 2.0])
4710}
4711
4712const CROWN_ROLES: [&str; 5] = ["L", "W", "G", "V", "R"];
4713
4714/// Tooth space 0's five walls on one ring, fitted on the shared breaks, junctions shared.
4715fn crown_walls(ring: &CrownRing, breaks: &[Vec<f64>]) -> Result<(Vec<NurbsCurve>, f64), KernelRefusal> {
4716    let mut curves: Vec<NurbsCurve> = Vec::with_capacity(5);
4717    let mut worst = 0.0_f64;
4718    for (role, role_breaks) in breaks.iter().enumerate() {
4719        let (curve, error) = fit_on_breaks3(&|t| ring.piece(role, t), role_breaks)?;
4720        worst = worst.max(error);
4721        curves.push(curve);
4722    }
4723    for index in 0..4 {
4724        let start = curves[index + 1].control_points[0];
4725        let last = curves[index].control_points.len() - 1;
4726        curves[index].control_points[last] = start;
4727    }
4728    Ok((curves, worst))
4729}
4730
4731/// Tooth space 0's five wall surfaces (u across the wall in role order, v from the inner radius out), skinned
4732/// through rings until the skin holds 1e-5 × module halfway between them.
4733fn crown_wall_surfaces(gear: &CrownGear, shaper: &CrownShaper, inner: f64, outer: f64, lift: f64) -> Result<Vec<NurbsSurface>, KernelRefusal> {
4734    let m = gear.module;
4735    let tolerance = GEAR_FIT_TOLERANCE * m;
4736    let skin_tolerance = 1e-5 * m;
4737    let probe: Vec<CrownRing> = [inner, 0.5 * (inner + outer), outer].iter().map(|&r| CrownRing::new(gear, shaper, r, lift)).collect::<Result<_, _>>()?;
4738    for ring in &probe {
4739        ring.check()?;
4740    }
4741    let mut breaks: Vec<Vec<f64>> = Vec::with_capacity(5);
4742    for role in 0..5 {
4743        let mut all: Vec<f64> = Vec::new();
4744        for ring in &probe {
4745            all.extend(adaptive_breaks3(&|t| ring.piece(role, t), tolerance)?);
4746        }
4747        all.sort_by(f64::total_cmp);
4748        all.dedup_by(|x, y| (*x - *y).abs() < 1e-12);
4749        breaks.push(all);
4750    }
4751    let length = outer - inner;
4752    let mut rings = 4usize;
4753    loop {
4754        let step = length / rings as f64;
4755        let delta = 1e-3 * step.min(m);
4756        let mut rows: Vec<Vec<NurbsCurve>> = Vec::with_capacity(rings + 1);
4757        let mut slopes: Vec<Vec<Vec<[f64; 3]>>> = Vec::with_capacity(rings + 1);
4758        let mut refit = false;
4759        for j in 0..=rings {
4760            let r = inner + step * j as f64;
4761            let ring = CrownRing::new(gear, shaper, r, lift)?;
4762            ring.check()?;
4763            let (walls, worst) = crown_walls(&ring, &breaks)?;
4764            if worst > tolerance {
4765                refit = true;
4766                break;
4767            }
4768            let lo = crown_walls(&CrownRing::new(gear, shaper, r - delta, lift)?, &breaks)?.0;
4769            let hi = crown_walls(&CrownRing::new(gear, shaper, r + delta, lift)?, &breaks)?.0;
4770            let slope: Vec<Vec<[f64; 3]>> = lo
4771                .iter()
4772                .zip(&hi)
4773                .map(|(l, h)| l.control_points.iter().zip(&h.control_points).map(|(p, q)| [(q.x - p.x) / (2.0 * delta), (q.y - p.y) / (2.0 * delta), (q.z - p.z) / (2.0 * delta)]).collect())
4774                .collect();
4775            rows.push(walls);
4776            slopes.push(slope);
4777        }
4778        if refit {
4779            for role_breaks in &mut breaks {
4780                let mut finer = Vec::with_capacity(2 * role_breaks.len());
4781                for pair in role_breaks.windows(2) {
4782                    finer.push(pair[0]);
4783                    finer.push(0.5 * (pair[0] + pair[1]));
4784                }
4785                finer.push(1.0);
4786                *role_breaks = finer;
4787            }
4788            continue;
4789        }
4790        let mut worst = 0.0_f64;
4791        for j in 0..rings {
4792            let r = inner + step * (j as f64 + 0.5);
4793            let exact = crown_walls(&CrownRing::new(gear, shaper, r, lift)?, &breaks)?.0;
4794            for role in 0..5 {
4795                for (k, p) in exact[role].control_points.iter().enumerate() {
4796                    let (p0, p1) = (rows[j][role].control_points[k], rows[j + 1][role].control_points[k]);
4797                    let (d0, d1) = (slopes[j][role][k], slopes[j + 1][role][k]);
4798                    let x = 0.5 * (p0.x + p1.x) + step * (d0[0] - d1[0]) / 8.0;
4799                    let y = 0.5 * (p0.y + p1.y) + step * (d0[1] - d1[1]) / 8.0;
4800                    let z = 0.5 * (p0.z + p1.z) + step * (d0[2] - d1[2]) / 8.0;
4801                    worst = worst.max(((x - p.x).powi(2) + (y - p.y).powi(2) + (z - p.z).powi(2)).sqrt());
4802                }
4803            }
4804        }
4805        if worst > skin_tolerance {
4806            if rings >= 256 {
4807                return Err(refuse("gear_fit", format!("The crown gear's tooth spaces could not be skinned within {skin_tolerance:.2e} ({worst:.2e}).")));
4808            }
4809            rings *= 2;
4810            continue;
4811        }
4812        let h = 1.0 / rings as f64;
4813        let mut knots_v = vec![0.0; 4];
4814        for j in 1..rings {
4815            let v = j as f64 * h;
4816            knots_v.extend([v, v]);
4817        }
4818        knots_v.extend([1.0; 4]);
4819        let mut surfaces = Vec::with_capacity(5);
4820        for role in 0..5 {
4821            let grid: Vec<Vec<Vec4>> = (0..rows[0][role].control_points.len())
4822                .map(|k| {
4823                    let mut row = Vec::with_capacity(2 * rings + 2);
4824                    for j in 0..=rings {
4825                        let q = rows[j][role].control_points[k];
4826                        let d = slopes[j][role][k];
4827                        let along = |s: f64| Vec4::from_point(Vec3::new(q.x + s * length * d[0], q.y + s * length * d[1], q.z + s * length * d[2]), 1.0);
4828                        if j > 0 {
4829                            row.push(along(-h / 3.0));
4830                        }
4831                        if j == 0 || j == rings {
4832                            row.push(along(0.0));
4833                        }
4834                        if j < rings {
4835                            row.push(along(h / 3.0));
4836                        }
4837                    }
4838                    row
4839                })
4840                .collect();
4841            surfaces.push(NurbsSurface::new(3, 3, rows[0][role].knots.clone(), knots_v.clone(), grid).map_err(|e| refuse("gear_surface", e))?);
4842        }
4843        return Ok(surfaces);
4844    }
4845}
4846
4847fn iso_u(surface: &NurbsSurface, last: bool) -> Result<NurbsCurve, KernelRefusal> {
4848    let row = if last { surface.control_points.len() - 1 } else { 0 };
4849    NurbsCurve::new(surface.degree_v, surface.knots_v.clone(), surface.control_points[row].clone()).map_err(|e| refuse("gear_edge", e))
4850}
4851
4852fn iso_v(surface: &NurbsSurface, last: bool) -> Result<NurbsCurve, KernelRefusal> {
4853    let column = if last { surface.control_points[0].len() - 1 } else { 0 };
4854    NurbsCurve::new(surface.degree_u, surface.knots_u.clone(), surface.control_points.iter().map(|row| row[column]).collect()).map_err(|e| refuse("gear_edge", e))
4855}
4856
4857fn turned_surface(surface: &NurbsSurface, angle: f64) -> Result<NurbsSurface, KernelRefusal> {
4858    let (s, c) = angle.sin_cos();
4859    let grid = surface.control_points.iter().map(|row| row.iter().map(|p| Vec4 { x: c * p.x - s * p.y, y: s * p.x + c * p.y, z: p.z, w: p.w }).collect()).collect();
4860    NurbsSurface::new(surface.degree_u, surface.degree_v, surface.knots_u.clone(), surface.knots_v.clone(), grid).map_err(|e| refuse("gear_surface", e))
4861}
4862
4863/// Arcs of `radius` about the z axis at height `z` through the given angles, as one curve whose span i (on
4864/// [i, i + 1]) is the arc from angle i to angle i + 1, and each span alone.
4865fn joined_arcs(radius: f64, z: f64, angles: &[f64]) -> Result<(NurbsCurve, Vec<NurbsCurve>), KernelRefusal> {
4866    let mut pieces = Vec::with_capacity(angles.len() - 1);
4867    for pair in angles.windows(2) {
4868        pieces.push(crate::make_arc(Vec3::new(0.0, 0.0, z), Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0), radius, pair[0], pair[1]).map_err(|e| refuse("gear_arc", e))?);
4869    }
4870    let degree = pieces[0].degree;
4871    let mut knots: Vec<f64> = Vec::new();
4872    let mut points: Vec<Vec4> = Vec::new();
4873    for (index, piece) in pieces.iter().enumerate() {
4874        let shift = index as f64;
4875        if index == 0 {
4876            knots.extend(piece.knots[..piece.knots.len() - 1].iter().map(|k| k + shift));
4877            points.extend(piece.control_points.iter().copied());
4878        } else {
4879            knots.extend(piece.knots[degree + 1..piece.knots.len() - 1].iter().map(|k| k + shift));
4880            points.extend(piece.control_points[1..].iter().copied());
4881        }
4882    }
4883    knots.push(pieces.len() as f64);
4884    Ok((NurbsCurve::new(degree, knots, points).map_err(|e| refuse("gear_arc", e))?, pieces))
4885}
4886
4887/// A crown gear solid and its data. Faces carry their names: per tooth space n `G<n>` (root land), `V<n>` /
4888/// `W<n>` (the +θ and −θ fillets), `R<n>` / `L<n>` (the +θ and −θ flanks), `I<n>` and `O<n>` (the inner and
4889/// outer cylinder from the middle of tooth n − 1 to the middle of tooth n); per tooth n (between spaces n and
4890/// n + 1) `K<n>` (tip land); and `B` (the back).
4891pub fn crown_solid(gear: &CrownGear) -> Result<(BrepSolid, GearData), KernelRefusal> {
4892    use crate::sweep_topology::{curve_to_plane_parameters, make_plane, parameter_line};
4893    let [r2, inner, outer, pitch, tip, _] = crown_sizes(gear)?;
4894    let shaper = CrownShaper::new(gear)?;
4895    let walls = crown_wall_surfaces(gear, &shaper, inner, outer, pitch)?;
4896    let teeth = gear.teeth;
4897    let tau = TAU / teeth as f64;
4898    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));
4899    let mut shell = ShellBuilder { vertices: Vec::new(), edges: Vec::new(), faces: Vec::new(), next: 0 };
4900    // Per space j: its walls turned by j tau, their corner vertices and edges.
4901    struct Space {
4902        walls: Vec<NurbsSurface>,
4903        inner: [u64; 6],
4904        outer: [u64; 6],
4905        /// Edges between walls (and the two tip edges), at u = 0 of wall 0 then u = 1 of each wall.
4906        across: [u64; 6],
4907        inner_edges: [u64; 5],
4908        outer_edges: [u64; 5],
4909    }
4910    let point_of = |p: Vec4| Vec3::new(p.x / p.w, p.y / p.w, p.z / p.w);
4911    let mut spaces: Vec<Space> = Vec::with_capacity(teeth);
4912    for j in 0..teeth {
4913        let turned: Vec<NurbsSurface> = walls.iter().map(|w| turned_surface(w, tau * j as f64)).collect::<Result<_, _>>()?;
4914        let mut inner_v = [0u64; 6];
4915        let mut outer_v = [0u64; 6];
4916        for k in 0..6 {
4917            let (wall, row) = if k < 5 { (&turned[k], 0) } else { (&turned[4], turned[4].control_points.len() - 1) };
4918            let column = &wall.control_points[row];
4919            inner_v[k] = shell.vertex(point_of(column[0]));
4920            outer_v[k] = shell.vertex(point_of(*column.last().expect("a row")));
4921        }
4922        let mut across = [0u64; 6];
4923        across[0] = shell.edge(iso_u(&turned[0], false)?, inner_v[0], outer_v[0])?;
4924        for k in 0..5 {
4925            across[k + 1] = shell.edge(iso_u(&turned[k], true)?, inner_v[k + 1], outer_v[k + 1])?;
4926        }
4927        let mut inner_edges = [0u64; 5];
4928        let mut outer_edges = [0u64; 5];
4929        for k in 0..5 {
4930            inner_edges[k] = shell.edge(iso_v(&turned[k], false)?, inner_v[k], inner_v[k + 1])?;
4931            outer_edges[k] = shell.edge(iso_v(&turned[k], true)?, outer_v[k], outer_v[k + 1])?;
4932        }
4933        spaces.push(Space { walls: turned, inner: inner_v, outer: outer_v, across, inner_edges, outer_edges });
4934    }
4935    // The walls' faces: u along the wall, v outwards; the outward side faces into the space (or up from the land).
4936    for (j, space) in spaces.iter().enumerate() {
4937        for k in 0..5 {
4938            let surface = space.walls[k].clone();
4939            let at = |u: f64, v: f64| surface.evaluate(u, v).map_err(|e| refuse("gear_surface", e));
4940            let p = at(0.5, 0.5)?;
4941            let du = at(0.5 + 1e-6, 0.5)?.sub(at(0.5 - 1e-6, 0.5)?);
4942            let dv = at(0.5, 0.5 + 1e-6)?.sub(at(0.5, 0.5 - 1e-6)?);
4943            let normal = du.cross(dv);
4944            let centre = tau * j as f64;
4945            let off = (p.y.atan2(p.x) - centre + PI).rem_euclid(TAU) - PI;
4946            let tangential = Vec3::new(-p.y, p.x, 0.0).scale(1.0 / p.x.hypot(p.y));
4947            let outward = Vec3::new(0.0, 0.0, 1.0).sub(tangential.scale(off.signum()));
4948            let same_sense = normal.dot(outward) > 0.0;
4949            let loops = vec![vec![
4950                (space.inner_edges[k], true, line([0.0, 0.0], [1.0, 0.0])?),
4951                (space.across[k + 1], true, line([1.0, 0.0], [1.0, 1.0])?),
4952                (space.outer_edges[k], false, line([0.0, 1.0], [1.0, 1.0])?),
4953                (space.across[k], false, line([0.0, 0.0], [0.0, 1.0])?),
4954            ]];
4955            shell.face(surface, same_sense, loops, format!("{}{j}", CROWN_ROLES[k]))?;
4956        }
4957    }
4958    // Side lines at the middle of every tooth, inner and outer, and the cylinders between them.
4959    let mut sides = Vec::with_capacity(teeth); // per tooth j: [(bottom, top) inner, (bottom, top) outer] vertices and edges
4960    for j in 0..teeth {
4961        let angle = tau * j as f64 + tau / 2.0;
4962        let mut side = Vec::with_capacity(2);
4963        for radius in [inner, outer] {
4964            let (s, c) = angle.sin_cos();
4965            let bottom = shell.vertex(Vec3::new(radius * c, radius * s, 0.0));
4966            let top = shell.vertex(Vec3::new(radius * c, radius * s, tip));
4967            let edge = shell.edge(crate::make_line(Vec3::new(radius * c, radius * s, 0.0), Vec3::new(radius * c, radius * s, tip)).map_err(|e| refuse("gear_edge", e))?, bottom, top)?;
4968            side.push((bottom, top, edge));
4969        }
4970        sides.push(side);
4971    }
4972    // Per space j and per radius: the bottom arc edge and the two tip arcs (the tooth before, the tooth after).
4973    let mut bottoms: [Vec<u64>; 2] = [Vec::new(), Vec::new()];
4974    let mut tip_arcs: [Vec<(u64, u64)>; 2] = [Vec::new(), Vec::new()];
4975    for j in 0..teeth {
4976        let space = &spaces[j];
4977        let before = &sides[(j + teeth - 1) % teeth];
4978        let after = &sides[j];
4979        let base_angle = tau * j as f64 - tau / 2.0;
4980        for (side, radius) in [inner, outer].into_iter().enumerate() {
4981            let corners = if side == 0 { space.inner } else { space.outer };
4982            let point = |id: u64| shell.vertices.iter().find(|v| v.id == id).expect("a vertex").point;
4983            let unwrap = |p: Vec3| base_angle + (p.y.atan2(p.x) - base_angle).rem_euclid(TAU);
4984            let angles = [base_angle, unwrap(point(corners[0])), unwrap(point(corners[5])), base_angle + tau];
4985            let (base, _) = joined_arcs(radius, 0.0, &angles)?;
4986            let (_, lifted) = joined_arcs(radius, tip, &angles)?;
4987            let bottom = shell.edge(base.clone(), before[side].0, after[side].0)?;
4988            let first = shell.edge(lifted[0].clone(), before[side].1, corners[0])?;
4989            let last = shell.edge(lifted[2].clone(), corners[5], after[side].1)?;
4990            bottoms[side].push(bottom);
4991            tip_arcs[side].push((first, last));
4992            let surface = crate::make_extrusion(&base, Vec3::new(0.0, 0.0, tip)).map_err(|e| refuse("gear_surface", e))?;
4993            let wall_edges = if side == 0 { space.inner_edges } else { space.outer_edges };
4994            let mut coedges = vec![
4995                (bottom, true, line([0.0, 0.0], [3.0, 0.0])?),
4996                (after[side].2, true, line([3.0, 0.0], [3.0, 1.0])?),
4997                (last, false, line([2.0, 1.0], [3.0, 1.0])?),
4998            ];
4999            for k in (0..5).rev() {
5000                let curve = shell.curve(wall_edges[k]).clone();
5001                let pcurve = crate::build_pcurve_on_surface(&surface, &curve).map_err(|e| refuse("gear_pcurve", e))?;
5002                coedges.push((wall_edges[k], false, pcurve));
5003            }
5004            coedges.push((first, false, line([0.0, 1.0], [1.0, 1.0])?));
5005            coedges.push((before[side].2, false, line([0.0, 0.0], [0.0, 1.0])?));
5006            // The extrusion's normal points out from the axis: outward for the outer cylinder, inward for the inner.
5007            shell.face(surface, side == 1, vec![coedges], format!("{}{j}", if side == 0 { "I" } else { "O" }))?;
5008        }
5009    }
5010    // Tip lands: tooth j between space j (its R tip edge) and space j + 1 (its L tip edge).
5011    let pad = outer * 1.1 + 1.0;
5012    let x_axis = Vec3::new(1.0, 0.0, 0.0);
5013    let y_axis = Vec3::new(0.0, 1.0, 0.0);
5014    let on_plane = |curve: &NurbsCurve, z: f64| curve_to_plane_parameters(curve, Vec3::new(-pad, -pad, z), x_axis, y_axis).map_err(|e| refuse("gear_pcurve", e));
5015    for j in 0..teeth {
5016        let next = (j + 1) % teeth;
5017        let mut coedges = Vec::with_capacity(6);
5018        for (edge, forward) in [
5019            (spaces[j].across[5], true),
5020            (tip_arcs[1][j].1, true),
5021            (tip_arcs[1][next].0, true),
5022            (spaces[next].across[0], false),
5023            (tip_arcs[0][next].0, false),
5024            (tip_arcs[0][j].1, false),
5025        ] {
5026            let pcurve = on_plane(shell.curve(edge), tip)?;
5027            coedges.push((edge, forward, pcurve));
5028        }
5029        let plane = make_plane(Vec3::new(-pad, -pad, tip), x_axis, y_axis, 2.0 * pad, 2.0 * pad).map_err(|e| refuse("gear_plane", e))?;
5030        shell.face(plane, true, vec![coedges], format!("K{j}"))?;
5031    }
5032    // The back: the outer and inner bottom arcs.
5033    let mut loops = Vec::with_capacity(2);
5034    for side in [1, 0] {
5035        let mut coedges = Vec::with_capacity(teeth);
5036        for &edge in &bottoms[side] {
5037            coedges.push((edge, true, on_plane(shell.curve(edge), 0.0)?));
5038        }
5039        loops.push(coedges);
5040    }
5041    let plane = make_plane(Vec3::new(-pad, -pad, 0.0), x_axis, y_axis, 2.0 * pad, 2.0 * pad).map_err(|e| refuse("gear_plane", e))?;
5042    shell.face(plane, false, loops, "B".into())?;
5043    let id = shell.id();
5044    let shell_id = shell.id();
5045    let solid = BrepSolid {
5046        mass_properties_cache: Default::default(),
5047        cells: Default::default(),
5048        id,
5049        vertices: shell.vertices,
5050        edges: shell.edges,
5051        shells: vec![crate::sweep_topology::ShellRecord { id: shell_id, faces: shell.faces }],
5052        genus: 1,
5053        kind: crate::BodyKind::Solid,
5054    };
5055    let issues = solid.validate();
5056    if !issues.is_empty() {
5057        return Err(KernelRefusal::internal(KernelStage::Validate, "validate", format!("crown gear is not valid: {issues:?}")));
5058    }
5059    let data = GearData {
5060        pitch_diameter: 2.0 * r2,
5061        base_diameter: 2.0 * r2 * gear.pressure_angle.cos(),
5062        tip_diameter: 2.0 * outer,
5063        root_diameter: 2.0 * inner,
5064        ..GearData::default()
5065    };
5066    Ok((solid, data))
5067}
5068