1use crate::{extrude_profile_brep, make_arc, BrepSolid, KernelRefusal, KernelStage, NurbsCurve, NurbsSurface, Vec3, Vec4};
20use std::f64::consts::{PI, TAU};
21
22pub const GEAR_FIT_TOLERANCE: f64 = 5e-7;
26
27#[derive(Clone, Debug)]
30pub struct SpurGear {
31 pub module: f64,
32 pub teeth: usize,
33 pub pressure_angle: f64,
34 pub profile_shift: f64,
36 pub addendum: f64,
38 pub dedendum: f64,
40 pub root_fillet: f64,
42 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#[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 pub form_diameter: f64,
72 pub tooth_thickness: f64,
74 pub tip_thickness: f64,
76 pub undercut: bool,
78 pub min_shift_without_undercut: f64,
80}
81
82#[derive(Clone, Debug)]
84pub struct SectionCurve {
85 pub curve: NurbsCurve,
86 pub role: &'static str,
88 pub tooth: usize,
89}
90
91impl SectionCurve {
92 pub fn suffix(&self) -> String {
94 format!("{}{}", self.role, self.tooth)
95 }
96}
97
98#[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
122struct RackCutter {
124 r: f64,
125 alpha: f64,
126 x_ref: f64,
128 y0: f64,
130 r_f: f64,
132 rho: f64,
133 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 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 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 fn fillet(&self, psi: f64) -> [f64; 2] {
168 let n = [-psi.cos(), -psi.sin()];
169 if self.rho == 0.0 {
170 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 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
186fn 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 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(°rees) {
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
304pub fn spur_section(gear: &SpurGear) -> Result<GearSection, KernelRefusal> {
306 check_spur(gear, 35.0)?;
307 generated_section(gear)
308}
309
310fn 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 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 let (x_join, psi_join) = if !undercut {
355 (x_flank_tangent, psi_end)
356 } else {
357 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 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 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 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 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)?; let fillet_fit = fit_planar(&|psi| rack.fillet(psi), 0.0, psi_join, tolerance)?; let root_angle = rack.centre[1] / r;
461 let land = 2.0 * half_pitch - 2.0 * root_angle;
462
463 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 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
500pub fn spur_solid(gear: &SpurGear) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
504 let section = spur_section(gear)?;
505 let solid = extrude_section(§ion, 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
512pub 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)?; let root_r = radius_of(start);
536 if locking {
537 let after = full.curves.iter().filter(|c| c.tooth == kept).next().expect("the next tooth").curve.clone();
539 let rise = point(&after, false)?; 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)?; 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 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(§ion, 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
572pub 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#[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 pub root_fillet: f64,
590 pub backlash: f64,
592 pub face_width: f64,
593 pub height: f64,
595 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
627pub 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(°rees) {
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; 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 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]; 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 let mut x_prev_root = length; 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 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 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
746pub 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 let degrees = rack.pressure_angle.to_degrees();
756 if !(10.0 - 1e-9..=35.0 + 1e-9).contains(°rees) {
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 let section = rack_section(rack)?;
762 let solid = extrude_section(§ion, 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 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 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
799fn 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#[derive(Clone, Debug)]
814pub struct RingGear {
815 pub module: f64,
816 pub teeth: usize,
817 pub pressure_angle: f64,
818 pub profile_shift: f64,
821 pub addendum: f64,
822 pub dedendum: f64,
823 pub root_fillet: f64,
826 pub backlash: f64,
828 pub face_width: f64,
829 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
850pub 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(°rees) {
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; let r_f = r + (gear.dedendum + gear.profile_shift) * m; 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 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 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 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 [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 let flank_fit = fit_planar(&|radius| flank(radius), r_a, join_radius, tolerance)?; let mut space: Vec<(&'static str, NurbsCurve)> = Vec::new();
974 space.push(("R", mirrored(&flank_fit)));
976 if rho > 0.0 {
977 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)?; 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
1016pub 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(§ion, outer, width, 1, &[0.0, 0.0, 1.0, 1.0], &rows)?;
1025 Ok((ring, section.data))
1026}
1027
1028pub 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; let outer = section.data.root_diameter / 2.0 + gear.rim;
1054 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(§ion, 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1072pub enum SprocketForm {
1073 Minimum,
1075 Maximum,
1077 Mean,
1079}
1080
1081#[derive(Clone, Debug)]
1083pub struct Sprocket {
1084 pub pitch: f64,
1085 pub roller_diameter: f64,
1086 pub teeth: usize,
1087 pub form: SprocketForm,
1088 pub width: f64,
1090}
1091
1092pub 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 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 let c = [d / 2.0, 0.0];
1129 let u = [-(alpha / 2.0).cos(), (alpha / 2.0).sin()]; 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]]; let half = tau / 2.0;
1135 let a_t = (t_up[1] - f[1]).atan2(t_up[0] - f[0]);
1136 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 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 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)?; let seat = centred_arc(c, ri, PI - alpha / 2.0, PI + alpha / 2.0)?.reversed().map_err(|e| refuse("gear_arc", e))?; let lower = mirrored(&upper).reversed().map_err(|e| refuse("gear_arc", e))?; let mut gap: Vec<(&'static str, NurbsCurve)> = vec![("A", lower), ("S", seat), ("C", upper)];
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
1197pub fn sprocket_solid(sprocket: &Sprocket) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
1200 let section = sprocket_section(sprocket)?;
1201 let solid = extrude_section(§ion, 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#[derive(Clone, Copy, Debug)]
1212pub enum Twist {
1213 Helical { turn: f64 },
1215 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
1244fn twist_basis(twist: Twist, reach: f64, tolerance: f64) -> Result<(Vec<f64>, Vec<[f64; 3]>), KernelRefusal> {
1248 let crease = matches!(twist, Twist::Herringbone { .. });
1249 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
1299pub 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
1322fn section_reach(section: &GearSection) -> Result<f64, KernelRefusal> {
1325 let mut reach: f64 = 0.0;
1326 for piece in §ion.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
1336pub 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 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 §ion.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 shell.face(surface, false, loops, piece.suffix())?;
1386 }
1387 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 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
1437pub 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1555pub enum Hand {
1556 Right,
1557 Left,
1558}
1559
1560#[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
1571pub fn helical_transverse(gear: &HelicalGear) -> Result<SpurGear, KernelRefusal> {
1573 let beta = gear.helix_angle;
1574 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 root_fillet: n.root_fillet * c,
1594 backlash: n.backlash,
1595 face_width: n.face_width,
1596 })
1597}
1598
1599pub 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 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(§ion, 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#[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 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
1649pub 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
1677pub fn straight_spline_shaft(spline: &StraightSpline) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
1680 let section = straight_spline_section(spline)?;
1681 let solid = extrude_section(§ion, 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
1688pub fn hub_from_section(section: &GearSection, outside: f64, length: f64) -> Result<BrepSolid, KernelRefusal> {
1692 let mut reach: f64 = 0.0;
1695 for piece in §ion.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
1712pub 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(§ion, outside, spline.length)?;
1716 Ok((hub, section.data))
1717}
1718
1719#[derive(Clone, Debug)]
1722pub struct TimingPulley {
1723 pub pitch: f64,
1725 pub teeth: usize,
1726 pub pld: f64,
1728 pub bottom_width: f64,
1730 pub depth: f64,
1732 pub side_angle: f64,
1734 pub bottom_radius: f64,
1736 pub top_radius: f64,
1738 pub width: f64,
1739}
1740
1741fn 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
1765pub 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]; let normal = [-s, c]; let corner = [x_bottom, bottom_width / 2.0];
1793 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 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 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 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#[derive(Clone, Debug)]
1866pub struct BeveloidGear {
1867 pub spur: SpurGear,
1868 pub cone_angle: f64,
1869}
1870
1871pub 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 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 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 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(§ion, 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#[derive(Clone, Debug)]
2036pub struct StarWheel {
2037 pub module: f64,
2038 pub teeth: usize,
2039 pub pinion_pins: usize,
2041 pub pin_diameter: f64,
2042 pub addendum: f64,
2044 pub clearance: f64,
2046 pub backlash: f64,
2047 pub face_width: f64,
2048}
2049
2050pub 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; 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 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 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 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 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 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 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 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
2202pub fn star_wheel_solid(wheel: &StarWheel) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
2204 let section = star_wheel_section(wheel)?;
2205 let solid = extrude_section(§ion, 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#[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 pub length: f64,
2225}
2226
2227pub 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 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 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
2315pub 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 §ion.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 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 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(§ion, 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#[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
2457pub 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 let tip = [ra, 0.0];
2480 let face_angle = PI + lean; 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 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 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 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
2520pub fn ratchet_solid(ratchet: &Ratchet) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
2522 let section = ratchet_section(ratchet)?;
2523 let solid = extrude_section(§ion, 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#[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 pub lock_radius: f64,
2543 pub width: f64,
2544}
2545
2546pub 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
2556pub 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; 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 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 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
2623pub fn geneva_solid(wheel: &GenevaWheel) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
2626 let section = geneva_section(wheel)?;
2627 let solid = extrude_section(§ion, 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#[derive(Clone, Debug)]
2637pub struct Worm {
2638 pub axial_module: f64,
2639 pub starts: usize,
2640 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 pub fn lead(&self) -> f64 {
2652 self.starts as f64 * PI * self.axial_module
2653 }
2654
2655 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
2661pub 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(°rees) {
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 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)?; 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
2723pub 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(§ion, 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#[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 pub clearance: f64,
2748 pub width: f64,
2749}
2750
2751impl CycloidalDisc {
2752 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 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 let n = [d[1] / length, -d[0] / length];
2771 [q[0] + offset * n[0], q[1] + offset * n[1]]
2772 }
2773}
2774
2775pub 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 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 let offset = dp / 2.0 + clearance / 2.0;
2795 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 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 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
2845pub fn cycloidal_disc_solid(disc: &CycloidalDisc) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
2847 let section = cycloidal_disc_section(disc)?;
2848 let solid = extrude_section(§ion, 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
2855pub 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 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 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(§ion, outside, width)?;
2892 Ok((ring, section.data))
2893}
2894
2895#[derive(Clone, Debug)]
2899pub struct CycloidalGear {
2900 pub module: f64,
2901 pub teeth: usize,
2902 pub generating_radius: f64,
2904 pub tooth_fraction: f64,
2906 pub addendum: f64,
2908 pub dedendum: f64,
2910 pub width: f64,
2911}
2912
2913pub 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; 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 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 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)?; 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
3001pub fn cycloidal_gear_solid(gear: &CycloidalGear) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
3003 let section = cycloidal_gear_section(gear)?;
3004 let solid = extrude_section(§ion, 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#[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
3028pub 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
3036fn 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
3048fn cone_angle(p: [f64; 3]) -> f64 {
3050 p[0].hypot(p[1]).atan2(p[2])
3051}
3052
3053fn project(p: [f64; 3], h: f64) -> [f64; 2] {
3055 [p[0] * h / p[2], p[1] * h / p[2]]
3056}
3057
3058pub 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(°rees) {
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 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 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 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 let extend = !(root > base); 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)?; 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 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 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 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
3166pub 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 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 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 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 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 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 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 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 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 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 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 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 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 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
3365fn 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
3415fn 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
3441pub(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 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 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 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#[derive(Clone, Debug)]
3539pub struct EllipticalGear {
3540 pub module: f64,
3541 pub teeth: usize,
3542 pub eccentricity: f64,
3544 pub pressure_angle: f64,
3545 pub addendum: f64,
3547 pub dedendum: f64,
3549 pub root_fillet: f64,
3551 pub backlash: f64,
3553 pub face_width: f64,
3554}
3555
3556struct PitchEllipse {
3558 latus: f64,
3560 e: f64,
3561 lobes: f64,
3562 segments: usize,
3563 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 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 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 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 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 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
3654pub fn elliptical_sizes(gear: &EllipticalGear) -> (f64, f64, f64, f64) {
3657 lobed_sizes(gear, 1)
3658}
3659
3660pub 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); 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
3669struct RollingRack<'a> {
3672 pitch: &'a PitchEllipse,
3673}
3674
3675impl RollingRack<'_> {
3676 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 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
3709pub fn elliptical_section(gear: &EllipticalGear) -> Result<GearSection, KernelRefusal> {
3715 lobed_section(gear, 1)
3716}
3717
3718pub 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(°rees) {
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 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 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; 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 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 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 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 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; 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
3877pub fn elliptical_solid(gear: &EllipticalGear) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
3880 lobed_solid(gear, 1)
3881}
3882
3883pub 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(§ion, 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
3893fn 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
3913fn 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
3941fn 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#[derive(Clone, Debug)]
3977pub struct WormWheel {
3978 pub worm: Worm,
3980 pub teeth: usize,
3981 pub addendum: f64,
3983 pub dedendum: f64,
3985 pub face_width: f64,
3986 pub backlash: f64,
3988}
3989
3990pub 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
4001struct WheelPlane<'a> {
4003 wheel: &'a WormWheel,
4004 c: f64,
4005 r2: f64,
4006 a: f64,
4007 rho_tip: f64,
4009 r_tip: f64,
4011 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 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 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 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 let n = [-t[1] / length, t[0] / length];
4062 if n[1] * side >= 0.0 { n } else { [-n[0], -n[1]] }
4063 }
4064
4065 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 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 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 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 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 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
4149fn 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
4164fn 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
4177pub 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)?; 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 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 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 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); 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 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 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 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 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 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(§ion, 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#[derive(Clone, Debug)]
4362pub struct CrownGear {
4363 pub module: f64,
4364 pub teeth: usize,
4365 pub pinion_teeth: usize,
4367 pub shaper_extra: usize,
4369 pub pressure_angle: f64,
4370 pub addendum: f64,
4372 pub dedendum: f64,
4374 pub inner_radius: f64,
4376 pub outer_radius: f64,
4378 pub rim: f64,
4380}
4381
4382const CROWN_TIP_ROUND: f64 = 0.2;
4384const CROWN_TIP_LAND: f64 = 0.05;
4386
4387struct CrownShaper {
4391 rs: f64,
4393 rb: f64,
4394 ra: f64,
4395 k: f64,
4397 c0: f64,
4399 rr: f64,
4401 centre: [f64; 2],
4402 uj: f64,
4403 bc: f64,
4405 psi_land: f64,
4407 psi_flank: f64,
4408}
4409
4410#[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 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 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 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 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 fn generate(&self, p: OutlinePoint, x: f64) -> Option<[f64; 3]> {
4486 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 fn on_cylinder(&self, p: OutlinePoint, radius: f64) -> Option<[f64; 2]> {
4501 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 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 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(°rees) {
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
4558struct CrownRing<'a> {
4560 shaper: &'a CrownShaper,
4561 radius: f64,
4562 u_tip: f64,
4564 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 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 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 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 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
4629pub 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 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 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
4692pub 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
4714fn 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
4731fn 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
4863fn 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
4887pub 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 struct Space {
4902 walls: Vec<NurbsSurface>,
4903 inner: [u64; 6],
4904 outer: [u64; 6],
4905 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 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 let mut sides = Vec::with_capacity(teeth); 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 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 shell.face(surface, side == 1, vec![coedges], format!("{}{j}", if side == 0 { "I" } else { "O" }))?;
5008 }
5009 }
5010 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 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