Skip to main content

machine_hexapod/
lib.rs

1//! Hexapod (Stewart-Gough platform): six electric cylinders between a base and a moving platform, each a ball screw
2//! driven by its own servo motor through a coupling. Six degrees of freedom: the tool pose is the platform centre x, y,
3//! z (m) and the platform's orientation as a rotation vector rx, ry, rz (rad, axis times angle, in the base frame).
4//!
5//! Geometry (generic proportions, `[hexapod]`): the base joints B_i on a circle of `base_radius_m` in pairs at
6//! 120 k +- `base_half_angle_deg`, the platform joints a_i (platform frame) on a circle of `platform_radius_m` at
7//! 120 k +- (60 - `platform_half_angle_deg`), so that each leg runs from a base pair to the neighbouring platform pair
8//! and the six legs form the usual triangles. Leg i's length is L_i = `leg.closed_length_m` + q_i with q_i the
9//! cylinder's extension, its joint coordinate (0 to `leg.stroke_m`).
10//!
11//! ```text
12//! inverse   P_i = p + R a_i,  d_i = P_i - B_i,  L_i = |d_i|,  q_i = L_i - L_closed                   (closed form)
13//! twist     xi = (v, w): q_i' = u_i . v + (b_i x u_i) . w,  u_i = d_i / L_i,  b_i = R a_i,  rows of J
14//! forward   Newton on the twist: xi = J^-1 (q - q(x)), p += v, R = exp(w) R, from the home pose, until |q - q(x)|
15//!           < 1e-13 m; refused (NaN) where it does not converge within 40 steps
16//! dynamics  M_xi xi' + c + g = J^T f,  M_xi = diag(m 1, R I R^T),  c = (0, w x I_w w),  g = (0, 0, m g, 0, 0, 0)
17//!           q'' = J xi' + a0,  a0_i = (|w_i|^2 - (u_i . w_i)^2) / L_i + u_i . (w x (w x b_i)),  w_i = v + w x b_i
18//!           so in leg space: M_q = J^-T M_xi J^-1,  h = J^-T (c + g - M_xi J^-1 a0),  M_q q'' + h = f
19//! ```
20//!
21//! f_i is the force leg i pushes the platform with: what its screw passes on (`chain::JointMachine`, one
22//! `joint::RotaryJoint` with a `transmission::BallScrew` per leg: the screw and nut stiffness, the coupling, backlash,
23//! friction in the screw and the rod's guide, the motor).
24//!
25//! Each leg is two bodies: the part on the platform joint (the rod and nut, mass `leg.platform_share` of `leg.mass_kg`,
26//! its centre `leg.platform_part_centre_m` from the platform joint towards the base) and the part on the base joint
27//! (cylinder and motor, the rest of the mass, its centre `leg.base_part_centre_m` from the base joint towards the
28//! platform), each with its inertia about its own centre across the leg (`leg.*_part_inertia_kgm2`, 0 = a point mass).
29//! Both turn with the leg's direction u = d / L. With d' = v + w x b (the platform joint's velocity) and L' = u . d':
30//!
31//! ```text
32//! u' = (d' - u L') / L,  L'' = u' . d' + u . d'',  u'' = (d'' - 2 u' L' - u L'') / L        (d'' = w x (w x b) at xi' = 0)
33//! base part  X = B + c u,        X' = c u' = A xi,    A = c A_u,           A_u = (1 - u u^T) [1, -[b]x] / L
34//! rod part   X = P - c u,        X' = P' - c u',      A = [1, -[b]x] - c A_u,  P = p + b
35//! ```
36//!
37//! and with `a0` the acceleration at xi' = 0 (c u'' for the base part, w x (w x b) - c u'' for the rod part) each part
38//! adds m A^T A + I_t A_u^T A_u to M_xi and m A^T (a0 + g e_z) + I_t A_u^T u'' to c + g (d'Alembert; I_t about the
39//! centre across the leg, whose turn is u x u'). The platform's mass and inertia are the platform's alone, the payload
40//! is a point mass at the platform centre with the inertia `mass.payload_inertia_kgm2` (x, y, z, about the centre,
41//! in the platform frame) that turns with the platform. The legs' rotors spin along their legs and turn with them
42//! (`effects.rotor_gyroscopic`): the moment h u' (h = J i q') reaches the platform as a couple across the leg,
43//! F = h (u x u') / L at its joint and b x F, which does no work (`rotor_gyroscopic`); each part's
44//! spin about the leg's axis is free between the two joints and nothing excites it.
45
46use sim_components::chain::{
47    JOINT_KEYS, JointMachine, JointSpec, Lu, MOTOR_IDS, MOTOR_KEYS, Mechanism, condition_number, solve,
48};
49use sim_components::joint::RotaryJoint;
50use sim_components::mech::{HardStop, ShaftFriction, ThermalFeedback};
51use sim_components::rigid::{M3, V3, about, add, cross, dot, matmul, mul};
52use sim_components::transmission::BallScrew;
53use sim_core::{
54    AxisInfo, Config, ConfigError, Label, Machine, MachineEntry, MotorInfo, Part, RatingCheck, Scene, Shape, SignalInfo,
55};
56use std::f64::consts::{PI, TAU};
57
58pub static ENTRY: MachineEntry = MachineEntry {
59    id: "hexapod",
60    key: "machine-hexapod",
61    default_config: include_str!("../default.toml"),
62    i18n: &[("en", include_str!("../i18n/en.ftl")), ("de", include_str!("../i18n/de.ftl"))],
63    build,
64    suite_configs,
65};
66
67const G: f64 = 9.80665;
68
69/// Effects that take energy out or put it in; the standard suite runs with them off.
70pub const LOSSY_EFFECTS: [&str; 7] = [
71    "joint_friction",
72    "motor_friction",
73    "gearbox_drag",
74    "gearbox_lost_motion",
75    "gearbox_efficiency",
76    "torque_ripple",
77    "holding_brake",
78];
79
80const AXIS_IDS: [&str; 6] = ["x", "y", "z", "rx", "ry", "rz"];
81const AXIS_KEYS: [&str; 6] = ["axis-x", "axis-y", "axis-z", "axis-rx", "axis-ry", "axis-rz"];
82
83/// The default config with every loss switched off.
84pub fn lossless_config() -> Config {
85    let mut cfg = ENTRY.config();
86    for effect in LOSSY_EFFECTS {
87        cfg.set_text(&format!("effects.{effect} = false")).unwrap();
88    }
89    cfg.set_text("gearbox.damping_nm_s_rad = 0.0").unwrap();
90    cfg.set_text("leg.stop_damping_n_s_m = 0.0").unwrap();
91    cfg
92}
93
94/// Loss-free rigid and elastic models, with and without the payload, all without gravity: held by constant leg forces,
95/// as the suite holds it after its pulse, the platform under its weight is unstable (pushing legs of constant force:
96/// d^2/dz^2 of m g z - sum f_i L_i = -sum f_i (1 - u_iz^2) / L_i < 0), and it runs away from the pose, a real property
97/// that the position loops hold and not a numerical one. Gravity's part is checked on the default config (static
98/// hold, loss budget) and by the hand-calculated leg forces.
99fn suite_configs() -> Vec<Config> {
100    [(false, true), (false, false), (true, true), (true, false)]
101        .into_iter()
102        .map(|(elastic, payload)| {
103            let mut cfg = lossless_config();
104            cfg.set_text(&format!("effects.joint_elasticity = {elastic}")).unwrap();
105            cfg.set_text(&format!("effects.payload = {payload}")).unwrap();
106            cfg.set_text("effects.gravity = false").unwrap();
107            cfg
108        })
109        .collect()
110}
111
112fn sub(a: V3, b: V3) -> V3 {
113    [a[0] - b[0], a[1] - b[1], a[2] - b[2]]
114}
115
116fn norm(a: V3) -> f64 {
117    dot(a, a).sqrt()
118}
119
120fn transpose(m: &M3) -> M3 {
121    std::array::from_fn(|i| std::array::from_fn(|j| m[j][i]))
122}
123
124/// The rotation of a rotation vector.
125pub fn exp(r: V3) -> M3 {
126    let angle = norm(r);
127    if angle == 0.0 { about([0.0, 0.0, 1.0], 0.0) } else { about(r.map(|v| v / angle), angle) }
128}
129
130/// The rotation vector (axis times angle, angle up to pi) of a rotation matrix.
131pub fn log(r: &M3) -> V3 {
132    let vee = [r[2][1] - r[1][2], r[0][2] - r[2][0], r[1][0] - r[0][1]];
133    let cos = ((r[0][0] + r[1][1] + r[2][2] - 1.0) / 2.0).clamp(-1.0, 1.0);
134    let sin = 0.5 * norm(vee);
135    let angle = sin.atan2(cos);
136    if angle < 1e-6 {
137        // sin a / a = 1 - a^2/6: below 1e-6 rad the correction is under 1e-12 of the angle.
138        return vee.map(|v| 0.5 * v * (1.0 + angle * angle / 6.0));
139    }
140    if angle < PI - 1e-6 {
141        return vee.map(|v| v * angle / (2.0 * sin));
142    }
143    let i = (0..3).max_by(|&a, &b| r[a][a].total_cmp(&r[b][b])).unwrap_or(0);
144    let col: V3 = std::array::from_fn(|k| r[k][i] + if k == i { 1.0 } else { 0.0 });
145    let n = norm(col);
146    let sign = if dot(col, vee) < 0.0 { -1.0 } else { 1.0 };
147    col.map(|v| sign * v / n * angle)
148}
149
150/// The inverse of J (rows), column by column; `None` where it is singular.
151fn inverse(j: &[[f64; 6]; 6]) -> Option<[[f64; 6]; 6]> {
152    Lu::new(j)?.inverse()
153}
154
155/// The legs at a platform pose: unit vectors u_i from base to platform joint, lengths L_i, and the platform joints'
156/// offsets b_i = R a_i from the platform centre (base frame).
157#[derive(Debug, Clone, Copy)]
158pub struct Legs {
159    pub u: [V3; 6],
160    pub length: [f64; 6],
161    pub b: [V3; 6],
162}
163
164/// The hexapod's geometry and kinematics, apart from masses and drives.
165#[derive(Debug, Clone)]
166pub struct Geometry {
167    /// Base joints (base frame) and platform joints (platform frame).
168    pub base: [V3; 6],
169    pub anchors: [V3; 6],
170    pub platform_radius: f64,
171    pub closed: f64,
172    pub stroke: f64,
173    /// The steepest angle a leg may make with the base's normal at its base joint and with the platform's normal at
174    /// its platform joint, rad.
175    pub max_joint_angle: f64,
176    pub max_condition: f64,
177    /// The pose Newton's forward kinematics starts from: the centre of the tool's box.
178    pub home: [f64; 6],
179}
180
181impl Geometry {
182    /// Joints at the azimuths 120 k -+ the base half angle and 120 k -+ (60 - the platform half angle), degrees.
183    pub fn new(base_radius: f64, base_half: f64, platform_radius: f64, platform_half: f64) -> Self {
184        let at = |radius: f64, deg: f64| [radius * deg.to_radians().cos(), radius * deg.to_radians().sin(), 0.0];
185        let base = std::array::from_fn(|i| {
186            let side = if i % 2 == 0 { -1.0 } else { 1.0 };
187            at(base_radius, 120.0 * (i / 2) as f64 + side * base_half)
188        });
189        let anchors = std::array::from_fn(|i| {
190            let side = if i % 2 == 0 { -1.0 } else { 1.0 };
191            at(platform_radius, 120.0 * (i / 2) as f64 + side * (60.0 - platform_half))
192        });
193        Self {
194            base,
195            anchors,
196            platform_radius,
197            closed: 0.0,
198            stroke: 1.0,
199            max_joint_angle: PI / 2.0,
200            max_condition: f64::INFINITY,
201            home: [0.0; 6],
202        }
203    }
204
205    fn rotation(tool: &[f64]) -> M3 {
206        exp([tool[3], tool[4], tool[5]])
207    }
208
209    /// The legs with the platform at `p` turned by `r`.
210    pub fn legs_at(&self, p: V3, r: &M3) -> Legs {
211        let mut legs = Legs { u: [[0.0; 3]; 6], length: [0.0; 6], b: [[0.0; 3]; 6] };
212        for i in 0..6 {
213            let b = mul(r, self.anchors[i]);
214            let d = sub(add(p, b), self.base[i]);
215            let l = norm(d);
216            legs.u[i] = d.map(|v| v / l);
217            legs.length[i] = l;
218            legs.b[i] = b;
219        }
220        legs
221    }
222
223    pub fn legs(&self, tool: &[f64]) -> Legs {
224        self.legs_at([tool[0], tool[1], tool[2]], &Self::rotation(tool))
225    }
226
227    /// The Jacobian J (6 x 6, row by row) of the legs' extension rates over the platform's twist (v, w).
228    pub fn jacobian(legs: &Legs) -> Vec<f64> {
229        Self::jacobian_rows(legs).concat()
230    }
231
232    /// `jacobian` by rows.
233    fn jacobian_rows(legs: &Legs) -> [[f64; 6]; 6] {
234        std::array::from_fn(|i| {
235            let m = cross(legs.b[i], legs.u[i]);
236            [legs.u[i][0], legs.u[i][1], legs.u[i][2], m[0], m[1], m[2]]
237        })
238    }
239
240    /// Leg extensions for a tool pose (closed form); `false` where a leg would be of no length.
241    pub fn inverse(&self, tool: &[f64], q: &mut [f64]) -> bool {
242        let legs = self.legs(tool);
243        for i in 0..6 {
244            q[i] = legs.length[i] - self.closed;
245        }
246        q.iter().all(|v| v.is_finite())
247    }
248
249    /// The tool pose for leg extensions, by Newton's method from `home`; NaN where it does not converge.
250    pub fn forward(&self, q: &[f64], tool: &mut [f64]) {
251        let home = ([self.home[0], self.home[1], self.home[2]], Self::rotation(&self.home));
252        let Some((p, r, _)) = self.solve_from(q, home.0, home.1) else {
253            tool.iter_mut().for_each(|v| *v = f64::NAN);
254            return;
255        };
256        let rv = log(&r);
257        tool[..6].copy_from_slice(&[p[0], p[1], p[2], rv[0], rv[1], rv[2]]);
258    }
259
260    /// Newton's method on the twist from the platform at `p` turned by `r` until every leg is within 1e-13 m of its
261    /// length for `q`: the platform's centre, rotation and its legs there; `None` where it does not converge within 40
262    /// steps.
263    fn solve_from(&self, q: &[f64], mut p: V3, mut r: M3) -> Option<(V3, M3, Legs)> {
264        for _ in 0..40 {
265            let legs = self.legs_at(p, &r);
266            let miss: [f64; 6] = std::array::from_fn(|i| q[i] + self.closed - legs.length[i]);
267            let worst = miss.iter().fold(0.0f64, |m, v| m.max(v.abs()));
268            if !worst.is_finite() {
269                return None;
270            }
271            if worst < 1e-13 {
272                return Some((p, r, legs));
273            }
274            let step = Lu::new(&Self::jacobian_rows(&legs)).and_then(|lu| lu.solve(miss))?;
275            p = add(p, [step[0], step[1], step[2]]);
276            r = matmul(&exp([step[3], step[4], step[5]]), &r);
277        }
278        None
279    }
280
281    /// The steepest leg angle at the joints, rad: against the base's normal and against the platform's.
282    pub fn joint_angle(&self, tool: &[f64]) -> f64 {
283        let legs = self.legs(tool);
284        let normal = mul(&Self::rotation(tool), [0.0, 0.0, 1.0]);
285        (0..6)
286            .map(|i| legs.u[i][2].clamp(-1.0, 1.0).acos().max(dot(legs.u[i], normal).clamp(-1.0, 1.0).acos()))
287            .fold(0.0, f64::max)
288    }
289
290    /// The condition number of J with the turns weighed by the platform radius (the platform joints' speed for w).
291    pub fn condition(&self, tool: &[f64]) -> f64 {
292        let mut j = Self::jacobian(&self.legs(tool));
293        for i in 0..6 {
294            for c in 3..6 {
295                j[i * 6 + c] /= self.platform_radius;
296            }
297        }
298        condition_number(&j, 6, 6)
299    }
300}
301
302/// The pose at a point of the leg extensions' grid (`ANCHOR_STEP`) the dynamics' Newton starts from: the grid point's
303/// index, its leg extensions, the platform's centre and rotation, and J^-1 there.
304#[derive(Debug, Clone, Copy)]
305struct Found {
306    key: [i64; 6],
307    q: [f64; 6],
308    p: V3,
309    r: M3,
310    jinv: [[f64; 6]; 6],
311}
312
313/// The grid of leg extensions the dynamics' Newton starts from, m: from the nearest point, so the pose is a function
314/// of the extensions alone, whatever was called before (a run, its replay and a perturbed run give the same numbers).
315const ANCHOR_STEP: f64 = 1e-3;
316
317/// The last grid point's pose behind a lock (`Mechanism` is `Send`, and the integrator calls `dynamics` through `&self`).
318#[derive(Debug, Default)]
319struct LastFound(std::sync::Mutex<Option<Found>>);
320
321impl LastFound {
322    fn get(&self) -> Option<Found> {
323        self.0.lock().ok().and_then(|f| *f)
324    }
325    fn set(&self, found: Option<Found>) {
326        if let Ok(mut f) = self.0.lock() {
327            *f = found;
328        }
329    }
330}
331
332impl Clone for LastFound {
333    fn clone(&self) -> Self {
334        Self(std::sync::Mutex::new(self.get()))
335    }
336}
337
338/// One body of a leg: its mass, its centre's distance from the joint it hangs on, its inertia across the leg about its
339/// centre, and whether it hangs on the platform joint (else on the base joint).
340#[derive(Debug, Clone, Copy)]
341struct LegPart {
342    mass: f64,
343    centre: f64,
344    inertia: f64,
345    on_platform: bool,
346}
347
348/// A leg part's motion at a pose and twist: A (its velocity per twist, as columns), its acceleration `a0` at zero twist
349/// acceleration, the leg direction's rate per twist `au` (columns) and its second derivative `u2` at zero twist
350/// acceleration.
351struct PartMotion {
352    a: [V3; 6],
353    a0: V3,
354    au: [V3; 6],
355    u2: V3,
356}
357
358#[derive(Clone)]
359pub struct Hexapod {
360    pub geo: Geometry,
361    screw: BallScrew,
362    /// Platform with the legs' platform shares; payload; inertia about the centre in the platform frame.
363    mass: f64,
364    payload: f64,
365    payload_inertia: M3,
366    attached: bool,
367    inertia: M3,
368    /// The two bodies of each leg: the part on the base joint, the part on the platform joint.
369    parts: [LegPart; 2],
370    g: f64,
371    required_life: Option<f64>,
372    /// The grid point's pose the dynamics' Newton starts from (`warm_pose`).
373    last: LastFound,
374    /// Each leg's rotor's angular momentum per m/s of its leg, J i (the rotor's inertia times the screw's ratio), N m s
375    /// per m/s, for `rotor_gyroscopic` (0 with `effects.rotor_gyroscopic` off). The rotor's speed taken as i q', the
376    /// elastic model's own rotor speed differing by the screw's stretch rate.
377    rotor_spin: f64,
378}
379
380fn build(cfg: &Config) -> Result<Box<dyn Machine>, ConfigError> {
381    let (machine, _) = Hexapod::from_config(cfg)?;
382    sim_components::base::mount(cfg, machine)
383}
384
385impl Hexapod {
386    /// The machine, and its mechanism alone for the tests.
387    pub fn from_config(cfg: &Config) -> Result<(Box<dyn Machine>, Hexapod), ConfigError> {
388        let mut geo = Geometry::new(
389            cfg.positive("hexapod.base_radius_m")?,
390            cfg.non_negative("hexapod.base_half_angle_deg")?,
391            cfg.positive("hexapod.platform_radius_m")?,
392            cfg.non_negative("hexapod.platform_half_angle_deg")?,
393        );
394        geo.closed = cfg.positive("leg.closed_length_m")?;
395        geo.stroke = cfg.positive("leg.stroke_m")?;
396        geo.max_joint_angle = cfg.positive("workspace.max_joint_angle_deg")?.to_radians();
397        geo.max_condition = cfg.positive("workspace.max_condition_number")?;
398        let (min, max) = (cfg.f64s("workspace.tool_min")?, cfg.f64s("workspace.tool_max")?);
399        if min.len() != 6 || max.len() != 6 {
400            return Err(ConfigError::Invalid("workspace.tool_min".into()));
401        }
402        if (0..6).any(|k| !(min[k] < max[k])) {
403            return Err(ConfigError::Invalid("workspace.tool_max".into()));
404        }
405        geo.home = std::array::from_fn(|k| 0.5 * (min[k] + max[k]));
406        let share = cfg.non_negative("leg.platform_share")?;
407        if share > 1.0 {
408            return Err(ConfigError::Invalid("leg.platform_share".into()));
409        }
410        let leg_mass = cfg.non_negative("leg.mass_kg")?;
411        let part = |key: &str, on_platform: bool, mass: f64| -> Result<LegPart, ConfigError> {
412            let get = |what: &str| cfg.non_negative(&format!("leg.{key}_{what}"));
413            Ok(LegPart { mass, centre: get("centre_m")?, inertia: get("inertia_kgm2")?, on_platform })
414        };
415        let parts =
416            [part("base_part", false, (1.0 - share) * leg_mass)?, part("platform_part", true, share * leg_mass)?];
417        let diag = cfg.f64s("mass.platform_inertia_kgm2")?;
418        if diag.len() != 3 || diag.iter().any(|v| !(*v > 0.0)) {
419            return Err(ConfigError::Invalid("mass.platform_inertia_kgm2".into()));
420        }
421        let inertia: M3 = std::array::from_fn(|i| std::array::from_fn(|j| if i == j { diag[i] } else { 0.0 }));
422        let d = cfg.f64s("mass.payload_inertia_kgm2")?;
423        if d.len() != 3 || d.iter().any(|v| !(*v >= 0.0)) {
424            return Err(ConfigError::Invalid("mass.payload_inertia_kgm2".into()));
425        }
426        let on = cfg.bool("effects.payload")?;
427        let payload_inertia: M3 =
428            std::array::from_fn(|i| std::array::from_fn(|j| if i == j && on { d[i] } else { 0.0 }));
429        let screw = BallScrew::from_config(cfg)?;
430        if screw.length < geo.stroke {
431            return Err(ConfigError::Invalid("screw.length_m".into()));
432        }
433        let on = cfg.bool("effects.joint_friction")?;
434        let friction = ShaftFriction {
435            coulomb: if on { cfg.non_negative("leg.friction_coulomb_n")? } else { 0.0 },
436            viscous: if on { cfg.non_negative("leg.friction_viscous_n_s_m")? } else { 0.0 },
437            smoothing: cfg.positive("leg.friction_smoothing_m_s")?,
438            ..ShaftFriction::NONE
439        };
440        let stops = if cfg.bool("effects.hard_stops")? {
441            HardStop {
442                stiffness: cfg.positive("leg.stop_stiffness_n_m")?,
443                damping: cfg.non_negative("leg.stop_damping_n_s_m")?,
444            }
445        } else {
446            HardStop { stiffness: 0.0, damping: 0.0 }
447        };
448        let mut joint = RotaryJoint::with(cfg, friction, stops, (0.0, geo.stroke))?;
449        // The mesh friction's bristle capped by the lighter of the rotor and what the nut moves at least: the platform
450        // pushed at its joint, 1 / (1 / m + r^2 / I_min) whatever the other legs hold (`Converter::apply_to`).
451        let r2 = geo.anchors.iter().map(|a| dot(*a, *a)).fold(0.0, f64::max);
452        let i_min = diag.iter().copied().fold(f64::INFINITY, f64::min);
453        let leg_output = 1.0 / (1.0 / cfg.positive("mass.platform_kg")? + r2 / i_min);
454        screw.converter(screw.softest_position()).apply_to(cfg, &mut joint, leg_output)?;
455        // The nut's preload drags like friction in the rod's guide, as a force at the nut.
456        if on {
457            joint.friction.coulomb += screw.preload_torque() * screw.ratio();
458        }
459        let lever = 1.0 / screw.ratio();
460        let mech = Hexapod {
461            geo,
462            screw,
463            mass: cfg.positive("mass.platform_kg")?,
464            payload: if cfg.bool("effects.payload")? { cfg.non_negative("mass.payload_kg")? } else { 0.0 },
465            payload_inertia,
466            attached: true,
467            inertia,
468            parts,
469            g: if cfg.bool("effects.gravity")? { G } else { 0.0 },
470            required_life: cfg.f64("ratings.required_life_h").ok(),
471            last: LastFound::default(),
472            rotor_spin: if cfg.get("effects.rotor_gyroscopic").is_ok() && cfg.bool("effects.rotor_gyroscopic")? {
473                joint.rotor_inertia * joint.ratio()
474            } else {
475                0.0
476            },
477        };
478        let axes = (0..6)
479            .map(|k| {
480                let unit = if k < 3 { "m" } else { "rad" };
481                let get =
482                    |what: &str, rate: &str| cfg.positive(&format!("axis.{}.max_{what}_{unit}_{rate}", AXIS_IDS[k]));
483                Ok(AxisInfo {
484                    id: AXIS_IDS[k],
485                    key: AXIS_KEYS[k],
486                    unit,
487                    min: min[k],
488                    max: max[k],
489                    max_vel: get("velocity", "s")?,
490                    max_acc: get("acceleration", "s2")?,
491                    max_jerk: get("jerk", "s3")?,
492                })
493            })
494            .collect::<Result<Vec<_>, ConfigError>>()?;
495        let specs = (0..6)
496            .map(|k| JointSpec {
497                drive: joint.clone(),
498                id: MOTOR_IDS[k],
499                key: JOINT_KEYS[k],
500                gear_lever: Some(lever),
501                unit: "m",
502            })
503            .collect();
504        let motors = (0..6).map(|k| MotorInfo { id: MOTOR_IDS[k], key: MOTOR_KEYS[k] }).collect();
505        let machine = JointMachine::new(
506            mech.clone(),
507            specs,
508            cfg.bool("effects.joint_elasticity")?,
509            ThermalFeedback::from_config(cfg)?,
510            axes,
511            motors,
512        );
513        Ok((Box::new(machine), mech))
514    }
515
516    fn moving(&self) -> f64 {
517        self.mass + if self.attached { self.payload } else { 0.0 }
518    }
519
520    /// The pose for leg extensions, its legs and rotation; `None` where the forward kinematics fails.
521    fn pose(&self, q: &[f64]) -> Option<([f64; 6], Legs, M3)> {
522        let mut tool = [0.0; 6];
523        self.geo.forward(q, &mut tool);
524        if !tool.iter().all(|v| v.is_finite()) {
525            return None;
526        }
527        Some((tool, self.geo.legs(&tool), Geometry::rotation(&tool)))
528    }
529
530    /// The legs, the platform's rotation and J^-1 for leg extensions, for the dynamics, which runs four times a
531    /// sub-step: Newton starts from the pose at the nearest point of the `ANCHOR_STEP` grid moved by J^-1 (q - q_grid),
532    /// which takes it two steps instead of about five from home (`forward`); from home where that does not converge.
533    /// The grid point's pose (from home) is kept until the legs leave its cell. The pose differs from `forward`'s by
534    /// Newton's tolerance (1e-13 m on the legs). `None` where the forward kinematics fails or J is singular.
535    fn warm_pose(&self, q: &[f64]) -> Option<(Legs, M3, [[f64; 6]; 6])> {
536        let key: [i64; 6] = std::array::from_fn(|i| (q[i] / ANCHOR_STEP).round() as i64);
537        let anchor = self.last.get().filter(|f| f.key == key).or_else(|| {
538            let g: [f64; 6] = std::array::from_fn(|i| key[i] as f64 * ANCHOR_STEP);
539            let (tool, legs, r) = self.pose(&g)?;
540            let jinv = inverse(&Geometry::jacobian_rows(&legs))?;
541            let found = Found { key, q: g, p: [tool[0], tool[1], tool[2]], r, jinv };
542            self.last.set(Some(found));
543            Some(found)
544        });
545        let warm = anchor.and_then(|f| {
546            let xi: [f64; 6] = std::array::from_fn(|r| (0..6).map(|c| f.jinv[r][c] * (q[c] - f.q[c])).sum());
547            self.geo.solve_from(q, add(f.p, [xi[0], xi[1], xi[2]]), matmul(&exp([xi[3], xi[4], xi[5]]), &f.r))
548        });
549        let (r, legs) = match warm {
550            Some((_, r, legs)) => (r, legs),
551            None => {
552                let (_, legs, r) = self.pose(q)?;
553                (r, legs)
554            }
555        };
556        Some((legs, r, inverse(&Geometry::jacobian_rows(&legs))?))
557    }
558
559    /// The platform's inertia about its centre in the platform frame, with the payload's as it is attached.
560    fn platform_inertia(&self) -> M3 {
561        let extra = if self.attached { self.payload_inertia } else { [[0.0; 3]; 3] };
562        std::array::from_fn(|i| std::array::from_fn(|j| self.inertia[i][j] + extra[i][j]))
563    }
564
565    /// Leg i's part `part` at a pose with the platform's twist `xi`: see the module's derivation.
566    fn part_motion(&self, i: usize, legs: &Legs, xi: &[f64; 6], part: &LegPart) -> PartMotion {
567        let (u, l, b) = (legs.u[i], legs.length[i], legs.b[i]);
568        let (v, w) = ([xi[0], xi[1], xi[2]], [xi[3], xi[4], xi[5]]);
569        let (d1, d2) = (add(v, cross(w, b)), cross(w, cross(w, b)));
570        let rate = dot(u, d1);
571        let up = sub(d1, u.map(|x| x * rate)).map(|x| x / l);
572        let rate2 = dot(up, d1) + dot(u, d2);
573        let u2: V3 = std::array::from_fn(|k| (d2[k] - 2.0 * up[k] * rate - u[k] * rate2) / l);
574        // The twist's unit columns: the platform joint's velocity per v_k (e_k) and per w_k (e_k x b).
575        let unit = |k: usize| -> V3 {
576            let e: V3 = std::array::from_fn(|r| if r == k % 3 { 1.0 } else { 0.0 });
577            if k < 3 { e } else { cross(e, b) }
578        };
579        let au: [V3; 6] = std::array::from_fn(|k| {
580            let d = unit(k);
581            let along = dot(u, d);
582            std::array::from_fn(|r| (d[r] - u[r] * along) / l)
583        });
584        let c = part.centre;
585        if part.on_platform {
586            PartMotion {
587                a: std::array::from_fn(|k| sub(unit(k), au[k].map(|x| x * c))),
588                a0: sub(d2, u2.map(|x| x * c)),
589                au,
590                u2,
591            }
592        } else {
593            PartMotion { a: au.map(|col| col.map(|x| x * c)), a0: u2.map(|x| x * c), au, u2 }
594        }
595    }
596
597    /// The leg parts' mass matrix over the twist (6 x 6) and their share of c + g at the twist `xi` (zero twist
598    /// acceleration), over all legs.
599    fn parts_terms(&self, legs: &Legs, xi: &[f64; 6]) -> ([[f64; 6]; 6], [f64; 6]) {
600        let (mut m, mut held) = ([[0.0; 6]; 6], [0.0; 6]);
601        for i in 0..6 {
602            for part in self.parts.iter().filter(|p| p.mass > 0.0 || p.inertia > 0.0) {
603                let pm = self.part_motion(i, legs, xi, part);
604                let accel = [pm.a0[0], pm.a0[1], pm.a0[2] + self.g];
605                for r in 0..6 {
606                    held[r] += part.mass * dot(pm.a[r], accel) + part.inertia * dot(pm.au[r], pm.u2);
607                    for c in 0..6 {
608                        m[r][c] += part.mass * dot(pm.a[r], pm.a[c]) + part.inertia * dot(pm.au[r], pm.au[c]);
609                    }
610                }
611            }
612        }
613        (m, held)
614    }
615
616    /// Where leg i's part `part` has its centre with the platform at `p`.
617    fn part_position(&self, i: usize, legs: &Legs, p: V3, part: &LegPart) -> V3 {
618        let u = legs.u[i].map(|x| x * part.centre);
619        if part.on_platform { sub(add(p, legs.b[i]), u) } else { add(self.geo.base[i], u) }
620    }
621
622    /// The wrench on the platform (force, its moment about the centre) from the legs' rotors turning with their legs: a
623    /// rotor's angular momentum h = J i q' along its leg's u turns as u does, so the leg must give it the moment
624    /// h u' (u' = (d' - u L') / L, d' the platform joint's velocity), which its two joints pass on as a couple across
625    /// it: on the platform at the joint F = h (u x u') / L, with its moment b x F. Gyroscopic: it does no work
626    /// (u x u' . d' = 0). Zero while the legs do not turn or the rotors stand.
627    fn rotor_gyroscopic(&self, legs: &Legs, xi: &[f64; 6], qd: &[f64]) -> [f64; 6] {
628        let (v, w) = ([xi[0], xi[1], xi[2]], [xi[3], xi[4], xi[5]]);
629        let mut out = [0.0; 6];
630        for i in 0..6 {
631            let d = add(v, cross(w, legs.b[i]));
632            let along = dot(legs.u[i], d);
633            let turn: V3 = std::array::from_fn(|k| (d[k] - legs.u[i][k] * along) / legs.length[i]);
634            let force = cross(legs.u[i], turn).map(|f| f * self.rotor_spin * qd[i] / legs.length[i]);
635            let moment = cross(legs.b[i], force);
636            (0..3).for_each(|k| (out[k], out[3 + k]) = (out[k] + force[k], out[3 + k] + moment[k]));
637        }
638        out
639    }
640
641    /// The platform's mass matrix over its twist (6 x 6).
642    fn twist_mass(&self, r: &M3) -> [[f64; 6]; 6] {
643        let iw = matmul(&matmul(r, &self.platform_inertia()), &transpose(r));
644        let mut m = [[0.0; 6]; 6];
645        for k in 0..3 {
646            m[k][k] = self.moving();
647            for c in 0..3 {
648                m[3 + k][3 + c] = iw[k][c];
649            }
650        }
651        m
652    }
653
654    /// The forces the legs push the platform with to hold it at rest at a tool pose: J^-T (0, 0, m g, 0, 0, 0), N.
655    pub fn static_leg_forces(&self, tool: &[f64]) -> Option<[f64; 6]> {
656        let jt: Vec<f64> = {
657            let j = Geometry::jacobian(&self.geo.legs(tool));
658            (0..36).map(|k| j[(k % 6) * 6 + k / 6]).collect()
659        };
660        // The weight is c + g at rest: the platform's and the payload's, and the leg parts' (m g times the z row of A).
661        let (_, parts) = self.parts_terms(&self.geo.legs(tool), &[0.0; 6]);
662        let mut weight = [0.0, 0.0, self.moving() * self.g, 0.0, 0.0, 0.0];
663        weight.iter_mut().zip(parts).for_each(|(w, p)| *w += p);
664        let f = solve(&jt, &weight)?;
665        Some(std::array::from_fn(|i| f[i]))
666    }
667}
668
669impl Mechanism for Hexapod {
670    fn dynamics(&self, q: &[f64], qd: &[f64], mass: &mut [f64], bias: &mut [f64]) {
671        let Some((legs, r, jinv)) = self.warm_pose(q) else {
672            mass.fill(f64::NAN);
673            bias.fill(f64::NAN);
674            return;
675        };
676        let xi: [f64; 6] = std::array::from_fn(|r| (0..6).map(|c| jinv[r][c] * qd[c]).sum());
677        let (v, w) = ([xi[0], xi[1], xi[2]], [xi[3], xi[4], xi[5]]);
678        let a0: [f64; 6] = std::array::from_fn(|i| {
679            let wi = add(v, cross(w, legs.b[i]));
680            let along = dot(legs.u[i], wi);
681            (dot(wi, wi) - along * along) / legs.length[i] + dot(legs.u[i], cross(w, cross(w, legs.b[i])))
682        });
683        let mut mx = self.twist_mass(&r);
684        let iw = [[mx[3][3], mx[3][4], mx[3][5]], [mx[4][3], mx[4][4], mx[4][5]], [mx[5][3], mx[5][4], mx[5][5]]];
685        let gyro = cross(w, mul(&iw, w));
686        let (parts_mass, parts_held) = self.parts_terms(&legs, &xi);
687        (0..6).for_each(|r| (0..6).for_each(|c| mx[r][c] += parts_mass[r][c]));
688        let jinv_a0: [f64; 6] = std::array::from_fn(|r| (0..6).map(|c| jinv[r][c] * a0[c]).sum());
689        let rotors = self.rotor_gyroscopic(&legs, &xi, qd);
690        let wrench: [f64; 6] = std::array::from_fn(|k| {
691            let held = [0.0, 0.0, self.moving() * self.g, gyro[0], gyro[1], gyro[2]][k] + parts_held[k] - rotors[k];
692            held - (0..6).map(|c| mx[k][c] * jinv_a0[c]).sum::<f64>()
693        });
694        // M_xi J^-1, once for every column of M_q.
695        let mx_jinv: [[f64; 6]; 6] =
696            std::array::from_fn(|k| std::array::from_fn(|j| (0..6).map(|l| mx[k][l] * jinv[l][j]).sum::<f64>()));
697        for i in 0..6 {
698            bias[i] = (0..6).map(|k| jinv[k][i] * wrench[k]).sum();
699            for j in 0..6 {
700                mass[i * 6 + j] = (0..6).map(|k| jinv[k][i] * mx_jinv[k][j]).sum();
701            }
702        }
703    }
704    /// The platform with the payload at its centre p with its twist (v, w): m v, p x m v + R I R^T w, its first moment
705    /// m p; each leg's two parts as points with their velocity A xi and their turn I_t u x u'. Each leg's rotor spins
706    /// along the leg's u_i.
707    fn frame_momentum(&self, q: &[f64], qd: &[f64], rotor_spin: &[f64]) -> Option<sim_core::FrameMomentum> {
708        let (tool, legs, r) = self.pose(q)?;
709        let jinv = inverse(&Geometry::jacobian_rows(&legs))?;
710        let xi: [f64; 6] = std::array::from_fn(|r| (0..6).map(|c| jinv[r][c] * qd[c]).sum());
711        let mut f = sim_core::FrameMomentum { gravity: [0.0, 0.0, -self.g], ..Default::default() };
712        sim_components::base::add_point(&mut f, self.moving(), [tool[0], tool[1], tool[2]], [xi[0], xi[1], xi[2]]);
713        let iw = matmul(&matmul(&r, &self.platform_inertia()), &transpose(&r));
714        let turning = mul(&iw, [xi[3], xi[4], xi[5]]);
715        (0..3).for_each(|k| f.angular[k] += turning[k]);
716        let p = [tool[0], tool[1], tool[2]];
717        for i in 0..6 {
718            for part in self.parts.iter().filter(|p| p.mass > 0.0 || p.inertia > 0.0) {
719                let pm = self.part_motion(i, &legs, &xi, part);
720                let speed: V3 = std::array::from_fn(|k| (0..6).map(|c| pm.a[c][k] * xi[c]).sum());
721                let at = self.part_position(i, &legs, p, part);
722                sim_components::base::add_point(&mut f, part.mass, at, speed);
723                if !part.on_platform {
724                    // The base-joint part's mass at its joint does not move (`FrameMomentum`): only its offset counts.
725                    f.mass -= part.mass;
726                    (0..3).for_each(|k| f.first_moment[k] -= part.mass * self.geo.base[i][k]);
727                }
728                // The part's turn about its own centre across the leg: u x u'.
729                let rate: V3 = std::array::from_fn(|k| (0..6).map(|c| pm.au[c][k] * xi[c]).sum());
730                let spin = cross(legs.u[i], rate);
731                (0..3).for_each(|k| f.angular[k] += part.inertia * spin[k]);
732            }
733        }
734        for (u, spin) in legs.u.iter().zip(rotor_spin) {
735            sim_components::base::add_spin(&mut f, *u, 1.0, *spin);
736        }
737        Some(f)
738    }
739    fn potential(&self, q: &[f64]) -> f64 {
740        self.pose(q).map_or(f64::NAN, |(tool, legs, _)| {
741            let p = [tool[0], tool[1], tool[2]];
742            let parts: f64 = (0..6)
743                .flat_map(|i| self.parts.iter().map(move |part| (i, part)))
744                .map(|(i, part)| part.mass * self.part_position(i, &legs, p, part)[2])
745                .sum();
746            self.g * (self.moving() * tool[2] + parts)
747        })
748    }
749    fn set_payload_attached(&mut self, attached: bool) {
750        self.attached = attached;
751    }
752
753    fn forward(&self, q: &[f64], tool: &mut [f64]) {
754        self.geo.forward(q, tool);
755    }
756    fn inverse(&self, tool: &[f64], q: &mut [f64]) -> bool {
757        self.geo.inverse(tool, q)
758    }
759    fn unreachable(&self, tool: &[f64], _slack: f64) -> Option<&'static str> {
760        if !(self.geo.joint_angle(tool) <= self.geo.max_joint_angle) {
761            return Some("error-hexapod-joint-angle");
762        }
763        if !(self.geo.condition(tool) <= self.geo.max_condition) {
764            return Some("error-hexapod-singularity");
765        }
766        None
767    }
768    fn condition(&self, tool: &[f64]) -> Option<f64> {
769        Some(self.geo.condition(tool))
770    }
771    fn tool_is_joints(&self) -> bool {
772        false
773    }
774
775    /// Per leg its screw's speed, d n and wear; then the condition number at the pose.
776    fn signal_infos(&self) -> Vec<SignalInfo> {
777        let mut out: Vec<SignalInfo> =
778            (0..6).flat_map(|i| self.screw.signal_infos(MOTOR_IDS[i], JOINT_KEYS[i])).collect();
779        out.push(SignalInfo::new("platform.condition", "group-hexapod", "quantity-condition-number", ""));
780        out
781    }
782    fn signals(&self, q: &[f64], qd: &[f64], _qdd: &[f64], force: &[f64], out: &mut Vec<f64>) {
783        for i in 0..6 {
784            self.screw.signals(qd[i], force[i], out);
785        }
786        out.push(self.pose(q).map_or(f64::INFINITY, |(tool, ..)| self.geo.condition(&tool)));
787    }
788    /// Each leg's screw: speed, d n, buckling and static load under the leg's force, life.
789    fn rating_checks(&self) -> Vec<RatingCheck> {
790        (0..6).flat_map(|i| self.screw.rating_checks(MOTOR_IDS[i], i, self.required_life)).collect()
791    }
792
793    fn collision_parts(&self) -> &'static [&'static str] {
794        &["tool", "payload"]
795    }
796
797    /// Base and platform as hexagons through their joints, each leg as its cylinder and rod, the motors below the
798    /// base joints.
799    fn scene(&self, q: &[f64], rotors: &[f64], rotor_speeds: &[f64], out: &mut Scene) {
800        let Some((tool, legs, _)) = self.pose(q) else { return };
801        let p = [tool[0], tool[1], tool[2]];
802        let top: Vec<V3> = (0..6).map(|i| add(p, legs.b[i])).collect();
803        for i in 0..6 {
804            let next = (i + 1) % 6;
805            out.parts.push(Part::new(
806                "base",
807                Shape::Segment { to: self.geo.base[next], width: 0.03 },
808                self.geo.base[i],
809                [0.55, 0.57, 0.6],
810            ));
811            out.parts.push(Part::new(
812                "platform",
813                Shape::Segment { to: top[next], width: 0.03 },
814                top[i],
815                [0.3, 0.45, 0.7],
816            ));
817        }
818        let body = 0.6 * self.geo.closed;
819        for i in 0..6 {
820            let (b, u) = (self.geo.base[i], legs.u[i]);
821            let end = add(b, u.map(|v| v * body));
822            out.parts.push(Part::new("cylinder", Shape::Segment { to: end, width: 0.05 }, b, [0.75, 0.75, 0.78]));
823            out.parts.push(Part::new(
824                "rod",
825                Shape::Segment { to: add(b, u.map(|v| v * 0.9 * body)), width: 0.025 },
826                top[i],
827                [0.85, 0.86, 0.9],
828            ));
829            out.parts.push(Part::new(
830                sim_core::scene::MOTOR_PART,
831                Shape::Box { size: [0.07, 0.07, 0.09] },
832                add(b, [0.0, 0.0, -0.06]),
833                [0.9, 0.45, 0.1],
834            ));
835            // The shaft's bar below the motor turns with the rotor, as on every machine.
836            out.parts.push(
837                Part::new("rotor-bar", Shape::Box { size: [0.07, 0.004, 0.012] }, add(b, [0.0, 0.0, -0.11]), [0.1; 3])
838                    .turned(rotors[i]),
839            );
840            out.labels.push(Label {
841                pos: add(b, [0.0, 0.0, -0.14]),
842                owner_key: MOTOR_KEYS[i],
843                value: rotor_speeds[i] * 60.0 / TAU,
844                unit_key: "unit-rpm",
845                decimals: 0,
846            });
847            out.labels.push(Label {
848                pos: add(b, u.map(|v| v * 0.5 * legs.length[i])),
849                owner_key: JOINT_KEYS[i],
850                value: legs.length[i],
851                unit_key: "unit-m",
852                decimals: 3,
853            });
854        }
855        out.parts.push(Part::new(
856            "tool",
857            Shape::Box { size: [0.06, 0.06, 0.03] },
858            add(p, [0.0, 0.0, 0.015]),
859            [0.2, 0.22, 0.26],
860        ));
861        if self.attached && self.payload > 0.0 {
862            out.parts.push(Part::new(
863                "payload",
864                Shape::Box { size: [0.12, 0.12, 0.08] },
865                add(p, [0.0, 0.0, 0.07]),
866                [0.2, 0.7, 0.3],
867            ));
868        }
869        out.labels.push(Label {
870            pos: add(p, [0.0, 0.0, 0.2]),
871            owner_key: "axis-z",
872            value: p[2],
873            unit_key: "unit-m",
874            decimals: 3,
875        });
876    }
877    fn scene_point(&self, tool: &[f64]) -> Option<[f64; 3]> {
878        Some([tool[0], tool[1], tool[2]])
879    }
880}
881
882#[cfg(test)]
883mod tests;