Skip to main content

machine_tripod/
lib.rs

1//! Tripod (3-RPS parallel mechanism): a platform on three electric cylinders of variable length, each a ball screw
2//! driven by its own servo motor through a coupling, with a revolute joint at the base and a spherical joint at the
3//! platform. Three degrees of freedom: the tool pose is the platform centre's height z (m) and the platform's tilts rx
4//! about x and ry about y (rad), as tilting tables, tool heads and motion bases use them.
5//!
6//! Why 3-RPS: the legs are electric cylinders (one per motor, the motor in line with the screw), each
7//! on a trunnion at the base that lets it swing in the vertical plane through the base's centre, and on a ball joint at
8//! the platform. The other common form, 3-PRS (three vertical slides carrying struts of fixed length, the Sprint Z3
9//! head), has the same constraints and dependent motion; the cylinders of variable length are this crate's form.
10//!
11//! Geometry (`[tripod]`): base joints B_i = rb (cos t_i, sin t_i, 0) at t_i = 0, 120, 240 degrees, each revolute about
12//! the tangent e_i = (-sin t_i, cos t_i, 0); platform joints a_i = rp (cos t_i, sin t_i, 0) in the platform frame. Leg
13//! i's length is L_i = `leg.closed_length_m` + q_i with q_i the cylinder's extension, its joint coordinate.
14//!
15//! ```text
16//! orientation  R = Rx(rx) Ry(ry) Rz(g): the pure tilt R0 = Rx(rx) Ry(ry), then a turn g about the platform's normal
17//! constraints  e_i . (p + R a_i) = 0 (each platform joint stays in its leg's plane), which for t_i = 0, 120, 240 are
18//!              R12 = R21, p_x = rp (R11 - R22) / 2, p_y = -rp R21, so in closed form (the dependent coordinates):
19//!              tan g = -sin rx sin ry / (cos rx + cos ry), p_x = rp (cos ry cos g + sin rx sin ry sin g - cos rx cos g) / 2,
20//!              p_y = rp cos ry sin g, p_z = z
21//! inverse      d_i = p + R a_i - B_i, L_i = |d_i|, q_i = L_i - L_closed                                    (closed form)
22//! twist        xi = (v, w): G xi = (q', 0), G's rows (u_i, b_i x u_i) (legs) and (e_i, b_i x e_i) (constraints),
23//!              b_i = R a_i, u_i = d_i / L_i; A = the first three columns of G^-1: xi = A q'
24//! rates        x' = (z', rx', ry') = S xi: z' = v_z, rx' = w_x + tan ry (sin rx w_y - cos rx w_z),
25//!              ry' = cos rx w_y + sin rx w_z (w = rx' e_x + ry' Rx e_y + g' R0 e_z solved); K^-1 = S A
26//! forward      chord iterations x += K(home)^-1 (q - q(x)) from the centre of the box, which contract over the working
27//!              range (`chord_contraction`, docs/mechanisms.md); after the first, steps with K(x1)^-1 at that iterate
28//!              while each halves the legs' miss, else the chord again; until |q - q(x)| < 1e-13 m, refused (NaN)
29//!              where that takes more than 100 steps.
30//! dynamics     G xi' = (q'' - a0, -c0), a0_i = (|w_i|^2 - (u_i . w_i)^2) / L_i + u_i . (w x (w x b_i)),
31//!              w_i = v + w x b_i, c0_i = e_i . (w x (w x b_i)), so xi' = A q'' + beta, beta = G^-1 (-a0, -c0);
32//!              M_xi xi' + c + g = J^T f + C^T lambda with M_xi = [[m 1, -[s]x], [[s]x, I_p]], s = R s_b the first
33//!              moment about the centre, c = (w x (w x s), w x I_p w), g = (0, 0, m g, g s_y, -g s_x, 0); A^T takes
34//!              the constraint forces out (C A = 0) and A^T J^T = 1: M_q = A^T M_xi A, h = A^T (M_xi beta + c + g)
35//! ```
36//!
37//! f_i is the force leg i pushes the platform with: what its screw passes on (`chain::JointMachine`, one
38//! `joint::RotaryJoint` with a `transmission::BallScrew` per leg). The payload is a body of its own mass and inertia
39//! with its centre at `mass.payload_offset_m` in the platform frame.
40//!
41//! Each leg is two bodies: the part on the platform joint (the rod and nut, mass `leg.platform_share` of `leg.mass_kg`,
42//! its centre `leg.platform_part_centre_m` from the platform joint towards the base) and the part on the base joint
43//! (cylinder and motor, the rest, its centre `leg.base_part_centre_m` from the base joint towards the platform), each
44//! with its inertia about its own centre across the leg (`leg.*_part_inertia_kgm2`, 0 = a point mass). Both turn with
45//! the leg's direction u = d / L (in the leg's plane). With d' = v + w x b (the platform joint's velocity) and
46//! L' = u . d':
47//!
48//! ```text
49//! 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)
50//! base part  X = B + c u,        X' = c u' = A_p xi,    A_p = c A_u,           A_u = (1 - u u^T) [1, -[b]x] / L
51//! rod part   X = P - c u,        X' = P' - c u',        A_p = [1, -[b]x] - c A_u,  P = p + b
52//! ```
53//!
54//! 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
55//! adds m A_p^T A_p + I_t A_u^T A_u to M_xi and m A_p^T (a0 + g e_z) + I_t A_u^T u'' to c + g (d'Alembert; I_t about
56//! the centre across the leg, whose turn is u x u'); the constraint forces drop out as for the platform. Each part's
57//! spin about the leg's axis is free between the two joints and nothing excites it.
58
59use sim_components::chain::{
60    JOINT_KEYS, JointMachine, JointSpec, MOTOR_IDS, MOTOR_KEYS, Mechanism, condition_number, invert,
61};
62use sim_components::joint::RotaryJoint;
63use sim_components::mech::{HardStop, ShaftFriction, ThermalFeedback};
64use sim_components::rigid::{M3, V3, add, cross, dot, matmul, mul, transpose};
65use sim_components::transmission::BallScrew;
66use sim_core::{
67    AxisInfo, Config, ConfigError, Label, Machine, MachineEntry, MotorInfo, Part, RatingCheck, Scene, Shape, SignalInfo,
68};
69use std::f64::consts::TAU;
70
71pub static ENTRY: MachineEntry = MachineEntry {
72    id: "tripod",
73    key: "machine-tripod",
74    default_config: include_str!("../default.toml"),
75    i18n: &[("en", include_str!("../i18n/en.ftl")), ("de", include_str!("../i18n/de.ftl"))],
76    build,
77    suite_configs,
78};
79
80const G: f64 = 9.80665;
81
82/// Effects that take energy out or put it in; the standard suite runs with them off.
83pub const LOSSY_EFFECTS: [&str; 7] = [
84    "joint_friction",
85    "motor_friction",
86    "gearbox_drag",
87    "gearbox_lost_motion",
88    "gearbox_efficiency",
89    "torque_ripple",
90    "holding_brake",
91];
92
93const AXIS_IDS: [&str; 3] = ["z", "rx", "ry"];
94const AXIS_KEYS: [&str; 3] = ["axis-z", "axis-rx", "axis-ry"];
95
96/// The default config with every loss switched off.
97pub fn lossless_config() -> Config {
98    let mut cfg = ENTRY.config();
99    for effect in LOSSY_EFFECTS {
100        cfg.set_text(&format!("effects.{effect} = false")).unwrap();
101    }
102    cfg.set_text("gearbox.damping_nm_s_rad = 0.0").unwrap();
103    cfg.set_text("leg.stop_damping_n_s_m = 0.0").unwrap();
104    cfg
105}
106
107/// Loss-free rigid and elastic models, with and without the payload, all without gravity: held by constant leg forces
108/// the platform under its weight is unstable (pushing legs of constant force, d^2/dz^2 of m g z - sum f_i L_i =
109/// -sum f_i (1 - u_iz^2) / L_i < 0), a real property that the position loops hold. Gravity's part is checked on the
110/// default config (static hold, loss budget) and by the hand-calculated leg forces.
111fn suite_configs() -> Vec<Config> {
112    [(false, true), (false, false), (true, true), (true, false)]
113        .into_iter()
114        .map(|(elastic, payload)| {
115            let mut cfg = lossless_config();
116            cfg.set_text(&format!("effects.joint_elasticity = {elastic}")).unwrap();
117            cfg.set_text(&format!("effects.payload = {payload}")).unwrap();
118            cfg.set_text("effects.gravity = false").unwrap();
119            cfg
120        })
121        .collect()
122}
123
124fn sub(a: V3, b: V3) -> V3 {
125    [a[0] - b[0], a[1] - b[1], a[2] - b[2]]
126}
127
128fn norm(a: V3) -> f64 {
129    dot(a, a).sqrt()
130}
131
132fn scale(a: V3, k: f64) -> V3 {
133    a.map(|v| v * k)
134}
135
136/// Rotation about x, y and z.
137fn rot_x(a: f64) -> M3 {
138    let (s, c) = a.sin_cos();
139    [[1.0, 0.0, 0.0], [0.0, c, -s], [0.0, s, c]]
140}
141fn rot_y(a: f64) -> M3 {
142    let (s, c) = a.sin_cos();
143    [[c, 0.0, s], [0.0, 1.0, 0.0], [-s, 0.0, c]]
144}
145fn rot_z(a: f64) -> M3 {
146    let (s, c) = a.sin_cos();
147    [[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]]
148}
149
150/// m (row by row, rows x cols) times v.
151fn apply(m: &[f64], v: &[f64]) -> Vec<f64> {
152    let cols = v.len();
153    (0..m.len() / cols).map(|r| (0..cols).map(|c| m[r * cols + c] * v[c]).sum()).collect()
154}
155
156/// The LU factors of G (6 x 6) with partial pivoting, to solve G x = b for several b at the price of one elimination.
157pub struct Lu {
158    a: [f64; 36],
159    perm: [usize; 6],
160}
161
162impl Lu {
163    /// `None` where G is singular.
164    pub fn new(m: &[f64]) -> Option<Self> {
165        let mut a = [0.0; 36];
166        a.copy_from_slice(&m[..36]);
167        let mut perm = [0, 1, 2, 3, 4, 5];
168        for c in 0..6 {
169            let p = (c..6).max_by(|&i, &j| a[i * 6 + c].abs().total_cmp(&a[j * 6 + c].abs()))?;
170            if !(a[p * 6 + c].abs() > 1e-300) {
171                return None;
172            }
173            if p != c {
174                for k in 0..6 {
175                    a.swap(p * 6 + k, c * 6 + k);
176                }
177                perm.swap(p, c);
178            }
179            for r in c + 1..6 {
180                let f = a[r * 6 + c] / a[c * 6 + c];
181                a[r * 6 + c] = f;
182                for k in c + 1..6 {
183                    a[r * 6 + k] -= f * a[c * 6 + k];
184                }
185            }
186        }
187        Some(Self { a, perm })
188    }
189
190    pub fn solve(&self, b: &[f64; 6]) -> [f64; 6] {
191        let mut x: [f64; 6] = std::array::from_fn(|i| b[self.perm[i]]);
192        for r in 1..6 {
193            for k in 0..r {
194                x[r] -= self.a[r * 6 + k] * x[k];
195            }
196        }
197        for r in (0..6).rev() {
198            for k in r + 1..6 {
199                x[r] -= self.a[r * 6 + k] * x[k];
200            }
201            x[r] /= self.a[r * 6 + r];
202        }
203        x
204    }
205
206    /// A, the first three columns of G^-1: the twist per leg rate, column by column.
207    pub fn columns(&self) -> [[f64; 6]; 3] {
208        std::array::from_fn(|c| self.solve(&std::array::from_fn(|r| if r == c { 1.0 } else { 0.0 })))
209    }
210}
211
212/// Where the platform is at a tool pose (z, rx, ry): its centre p, its rotation R and the dependent turn g about its
213/// normal (the parasitic x, y are p's).
214#[derive(Debug, Clone, Copy)]
215pub struct Place {
216    pub p: V3,
217    pub r: M3,
218    pub turn: f64,
219}
220
221/// The legs at a platform place: unit vectors u_i from base to platform joint, lengths L_i, and the platform joints'
222/// offsets b_i = R a_i from the platform centre (base frame).
223#[derive(Debug, Clone, Copy)]
224pub struct Legs {
225    pub u: [V3; 3],
226    pub length: [f64; 3],
227    pub b: [V3; 3],
228}
229
230/// The tripod's geometry and kinematics, apart from masses and drives.
231#[derive(Debug, Clone)]
232pub struct Geometry {
233    /// Base joints (base frame), platform joints (platform frame), the base joints' revolute axes (tangents) and the
234    /// legs' radial directions.
235    pub base: [V3; 3],
236    pub anchors: [V3; 3],
237    pub tangents: [V3; 3],
238    pub radial: [V3; 3],
239    pub platform_radius: f64,
240    pub closed: f64,
241    pub stroke: f64,
242    /// The largest swing of a leg in its plane about its base joint, from the base's normal, and the largest cone
243    /// angle of a spherical joint (the leg against the platform's normal), rad.
244    pub max_revolute: f64,
245    pub max_cone: f64,
246    pub max_condition: f64,
247    /// The pose the forward kinematics starts from (the centre of the tool's box) and K^-1 there, row by row.
248    pub home: [f64; 3],
249    pub chord: Vec<f64>,
250}
251
252impl Geometry {
253    pub fn new(base_radius: f64, platform_radius: f64) -> Self {
254        let azimuth = [0.0f64, 120.0, 240.0].map(|deg| deg.to_radians().sin_cos());
255        let radial = azimuth.map(|(s, c)| [c, s, 0.0]);
256        Self {
257            base: radial.map(|r| scale(r, base_radius)),
258            anchors: radial.map(|r| scale(r, platform_radius)),
259            tangents: azimuth.map(|(s, c)| [-s, c, 0.0]),
260            radial,
261            platform_radius,
262            closed: 0.0,
263            stroke: 1.0,
264            max_revolute: std::f64::consts::FRAC_PI_2,
265            max_cone: std::f64::consts::FRAC_PI_2,
266            max_condition: f64::INFINITY,
267            home: [0.0; 3],
268            chord: Vec::new(),
269        }
270    }
271
272    /// Sets the start of the forward kinematics and its chord matrix K(home)^-1; `false` where home is singular.
273    pub fn set_home(&mut self, home: [f64; 3]) -> bool {
274        self.home = home;
275        let legs = self.legs(&home);
276        match self.rates(&home, &legs) {
277            Some(k) => {
278                self.chord = k;
279                true
280            }
281            None => false,
282        }
283    }
284
285    /// The platform's place at a tool pose, in closed form.
286    pub fn place(&self, tool: &[f64]) -> Place {
287        let (z, a, b) = (tool[0], tool[1], tool[2]);
288        let (sa, ca) = a.sin_cos();
289        let (sb, cb) = b.sin_cos();
290        let turn = (-sa * sb).atan2(ca + cb);
291        let (sg, cg) = turn.sin_cos();
292        let rp = self.platform_radius;
293        let p = [rp * (cb * cg + sa * sb * sg - ca * cg) / 2.0, rp * cb * sg, z];
294        Place { p, r: matmul(&matmul(&rot_x(a), &rot_y(b)), &rot_z(turn)), turn }
295    }
296
297    pub fn legs_at(&self, place: &Place) -> Legs {
298        let mut legs = Legs { u: [[0.0; 3]; 3], length: [0.0; 3], b: [[0.0; 3]; 3] };
299        for i in 0..3 {
300            let b = mul(&place.r, self.anchors[i]);
301            let d = sub(add(place.p, b), self.base[i]);
302            let l = norm(d);
303            legs.u[i] = scale(d, 1.0 / l);
304            legs.length[i] = l;
305            legs.b[i] = b;
306        }
307        legs
308    }
309
310    pub fn legs(&self, tool: &[f64]) -> Legs {
311        self.legs_at(&self.place(tool))
312    }
313
314    /// G (6 x 6, row by row): the legs' extension rates and the constraints' rates over the platform's twist (v, w).
315    pub fn constraint_matrix(&self, legs: &Legs) -> Vec<f64> {
316        let mut g = vec![0.0; 36];
317        for i in 0..3 {
318            let (m, n) = (cross(legs.b[i], legs.u[i]), cross(legs.b[i], self.tangents[i]));
319            let e = self.tangents[i];
320            g[i * 6..i * 6 + 6].copy_from_slice(&[legs.u[i][0], legs.u[i][1], legs.u[i][2], m[0], m[1], m[2]]);
321            g[(3 + i) * 6..(3 + i) * 6 + 6].copy_from_slice(&[e[0], e[1], e[2], n[0], n[1], n[2]]);
322        }
323        g
324    }
325
326    /// The tool's rates (z', rx', ry') per twist: S (3 x 6, row by row), at the tool pose's tilts.
327    fn selection(tool: &[f64]) -> [f64; 18] {
328        let (sa, ca) = tool[1].sin_cos();
329        let tb = tool[2].tan();
330        let mut s = [0.0; 18];
331        s[2] = 1.0;
332        s[6 + 3] = 1.0;
333        s[6 + 4] = tb * sa;
334        s[6 + 5] = -tb * ca;
335        s[12 + 4] = ca;
336        s[12 + 5] = sa;
337        s
338    }
339
340    /// K^-1 = S A (3 x 3, row by row): the tool's rates per leg rates, at a tool pose and its legs; `None` where G is
341    /// singular.
342    pub fn rates(&self, tool: &[f64], legs: &Legs) -> Option<Vec<f64>> {
343        let a = Lu::new(&self.constraint_matrix(legs))?.columns();
344        let s = Self::selection(tool);
345        Some((0..9).map(|rc| (0..6).map(|k| s[rc / 3 * 6 + k] * a[rc % 3][k]).sum()).collect())
346    }
347
348    /// The Jacobian K (3 x 3, row by row) of the legs' extension rates over the tool's rates (z', rx', ry').
349    pub fn jacobian(&self, tool: &[f64]) -> Option<Vec<f64>> {
350        invert(&self.rates(tool, &self.legs(tool))?, 3)
351    }
352
353    /// Leg extensions for a tool pose (closed form); `false` where a leg would be of no length.
354    pub fn inverse(&self, tool: &[f64], q: &mut [f64]) -> bool {
355        let legs = self.legs(tool);
356        for i in 0..3 {
357            q[i] = legs.length[i] - self.closed;
358        }
359        q[..3].iter().all(|v| v.is_finite()) && legs.length.iter().all(|l| *l > 0.0)
360    }
361
362    /// The legs' miss q + L_closed - L(x) at a tool pose and its largest magnitude.
363    fn miss(&self, q: &[f64], x: &[f64; 3]) -> (Vec<f64>, f64) {
364        let legs = self.legs(x);
365        let miss: Vec<f64> = (0..3).map(|i| q[i] + self.closed - legs.length[i]).collect();
366        let worst = miss.iter().fold(0.0f64, |m, v| m.max(v.abs()));
367        (miss, worst)
368    }
369
370    /// The tool pose for leg extensions; NaN where it does not converge. Chord steps x += K(home)^-1 (q - q(x)) from
371    /// `home`, which contract over the working range (`chord_contraction`); after the first of them the steps take
372    /// K(x1)^-1 at that first iterate instead, which near the solution contract far faster, as long as each at least
373    /// halves the legs' miss; at the first that does not, the chord steps take over for good. Until the legs miss by
374    /// less than 1e-13 m, within 100 steps.
375    pub fn forward(&self, q: &[f64], tool: &mut [f64]) {
376        let mut x = self.home;
377        let (mut miss, mut worst) = self.miss(q, &x);
378        let (mut fast, mut fell_back, mut converged) = (None::<Vec<f64>>, false, false);
379        for _ in 0..100 {
380            if !worst.is_finite() || x[1].abs() > 1.5 || x[2].abs() > 1.5 {
381                break;
382            }
383            if worst < 1e-13 {
384                converged = true;
385                break;
386            }
387            let step = apply(fast.as_deref().unwrap_or(&self.chord), &miss);
388            let next = [x[0] + step[0], x[1] + step[1], x[2] + step[2]];
389            let (next_miss, next_worst) = self.miss(q, &next);
390            if fast.is_some() && !(next_worst < 0.5 * worst) {
391                (fast, fell_back) = (None, true);
392                continue;
393            }
394            (x, miss, worst) = (next, next_miss, next_worst);
395            if fast.is_none() && !fell_back {
396                fast = self.rates(&x, &self.legs(&x));
397                fell_back = fast.is_none();
398            }
399        }
400        if converged {
401            tool[..3].copy_from_slice(&x);
402        } else {
403            tool.iter_mut().for_each(|v| *v = f64::NAN);
404        }
405    }
406
407    /// Per leg its swing about the base joint from the base's normal (signed, outwards positive) and the spherical
408    /// joint's cone angle against the platform's normal, rad.
409    pub fn joint_angles(&self, tool: &[f64]) -> ([f64; 3], [f64; 3]) {
410        let place = self.place(tool);
411        let legs = self.legs_at(&place);
412        let normal = [place.r[0][2], place.r[1][2], place.r[2][2]];
413        (
414            std::array::from_fn(|i| dot(legs.u[i], self.radial[i]).atan2(legs.u[i][2])),
415            std::array::from_fn(|i| dot(legs.u[i], normal).clamp(-1.0, 1.0).acos()),
416        )
417    }
418
419    /// The condition number of K with the tilts weighed by the platform radius (the platform joints' speed for a
420    /// tilt): that of diag(1, rp, rp) K^-1, as a matrix and its inverse share it.
421    pub fn condition(&self, tool: &[f64]) -> f64 {
422        let Some(mut k) = self.rates(tool, &self.legs(tool)) else { return f64::INFINITY };
423        for v in &mut k[3..] {
424            *v *= self.platform_radius;
425        }
426        condition_number(&k, 3, 3)
427    }
428
429    /// The parasitic motion at a tool pose: the centre's x and y, the turn about the normal, and the pose's error
430    /// against the pure tilt about (0, 0, z): the farthest any point of the joint circle (radius rp) lies from where the
431    /// pure tilt puts it, sqrt(|d|^2 + c^2 + 2 c |(R0^T d)_xy|), d = (p_x, p_y, 0), c = 2 rp |sin(g / 2)|.
432    pub fn parasitic(&self, tool: &[f64]) -> [f64; 4] {
433        let place = self.place(tool);
434        let d = [place.p[0], place.p[1], 0.0];
435        let pure = matmul(&rot_x(tool[1]), &rot_y(tool[2]));
436        let local = mul(&transpose(&pure), d);
437        let c = 2.0 * self.platform_radius * (0.5 * place.turn).sin().abs();
438        let error = (dot(d, d) + c * c + 2.0 * c * local[0].hypot(local[1])).sqrt();
439        [place.p[0], place.p[1], place.turn, error]
440    }
441
442    /// The chord iteration's contraction at a tool pose: the max-row-sum norm of W (1 - K(home)^-1 K(x)) W^-1, W =
443    /// diag(1, rp, rp), the factor by which one chord step shrinks the error (weighed so) near x.
444    pub fn chord_contraction(&self, tool: &[f64]) -> f64 {
445        let Some(k) = self.jacobian(tool) else { return f64::INFINITY };
446        let w = [1.0, self.platform_radius, self.platform_radius];
447        (0..3)
448            .map(|r| {
449                (0..3)
450                    .map(|c| {
451                        let prod: f64 = (0..3).map(|m| self.chord[r * 3 + m] * k[m * 3 + c]).sum();
452                        (w[r] * (if r == c { 1.0 } else { 0.0 } - prod) / w[c]).abs()
453                    })
454                    .sum::<f64>()
455            })
456            .fold(0.0, f64::max)
457    }
458}
459
460/// The moving body: mass, first moment about the platform centre (platform frame) and inertia about the centre
461/// (platform frame).
462#[derive(Debug, Clone, Copy)]
463struct Body {
464    mass: f64,
465    moment: V3,
466    inertia: M3,
467}
468
469impl Body {
470    /// A body of mass m with its centre at c and its inertia `own` about its centre, about the origin.
471    fn at(m: f64, c: V3, own: M3) -> Self {
472        let inertia = std::array::from_fn(|i| {
473            std::array::from_fn(|j| own[i][j] + m * (if i == j { dot(c, c) } else { 0.0 } - c[i] * c[j]))
474        });
475        Self { mass: m, moment: scale(c, m), inertia }
476    }
477    fn plus(self, o: Self) -> Self {
478        Self {
479            mass: self.mass + o.mass,
480            moment: add(self.moment, o.moment),
481            inertia: std::array::from_fn(|i| std::array::from_fn(|j| self.inertia[i][j] + o.inertia[i][j])),
482        }
483    }
484}
485
486fn diagonal(cfg: &Config, key: &str) -> Result<M3, ConfigError> {
487    let d = cfg.f64s(key)?;
488    if d.len() != 3 || d.iter().any(|v| !(*v >= 0.0)) {
489        return Err(ConfigError::Invalid(key.into()));
490    }
491    Ok(std::array::from_fn(|i| std::array::from_fn(|j| if i == j { d[i] } else { 0.0 })))
492}
493
494/// One body of a leg: its mass, its centre's distance from the joint it hangs on, its inertia across the leg about its
495/// centre, and whether it hangs on the platform joint (else on the base joint).
496#[derive(Debug, Clone, Copy)]
497struct LegPart {
498    mass: f64,
499    centre: f64,
500    inertia: f64,
501    on_platform: bool,
502}
503
504/// A leg part's motion at a pose and twist: A_p (its velocity per twist, as columns), its acceleration `a0` at zero twist
505/// acceleration, the leg direction's rate per twist `au` (columns) and its second derivative `u2` at zero twist
506/// acceleration.
507struct PartMotion {
508    a: [V3; 6],
509    a0: V3,
510    au: [V3; 6],
511    u2: V3,
512}
513
514#[derive(Clone)]
515pub struct Tripod {
516    pub geo: Geometry,
517    screw: BallScrew,
518    /// The platform, and with the payload too.
519    empty: Body,
520    loaded: Body,
521    /// The two bodies of each leg: the part on the base joint, the part on the platform joint.
522    parts: [LegPart; 2],
523    attached: bool,
524    g: f64,
525    required_life: Option<f64>,
526    max_force: f64,
527    parasitic_tolerance: Option<f64>,
528}
529
530fn build(cfg: &Config) -> Result<Box<dyn Machine>, ConfigError> {
531    let (machine, _) = Tripod::from_config(cfg)?;
532    sim_components::base::mount(cfg, machine)
533}
534
535impl Tripod {
536    /// The machine, and its mechanism alone for the tests.
537    pub fn from_config(cfg: &Config) -> Result<(Box<dyn Machine>, Tripod), ConfigError> {
538        let mut geo = Geometry::new(cfg.positive("tripod.base_radius_m")?, cfg.positive("tripod.platform_radius_m")?);
539        geo.closed = cfg.positive("leg.closed_length_m")?;
540        geo.stroke = cfg.positive("leg.stroke_m")?;
541        geo.max_revolute = cfg.positive("workspace.max_revolute_angle_deg")?.to_radians();
542        geo.max_cone = cfg.positive("workspace.max_cone_angle_deg")?.to_radians();
543        geo.max_condition = cfg.positive("workspace.max_condition_number")?;
544        let (min, max) = (cfg.f64s("workspace.tool_min")?, cfg.f64s("workspace.tool_max")?);
545        if min.len() != 3 || max.len() != 3 {
546            return Err(ConfigError::Invalid("workspace.tool_min".into()));
547        }
548        if (0..3).any(|k| !(min[k] < max[k])) || (1..3).any(|k| !(min[k] > -1.0 && max[k] < 1.0)) {
549            return Err(ConfigError::Invalid("workspace.tool_max".into()));
550        }
551        if !geo.set_home(std::array::from_fn(|k| 0.5 * (min[k] + max[k]))) {
552            return Err(ConfigError::Invalid("workspace.tool_min".into()));
553        }
554        let share = cfg.non_negative("leg.platform_share")?;
555        if share > 1.0 {
556            return Err(ConfigError::Invalid("leg.platform_share".into()));
557        }
558        let leg_mass = cfg.non_negative("leg.mass_kg")?;
559        let part = |key: &str, on_platform: bool, mass: f64| -> Result<LegPart, ConfigError> {
560            let get = |what: &str| cfg.non_negative(&format!("leg.{key}_{what}"));
561            Ok(LegPart { mass, centre: get("centre_m")?, inertia: get("inertia_kgm2")?, on_platform })
562        };
563        let parts =
564            [part("base_part", false, (1.0 - share) * leg_mass)?, part("platform_part", true, share * leg_mass)?];
565        let platform_inertia = diagonal(cfg, "mass.platform_inertia_kgm2")?;
566        let empty = Body::at(cfg.positive("mass.platform_kg")?, [0.0; 3], platform_inertia);
567        let offset = cfg.f64s("mass.payload_offset_m")?;
568        if offset.len() != 3 || offset.iter().any(|v| !v.is_finite()) {
569            return Err(ConfigError::Invalid("mass.payload_offset_m".into()));
570        }
571        let payload = if cfg.bool("effects.payload")? { cfg.non_negative("mass.payload_kg")? } else { 0.0 };
572        let own = if payload > 0.0 { diagonal(cfg, "mass.payload_inertia_kgm2")? } else { [[0.0; 3]; 3] };
573        let loaded = empty.plus(Body::at(payload, [offset[0], offset[1], offset[2]], own));
574        let screw = BallScrew::from_config(cfg)?;
575        if screw.length < geo.stroke {
576            return Err(ConfigError::Invalid("screw.length_m".into()));
577        }
578        let on = cfg.bool("effects.joint_friction")?;
579        let friction = ShaftFriction {
580            coulomb: if on { cfg.non_negative("leg.friction_coulomb_n")? } else { 0.0 },
581            viscous: if on { cfg.non_negative("leg.friction_viscous_n_s_m")? } else { 0.0 },
582            smoothing: cfg.positive("leg.friction_smoothing_m_s")?,
583            ..ShaftFriction::NONE
584        };
585        let stops = if cfg.bool("effects.hard_stops")? {
586            HardStop {
587                stiffness: cfg.positive("leg.stop_stiffness_n_m")?,
588                damping: cfg.non_negative("leg.stop_damping_n_s_m")?,
589            }
590        } else {
591            HardStop { stiffness: 0.0, damping: 0.0 }
592        };
593        let mut joint = RotaryJoint::with(cfg, friction, stops, (0.0, geo.stroke))?;
594        // The mesh friction's bristle capped by the lighter of the rotor and what the nut moves at least: the platform
595        // pushed at its joint, 1 / (1 / m + r^2 / I_min) whatever the other legs hold (`Converter::apply_to`).
596        let r2 = geo.anchors.iter().map(|a| dot(*a, *a)).fold(0.0, f64::max);
597        let i_min = (0..3).map(|k| platform_inertia[k][k]).fold(f64::INFINITY, f64::min);
598        let leg_output = 1.0 / (1.0 / cfg.positive("mass.platform_kg")? + r2 / i_min);
599        screw.converter(screw.softest_position()).apply_to(cfg, &mut joint, leg_output)?;
600        // The nut's preload drags like friction in the rod's guide, as a force at the nut.
601        if on {
602            joint.friction.coulomb += screw.preload_torque() * screw.ratio();
603        }
604        let lever = 1.0 / screw.ratio();
605        let mech = Tripod {
606            geo,
607            screw,
608            empty,
609            loaded,
610            parts,
611            attached: true,
612            g: if cfg.bool("effects.gravity")? { G } else { 0.0 },
613            required_life: cfg.f64("ratings.required_life_h").ok(),
614            max_force: cfg.positive("leg.max_force_n")?,
615            parasitic_tolerance: cfg.f64("ratings.parasitic_tolerance_m").ok(),
616        };
617        let axes = (0..3)
618            .map(|k| {
619                let unit = if k < 1 { "m" } else { "rad" };
620                let get =
621                    |what: &str, rate: &str| cfg.positive(&format!("axis.{}.max_{what}_{unit}_{rate}", AXIS_IDS[k]));
622                Ok(AxisInfo {
623                    id: AXIS_IDS[k],
624                    key: AXIS_KEYS[k],
625                    unit,
626                    min: min[k],
627                    max: max[k],
628                    max_vel: get("velocity", "s")?,
629                    max_acc: get("acceleration", "s2")?,
630                    max_jerk: get("jerk", "s3")?,
631                })
632            })
633            .collect::<Result<Vec<_>, ConfigError>>()?;
634        let specs = (0..3)
635            .map(|k| JointSpec {
636                drive: joint.clone(),
637                id: MOTOR_IDS[k],
638                key: JOINT_KEYS[k],
639                gear_lever: Some(lever),
640                unit: "m",
641            })
642            .collect();
643        let motors = (0..3).map(|k| MotorInfo { id: MOTOR_IDS[k], key: MOTOR_KEYS[k] }).collect();
644        let machine = JointMachine::new(
645            mech.clone(),
646            specs,
647            cfg.bool("effects.joint_elasticity")?,
648            ThermalFeedback::from_config(cfg)?,
649            axes,
650            motors,
651        );
652        Ok((Box::new(machine), mech))
653    }
654
655    fn body(&self) -> Body {
656        if self.attached { self.loaded } else { self.empty }
657    }
658
659    /// The pose for leg extensions, its place and legs; `None` where the forward kinematics fails.
660    fn pose(&self, q: &[f64]) -> Option<([f64; 3], Place, Legs)> {
661        let mut tool = [0.0; 3];
662        self.geo.forward(q, &mut tool);
663        if !tool.iter().all(|v| v.is_finite()) {
664            return None;
665        }
666        let place = self.geo.place(&tool);
667        Some((tool, place, self.geo.legs_at(&place)))
668    }
669
670    /// The body in the base frame at rotation R: mass, first moment s = R s_b, inertia about the centre R I_b R^T.
671    fn turned(&self, r: &M3) -> (f64, V3, M3) {
672        let b = self.body();
673        (b.mass, mul(r, b.moment), matmul(&matmul(r, &b.inertia), &transpose(r)))
674    }
675
676    /// Leg i's part `part` at a pose with the platform's twist `xi`: see the module's derivation.
677    fn part_motion(&self, i: usize, legs: &Legs, xi: &[f64; 6], part: &LegPart) -> PartMotion {
678        let (u, l, b) = (legs.u[i], legs.length[i], legs.b[i]);
679        let (v, w) = ([xi[0], xi[1], xi[2]], [xi[3], xi[4], xi[5]]);
680        let (d1, d2) = (add(v, cross(w, b)), cross(w, cross(w, b)));
681        let rate = dot(u, d1);
682        let up = scale(sub(d1, scale(u, rate)), 1.0 / l);
683        let rate2 = dot(up, d1) + dot(u, d2);
684        let u2: V3 = std::array::from_fn(|k| (d2[k] - 2.0 * up[k] * rate - u[k] * rate2) / l);
685        // The twist's unit columns: the platform joint's velocity per v_k (e_k) and per w_k (e_k x b).
686        let unit = |k: usize| -> V3 {
687            let e: V3 = std::array::from_fn(|r| if r == k % 3 { 1.0 } else { 0.0 });
688            if k < 3 { e } else { cross(e, b) }
689        };
690        let au: [V3; 6] = std::array::from_fn(|k| {
691            let d = unit(k);
692            scale(sub(d, scale(u, dot(u, d))), 1.0 / l)
693        });
694        let c = part.centre;
695        if part.on_platform {
696            PartMotion { a: std::array::from_fn(|k| sub(unit(k), scale(au[k], c))), a0: sub(d2, scale(u2, c)), au, u2 }
697        } else {
698            PartMotion { a: au.map(|col| scale(col, c)), a0: scale(u2, c), au, u2 }
699        }
700    }
701
702    /// The leg parts' mass matrix over the twist (6 x 6, row by row) and their share of c + g at the twist `xi` (zero
703    /// twist acceleration), over all legs.
704    fn parts_terms(&self, legs: &Legs, xi: &[f64; 6]) -> (Vec<f64>, [f64; 6]) {
705        let (mut m, mut held) = (vec![0.0; 36], [0.0; 6]);
706        for i in 0..3 {
707            for part in self.parts.iter().filter(|p| p.mass > 0.0 || p.inertia > 0.0) {
708                let pm = self.part_motion(i, legs, xi, part);
709                let accel = [pm.a0[0], pm.a0[1], pm.a0[2] + self.g];
710                for r in 0..6 {
711                    held[r] += part.mass * dot(pm.a[r], accel) + part.inertia * dot(pm.au[r], pm.u2);
712                    for c in 0..6 {
713                        m[r * 6 + c] += part.mass * dot(pm.a[r], pm.a[c]) + part.inertia * dot(pm.au[r], pm.au[c]);
714                    }
715                }
716            }
717        }
718        (m, held)
719    }
720
721    /// Where leg i's part `part` has its centre with the platform at `p`.
722    fn part_position(&self, i: usize, legs: &Legs, p: V3, part: &LegPart) -> V3 {
723        let u = scale(legs.u[i], part.centre);
724        if part.on_platform { sub(add(p, legs.b[i]), u) } else { add(self.geo.base[i], u) }
725    }
726
727    /// The twist's mass matrix (6 x 6, row by row): [[m 1, -[s]x], [[s]x, I_p]].
728    fn twist_mass(m: f64, s: V3, ip: &M3) -> Vec<f64> {
729        let sx = [[0.0, -s[2], s[1]], [s[2], 0.0, -s[0]], [-s[1], s[0], 0.0]];
730        let mut out = vec![0.0; 36];
731        for r in 0..3 {
732            out[r * 6 + r] = m;
733            for c in 0..3 {
734                out[r * 6 + 3 + c] = -sx[r][c];
735                out[(3 + r) * 6 + c] = sx[r][c];
736                out[(3 + r) * 6 + 3 + c] = ip[r][c];
737            }
738        }
739        out
740    }
741
742    /// The weight as the wrench the legs must hold: g = (0, 0, m g, g s_y, -g s_x, 0).
743    fn weight(&self, m: f64, s: V3) -> [f64; 6] {
744        [0.0, 0.0, m * self.g, self.g * s[1], -self.g * s[0], 0.0]
745    }
746
747    /// The forces the legs push the platform with to hold it at rest at a tool pose: A^T g, N.
748    pub fn static_leg_forces(&self, tool: &[f64]) -> Option<[f64; 3]> {
749        let place = self.geo.place(tool);
750        let legs = self.geo.legs_at(&place);
751        let a = Lu::new(&self.geo.constraint_matrix(&legs))?.columns();
752        let (m, s, _) = self.turned(&place.r);
753        let mut g = self.weight(m, s);
754        // The leg parts' weight: m g times the z row of their A_p.
755        let (_, parts) = self.parts_terms(&legs, &[0.0; 6]);
756        g.iter_mut().zip(parts).for_each(|(w, p)| *w += p);
757        Some(std::array::from_fn(|i| (0..6).map(|k| a[i][k] * g[k]).sum()))
758    }
759}
760
761impl Mechanism for Tripod {
762    fn dynamics(&self, q: &[f64], qd: &[f64], mass: &mut [f64], bias: &mut [f64]) {
763        let fail = |mass: &mut [f64], bias: &mut [f64]| {
764            mass.fill(f64::NAN);
765            bias.fill(f64::NAN);
766        };
767        let Some((_, place, legs)) = self.pose(q) else { return fail(mass, bias) };
768        let Some(lu) = Lu::new(&self.geo.constraint_matrix(&legs)) else { return fail(mass, bias) };
769        // A = the first three columns of G^-1.
770        let columns = lu.columns();
771        let a = |r: usize, c: usize| columns[c][r];
772        let xi: Vec<f64> = (0..6).map(|r| (0..3).map(|c| a(r, c) * qd[c]).sum()).collect();
773        let (v, w) = ([xi[0], xi[1], xi[2]], [xi[3], xi[4], xi[5]]);
774        let mut rest = [0.0; 6];
775        for i in 0..3 {
776            let spin = cross(w, cross(w, legs.b[i]));
777            let wi = add(v, cross(w, legs.b[i]));
778            let along = dot(legs.u[i], wi);
779            rest[i] = -((dot(wi, wi) - along * along) / legs.length[i] + dot(legs.u[i], spin));
780            rest[3 + i] = -dot(self.geo.tangents[i], spin);
781        }
782        let beta = lu.solve(&rest);
783        let (m, s, ip) = self.turned(&place.r);
784        let mut mx = Self::twist_mass(m, s, &ip);
785        let xi6: [f64; 6] = std::array::from_fn(|r| xi[r]);
786        let (parts_mass, parts_held) = self.parts_terms(&legs, &xi6);
787        mx.iter_mut().zip(&parts_mass).for_each(|(a, b)| *a += b);
788        let (lin, gyro) = (cross(w, cross(w, s)), cross(w, mul(&ip, w)));
789        let weight = self.weight(m, s);
790        let held: [f64; 6] =
791            std::array::from_fn(|k| [lin[0], lin[1], lin[2], gyro[0], gyro[1], gyro[2]][k] + parts_held[k]);
792        let mbeta = apply(&mx, &beta);
793        let wrench: Vec<f64> = (0..6).map(|k| mbeta[k] + held[k] + weight[k]).collect();
794        for i in 0..3 {
795            bias[i] = (0..6).map(|k| a(k, i) * wrench[k]).sum();
796            for j in 0..3 {
797                mass[i * 3 + j] = (0..6).map(|k| a(k, i) * (0..6).map(|l| mx[k * 6 + l] * a(l, j)).sum::<f64>()).sum();
798            }
799        }
800    }
801
802    /// The platform (and the payload with it) at its centre p with its twist (v, w): L = m v + w x s, about the origin
803    /// s x v + I_p w + p x L, its first moment m p + s; each leg's two parts as points with their velocity A_p xi and
804    /// their turn I_t u x u'. Each leg's rotor spins along the leg's u_i.
805    fn frame_momentum(&self, q: &[f64], qd: &[f64], rotor_spin: &[f64]) -> Option<sim_core::FrameMomentum> {
806        let (_, place, legs) = self.pose(q)?;
807        let a = Lu::new(&self.geo.constraint_matrix(&legs))?.columns();
808        let xi: Vec<f64> = (0..6).map(|r| (0..3).map(|c| a[c][r] * qd[c]).sum()).collect();
809        let (v, w) = ([xi[0], xi[1], xi[2]], [xi[3], xi[4], xi[5]]);
810        let (m, s, ip) = self.turned(&place.r);
811        let p = place.p;
812        let linear = add(scale(v, m), cross(w, s));
813        let angular = add(add(cross(s, v), mul(&ip, w)), cross(p, linear));
814        let mut f = sim_core::FrameMomentum { gravity: [0.0, 0.0, -self.g], ..Default::default() };
815        f.linear = linear;
816        f.angular = angular;
817        f.mass = m;
818        f.first_moment = add(scale(p, m), s);
819        let xi6: [f64; 6] = std::array::from_fn(|r| xi[r]);
820        for i in 0..3 {
821            for part in self.parts.iter().filter(|p| p.mass > 0.0 || p.inertia > 0.0) {
822                let pm = self.part_motion(i, &legs, &xi6, part);
823                let speed: V3 = std::array::from_fn(|k| (0..6).map(|c| pm.a[c][k] * xi6[c]).sum());
824                let at = self.part_position(i, &legs, p, part);
825                sim_components::base::add_point(&mut f, part.mass, at, speed);
826                if !part.on_platform {
827                    // The base-joint part's mass at its joint does not move (`FrameMomentum`): only its offset counts.
828                    f.mass -= part.mass;
829                    (0..3).for_each(|k| f.first_moment[k] -= part.mass * self.geo.base[i][k]);
830                }
831                // The part's turn about its own centre across the leg: u x u'.
832                let rate: V3 = std::array::from_fn(|k| (0..6).map(|c| pm.au[c][k] * xi6[c]).sum());
833                let spin = cross(legs.u[i], rate);
834                (0..3).for_each(|k| f.angular[k] += part.inertia * spin[k]);
835            }
836        }
837        for (u, spin) in legs.u.iter().zip(rotor_spin) {
838            sim_components::base::add_spin(&mut f, *u, 1.0, *spin);
839        }
840        Some(f)
841    }
842    fn potential(&self, q: &[f64]) -> f64 {
843        self.pose(q).map_or(f64::NAN, |(_, place, legs)| {
844            let (m, s, _) = self.turned(&place.r);
845            let parts: f64 = (0..3)
846                .flat_map(|i| self.parts.iter().map(move |part| (i, part)))
847                .map(|(i, part)| part.mass * self.part_position(i, &legs, place.p, part)[2])
848                .sum();
849            self.g * (m * place.p[2] + s[2] + parts)
850        })
851    }
852    fn set_payload_attached(&mut self, attached: bool) {
853        self.attached = attached;
854    }
855
856    fn forward(&self, q: &[f64], tool: &mut [f64]) {
857        self.geo.forward(q, tool);
858    }
859    fn inverse(&self, tool: &[f64], q: &mut [f64]) -> bool {
860        self.geo.inverse(tool, q)
861    }
862    fn unreachable(&self, tool: &[f64], _slack: f64) -> Option<&'static str> {
863        let (swing, cone) = self.geo.joint_angles(tool);
864        if !swing.iter().all(|a| a.abs() <= self.geo.max_revolute) {
865            return Some("error-tripod-revolute-angle");
866        }
867        if !cone.iter().all(|a| *a <= self.geo.max_cone) {
868            return Some("error-tripod-cone-angle");
869        }
870        if !(self.geo.condition(tool) <= self.geo.max_condition) {
871            return Some("error-tripod-singularity");
872        }
873        None
874    }
875    fn condition(&self, tool: &[f64]) -> Option<f64> {
876        Some(self.geo.condition(tool))
877    }
878    fn tool_is_joints(&self) -> bool {
879        false
880    }
881
882    /// Per leg its screw's speed, d n and wear, its stroke from the middle, its swing at the base joint and its cone
883    /// angle at the platform joint; then the condition number and the parasitic motion at the pose.
884    fn signal_infos(&self) -> Vec<SignalInfo> {
885        let mut out = Vec::new();
886        for i in 0..3 {
887            out.extend(self.screw.signal_infos(MOTOR_IDS[i], JOINT_KEYS[i]));
888        }
889        for i in 0..3 {
890            let id = MOTOR_IDS[i];
891            out.push(SignalInfo::new(format!("leg.{id}.from_middle"), JOINT_KEYS[i], "quantity-leg-from-middle", "m"));
892            out.push(SignalInfo::new(format!("leg.{id}.swing"), JOINT_KEYS[i], "quantity-revolute-swing", "rad"));
893            out.push(SignalInfo::new(format!("leg.{id}.cone"), JOINT_KEYS[i], "quantity-cone-angle", "rad"));
894        }
895        out.push(SignalInfo::new("platform.condition", "group-tripod", "quantity-condition-number", ""));
896        out.push(SignalInfo::new("platform.x", "group-tripod", "quantity-parasitic-x", "m"));
897        out.push(SignalInfo::new("platform.y", "group-tripod", "quantity-parasitic-y", "m"));
898        out.push(SignalInfo::new("platform.turn", "group-tripod", "quantity-parasitic-turn", "rad"));
899        out.push(SignalInfo::new("platform.pose_error", "group-tripod", "quantity-pose-error", "m"));
900        out
901    }
902    fn signals(&self, q: &[f64], qd: &[f64], _qdd: &[f64], force: &[f64], out: &mut Vec<f64>) {
903        for i in 0..3 {
904            self.screw.signals(qd[i], force[i], out);
905        }
906        let tool = self.pose(q).map(|(tool, ..)| tool);
907        let (swing, cone) = tool.map_or(([f64::NAN; 3], [f64::NAN; 3]), |t| self.geo.joint_angles(&t));
908        for i in 0..3 {
909            out.extend([q[i] - 0.5 * self.geo.stroke, swing[i], cone[i]]);
910        }
911        out.push(tool.map_or(f64::INFINITY, |t| self.geo.condition(&t)));
912        out.extend(tool.map_or([f64::NAN; 4], |t| self.geo.parasitic(&t)));
913    }
914    /// Each leg's screw (speed, d n, buckling and static load under the leg's force, life), the leg's force against
915    /// the cylinder's, its stroke, its joints' angles; the parasitic motion where a tolerance is given.
916    fn rating_checks(&self) -> Vec<RatingCheck> {
917        let mut out: Vec<RatingCheck> =
918            (0..3).flat_map(|i| self.screw.rating_checks(MOTOR_IDS[i], i, self.required_life)).collect();
919        for i in 0..3 {
920            let id = MOTOR_IDS[i];
921            let check = |check: &'static str, signal: String, limit: f64| RatingCheck {
922                check,
923                signal,
924                motor: Some(i),
925                limit,
926                life: false,
927            };
928            out.push(check("tripod-leg-force", format!("joint.{id}.force"), self.max_force));
929            out.push(check("tripod-leg-stroke", format!("leg.{id}.from_middle"), 0.5 * self.geo.stroke));
930            out.push(check("tripod-revolute-angle", format!("leg.{id}.swing"), self.geo.max_revolute));
931            out.push(check("tripod-cone-angle", format!("leg.{id}.cone"), self.geo.max_cone));
932        }
933        if let Some(limit) = self.parasitic_tolerance {
934            out.push(RatingCheck {
935                check: "tripod-parasitic",
936                signal: "platform.pose_error".into(),
937                motor: None,
938                limit,
939                life: false,
940            });
941        }
942        out
943    }
944
945    fn collision_parts(&self) -> &'static [&'static str] {
946        &["tool", "payload"]
947    }
948
949    /// Base and platform as triangles through their joints, each leg as its cylinder and rod, the motors below the
950    /// base joints, the payload at its centre.
951    fn scene(&self, q: &[f64], rotors: &[f64], rotor_speeds: &[f64], out: &mut Scene) {
952        let Some((_, place, legs)) = self.pose(q) else { return };
953        let p = place.p;
954        let top: Vec<V3> = (0..3).map(|i| add(p, legs.b[i])).collect();
955        for i in 0..3 {
956            let next = (i + 1) % 3;
957            out.parts.push(Part::new(
958                "base",
959                Shape::Segment { to: self.geo.base[next], width: 0.04 },
960                self.geo.base[i],
961                [0.55, 0.57, 0.6],
962            ));
963            out.parts.push(Part::new(
964                "platform",
965                Shape::Segment { to: top[next], width: 0.04 },
966                top[i],
967                [0.3, 0.45, 0.7],
968            ));
969        }
970        let body = 0.6 * self.geo.closed;
971        for i in 0..3 {
972            let (b, u) = (self.geo.base[i], legs.u[i]);
973            let end = add(b, scale(u, body));
974            out.parts.push(Part::new("cylinder", Shape::Segment { to: end, width: 0.06 }, b, [0.75, 0.75, 0.78]));
975            out.parts.push(Part::new(
976                "rod",
977                Shape::Segment { to: add(b, scale(u, 0.9 * body)), width: 0.03 },
978                top[i],
979                [0.85, 0.86, 0.9],
980            ));
981            out.parts.push(Part::new(
982                sim_core::scene::MOTOR_PART,
983                Shape::Box { size: [0.08, 0.08, 0.1] },
984                add(b, [0.0, 0.0, -0.07]),
985                [0.9, 0.45, 0.1],
986            ));
987            // The shaft's bar below the motor turns with the rotor, as on every machine.
988            out.parts.push(
989                Part::new("rotor-bar", Shape::Box { size: [0.08, 0.004, 0.012] }, add(b, [0.0, 0.0, -0.13]), [0.1; 3])
990                    .turned(rotors[i]),
991            );
992            out.labels.push(Label {
993                pos: add(b, [0.0, 0.0, -0.16]),
994                owner_key: MOTOR_KEYS[i],
995                value: rotor_speeds[i] * 60.0 / TAU,
996                unit_key: "unit-rpm",
997                decimals: 0,
998            });
999            out.labels.push(Label {
1000                pos: add(b, scale(u, 0.5 * legs.length[i])),
1001                owner_key: JOINT_KEYS[i],
1002                value: legs.length[i],
1003                unit_key: "unit-m",
1004                decimals: 3,
1005            });
1006        }
1007        let normal = [place.r[0][2], place.r[1][2], place.r[2][2]];
1008        out.parts.push(Part::new(
1009            "tool",
1010            Shape::Box { size: [0.08, 0.08, 0.03] },
1011            add(p, scale(normal, 0.015)),
1012            [0.2, 0.22, 0.26],
1013        ));
1014        let b = self.body();
1015        if self.attached && (b.mass - self.empty.mass) > 0.0 {
1016            let own = sub(b.moment, self.empty.moment);
1017            let centre = add(p, mul(&place.r, scale(own, 1.0 / (b.mass - self.empty.mass))));
1018            out.parts.push(Part::new("payload", Shape::Box { size: [0.2, 0.2, 0.12] }, centre, [0.2, 0.7, 0.3]));
1019        }
1020        out.labels.push(Label {
1021            pos: add(p, [0.0, 0.0, 0.25]),
1022            owner_key: "axis-z",
1023            value: p[2],
1024            unit_key: "unit-m",
1025            decimals: 3,
1026        });
1027    }
1028    fn scene_point(&self, tool: &[f64]) -> Option<[f64; 3]> {
1029        Some(self.geo.place(tool).p)
1030    }
1031}
1032
1033#[cfg(test)]
1034mod tests;