1use crate::model::{Kinematics, Machine, MachineKind, Point3, RigidTransform, RotaryAxis};
22use std::f64::consts::PI;
23
24pub mod library;
25pub mod post;
26pub mod sequence;
27
28#[derive(Clone, Copy, Debug, PartialEq, Eq)]
30pub enum Carrier {
31 Table,
33 Head,
35}
36
37#[derive(Clone, Debug, PartialEq)]
39pub struct Joint {
40 pub name: String,
42 pub direction: Point3,
44 pub origin: Point3,
47 pub limits_deg: Option<[f64; 2]>,
49 pub carrier: Carrier,
50}
51
52pub use crate::model::Link;
55
56#[derive(Clone, Copy, Debug, PartialEq, Eq)]
58pub enum ChainKind {
59 Mill3,
61 Mill4,
63 TableTable,
65 HeadHead,
67 HeadTable,
69}
70
71#[derive(Clone, Debug, PartialEq)]
73pub struct Chain {
74 pub kind: ChainKind,
75 pub joints: Vec<Joint>,
76}
77
78#[derive(Clone, Copy, Debug, PartialEq)]
80pub struct KinematicsOptions {
81 pub tcp: bool,
85 pub singular_cone_deg: f64,
88 pub cos_eps: f64,
91}
92
93impl Default for KinematicsOptions {
94 fn default() -> Self {
95 Self { tcp: true, singular_cone_deg: 0.5, cos_eps: 1e-6 }
96 }
97}
98
99impl KinematicsOptions {
100 pub fn validate(&self) -> Result<(), KinematicsError> {
101 if !self.singular_cone_deg.is_finite() || self.singular_cone_deg < 0.0 || self.singular_cone_deg >= 90.0 {
102 return Err(KinematicsError::InvalidInput("singular cone must be in [0, 90) degrees".into()));
103 }
104 if !self.cos_eps.is_finite() || self.cos_eps < 0.0 || self.cos_eps > 1e-3 {
105 return Err(KinematicsError::InvalidInput("cosine tolerance must be in [0, 1e-3]".into()));
106 }
107 Ok(())
108 }
109}
110
111#[derive(Clone, Debug, PartialEq)]
113pub struct Pose {
114 pub linear: Point3,
116 pub angles_deg: Vec<f64>,
119 pub branch: u8,
121 pub singular: bool,
123}
124
125#[derive(Clone, Debug, PartialEq)]
126pub enum KinematicsError {
127 InvalidMachine(String),
129 InvalidInput(String),
130 InvalidAxis,
132 Unreachable { axis: Point3 },
134 LimitViolation { index: usize, joint: String },
136}
137
138impl std::fmt::Display for KinematicsError {
139 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
140 match self {
141 KinematicsError::InvalidMachine(m) => write!(f, "machine: {m}"),
142 KinematicsError::InvalidInput(m) => write!(f, "kinematics: {m}"),
143 KinematicsError::InvalidAxis => write!(f, "tool axis must be a finite non-zero vector"),
144 KinematicsError::Unreachable { axis } => {
145 write!(f, "tool axis [{}, {}, {}] is unreachable on this machine", axis.x, axis.y, axis.z)
146 }
147 KinematicsError::LimitViolation { index, joint } => {
148 write!(f, "CL point {index} needs rotary {joint} outside its limits")
149 }
150 }
151 }
152}
153
154impl std::error::Error for KinematicsError {}
155
156impl From<KinematicsError> for crate::CamError {
157 fn from(e: KinematicsError) -> Self {
158 crate::CamError::InvalidInput(e.to_string())
159 }
160}
161
162pub fn rotate(d: Point3, theta: f64, v: Point3) -> Point3 {
168 let (s, c) = theta.sin_cos();
169 v.scale(c).add(d.cross(v).scale(s)).add(d.scale(d.dot(v) * (1.0 - c)))
170}
171
172pub fn rotate_about(o: Point3, d: Point3, theta: f64, x: Point3) -> Point3 {
174 o.add(rotate(d, theta, x.sub(o)))
175}
176
177fn signed_angle(d: Point3, x: Point3, y: Point3) -> f64 {
180 (x.cross(y).dot(d)).atan2(x.dot(y))
181}
182
183fn perp(d: Point3, v: Point3) -> Point3 {
185 v.sub(d.scale(v.dot(d)))
186}
187
188fn wrap_pi(a: f64) -> f64 {
190 let mut r = a % (2.0 * PI);
191 if r <= -PI {
192 r += 2.0 * PI;
193 } else if r > PI {
194 r -= 2.0 * PI;
195 }
196 r
197}
198
199pub fn wrap_deg(a: f64) -> f64 {
201 let mut r = a % 360.0;
202 if r <= -180.0 {
203 r += 360.0;
204 } else if r > 180.0 {
205 r -= 360.0;
206 }
207 r
208}
209
210#[derive(Clone, Copy, Debug, PartialEq)]
212pub struct TwoAxisSolution {
213 pub alpha: f64,
215 pub beta: f64,
217 pub singular: bool,
218}
219
220pub fn two_axis(
227 d_a: Point3,
228 d_b: Point3,
229 u: Point3,
230 w: Point3,
231 prev: [f64; 2],
232 cone: f64,
233 cos_eps: f64,
234) -> Vec<TwoAxisSolution> {
235 let ua = u.dot(d_a);
238 let ab = d_a.dot(d_b);
239 let a = u.dot(d_b) - ua * ab;
240 let b = d_a.cross(u).dot(d_b);
241 let c = ua * ab;
242 let k = w.dot(d_b);
243 let r = a.hypot(b);
246 let sin_cone = cone.sin().max(0.0);
247 let mut alphas: Vec<(f64, bool)> = Vec::new();
248 if r <= sin_cone.max(cos_eps) {
249 if (k - c).abs() > r + cos_eps {
250 return Vec::new();
251 }
252 alphas.push((prev[0], true));
253 } else {
254 let phi = b.atan2(a);
255 let ratio = (k - c) / r;
256 if ratio > 1.0 + cos_eps || ratio < -1.0 - cos_eps {
257 return Vec::new();
258 }
259 let delta = ratio.clamp(-1.0, 1.0).acos();
260 alphas.push((wrap_pi(phi + delta), false));
261 if delta > 0.0 {
262 alphas.push((wrap_pi(phi - delta), false));
263 }
264 }
265 let w_perp = perp(d_b, w);
266 let w_singular = w_perp.length() <= sin_cone.max(cos_eps);
267 let mut out = Vec::new();
268 for (alpha, alpha_free) in alphas {
269 let u1 = rotate(d_a, alpha, u);
270 let u_perp = perp(d_b, u1);
271 let (beta, beta_free) = if w_singular || u_perp.length() <= 1e-12 {
272 (prev[1], true)
273 } else {
274 (wrap_pi(signed_angle(d_b, u_perp, w_perp)), false)
275 };
276 out.push(TwoAxisSolution { alpha, beta, singular: alpha_free || beta_free });
277 }
278 out
279}
280
281pub fn one_axis(d: Point3, u: Point3, w: Point3, prev: f64, cone: f64, cos_eps: f64) -> Option<(f64, bool)> {
284 if (u.dot(d) - w.dot(d)).abs() > cos_eps {
285 return None;
286 }
287 let up = perp(d, u);
288 let wp = perp(d, w);
289 if wp.length() <= cone.sin().max(cos_eps) || up.length() <= cos_eps {
290 return Some((prev, true));
291 }
292 Some((wrap_pi(signed_angle(d, up, wp)), false))
293}
294
295fn joint(axis: &RotaryAxis, carrier: Carrier, wcs_origin: Point3) -> Result<Joint, KinematicsError> {
300 axis.validate().map_err(KinematicsError::InvalidMachine)?;
301 let direction = axis.direction.normalized().ok_or_else(|| {
302 KinematicsError::InvalidMachine(format!("rotary axis {} has a zero direction", axis.name))
303 })?;
304 let origin = match carrier {
305 Carrier::Table => axis.origin.sub(wcs_origin),
306 Carrier::Head => axis.origin,
307 };
308 Ok(Joint { name: axis.name.clone(), direction, origin, limits_deg: axis.limits_deg, carrier })
309}
310
311impl Chain {
312 pub fn from_machine(machine: &Machine, wcs_origin: Point3) -> Result<Chain, KinematicsError> {
315 machine.validate().map_err(KinematicsError::InvalidMachine)?;
316 if !wcs_origin.is_finite() {
317 return Err(KinematicsError::InvalidMachine("work offset origin is not finite".into()));
318 }
319 let chain = match &machine.kind {
320 MachineKind::Mill3 => Chain { kind: ChainKind::Mill3, joints: Vec::new() },
321 MachineKind::Lathe => {
322 return Err(KinematicsError::InvalidMachine("lathe kinematics are not a milling chain".into()))
323 }
324 MachineKind::Mill4 { rotary } => {
325 Chain { kind: ChainKind::Mill4, joints: vec![joint(rotary, Carrier::Table, wcs_origin)?] }
326 }
327 MachineKind::MillTurn { c_axis, .. } => {
330 Chain { kind: ChainKind::Mill4, joints: vec![joint(c_axis, Carrier::Table, wcs_origin)?] }
331 }
332 MachineKind::Mill5 { kinematics } => match kinematics {
333 Kinematics::TableTable { primary, secondary } => Chain {
334 kind: ChainKind::TableTable,
335 joints: vec![
336 joint(primary, Carrier::Table, wcs_origin)?,
337 joint(secondary, Carrier::Table, wcs_origin)?,
338 ],
339 },
340 Kinematics::HeadHead { primary, secondary } => Chain {
341 kind: ChainKind::HeadHead,
342 joints: vec![
343 joint(primary, Carrier::Head, wcs_origin)?,
344 joint(secondary, Carrier::Head, wcs_origin)?,
345 ],
346 },
347 Kinematics::HeadTable { head, table } => Chain {
348 kind: ChainKind::HeadTable,
349 joints: vec![joint(head, Carrier::Head, wcs_origin)?, joint(table, Carrier::Table, wcs_origin)?],
350 },
351 },
352 };
353 if chain.joints.len() == 2 {
354 let (a, b) = (chain.joints[0].direction, chain.joints[1].direction);
355 if a.cross(b).length() <= 1e-9 {
356 return Err(KinematicsError::InvalidMachine("the two rotary axes are parallel".into()));
357 }
358 if chain.joints[0].name == chain.joints[1].name {
359 return Err(KinematicsError::InvalidMachine("the two rotary axes share a name".into()));
360 }
361 }
362 Ok(chain)
363 }
364
365 pub fn mill3() -> Chain {
367 Chain { kind: ChainKind::Mill3, joints: Vec::new() }
368 }
369
370 pub fn rotary_count(&self) -> usize {
371 self.joints.len()
372 }
373
374 pub fn joint_names(&self) -> Vec<&str> {
376 self.joints.iter().map(|j| j.name.as_str()).collect()
377 }
378
379 fn check_angles(&self, angles_deg: &[f64]) -> Result<(), KinematicsError> {
380 if angles_deg.len() != self.joints.len() {
381 return Err(KinematicsError::InvalidInput(format!(
382 "expected {} rotary angles, got {}",
383 self.joints.len(),
384 angles_deg.len()
385 )));
386 }
387 if angles_deg.iter().any(|a| !a.is_finite()) {
388 return Err(KinematicsError::InvalidInput("rotary angle is not finite".into()));
389 }
390 Ok(())
391 }
392
393 fn joint_transform(j: &Joint, theta: f64) -> RigidTransform {
395 let r = RigidTransform::axis_angle(j.direction, theta, Point3::ZERO).unwrap_or_else(|_| RigidTransform::identity());
396 let shift = j.origin.sub(r.apply_vector(j.origin));
397 RigidTransform { rotation: r.rotation, translation: shift }
398 }
399
400 pub fn link_transform(&self, link: Link, angles_deg: &[f64], linear: Point3) -> Result<RigidTransform, KinematicsError> {
404 self.check_angles(angles_deg)?;
405 let th: Vec<f64> = angles_deg.iter().map(|a| a.to_radians()).collect();
406 let j = &self.joints;
407 let table_joints: Vec<usize> = (0..j.len()).filter(|&k| j[k].carrier == Carrier::Table).collect();
408 let head_joints: Vec<usize> = (0..j.len()).filter(|&k| j[k].carrier == Carrier::Head).collect();
409 let compose = |ids: &[usize]| -> RigidTransform {
411 let mut t = RigidTransform::identity();
412 for &k in ids.iter().rev() {
413 t = t.then(&Self::joint_transform(&j[k], th[k]));
415 }
416 t
417 };
418 let shift = RigidTransform::translation(linear);
419 Ok(match link {
420 Link::Base => RigidTransform::identity(),
421 Link::Part => compose(&table_joints),
422 Link::Tool => compose(&head_joints).then(&shift),
423 Link::Joint { index: k } => {
424 if k >= j.len() {
425 return Err(KinematicsError::InvalidInput(format!("link joint {k} does not exist")));
426 }
427 match j[k].carrier {
428 Carrier::Table => {
429 let upto: Vec<usize> = table_joints.iter().copied().take_while(|&i| i <= k).collect();
430 compose(&upto)
431 }
432 Carrier::Head => {
433 let upto: Vec<usize> = head_joints.iter().copied().take_while(|&i| i <= k).collect();
434 compose(&upto).then(&shift)
435 }
436 }
437 }
438 })
439 }
440
441 pub fn part_to_world(&self, angles_deg: &[f64], x: Point3) -> Point3 {
443 let j = &self.joints;
444 match self.kind {
445 ChainKind::Mill3 | ChainKind::HeadHead => x,
446 ChainKind::Mill4 => rotate_about(j[0].origin, j[0].direction, angles_deg[0].to_radians(), x),
447 ChainKind::TableTable => {
448 let inner = rotate_about(j[1].origin, j[1].direction, angles_deg[1].to_radians(), x);
449 rotate_about(j[0].origin, j[0].direction, angles_deg[0].to_radians(), inner)
450 }
451 ChainKind::HeadTable => rotate_about(j[1].origin, j[1].direction, angles_deg[1].to_radians(), x),
452 }
453 }
454
455 pub fn world_to_part(&self, angles_deg: &[f64], x: Point3) -> Point3 {
457 let j = &self.joints;
458 match self.kind {
459 ChainKind::Mill3 | ChainKind::HeadHead => x,
460 ChainKind::Mill4 => rotate_about(j[0].origin, j[0].direction, -angles_deg[0].to_radians(), x),
461 ChainKind::TableTable => {
462 let outer = rotate_about(j[0].origin, j[0].direction, -angles_deg[0].to_radians(), x);
463 rotate_about(j[1].origin, j[1].direction, -angles_deg[1].to_radians(), outer)
464 }
465 ChainKind::HeadTable => rotate_about(j[1].origin, j[1].direction, -angles_deg[1].to_radians(), x),
466 }
467 }
468
469 pub fn part_dir_to_world(&self, angles_deg: &[f64], v: Point3) -> Point3 {
471 let j = &self.joints;
472 match self.kind {
473 ChainKind::Mill3 | ChainKind::HeadHead => v,
474 ChainKind::Mill4 => rotate(j[0].direction, angles_deg[0].to_radians(), v),
475 ChainKind::TableTable => {
476 let inner = rotate(j[1].direction, angles_deg[1].to_radians(), v);
477 rotate(j[0].direction, angles_deg[0].to_radians(), inner)
478 }
479 ChainKind::HeadTable => rotate(j[1].direction, angles_deg[1].to_radians(), v),
480 }
481 }
482
483 pub fn tool_axis_world(&self, angles_deg: &[f64]) -> Point3 {
485 let j = &self.joints;
486 match self.kind {
487 ChainKind::Mill3 | ChainKind::Mill4 | ChainKind::TableTable => Point3::Z,
488 ChainKind::HeadHead => {
489 let inner = rotate(j[1].direction, angles_deg[1].to_radians(), Point3::Z);
490 rotate(j[0].direction, angles_deg[0].to_radians(), inner)
491 }
492 ChainKind::HeadTable => rotate(j[0].direction, angles_deg[0].to_radians(), Point3::Z),
493 }
494 }
495
496 pub fn head_offset(&self, angles_deg: &[f64]) -> Point3 {
499 let j = &self.joints;
500 match self.kind {
501 ChainKind::Mill3 | ChainKind::Mill4 | ChainKind::TableTable => Point3::ZERO,
502 ChainKind::HeadHead => {
503 let (t1, t2) = (angles_deg[0].to_radians(), angles_deg[1].to_radians());
504 let o1 = j[0].origin;
505 let o2 = j[1].origin;
506 let inner = o2.sub(rotate(j[1].direction, t2, o2)).sub(o1);
507 o1.add(rotate(j[0].direction, t1, inner))
508 }
509 ChainKind::HeadTable => {
510 let o = j[0].origin;
511 o.sub(rotate(j[0].direction, angles_deg[0].to_radians(), o))
512 }
513 }
514 }
515
516 pub fn forward(&self, pose: &Pose, options: &KinematicsOptions) -> Result<(Point3, Point3), KinematicsError> {
518 self.check_angles(&pose.angles_deg)?;
519 if !pose.linear.is_finite() {
520 return Err(KinematicsError::InvalidInput("linear position is not finite".into()));
521 }
522 let axis_w = self.tool_axis_world(&pose.angles_deg);
523 let axis = self.world_dir_to_part(&pose.angles_deg, axis_w);
524 let tip = if options.tcp {
525 pose.linear
526 } else {
527 let tip_w = pose.linear.add(self.head_offset(&pose.angles_deg));
528 self.world_to_part(&pose.angles_deg, tip_w)
529 };
530 Ok((tip, axis))
531 }
532
533 pub fn world_dir_to_part(&self, angles_deg: &[f64], v: Point3) -> Point3 {
535 let j = &self.joints;
536 match self.kind {
537 ChainKind::Mill3 | ChainKind::HeadHead => v,
538 ChainKind::Mill4 => rotate(j[0].direction, -angles_deg[0].to_radians(), v),
539 ChainKind::TableTable => {
540 let outer = rotate(j[0].direction, -angles_deg[0].to_radians(), v);
541 rotate(j[1].direction, -angles_deg[1].to_radians(), outer)
542 }
543 ChainKind::HeadTable => rotate(j[1].direction, -angles_deg[1].to_radians(), v),
544 }
545 }
546
547 pub fn linear_for(&self, tip: Point3, angles_deg: &[f64], options: &KinematicsOptions) -> Point3 {
549 if options.tcp {
550 tip
551 } else {
552 self.part_to_world(angles_deg, tip).sub(self.head_offset(angles_deg))
553 }
554 }
555
556 pub fn inverse(
562 &self,
563 tip: Point3,
564 axis: Option<Point3>,
565 previous: Option<&[f64]>,
566 options: &KinematicsOptions,
567 ) -> Result<Vec<Pose>, KinematicsError> {
568 options.validate()?;
569 if !tip.is_finite() {
570 return Err(KinematicsError::InvalidInput("tool tip is not finite".into()));
571 }
572 let a = match axis {
573 None => Point3::Z,
574 Some(v) => v.normalized().ok_or(KinematicsError::InvalidAxis)?,
575 };
576 let prev: Vec<f64> = match previous {
577 Some(p) => {
578 self.check_angles(p)?;
579 p.iter().map(|d| d.to_radians()).collect()
580 }
581 None => vec![0.0; self.joints.len()],
582 };
583 let cone = options.singular_cone_deg.to_radians();
584 let eps = options.cos_eps;
585 let unreachable = || KinematicsError::Unreachable { axis: a };
586 let j = &self.joints;
587 let mut raw: Vec<(Vec<f64>, bool)> = Vec::new();
588 match self.kind {
589 ChainKind::Mill3 => {
590 if 1.0 - a.dot(Point3::Z) > eps {
591 return Err(unreachable());
592 }
593 raw.push((Vec::new(), false));
594 }
595 ChainKind::Mill4 => {
596 let (theta, singular) =
597 one_axis(j[0].direction, a, Point3::Z, prev[0], cone, eps).ok_or_else(unreachable)?;
598 raw.push((vec![theta], singular));
599 }
600 ChainKind::TableTable => {
601 for s in two_axis(j[1].direction, j[0].direction, a, Point3::Z, [prev[1], prev[0]], cone, eps) {
603 raw.push((vec![s.beta, s.alpha], s.singular));
604 }
605 }
606 ChainKind::HeadHead => {
607 for s in two_axis(j[1].direction, j[0].direction, Point3::Z, a, [prev[1], prev[0]], cone, eps) {
609 raw.push((vec![s.beta, s.alpha], s.singular));
610 }
611 }
612 ChainKind::HeadTable => {
613 for s in two_axis(j[0].direction, j[1].direction, Point3::Z, a, [prev[0], -prev[1]], cone, eps) {
615 raw.push((vec![s.alpha, -s.beta], s.singular));
616 }
617 }
618 }
619 if raw.is_empty() {
620 return Err(unreachable());
621 }
622 let mut poses = Vec::with_capacity(raw.len());
623 for (branch, (angles, singular)) in raw.into_iter().enumerate() {
624 let angles_deg: Vec<f64> = angles.iter().map(|r| wrap_deg(r.to_degrees())).collect();
625 let linear = self.linear_for(tip, &angles_deg, options);
626 poses.push(Pose { linear, angles_deg, branch: branch as u8, singular });
627 }
628 Ok(poses)
629 }
630}
631