Skip to main content

brep_cam/kinematics/
mod.rs

1//! Machine kinematics (lane C10, row 1): forward and inverse kinematics of
2//! 3-, 4- and 5-axis mills from the shared [`Machine`] definition.
3//!
4//! Conventions (sections 1-3):
5//! - A cutter-location point is the tool tip `p` plus the unit tool axis `a`
6//!   (tip toward spindle), both in the SETUP frame S. `None` axis is `+Z`.
7//! - A rotary joint `(d, o, θ)` rotates by `θ` (right-hand rule about the unit
8//!   direction `d`) about the line through `o`. A TABLE joint rotates the part,
9//!   a HEAD joint rotates the tool. The primary joint carries the secondary.
10//! - Head pivots are relative to the controlled point (tool tip at zero
11//!   angles); table pivots are in S.
12//! - Angles are degrees in the API and radians inside. Controller sign
13//!   conventions belong to the post.
14//!
15//! Every chain reduces to one inverse problem, [`two_axis`]: rotate `u` first
16//! about `d_a` by `α`, then about `d_b` by `β`, to reach `w`. No orthogonality
17//! between the axes is assumed, so nutating heads solve with the same code.
18//! Both solution branches are returned; a free angle inside the singular cone
19//! is held at the previous value and tagged `singular`.
20
21use 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/// Which side of the machine a rotary joint moves.
29#[derive(Clone, Copy, Debug, PartialEq, Eq)]
30pub enum Carrier {
31    /// Rotates the part.
32    Table,
33    /// Rotates the tool.
34    Head,
35}
36
37/// One rotary joint of a chain.
38#[derive(Clone, Debug, PartialEq)]
39pub struct Joint {
40    /// Axis letter the post emits.
41    pub name: String,
42    /// Unit rotation direction.
43    pub direction: Point3,
44    /// A point on the axis: in S for table joints, relative to the controlled
45    /// point for head joints.
46    pub origin: Point3,
47    /// Angular limits in degrees (`None`: continuous).
48    pub limits_deg: Option<[f64; 2]>,
49    pub carrier: Carrier,
50}
51
52/// A rigid link of the machine that solids attach to: the model's type, re-exported
53/// so machine definitions and the chain share one `Link`.
54pub use crate::model::Link;
55
56/// The kinematic arrangement, with the joints in output order.
57#[derive(Clone, Copy, Debug, PartialEq, Eq)]
58pub enum ChainKind {
59    /// No rotary joint; only `+Z` tool axes are reachable.
60    Mill3,
61    /// One table rotary (`joints[0]`).
62    Mill4,
63    /// `joints[0]` primary table carries `joints[1]` secondary table.
64    TableTable,
65    /// `joints[0]` primary head carries `joints[1]` secondary head (spindle).
66    HeadHead,
67    /// `joints[0]` head tilts the tool, `joints[1]` table turns the part.
68    HeadTable,
69}
70
71/// A machine's kinematic chain.
72#[derive(Clone, Debug, PartialEq)]
73pub struct Chain {
74    pub kind: ChainKind,
75    pub joints: Vec<Joint>,
76}
77
78/// Solver settings.
79#[derive(Clone, Copy, Debug, PartialEq)]
80pub struct KinematicsOptions {
81    /// Rotary tool-centre-point control (G43.4 / TRAORI / M128): linear words
82    /// are the tip in S. Off: linear words are the machine axes with the
83    /// pivots pushed through the chain.
84    pub tcp: bool,
85    /// Half-angle of the cone about a joint's direction inside which the
86    /// tool axis leaves that joint's angle free (the near-vertical C problem).
87    pub singular_cone_deg: f64,
88    /// Reachability tolerance on direction cosines (a 4-axis tool axis that
89    /// misses the rotary's plane by more than this is refused).
90    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/// One machine configuration reaching a CL point.
112#[derive(Clone, Debug, PartialEq)]
113pub struct Pose {
114    /// Linear axis words: the tip in S with TCP on, the machine axes with TCP off.
115    pub linear: Point3,
116    /// Rotary angles in degrees, in `Chain::joints` order, in `(-180, 180]`
117    /// unless the sequence solver unwound them.
118    pub angles_deg: Vec<f64>,
119    /// Solution branch (0 or 1) of the inverse problem.
120    pub branch: u8,
121    /// A free angle was held at the previous (or zero) value.
122    pub singular: bool,
123}
124
125#[derive(Clone, Debug, PartialEq)]
126pub enum KinematicsError {
127    /// The machine definition cannot be turned into a chain.
128    InvalidMachine(String),
129    InvalidInput(String),
130    /// The tool axis is not finite or zero.
131    InvalidAxis,
132    /// No joint configuration reaches the tool axis (ignoring limits).
133    Unreachable { axis: Point3 },
134    /// Every solution violates a joint's limits. `index` is the CL point.
135    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
162// ---------------------------------------------------------------------------
163// Rotation helpers
164// ---------------------------------------------------------------------------
165
166/// Rodrigues rotation of `v` by `theta` radians about the unit direction `d`.
167pub 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
172/// Rotation of the point `x` about the line through `o` with direction `d`.
173pub fn rotate_about(o: Point3, d: Point3, theta: f64, x: Point3) -> Point3 {
174    o.add(rotate(d, theta, x.sub(o)))
175}
176
177/// Signed angle (radians) about `d` from `x` to `y`, both perpendicular to `d`
178/// and non-zero.
179fn signed_angle(d: Point3, x: Point3, y: Point3) -> f64 {
180    (x.cross(y).dot(d)).atan2(x.dot(y))
181}
182
183/// Component of `v` perpendicular to the unit direction `d`.
184fn perp(d: Point3, v: Point3) -> Point3 {
185    v.sub(d.scale(v.dot(d)))
186}
187
188/// Wrap radians into `(-π, π]`.
189fn 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
199/// Wrap degrees into `(-180, 180]`.
200pub 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/// One branch of [`two_axis`].
211#[derive(Clone, Copy, Debug, PartialEq)]
212pub struct TwoAxisSolution {
213    /// Angle about the first axis (radians).
214    pub alpha: f64,
215    /// Angle about the second axis (radians).
216    pub beta: f64,
217    pub singular: bool,
218}
219
220/// Solve `R(d_b, β) R(d_a, α) u = w` for unit `u`, `w`, `d_a`, `d_b`.
221///
222/// `prev` supplies the held values of free angles (singular configurations).
223/// `cone` is the singular cone half-angle in radians: when `w` is within
224/// it of `±d_b`, `β` is free; when the first rotation cannot change the dot
225/// product with `d_b`, `α` is free. Returns 0, 1 or 2 branches, branch 0 first.
226pub 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    // Rotation about d_b preserves the dot with d_b:
236    //   (R(d_a, α) u)·d_b = A cos α + B sin α + C = k.
237    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    // r = sin(u, d_a) · sin(d_a, d_b): the amplitude the first joint can give
244    // the dot product. Inside the singular cone the first angle is free.
245    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
281/// Solve `R(d, θ) u = w` for one joint: reachable only when `u·d = w·d`.
282/// `prev` holds the free angle when `u ∥ d`.
283pub 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
295// ---------------------------------------------------------------------------
296// Chains
297// ---------------------------------------------------------------------------
298
299fn 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    /// Build the chain of `machine`. Table pivots given in machine coordinates
313    /// are shifted into S by the setup's `wcs_origin`.
314    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            // A mill-turn's C axis is one table joint, as C11b specified (item 3 of its
328            // request); the optional Y is constrained in the owned millturn API.
329            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    /// A chain without rotary joints.
366    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    /// Joint names in output order.
375    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    /// Rigid transform of a rotary joint at `theta` radians: `x ↦ o + R(x − o)`.
394    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    /// World placement of a link's frame at the given angles and linear
401    /// position (`x_world = T(x_link)`). Table links are given in S at zero
402    /// angles; head and tool links relative to the controlled point.
403    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        // Outer-to-inner composition: for joints [a, b] carried in order, x_world = T_a(T_b(x)).
410        let compose = |ids: &[usize]| -> RigidTransform {
411            let mut t = RigidTransform::identity();
412            for &k in ids.iter().rev() {
413                // t = T_k ∘ t  (apply t first, then T_k)
414                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    /// Part point `x` (in S) to the machine frame W at the given angles.
442    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    /// Machine-frame point to S at the given angles (inverse of [`Chain::part_to_world`]).
456    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    /// Part-frame direction to W (rotation only).
470    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    /// Tool axis in W at the given angles.
484    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    /// Offset from the controlled point (linear axes) to the tool tip in W,
497    /// produced by the head joints: zero for table-only chains.
498    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    /// Forward kinematics: the tip and unit tool axis in S of a pose.
517    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    /// W direction to the part frame (rotation only).
534    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    /// Linear axis words for a tip in S at the given angles.
548    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    /// Inverse kinematics: every joint configuration (ignoring limits, angles
557    /// in `(-180, 180]`) that puts the tool along `axis` at `tip`.
558    /// `previous` holds free angles in singular configurations (zero when
559    /// `None`). Returns an empty vector only for a 3-axis chain whose tool
560    /// axis is not `+Z` (reported as `Unreachable`).
561    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                // R_P(θ1) R_Sec(θ2) a = Z: first the secondary, then the primary.
602                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                // R_P(θ1) R_Sec(θ2) Z = a.
608                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                // R_H(θh) Z = R_T(θt) a  ⇔  R_T(−θt) R_H(θh) Z = a.
614                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