Skip to main content

machine_delta_h4/
lib.rs

1//! Four-arm delta of the Quattro / H4 type (Pierrot's H4, the Adept/Omron Quattro): four motor-driven arms on the base
2//! at 90 degrees, arm k along the azimuth (k - 1) 90 degrees, each carrying a parallelogram of two forearms down to a
3//! travelling plate in two parts. Arms 1 and 2 carry part A, arms 3 and 4 part B. The tool is x, y, z and its turn c
4//! about +z.
5//!
6//! Which arms share a part: two neighbouring ones. A parallelogram keeps its plate end parallel to its elbow's axis,
7//! leaving the part one turn, about that axis; two neighbouring arms' axes are at right angles, so a part on them cannot
8//! turn at all. Two opposite arms' axes are parallel and would leave a part free to turn about them.
9//!
10//! The two parts slide against each other along the horizontal d = (1, -1, 0) / sqrt 2, each by the half slide h from
11//! the tool's point the other way: part A at p - h d, part B at p + h d. A pinion between a rack on each part rolls by
12//! h / r_p, its centre on a carriage that the parts guide between them stays at the tool's point p, and a gear stage of
13//! ratio i_p turns the tool: c = kappa h, kappa = i_p / r_p (`Plate`). d is across the line between the parts: along it,
14//! d = (1, 1, 0) / sqrt 2, the slide would move the four forearms' ends as the plate's descent does at the centre, and
15//! the Jacobian would be singular there.
16//!
17//! Kinematics in x = (p, h), leg k at azimuth phi_k, side sigma_k (-1 on part A, +1 on part B), the plate parts' radius
18//! folded into e = base radius - plate radius as on the D3, theta_k the arm angle (0 horizontal, positive down):
19//!
20//! ```text
21//! elbow     c_k = R_z(phi_k) (e + L_a cos theta, 0, -L_a sin theta)
22//! end       q_k = p + sigma_k h d
23//! constraint |q_k - c_k|^2 = L_b^2
24//! inverse   per leg the D3's closed form at q_k (elbow out)
25//! forward   Newton on the four constraints from the D3's trilateration of legs 1 to 3 at h = 0 (the lower point)
26//! Jacobian  J_x x' = J_q theta', J_x row k (u_k, sigma_k u_k . d), u_k = q_k - c_k, J_q = diag(u_k . dc_k/dtheta_k)
27//!           J_x x'' = J_q theta'' + w, w_k = theta_k'^2 (u_k . c_k'') - |q_k' - c_k' theta_k'|^2
28//! ```
29//!
30//! Dynamics, by virtual work as the D3's (Codourey 1998, Olsson 2009): each forearm pair's mass split, a share r at the
31//! elbow and 1 - r at its plate part (or, with effects.forearm_inertia, a rigid rod: a sixth at each end, two thirds
32//! at its middle, and its spin about its own axis), and every body a point with its Jacobian P (3 x 4) in the arm
33//! angles: the parts, m_part + 2 (1 - r) m_fb each, with P = J_p -+ d J_h; the carriage and the payload at p; the tool's
34//! turn, I_t c'^2 / 2 = I_t kappa^2 h'^2 / 2; the arms about their joints. Each body adds m P^T P to M, m P^T a0 to
35//! the velocity term (a0 its acceleration at no arm acceleration) and -m g P_z to the gravity:
36//!
37//! ```text
38//! M(theta) theta'' = tau_gear + Q_g - v + tau_joint
39//! ```
40//!
41//! With effects.amplifier_compliance the tool is a body of its own, its angle phi on the amplifier's spring
42//! (`Amplifier`, with effects.amplifier_backlash a dead band in it): tau_a = k (kappa h - phi) + c (kappa h' - phi'),
43//! I_t phi'' = tau_a, and the arms feel -kappa J_h^T tau_a. Each joint is a `RotaryJoint` (gearbox with stiffness,
44//! backlash and efficiency, motor with friction, ripple and brake, joint friction, stops), as on the D3.
45//!
46//! With effects.arm_bending each upper arm bends as the D3's does (effects.link_elasticity there): in the plane it turns
47//! in, the elbow turns by delta_i against the arm's root on a spring k_b = 3 E I / L_a (a cantilever's tip deflection as
48//! a turn about the shoulder) with a damper; out of it, the elbow moves by y_i along its axis on the tube's lateral
49//! spring k_l = 3 E I / L_a^3 with a damper, E I the arm tube's (`[upper_arm]` tube_outer_diameter_m, tube_wall_m,
50//! youngs_modulus_pa: I = pi (D^4 - (D - 2 s)^4) / 64). The tube (I_arm, m_arm l_cg) stays with the root, at the joint's angle
51//! theta; the elbow block and the forearms' share, and all beyond, move with the elbow angle e = theta + delta and the
52//! moves y: the forearm constraint is |q_k - c_k - y_k a_k|^2 = L_b^2 (a_k the elbow's axis), so
53//! J_x x' = J_q e' + J_y y', J_y = diag(u_k . a_k), and w gains -|q' - c' e' - a y'|^2 (`Legs::velocity_term_moved`).
54//! The load beyond the tubes is 8 coordinates (e, y) with the same bodies as before on their Jacobian P (4 x 8):
55//! M_d q'' = Q_d - v_d - (k_b delta + c_b delta', k_l y + c_l y') - kappa P_h^T tau_a, and the joints carry the root
56//! alone: I_arm theta'' = tau_gear + g m_arm l_cg cos theta + k_b delta + c_b delta'. Energy: the root's and the
57//! distal kinetic energy, the springs' (k_b delta^2 + k_l y^2) / 2, the weights; the dampers' power is the loss
58//! `arm_bending`.
59//!
60//! With effects.arm_tube_inertia as well, the tube bends in the static shape of a cantilever under a tip load,
61//! psi = (3 xi^2 - xi^3) / 2 (psi(L_a) = 1), the mode consistent with the springs' 3 E I (Rayleigh), as the D3's.
62//! The tube is as much of the arm's mass as its inertia allows a uniform tube, m = min(m_arm, 3 I_arm / L_a^2), the
63//! rest a hub on the shoulder's axis. 33/140 of its mass (int psi^2) moves with the elbow's bend, so 33/140 m L_a^2 of
64//! its inertia and 3/8 m L_a of its first moment (int psi) go from the root to the elbow; out of its plane 33/140 of its
65//! mass moves with the elbow's move y, and the elbow block turns with the tube's tip slope, 3/2 y / L_a, about the arm's
66//! normal: its twist inertia (`mass.elbow_twist_inertia_kgm2`, and the forearms' share at the rods' ends, half the
67//! spacing off its middle) counts J (1.5 / L_a)^2 on y. The tube's kinetic energy in the plane, its sections at
68//! s theta' + psi(s) L_a delta', is m L_a^2 (theta'^2 / 3 + 2 int(xi psi) theta' delta' + int(psi^2) delta'^2) / 2,
69//! int(xi psi) = 11/40: in the root's and the elbow's angles theta and e = theta + delta that is
70//! I_r theta'^2 / 2 + B theta' e' + 33/280 m L_a^2 e'^2 with B = (11/40 - 33/140) m L_a^2 and
71//! I_r = I_arm - 33/140 m L_a^2 - 2 B. The coupling B joins the joints' equation to the elbows':
72//! (I_r - B^2 (M_d^-1)_ee) theta'' = tau + f_r - B (M_d^-1 f_d)_e (`joint_load_at`), then M_d q'' = f_d - B theta'' on
73//! the elbows' rows (`bend_rates`). (Moving only the mode's share of the inertia without B, as the D3 once did (it takes
74//! B the same way now, `sim-netlist`'s spatial delta), puts the root's inertia with the elbow held some 40 % low in the
75//! gearboxes' modes.) Until 22 November the tube took the first exact mode's shape (int phi^2 = 1/4, int phi = 0.3915,
76//! int(xi phi) = 0.2844, tip slope 1.3765) with the static stiffness: against the exact Euler-Bernoulli cantilever with
77//! the elbow at its tip (`beam::cantilever_first_frequency`) the arm's mode read 0.95 % low, and its sag under its own
78//! weight and the elbow's 2.3 % high; with the static shape +0.23 % and exact.
79
80use sim_components::joint::RotaryJoint;
81use sim_components::mech::ThermalFeedback;
82use sim_core::{
83    AxisInfo, Config, ConfigError, ENERGY_PARTS, LOSS_PREFIX, Label, Machine, MachineEntry, Mode, MotorInfo, Part,
84    Scene, Shape, SignalInfo, TORQUE_PARTS, ThermalPart,
85};
86
87pub static ENTRY: MachineEntry = MachineEntry {
88    id: "delta-h4",
89    key: "machine-delta-h4",
90    default_config: include_str!("../default.toml"),
91    i18n: &[("en", include_str!("../i18n/en.ftl")), ("de", include_str!("../i18n/de.ftl"))],
92    build,
93    suite_configs,
94};
95
96const G: f64 = 9.80665;
97
98/// Effects that take energy out or put it in; the standard suite runs with them off.
99pub const LOSSY_EFFECTS: [&str; 7] = [
100    "joint_friction",
101    "motor_friction",
102    "gearbox_drag",
103    "gearbox_lost_motion",
104    "gearbox_efficiency",
105    "torque_ripple",
106    "holding_brake",
107];
108
109fn build(cfg: &Config) -> Result<Box<dyn Machine>, ConfigError> {
110    sim_components::base::mount(cfg, Box::new(H4::new(cfg)?))
111}
112
113/// The start pose and the cycle's targets moved by `dz` in z, the tool's turn kept.
114fn lowered(cfg: &mut Config, dz: f64) {
115    let s = cfg.f64s("start.pose").unwrap();
116    cfg.set_text(&format!("start.pose = [{:?}, {:?}, {:?}, {:?}]", s[0], s[1], s[2] + dz, s[3])).unwrap();
117    let segments: Vec<String> = cfg
118        .array("cycle.segment")
119        .unwrap()
120        .iter()
121        .map(|s| {
122            let t: Vec<f64> = s["target"].as_array().unwrap().iter().map(|v| v.as_float().unwrap()).collect();
123            format!(
124                "{{ target = [{:?}, {:?}, {:?}, {:?}], dwell_s = {:?}, payload = {} }}",
125                t[0],
126                t[1],
127                t[2] + dz,
128                t[3],
129                s["dwell_s"].as_float().unwrap(),
130                s["payload"].as_bool().unwrap()
131            )
132        })
133        .collect();
134    cfg.set_text(&format!("cycle.segment = [{}]", segments.join(", "))).unwrap();
135}
136
137/// The default config with every loss switched off.
138pub fn lossless_config() -> Config {
139    let mut cfg = ENTRY.config();
140    for effect in LOSSY_EFFECTS {
141        cfg.set_text(&format!("effects.{effect} = false")).unwrap();
142    }
143    for damping in ["gearbox.damping_nm_s_rad", "joint.stop_damping_nm_s_rad", "plate.amplifier_damping_nm_s_rad"] {
144        cfg.set_text(&format!("{damping} = 0.0")).unwrap();
145    }
146    cfg
147}
148
149/// Loss-free rigid and elastic models, with and without the payload; the elastic ones with the amplifier's spring (and
150/// its backlash) and, with the payload, part heating and the temperature feedback (no loss, so the gearboxes stay at
151/// ambient).
152///
153/// As on the D3, their working range, start pose and cycle lie lower than the default's, here by 200 mm (top 950 mm
154/// below the shoulders, the suite's middle pose 1175 mm down): held by constant motor torques, as the suite holds it
155/// for 10 s after a pulse, the plate is unstable in its vertical mode in the upper part of the range, where its weight
156/// pulls harder through the Jacobian the further it sinks (the potential's second derivative, by hand at the centre with
157/// the lumped forearms, 9.8 kg of weight on the plate: -4.7 N m/rad at 975 mm down, +5.45 at 1175 mm; see
158/// `the_vertical_mode_under_constant_torques_is_unstable_high_up`). The drives' position loops hold it.
159fn suite_configs() -> Vec<Config> {
160    let mut out = Vec::new();
161    for (elastic, payload) in [(false, true), (false, false), (true, true), (true, false)] {
162        let mut cfg = lossless_config();
163        cfg.set_text("workspace.top_z_m = -0.95").unwrap();
164        lowered(&mut cfg, -0.2);
165        cfg.set_text(&format!("effects.joint_elasticity = {elastic}")).unwrap();
166        cfg.set_text(&format!("effects.amplifier_compliance = {elastic}")).unwrap();
167        cfg.set_text(&format!("effects.payload = {payload}")).unwrap();
168        cfg.set_text(&format!("effects.part_heating = {}", elastic && payload)).unwrap();
169        cfg.set_text(&format!("effects.thermal_feedback = {}", elastic && payload)).unwrap();
170        out.push(cfg);
171    }
172    out
173}
174
175type V3 = [f64; 3];
176type V4 = [f64; 4];
177type M4 = [[f64; 4]; 4];
178/// Mass matrix, velocity term and gravity in N coordinates: the arm angles (4) and with effects.arm_bending the elbows'
179/// moves out of the arms' planes (8).
180type LoadN<const N: usize> = ([[f64; N]; N], [f64; N], [f64; N]);
181/// In the arm angles.
182type Load = LoadN<4>;
183/// A pose x = (p, h) of the plate, with its Jacobians by the elbow angles and by the elbows' moves out of the planes.
184type Pose = (V4, M4, M4);
185
186fn dot(a: V3, b: V3) -> f64 {
187    a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
188}
189
190fn sub(a: V3, b: V3) -> V3 {
191    [a[0] - b[0], a[1] - b[1], a[2] - b[2]]
192}
193
194fn cross(a: V3, b: V3) -> V3 {
195    [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
196}
197
198fn norm(a: V3) -> f64 {
199    dot(a, a).sqrt()
200}
201
202fn dot4(a: V4, b: V4) -> f64 {
203    a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3]
204}
205
206fn mul4(m: &M4, v: V4) -> V4 {
207    std::array::from_fn(|r| dot4(m[r], v))
208}
209
210/// Solves m x = b by Gaussian elimination with partial pivoting; `None` where m is singular.
211fn solve4(m: &M4, b: V4) -> Option<V4> {
212    let (mut a, mut x) = (*m, b);
213    for c in 0..4 {
214        let p = (c..4).max_by(|&i, &j| a[i][c].abs().total_cmp(&a[j][c].abs()))?;
215        if !(a[p][c].abs() > 1e-300) {
216            return None;
217        }
218        a.swap(p, c);
219        x.swap(p, c);
220        for r in c + 1..4 {
221            let f = a[r][c] / a[c][c];
222            for k in c..4 {
223                a[r][k] -= f * a[c][k];
224            }
225            x[r] -= f * x[c];
226        }
227    }
228    for c in (0..4).rev() {
229        let s: f64 = (c + 1..4).map(|k| a[c][k] * x[k]).sum();
230        x[c] = (x[c] - s) / a[c][c];
231    }
232    x.iter().all(|v| v.is_finite()).then_some(x)
233}
234
235/// The inverse of a 4 x 4 matrix, column by column as `solve4` finds each, eliminated once; `None` where it is singular.
236fn inverse4(m: &M4) -> Option<M4> {
237    sim_components::chain::Lu::new(m)?.inverse()
238}
239
240/// A point mass m into `load`: its Jacobian jm (3 x N), its acceleration am at no acceleration of the coordinates, its
241/// weight down z at g.
242fn add_point<const N: usize>(load: &mut LoadN<N>, m: f64, jm: &[[f64; N]; 3], am: V3, g: f64) {
243    for r in 0..N {
244        for c in 0..N {
245            load.0[r][c] += m * (0..3).map(|k| jm[k][r] * jm[k][c]).sum::<f64>();
246        }
247        load.1[r] += m * (0..3).map(|k| jm[k][r] * am[k]).sum::<f64>();
248        load.2[r] -= m * g * jm[2][r];
249    }
250}
251
252/// A turn with inertia `inertia` at the rate row . q' into `load`, its acceleration a0 at no acceleration of the
253/// coordinates: no weight.
254fn add_turn<const N: usize>(load: &mut LoadN<N>, inertia: f64, row: [f64; N], a0: f64) {
255    for r in 0..N {
256        for c in 0..N {
257            load.0[r][c] += inertia * row[r] * row[c];
258        }
259        load.1[r] += inertia * row[r] * a0;
260    }
261}
262
263/// The arms' modes with the motors held (by their position loops), as the D3's `arm_modes` for four arms: per arm the
264/// gearbox's spring k_g from the motor to the arm's root (inertia `root`; `k_gear` one per arm), the bending spring k_b
265/// from the root to the elbow, and the rest of the machine as the mass matrix `distal` (8 x 8) in the elbow angles and
266/// the elbows' moves out of the arms' planes, each on its lateral spring k_l; `coupling` the tube's inertia that joins
267/// each root to its elbow (`H4::tube_coupling`). `None` for a rigid spring (infinite
268/// stiffness: the two ends one body). The coordinates are (roots, elbow angles, elbow moves), the flexibility per arm
269/// K^-1 = [[1/k_g, 1/k_g], [1/k_g, 1/k_g + 1/k_b]] (root, elbow) and 1/k_l; with M = L L^T (Cholesky) the eigenvalues
270/// mu = 1/w^2 of the symmetric L^T K^-1 L, by Jacobi rotations, the shape v = K^-1 L z / mu. A rigid connection has
271/// mu = 0 and is no mode. Gravity's stiffness and the stops are left out. Returns w^2 and the shape per mode, lowest
272/// first.
273fn arm_modes(
274    (root, coupling): (f64, f64),
275    distal: &[Vec<f64>],
276    k_gear: Option<V4>,
277    k_bend: f64,
278    k_lateral: f64,
279) -> Vec<(f64, Vec<f64>)> {
280    let (fb, fl) = (1.0 / k_bend, 1.0 / k_lateral);
281    let n = 4 + distal.len();
282    let (mut m, mut f) = (vec![vec![0.0; n]; n], vec![vec![0.0; n]; n]);
283    for i in 0..4 {
284        m[i][i] = root;
285        (m[i][4 + i], m[4 + i][i]) = (coupling, coupling);
286        let fg = k_gear.map_or(0.0, |k| 1.0 / k[i]);
287        (f[i][i], f[i][4 + i], f[4 + i][i], f[4 + i][4 + i]) = (fg, fg, fg, fg + fb);
288        f[8 + i][8 + i] = fl;
289    }
290    for (r, row) in distal.iter().enumerate() {
291        m[4 + r][4..].copy_from_slice(row);
292    }
293    let mut l = vec![vec![0.0; n]; n];
294    for i in 0..n {
295        for j in 0..=i {
296            let s = m[i][j] - (0..j).map(|k| l[i][k] * l[j][k]).sum::<f64>();
297            l[i][j] = if i == j { s.max(0.0).sqrt() } else { s / l[j][j] };
298        }
299    }
300    let times = |a: &[Vec<f64>], b: &[Vec<f64>]| -> Vec<Vec<f64>> {
301        (0..n).map(|r| (0..n).map(|c| (0..n).map(|k| a[r][k] * b[k][c]).sum()).collect()).collect()
302    };
303    let lt: Vec<Vec<f64>> = (0..n).map(|r| (0..n).map(|c| l[c][r]).collect()).collect();
304    let fl_ = times(&f, &l);
305    let (mu, z) = symmetric_eigen(times(&lt, &fl_));
306    let largest = mu.iter().fold(0f64, |a, b| a.max(*b));
307    let mut out: Vec<(f64, Vec<f64>)> = (0..n)
308        .filter(|&k| mu[k] > 1e-9 * largest)
309        .map(|k| (1.0 / mu[k], (0..n).map(|r| (0..n).map(|c| fl_[r][c] * z[c][k]).sum::<f64>() / mu[k]).collect()))
310        .collect();
311    out.sort_by(|a, b| a.0.total_cmp(&b.0));
312    out
313}
314
315/// The eigenvalues and eigenvectors (columns) of a symmetric matrix, by cyclic Jacobi rotations.
316fn symmetric_eigen(mut a: Vec<Vec<f64>>) -> (Vec<f64>, Vec<Vec<f64>>) {
317    let n = a.len();
318    let mut v: Vec<Vec<f64>> = (0..n).map(|i| (0..n).map(|j| if i == j { 1.0 } else { 0.0 }).collect()).collect();
319    for _ in 0..50 {
320        let off: f64 = (0..n).flat_map(|p| (p + 1..n).map(move |q| (p, q))).map(|(p, q)| a[p][q] * a[p][q]).sum();
321        let diagonal: f64 = (0..n).map(|i| a[i][i] * a[i][i]).sum();
322        if !(off > 1e-30 * diagonal) {
323            break;
324        }
325        for p in 0..n {
326            for q in p + 1..n {
327                if a[p][q] == 0.0 {
328                    continue;
329                }
330                let theta = (a[q][q] - a[p][p]) / (2.0 * a[p][q]);
331                let t = theta.signum() / (theta.abs() + (theta * theta + 1.0).sqrt());
332                let c = 1.0 / (t * t + 1.0).sqrt();
333                let s = t * c;
334                for k in 0..n {
335                    (a[k][p], a[k][q]) = (c * a[k][p] - s * a[k][q], s * a[k][p] + c * a[k][q]);
336                }
337                for k in 0..n {
338                    (a[p][k], a[q][k]) = (c * a[p][k] - s * a[q][k], s * a[p][k] + c * a[q][k]);
339                    (v[k][p], v[k][q]) = (c * v[k][p] - s * v[k][q], s * v[k][p] + c * v[k][q]);
340                }
341            }
342        }
343    }
344    ((0..n).map(|i| a[i][i]).collect(), v)
345}
346
347/// The 2-norm condition number of the 4 x 4 Jacobian in (x, y, z, h): the square root of the largest over the smallest
348/// eigenvalue of J^T J. In h, the half slide, a part moves as far as the plate does in x, y or z: the tool's turn c,
349/// in rad, would weigh by the amplifier's ratio instead.
350pub fn condition_number(j: &M4) -> f64 {
351    let jtj: Vec<Vec<f64>> =
352        (0..4).map(|r| (0..4).map(|c| (0..4).map(|k| j[k][r] * j[k][c]).sum()).collect()).collect();
353    let (eigen, _) = symmetric_eigen(jtj);
354    let (smallest, largest) = eigen.iter().fold((f64::INFINITY, 0f64), |(lo, hi), e| (lo.min(*e), hi.max(*e)));
355    if smallest <= 0.0 || !smallest.is_finite() { f64::INFINITY } else { (largest / smallest).sqrt() }
356}
357
358/// Which side of the slide each leg's plate part is on: -1 for part A (arms 1 and 2), +1 for part B (arms 3 and 4).
359pub const SIDE: [f64; 4] = [-1.0, -1.0, 1.0, 1.0];
360
361/// The leg geometry and the kinematics, apart from masses and drives.
362#[derive(Debug, Clone)]
363pub struct Legs {
364    /// Base radius less plate radius, upper arm, forearm.
365    pub e: f64,
366    pub la: f64,
367    pub lb: f64,
368    /// cos and sin of the legs' azimuths, 0, 90, 180 and 270 degrees.
369    pub azimuth: [(f64, f64); 4],
370    /// The direction the parts slide along, d.
371    pub slide: V3,
372}
373
374impl Legs {
375    pub fn new(e: f64, la: f64, lb: f64) -> Self {
376        let azimuth = [0.0f64, 90.0, 180.0, 270.0].map(|deg| (deg.to_radians().cos(), deg.to_radians().sin()));
377        let s = std::f64::consts::FRAC_1_SQRT_2;
378        Self { e, la, lb, azimuth, slide: [s, -s, 0.0] }
379    }
380
381    /// A vector in leg i's frame turned into the base frame (R_z(phi_i) v), and back.
382    fn to_base(&self, i: usize, v: V3) -> V3 {
383        let (c, s) = self.azimuth[i];
384        [c * v[0] - s * v[1], s * v[0] + c * v[1], v[2]]
385    }
386    fn to_leg(&self, i: usize, v: V3) -> V3 {
387        let (c, s) = self.azimuth[i];
388        [c * v[0] + s * v[1], -s * v[0] + c * v[1], v[2]]
389    }
390
391    /// The elbow of leg i at arm angle t, and its first and second derivative by t.
392    pub fn elbow(&self, i: usize, t: f64) -> [V3; 3] {
393        let (s, c) = t.sin_cos();
394        let la = self.la;
395        [
396            self.to_base(i, [self.e + la * c, 0.0, -la * s]),
397            self.to_base(i, [-la * s, 0.0, -la * c]),
398            self.to_base(i, [-la * c, 0.0, la * s]),
399        ]
400    }
401
402    /// The direction of leg i's elbow axis: the rods of a pair are apart along it.
403    pub fn tangent(&self, i: usize) -> V3 {
404        self.to_base(i, [0.0, 1.0, 0.0])
405    }
406
407    /// Where leg i's forearm pair meets its plate part at x = (p, h), the plate radius folded into e.
408    pub fn end(&self, i: usize, x: V4) -> V3 {
409        std::array::from_fn(|k| x[k] + SIDE[i] * x[3] * self.slide[k])
410    }
411
412    /// The elbows at arm angles t, each moved by y_i along its tangent (the arms bent out of their planes).
413    pub fn elbows_moved(&self, t: V4, y: V4) -> [V3; 4] {
414        std::array::from_fn(|i| {
415            let (c, tg) = (self.elbow(i, t[i])[0], self.tangent(i));
416            std::array::from_fn(|k| c[k] + y[i] * tg[k])
417        })
418    }
419
420    /// Arm angles for x = (p, h), elbows out; `None` out of reach.
421    pub fn inverse(&self, x: V4) -> Option<V4> {
422        self.inverse_moved(x, [0.0; 4])
423    }
424
425    /// `inverse` with the elbows moved by y along their tangents: in the leg's frame the forearm's end is y_i nearer.
426    pub fn inverse_moved(&self, x: V4, moved: V4) -> Option<V4> {
427        let mut out = [0.0; 4];
428        for (i, t) in out.iter_mut().enumerate() {
429            let [lx, ly, lz] = self.to_leg(i, self.end(i, x));
430            let ly = ly - moved[i];
431            let (a, b, c) = (
432                -2.0 * self.la * (lx - self.e),
433                2.0 * self.la * lz,
434                (lx - self.e).powi(2) + ly * ly + lz * lz + self.la * self.la - self.lb * self.lb,
435            );
436            let d = a * a + b * b - c * c;
437            if !(d >= 0.0) {
438                return None;
439            }
440            // tan(t/2) = (-b - sqrt d) / (c - a) = (a + c) / (sqrt d - b): the second where the first's terms cancel
441            // (b < 0, the plate below the arms; near a = c it lost 2e-11 rad).
442            *t = 2.0 * if b < 0.0 { (a + c) / (d.sqrt() - b) } else { (-b - d.sqrt()) / (c - a) }.atan();
443        }
444        Some(out)
445    }
446
447    /// x = (p, h) for arm angles: Newton on the four constraints, from the lower point at a forearm's length from the
448    /// first three elbows (h = 0). `None` where the legs cannot be assembled with the forearms down from the elbows.
449    pub fn forward(&self, t: V4) -> Option<V4> {
450        self.forward_moved(t, [0.0; 4])
451    }
452
453    /// `forward` with the elbows moved by y along their tangents.
454    pub fn forward_moved(&self, t: V4, moves: V4) -> Option<V4> {
455        let moved = self.elbows_moved(t, moves);
456        let c: [V3; 3] = std::array::from_fn(|i| moved[i]);
457        let ex = sub(c[1], c[0]);
458        let d = norm(ex);
459        let ex = ex.map(|v| v / d);
460        let to3 = sub(c[2], c[0]);
461        let i = dot(ex, to3);
462        let ey = sub(to3, ex.map(|v| v * i));
463        let ey_len = norm(ey);
464        if !(d > 1e-12 && ey_len > 1e-12) {
465            return None;
466        }
467        let ey = ey.map(|v| v / ey_len);
468        let ez = cross(ex, ey);
469        let j = dot(ey, to3);
470        let x = d / 2.0;
471        let y = (i * i + j * j - 2.0 * i * x) / (2.0 * j);
472        // Short of reach at h = 0 the start is the three elbows' plane; Newton goes on from there.
473        let z = (self.lb * self.lb - x * x - y * y).max(0.0).sqrt();
474        let base: V3 = std::array::from_fn(|k| c[0][k] + x * ex[k] + y * ey[k]);
475        let (up, down): (V3, V3) =
476            (std::array::from_fn(|k| base[k] + z * ez[k]), std::array::from_fn(|k| base[k] - z * ez[k]));
477        let start = if up[2] < down[2] { up } else { down };
478        self.forward_from_moved(t, moves, [start[0], start[1], start[2], 0.0])
479    }
480
481    /// `forward` by Newton from `x`: J_x dx = -(|u_k|^2 - L_b^2) / 2.
482    pub fn forward_from(&self, t: V4, x: V4) -> Option<V4> {
483        self.forward_from_moved(t, [0.0; 4], x)
484    }
485
486    /// `forward_from` with the elbows moved by y along their tangents.
487    pub fn forward_from_moved(&self, t: V4, y: V4, mut x: V4) -> Option<V4> {
488        let lb2 = self.lb * self.lb;
489        for _ in 0..50 {
490            let (jx, ..) = self.constraint_moved(t, y, x);
491            let r: V4 = std::array::from_fn(|k| {
492                let u = [jx[k][0], jx[k][1], jx[k][2]];
493                -0.5 * (dot(u, u) - lb2)
494            });
495            let dx = solve4(&jx, r)?;
496            for k in 0..4 {
497                x[k] += dx[k];
498            }
499            if dx.iter().all(|v| v.abs() < 1e-14) {
500                break;
501            }
502        }
503        let (jx, ..) = self.constraint_moved(t, y, x);
504        (0..4)
505            .all(|k| {
506                let u = [jx[k][0], jx[k][1], jx[k][2]];
507                (dot(u, u) - lb2).abs() < 1e-9 * lb2 && u[2] < 0.0
508            })
509            .then_some(x)
510    }
511
512    /// J_x (rows: the forearm vectors u_k = q_k - c_k - y_k a_k and sigma_k u_k . d), the diagonal of J_q (u_k . dc_k/dt)
513    /// and that of the elbows' moves (u_k . a_k), the elbows moved by y along their axes a_k.
514    fn constraint_moved(&self, t: V4, y: V4, x: V4) -> (M4, V4, V4) {
515        let (mut jx, mut jq, mut jy) = ([[0.0; 4]; 4], [0.0; 4], [0.0; 4]);
516        for k in 0..4 {
517            let ([c, d1, _], a) = (self.elbow(k, t[k]), self.tangent(k));
518            let moved: V3 = std::array::from_fn(|i| c[i] + y[k] * a[i]);
519            let u = sub(self.end(k, x), moved);
520            jx[k] = [u[0], u[1], u[2], SIDE[k] * dot(u, self.slide)];
521            jq[k] = dot(u, d1);
522            jy[k] = dot(u, a);
523        }
524        (jx, jq, jy)
525    }
526
527    /// The Jacobian J[i][j] = dx_i / dtheta_j, x = (p, h), at arm angles t and x; `None` at a direct singularity.
528    pub fn jacobian(&self, t: V4, x: V4) -> Option<M4> {
529        self.jacobians(t, [0.0; 4], x).map(|(j, _)| j)
530    }
531
532    /// x's Jacobians by the arm angles and by the elbows' moves y along their axes, with the elbows moved by y:
533    /// J_x^-1 J_q and J_x^-1 diag(u_k . a_k).
534    pub fn jacobians(&self, t: V4, y: V4, x: V4) -> Option<(M4, M4)> {
535        let (jx, jq, jy) = self.constraint_moved(t, y, x);
536        let inv = inverse4(&jx)?;
537        let scaled = |d: V4| -> M4 { std::array::from_fn(|i| std::array::from_fn(|j| inv[i][j] * d[j])) };
538        Some((scaled(jq), scaled(jy)))
539    }
540
541    /// J' theta' = J_x^-1 w: the acceleration of x at arm speeds `wt` and no arm acceleration, x moving at `xv`.
542    pub fn velocity_term(&self, t: V4, x: V4, wt: V4, xv: V4) -> Option<V4> {
543        self.velocity_term_moved(t, [0.0; 4], x, wt, [0.0; 4], xv)
544    }
545
546    /// `velocity_term` with the elbows moved by y and moving at yv along their axes, which stay as they are:
547    /// w_k = theta_k'^2 (u_k . c_k'') - |q_k' - c_k' theta_k' - a_k y_k'|^2.
548    pub fn velocity_term_moved(&self, t: V4, y: V4, x: V4, wt: V4, yv: V4, xv: V4) -> Option<V4> {
549        let (jx, ..) = self.constraint_moved(t, y, x);
550        let w: V4 = std::array::from_fn(|k| {
551            let ([_, d1, d2], a) = (self.elbow(k, t[k]), self.tangent(k));
552            let rel: V3 =
553                std::array::from_fn(|i| xv[i] + SIDE[k] * xv[3] * self.slide[i] - d1[i] * wt[k] - a[i] * yv[k]);
554            wt[k] * wt[k] * dot([jx[k][0], jx[k][1], jx[k][2]], d2) - dot(rel, rel)
555        });
556        solve4(&jx, w)
557    }
558
559    /// The two rods of leg i's forearm pair, elbow end to plate end, at arm angle t and x, as drawn: `spacing` apart
560    /// along the elbow's axis, their ends at the base radius (the legs' elbow is at e, `r` the plate radius added back)
561    /// and at the plate part's.
562    pub fn rods(&self, i: usize, t: f64, x: V4, r: f64, spacing: f64) -> [(V3, V3); 2] {
563        self.rods_moved(i, t, 0.0, x, r, spacing)
564    }
565
566    /// `rods` with the elbow moved by y along its axis (the arm bent out of its plane).
567    pub fn rods_moved(&self, i: usize, t: f64, y: f64, x: V4, r: f64, spacing: f64) -> [(V3, V3); 2] {
568        let (c, sn) = self.azimuth[i];
569        let (at, tg) = (self.elbow(i, t)[0], self.tangent(i));
570        let elbow: V3 = std::array::from_fn(|k| at[k] + y * tg[k]);
571        let end = self.end(i, x);
572        let half = [-0.5 * spacing * sn, 0.5 * spacing * c, 0.0];
573        let (arm_end, plate_end) =
574            ([elbow[0] + r * c, elbow[1] + r * sn, elbow[2]], [end[0] + r * c, end[1] + r * sn, end[2]]);
575        [-1.0, 1.0].map(|side| {
576            (
577                std::array::from_fn(|k| arm_end[k] + side * half[k]),
578                std::array::from_fn(|k| plate_end[k] + side * half[k]),
579            )
580        })
581    }
582}
583
584/// The amplifier's spring between the slide and the tool (effects.amplifier_compliance), at the tool: N m/rad, N m s/rad,
585/// and half its play (effects.amplifier_backlash; 0 without), rad.
586#[derive(Debug, Clone, Copy)]
587pub struct Amplifier {
588    pub stiffness: f64,
589    pub damping: f64,
590    pub half_backlash: f64,
591}
592
593impl Amplifier {
594    /// The twist beyond the play, with its sign; 0 within the play.
595    fn beyond(&self, twist: f64) -> f64 {
596        (twist.abs() - self.half_backlash).max(0.0) * twist.signum()
597    }
598    fn contact(&self, twist: f64) -> bool {
599        self.half_backlash == 0.0 || twist.abs() > self.half_backlash
600    }
601    /// The torque on the tool at a twist (kappa h - phi) and its rate.
602    pub fn torque(&self, twist: f64, rate: f64) -> f64 {
603        if self.contact(twist) { self.stiffness * self.beyond(twist) + self.damping * rate } else { 0.0 }
604    }
605    pub fn energy(&self, twist: f64) -> f64 {
606        0.5 * self.stiffness * self.beyond(twist).powi(2)
607    }
608    pub fn loss_power(&self, twist: f64, rate: f64) -> f64 {
609        if self.contact(twist) { self.damping * rate * rate } else { 0.0 }
610    }
611}
612
613/// The upper arms' bending (effects.arm_bending): in the plane an arm turns in, a turn of the elbow against the root,
614/// N m/rad and N m s/rad; out of it, a move of the elbow along its axis, N/m and N s/m.
615#[derive(Debug, Clone, Copy)]
616struct Bending {
617    k: f64,
618    c: f64,
619    k_lateral: f64,
620    c_lateral: f64,
621}
622
623pub struct H4 {
624    legs: Legs,
625    /// The geometry as configured, for the scene: base and plate radius, the rods' spacing.
626    base_radius: f64,
627    plate_radius: f64,
628    rod_spacing: f64,
629    elastic: bool,
630    g: f64,
631    /// The arm's inertia about its joint and its m_LG, the elbow's share of the forearms included, rotor not.
632    arm_inertia: f64,
633    arm_moment: f64,
634    /// The arm split for its bend: inertia and first moment of the tube (at the root, about the joint) and of what sits
635    /// at the elbow (tip: the elbow block and the forearms' share), and the mass that moves with the elbow out of the
636    /// arm's plane. The two parts add up to `arm_inertia` and `arm_moment`.
637    root_inertia: f64,
638    root_moment: f64,
639    tip_inertia: f64,
640    tip_moment: f64,
641    m_lateral: f64,
642    /// What sits at the elbow as a point (the elbow block and the forearms' share), and with effects.arm_tube_inertia the
643    /// tube's mass and the elbow block's twist inertia (both 0 without it): the frame momentum takes them apart.
644    m_elbow: f64,
645    tube_mass: f64,
646    twist_inertia: f64,
647    /// B, the tube's inertia that joins each root to its elbow (effects.arm_tube_inertia, else 0), kg m^2.
648    tube_coupling: f64,
649    /// effects.arm_bending: the upper arms' bending.
650    bending: Option<Bending>,
651    /// The mass at each forearm's middle and its rods' spin inertia (both rods; effects.forearm_inertia, else 0).
652    m_rod_middle: f64,
653    /// Each forearm pair's mass and the share of it the inertia puts at the elbow (a sixth with the rods), for the
654    /// weight and the frame momentum, which take the rods as rods: their weight at the middles, half at each end.
655    m_forearms: f64,
656    forearm_share: f64,
657    /// Per leg, the forearm weight the lumped split puts at the elbow beyond the half a rod's weight has there
658    /// ((share - 1/2) m_fb; 0 with the rods): the weight takes it from the elbow to the plate's end.
659    weight_shift: f64,
660    rod_spin: f64,
661    /// Each plate part with its forearms' share, the carriage, the payload.
662    m_part: f64,
663    m_carriage: f64,
664    m_payload: f64,
665    /// The tool's turn per half slide, c / h, rad/m.
666    kappa: f64,
667    /// The tool, and the payload's, inertia about the tool's axis.
668    j_tool: f64,
669    j_payload: f64,
670    /// effects.amplifier_compliance.
671    amplifier: Option<Amplifier>,
672    payload_attached: bool,
673    brake_engaged: bool,
674    /// An obstacle's push on the tool (`Machine::set_tool_force`), held until changed.
675    push: V4,
676    joints: [RotaryJoint; 4],
677    thermal: Option<ThermalFeedback>,
678    /// The working range: radius, top, bottom sphere's centre height and radius; the condition number refused above.
679    radius: f64,
680    top: f64,
681    sphere: (f64, f64),
682    max_condition: f64,
683    axes: [AxisInfo; 4],
684    motors: [MotorInfo; 4],
685    /// `Machine::setpoint_slack`, worked out once (`rest_sag`).
686    rest_slack: f64,
687}
688
689// Elastic state: [theta 1..4, omega 1..4, rotor angle 1..4, rotor speed 1..4, brake 1..4], then with
690// effects.amplifier_compliance the tool's angle and speed, then with effects.arm_bending the arms' bend (4 turns of the
691// elbows against the roots, their 4 rates, the elbows' 4 moves out of the planes, their 4 rates). Rigid: [theta 1..4,
692// omega 1..4, brake 1..4], then the tool's and the bend.
693const N_ELASTIC: usize = 20;
694const N_RIGID: usize = 12;
695
696/// The losses of one moment: per joint its friction, its motor's friction with the brake, its gearbox; the stops, what
697/// the ripple gives off, the amplifier's damping, the arms' bending damping; and per joint the gearbox loss as a torque
698/// at the rotor.
699struct Losses {
700    powers: [f64; 16],
701    gear_at_rotor: V4,
702}
703
704impl H4 {
705    pub fn new(cfg: &Config) -> Result<Self, ConfigError> {
706        let base_radius = cfg.positive("geometry.base_radius_m")?;
707        let plate_radius = cfg.non_negative("geometry.plate_radius_m")?;
708        let (la, lb) = (cfg.positive("geometry.upper_arm_m")?, cfg.positive("geometry.forearm_m")?);
709        if lb <= la {
710            return Err(ConfigError::Invalid("geometry.forearm_m".into()));
711        }
712        let share = cfg.non_negative("mass.forearm_elbow_share")?;
713        if share > 1.0 {
714            return Err(ConfigError::Invalid("mass.forearm_elbow_share".into()));
715        }
716        let (m_arm, cg, i_arm) = (
717            cfg.positive("mass.upper_arm_kg")?,
718            cfg.non_negative("mass.upper_arm_cg_m")?,
719            cfg.positive("mass.upper_arm_inertia_kgm2")?,
720        );
721        let (m_elbow, m_fb) = (cfg.non_negative("mass.elbow_kg")?, cfg.non_negative("mass.forearm_pair_kg")?);
722        // A rigid rod: a sixth at each end, two thirds at its middle (see the crate's doc).
723        let rods = cfg.bool("effects.forearm_inertia")?;
724        let (share, middle) = if rods { (1.0 / 6.0, 2.0 / 3.0) } else { (share, 0.0) };
725        let elbow = m_elbow + share * m_fb;
726        let spin = cfg.non_negative("mass.forearm_rod_spin_inertia_kgm2")?;
727        let kappa = cfg.positive("plate.gear_ratio")? / cfg.positive("plate.pinion_radius_m")?;
728        let amplifier = Amplifier {
729            stiffness: cfg.positive("plate.amplifier_stiffness_nm_rad")?,
730            damping: cfg.non_negative("plate.amplifier_damping_nm_s_rad")?,
731            half_backlash: 0.5 * cfg.non_negative("plate.amplifier_backlash_rad")?,
732        };
733        let amplifier = Amplifier {
734            half_backlash: if cfg.bool("effects.amplifier_backlash")? { amplifier.half_backlash } else { 0.0 },
735            ..amplifier
736        };
737        let (radius, top) = (cfg.positive("workspace.radius_m")?, cfg.f64("workspace.top_z_m")?);
738        let (edge, centre) = (cfg.positive("workspace.height_edge_m")?, cfg.positive("workspace.height_centre_m")?);
739        if centre < edge {
740            return Err(ConfigError::Invalid("workspace.height_centre_m".into()));
741        }
742        // The bottom: a sphere through the centre's depth and the edge's ring; flat where both heights are the same.
743        let sag = centre - edge;
744        let sphere = if sag > 0.0 {
745            let r = (radius * radius + sag * sag) / (2.0 * sag);
746            (top - centre + r, r)
747        } else {
748            (f64::INFINITY, f64::INFINITY)
749        };
750        let joint = RotaryJoint::from_config(cfg)?;
751        let axis = |id: &'static str, key: &'static str, min: f64, max: f64| -> Result<AxisInfo, ConfigError> {
752            Ok(AxisInfo {
753                id,
754                key,
755                unit: "m",
756                min,
757                max,
758                max_vel: cfg.positive(&format!("axis.{id}.max_velocity_m_s"))?,
759                max_acc: cfg.positive(&format!("axis.{id}.max_acceleration_m_s2"))?,
760                max_jerk: cfg.positive(&format!("axis.{id}.max_jerk_m_s3"))?,
761            })
762        };
763        let (c_min, c_max) =
764            (cfg.f64("axis.c.min_angle_deg")?.to_radians(), cfg.f64("axis.c.max_angle_deg")?.to_radians());
765        if c_min >= c_max {
766            return Err(ConfigError::Invalid("axis.c.max_angle_deg".into()));
767        }
768        // effects.arm_bending: a config without the switch reads it as off. The tube stays with the root, the elbow
769        // block and the forearms' share sit at the elbow.
770        let bending = if cfg.get("effects.arm_bending").is_ok() && cfg.bool("effects.arm_bending")? {
771            // The tube a cantilever from the shoulder, round (E I alike both ways): its tip deflection F L^3 / (3 E I)
772            // as a turn about the shoulder in the plane, as a move along the elbow's axis out of it.
773            let (d, wall) = (cfg.positive("upper_arm.tube_outer_diameter_m")?, cfg.positive("upper_arm.tube_wall_m")?);
774            if 2.0 * wall > d {
775                return Err(ConfigError::Invalid("upper_arm.tube_wall_m".into()));
776            }
777            let ei = cfg.positive("upper_arm.youngs_modulus_pa")? * std::f64::consts::PI / 64.0
778                * (d.powi(4) - (d - 2.0 * wall).powi(4));
779            Some(Bending {
780                k: 3.0 * ei / la,
781                c: cfg.non_negative("upper_arm.bending_damping_nm_s_rad")?,
782                k_lateral: 3.0 * ei / la.powi(3),
783                c_lateral: cfg.non_negative("upper_arm.lateral_damping_n_s_m")?,
784            })
785        } else {
786            None
787        };
788        // effects.arm_tube_inertia (with the bending arms, see the crate's doc); a config without the switch reads it
789        // as off.
790        let rod_spacing = cfg.non_negative("geometry.forearm_spacing_m")?;
791        let (mut root_inertia, mut root_moment, mut tip_inertia, mut tip_moment, mut m_lateral) =
792            (i_arm, m_arm * cg, la * la * elbow, la * elbow, elbow);
793        let (mut tube_mass, mut twist_inertia, mut tube_coupling) = (0.0, 0.0, 0.0);
794        if bending.is_some() && cfg.get("effects.arm_tube_inertia").is_ok() && cfg.bool("effects.arm_tube_inertia")? {
795            use sim_components::beam::{STATIC_SHAPE_MASS, STATIC_SHAPE_PARTICIPATION, STATIC_SHAPE_TIP_SLOPE};
796            // The tube: as much of the arm's mass as its inertia allows a uniform tube (m L^2 / 3), the rest a hub on
797            // the shoulder's axis. The root keeps I_arm - 33/140 m_t L^2 - 2 B >= 0.0571 I_arm.
798            let m_tube = m_arm.min(3.0 * i_arm / (la * la));
799            let (inertia, moment) = (STATIC_SHAPE_MASS * m_tube * la * la, STATIC_SHAPE_PARTICIPATION * m_tube * la);
800            tube_coupling = (TUBE_MOMENT - STATIC_SHAPE_MASS) * m_tube * la * la;
801            if moment > root_moment {
802                return Err(ConfigError::Invalid("mass.upper_arm_inertia_kgm2".into()));
803            }
804            (root_inertia, root_moment, tip_inertia, tip_moment) = (
805                root_inertia - inertia - 2.0 * tube_coupling,
806                root_moment - moment,
807                tip_inertia + inertia,
808                tip_moment + moment,
809            );
810            twist_inertia =
811                cfg.non_negative("mass.elbow_twist_inertia_kgm2")? + share * m_fb * rod_spacing * rod_spacing / 4.0;
812            m_lateral += STATIC_SHAPE_MASS * m_tube + twist_inertia * (STATIC_SHAPE_TIP_SLOPE / la).powi(2);
813            tube_mass = m_tube;
814        }
815        let mut h4 = Self {
816            legs: Legs::new(base_radius - plate_radius, la, lb),
817            root_inertia,
818            root_moment,
819            tip_inertia,
820            tip_moment,
821            m_lateral,
822            m_elbow: elbow,
823            tube_mass,
824            twist_inertia,
825            tube_coupling,
826            bending,
827            base_radius,
828            plate_radius,
829            rod_spacing,
830            elastic: cfg.bool("effects.joint_elasticity")?,
831            g: if cfg.bool("effects.gravity")? { G } else { 0.0 },
832            arm_inertia: i_arm + la * la * elbow,
833            arm_moment: m_arm * cg + la * elbow,
834            m_rod_middle: middle * m_fb,
835            m_forearms: m_fb,
836            forearm_share: share,
837            weight_shift: if rods { 0.0 } else { (share - 0.5) * m_fb },
838            rod_spin: if rods { 2.0 * spin } else { 0.0 },
839            m_part: cfg.non_negative("mass.plate_part_kg")? + 2.0 * (1.0 - share - middle) * m_fb,
840            m_carriage: cfg.positive("mass.carriage_kg")?,
841            m_payload: if cfg.bool("effects.payload")? { cfg.non_negative("mass.payload_kg")? } else { 0.0 },
842            kappa,
843            j_tool: cfg.positive("tool.inertia_kgm2")?,
844            j_payload: if cfg.bool("effects.payload")? { cfg.non_negative("tool.payload_inertia_kgm2")? } else { 0.0 },
845            amplifier: cfg.bool("effects.amplifier_compliance")?.then_some(amplifier),
846            payload_attached: true,
847            brake_engaged: false,
848            push: [0.0; 4],
849            joints: [joint.clone(), joint.clone(), joint.clone(), joint],
850            thermal: ThermalFeedback::from_config(cfg)?,
851            radius,
852            top,
853            sphere,
854            max_condition: cfg.positive("workspace.max_condition_number")?,
855            axes: [
856                axis("x", "axis-x", -radius, radius)?,
857                axis("y", "axis-y", -radius, radius)?,
858                axis("z", "axis-z", top - centre, top)?,
859                AxisInfo {
860                    id: "c",
861                    key: "axis-c",
862                    unit: "rad",
863                    min: c_min,
864                    max: c_max,
865                    max_vel: cfg.positive("axis.c.max_velocity_rad_s")?,
866                    max_acc: cfg.positive("axis.c.max_acceleration_rad_s2")?,
867                    max_jerk: cfg.positive("axis.c.max_jerk_rad_s3")?,
868                },
869            ],
870            motors: [
871                MotorInfo { id: "1", key: "motor-arm-1" },
872                MotorInfo { id: "2", key: "motor-arm-2" },
873                MotorInfo { id: "3", key: "motor-arm-3" },
874                MotorInfo { id: "4", key: "motor-arm-4" },
875            ],
876            rest_slack: 0.0,
877        };
878        h4.rest_slack = h4.rest_sag();
879        Ok(h4)
880    }
881
882    pub fn legs(&self) -> &Legs {
883        &self.legs
884    }
885
886    /// The tool's turn per half slide, c / h, rad/m.
887    pub fn kappa(&self) -> f64 {
888        self.kappa
889    }
890
891    fn ratio(&self) -> f64 {
892        self.joints[0].ratio()
893    }
894
895    /// The mass at the tool's point: carriage and, while held, the payload.
896    pub fn carried(&self) -> f64 {
897        self.m_carriage + if self.payload_attached { self.m_payload } else { 0.0 }
898    }
899
900    /// Each plate part with its forearms' share.
901    pub fn part_mass(&self) -> f64 {
902        self.m_part
903    }
904
905    /// What the tool's turn moves: tool and, while held, the payload.
906    pub fn tool_inertia(&self) -> f64 {
907        self.j_tool + if self.payload_attached { self.j_payload } else { 0.0 }
908    }
909
910    /// The arm's inertia about its joint and its m_LG (the gravity torque is g m_LG cos theta), rotor not included.
911    pub fn arm_inertia(&self) -> f64 {
912        self.arm_inertia
913    }
914    pub fn arm_moment(&self) -> f64 {
915        self.arm_moment
916    }
917
918    /// x = (p, h) of a tool pose.
919    fn coordinates(&self, tool: &[f64]) -> V4 {
920        [tool[0], tool[1], tool[2], tool[3] / self.kappa]
921    }
922
923    /// Arm angles and speeds of a state: at the joints, the gearboxes' output side.
924    fn arms(&self, s: &[f64]) -> (V4, V4) {
925        ([s[0], s[1], s[2], s[3]], [s[4], s[5], s[6], s[7]])
926    }
927
928    /// Rotor angles and speeds of a state.
929    fn rotors(&self, s: &[f64]) -> (V4, V4) {
930        if self.elastic {
931            ([s[8], s[9], s[10], s[11]], [s[12], s[13], s[14], s[15]])
932        } else {
933            let i = self.ratio();
934            ([s[0] * i, s[1] * i, s[2] * i, s[3] * i], [s[4] * i, s[5] * i, s[6] * i, s[7] * i])
935        }
936    }
937
938    fn brakes(&self, s: &[f64]) -> V4 {
939        let at = if self.elastic { 16 } else { 8 };
940        [s[at], s[at + 1], s[at + 2], s[at + 3]]
941    }
942
943    /// Where the tool's angle and speed sit in the state with effects.amplifier_compliance.
944    fn turn_at(&self) -> usize {
945        if self.elastic { N_ELASTIC } else { N_RIGID }
946    }
947
948    /// Where the arms' bend sits in the state (effects.arm_bending), after the tool's angle and speed.
949    fn bend_at(&self) -> usize {
950        self.turn_at() + if self.amplifier.is_some() { 2 } else { 0 }
951    }
952
953    /// The arms' bend (the elbow's turn against the arm's root) and its rate; zero with rigid links.
954    fn bend(&self, s: &[f64]) -> (V4, V4) {
955        if self.bending.is_none() {
956            return ([0.0; 4], [0.0; 4]);
957        }
958        let at = self.bend_at();
959        ([s[at], s[at + 1], s[at + 2], s[at + 3]], [s[at + 4], s[at + 5], s[at + 6], s[at + 7]])
960    }
961
962    /// The elbows' moves out of the arms' planes, along their axes, and their rates; zero with rigid links.
963    fn lateral(&self, s: &[f64]) -> (V4, V4) {
964        if self.bending.is_none() {
965            return ([0.0; 4], [0.0; 4]);
966        }
967        let at = self.bend_at() + 8;
968        ([s[at], s[at + 1], s[at + 2], s[at + 3]], [s[at + 4], s[at + 5], s[at + 6], s[at + 7]])
969    }
970
971    /// The push at the tool on the N rates from `at` in the state: its virtual power per unit of each
972    /// (`sim_core::tool_force_on_rates`); zero without a push.
973    fn pushed<const N: usize>(&self, s: &[f64], at: usize) -> [f64; N] {
974        sim_core::tool_force_on_rates(self, s, &self.push, at..at + N)
975            .map_or([0.0; N], |q| std::array::from_fn(|i| q[i]))
976    }
977
978    /// The push on the arms: none with bending arms, where it acts beyond the bend (`distal`).
979    fn pushed_on_arms(&self, s: &[f64]) -> V4 {
980        if self.bending.is_some() { [0.0; 4] } else { self.pushed(s, 4) }
981    }
982
983    /// The elbow angles and speeds, which the kinematics take: the arms' plus their bend.
984    fn elbows(&self, s: &[f64]) -> (V4, V4) {
985        let ((t, w), (b, r)) = (self.arms(s), self.bend(s));
986        (std::array::from_fn(|k| t[k] + b[k]), std::array::from_fn(|k| w[k] + r[k]))
987    }
988
989    /// x and the Jacobian at arm angles t; NaN where the legs cannot be assembled.
990    fn pose(&self, t: V4) -> (V4, M4) {
991        let (x, j, _) = self.pose_moved(t, [0.0; 4]);
992        (x, j)
993    }
994
995    /// `pose` with the elbows moved by y out of the arms' planes, and the Jacobian by those moves.
996    fn pose_moved(&self, t: V4, y: V4) -> Pose {
997        self.legs
998            .forward_moved(t, y)
999            .and_then(|x| {
1000                let (j, jy) = self.legs.jacobians(t, y, x)?;
1001                Some((x, j, jy))
1002            })
1003            .unwrap_or(([f64::NAN; 4], [[f64::NAN; 4]; 4], [[f64::NAN; 4]; 4]))
1004    }
1005
1006    /// The pose at state s: of the elbows' angles (the arms' plus their bend) and moves.
1007    fn pose_at(&self, s: &[f64]) -> Pose {
1008        self.pose_moved(self.elbows(s).0, self.lateral(s).0)
1009    }
1010
1011    /// The slide's turn kappa h and its rate at state s, the pose (`pose_at`) known.
1012    fn slide_of(&self, s: &[f64], (x, j, jy): &Pose) -> (f64, f64) {
1013        let ((_, w), (_, yv)) = (self.elbows(s), self.lateral(s));
1014        (self.kappa * x[3], self.kappa * (dot4(j[3], w) + dot4(jy[3], yv)))
1015    }
1016
1017    /// The amplifier's twist kappa h - phi and its rate; zero without effects.amplifier_compliance.
1018    fn twist(&self, s: &[f64]) -> (f64, f64) {
1019        if self.amplifier.is_none() {
1020            return (0.0, 0.0);
1021        }
1022        self.twist_at(s, &self.pose_at(s))
1023    }
1024
1025    /// `twist` with the pose (`pose_at`) known.
1026    fn twist_at(&self, s: &[f64], pose: &Pose) -> (f64, f64) {
1027        let at = self.turn_at();
1028        let (slide, rate) = self.slide_of(s, pose);
1029        (slide - s[at], rate - s[at + 1])
1030    }
1031
1032    /// The amplifier's torque on the tool, the pose (`pose_at`) known; zero without effects.amplifier_compliance.
1033    fn amplifier_torque_at(&self, s: &[f64], pose: &Pose) -> f64 {
1034        self.amplifier.map_or(0.0, |a| {
1035            let (twist, rate) = self.twist_at(s, pose);
1036            a.torque(twist, rate)
1037        })
1038    }
1039
1040    /// The load's mass matrix M, velocity term and gravity Q_g at arm angles t and speeds w: the two plate parts, the
1041    /// mass `carried` at the tool's point, the tool's turn with the inertia `spin` (0 where the tool is a body of its
1042    /// own), the rods' middles and spin (effects.forearm_inertia), the arms.
1043    pub fn load_at(&self, t: V4, w: V4, carried: f64, spin: f64) -> Load {
1044        let (x, j) = self.pose(t);
1045        self.load_with(t, x, j, w, carried, spin)
1046    }
1047
1048    /// `load_at` with x and the Jacobian known.
1049    fn load_with(&self, t: V4, x: V4, j: M4, w: V4, carried: f64, spin: f64) -> Load {
1050        self.load_n::<4>(t, [0.0; 4], (x, j, [[0.0; 4]; 4]), w, [0.0; 4], carried, spin, true)
1051    }
1052
1053    /// `load_at` in N coordinates, at the pose (`pose_moved`) of the elbow angles t and moves y: the elbow angles t
1054    /// (speeds w) and, with N = 8, the elbows' moves y out of the arms' planes along their axes (rates yv). Each body
1055    /// (the plate's two parts, the carriage and payload, the rods' middles, the tool's turn, and on the moves the
1056    /// elbows) counts with its Jacobian P (3 x N): m P^T P in the mass matrix, m P^T a0 in the velocity term (a0 its
1057    /// acceleration at no acceleration of the coordinates), -m g P_z in the gravity. `root` takes the whole arm on the
1058    /// angles (`arm_inertia`, `arm_moment`), else only what lies beyond the tubes (`tip_inertia`, `tip_moment`: what
1059    /// the bending springs carry).
1060    fn load_n<const N: usize>(
1061        &self,
1062        t: V4,
1063        y: V4,
1064        (x, j, jy): Pose,
1065        w: V4,
1066        yv: V4,
1067        carried: f64,
1068        spin: f64,
1069        root: bool,
1070    ) -> LoadN<N> {
1071        // x's Jacobian by the coordinates: the elbow angles, then the moves.
1072        let jx: [[f64; N]; 4] =
1073            std::array::from_fn(|r| std::array::from_fn(|c| if c < 4 { j[r][c] } else { jy[r][c - 4] }));
1074        let qv: [f64; N] = std::array::from_fn(|c| if c < 4 { w[c] } else { yv[c - 4] });
1075        let xv: V4 = std::array::from_fn(|r| (0..N).map(|c| jx[r][c] * qv[c]).sum());
1076        let a0 = self.legs.velocity_term_moved(t, y, x, w, yv, xv).unwrap_or([f64::NAN; 4]);
1077        let d = self.legs.slide;
1078        // A point at p + side h d: its Jacobian and its acceleration at no acceleration of the coordinates.
1079        let point = |side: f64| -> ([[f64; N]; 3], V3) {
1080            (
1081                std::array::from_fn(|r| std::array::from_fn(|c| jx[r][c] + side * d[r] * jx[3][c])),
1082                std::array::from_fn(|r| a0[r] + side * d[r] * a0[3]),
1083            )
1084        };
1085        let mut load = ([[0.0; N]; N], [0.0; N], [0.0; N]);
1086        for side in [-1.0, 1.0] {
1087            let (jp, ap) = point(side);
1088            add_point(&mut load, self.m_part, &jp, ap, self.g);
1089        }
1090        let (jp, ap) = point(0.0);
1091        add_point(&mut load, carried, &jp, ap, self.g);
1092        add_turn(&mut load, spin * self.kappa * self.kappa, jx[3], a0[3]);
1093        let (inertia, moment) =
1094            if root { (self.arm_inertia, self.arm_moment) } else { (self.tip_inertia, self.tip_moment) };
1095        for i in 0..4 {
1096            load.0[i][i] += inertia;
1097            load.2[i] += self.g * moment * t[i].cos();
1098            if N == 8 {
1099                // Along its axis the elbow mass has no acceleration at none of the coordinates', and no weight.
1100                load.0[4 + i][4 + i] += self.m_lateral;
1101            }
1102            if self.weight_shift != 0.0 {
1103                // The lumped forearms' weight at their middles: the split's excess at the elbow weighs on the plate end.
1104                load.2[i] -= self.g * self.weight_shift * self.legs.la * t[i].cos();
1105                let (jq, _) = point(SIDE[i]);
1106                (0..N).for_each(|c| load.2[c] -= self.weight_shift * self.g * jq[2][c]);
1107            }
1108            if self.m_rod_middle == 0.0 && self.rod_spin == 0.0 {
1109                continue;
1110            }
1111            // The elbow's Jacobian: dc/dtheta on its own angle, its axis on its move; c'' = d2 w^2 at no acceleration.
1112            let ([elbow, d1, d2], axis) = (self.legs.elbow(i, t[i]), self.legs.tangent(i));
1113            let (jq, aq) = point(SIDE[i]);
1114            let je: [[f64; N]; 3] = std::array::from_fn(|r| {
1115                std::array::from_fn(|c| {
1116                    if c == i {
1117                        d1[r]
1118                    } else if c == 4 + i {
1119                        axis[r]
1120                    } else {
1121                        0.0
1122                    }
1123                })
1124            });
1125            let ae = d2.map(|v| v * w[i] * w[i]);
1126            if self.m_rod_middle > 0.0 {
1127                let jm = std::array::from_fn(|r| std::array::from_fn(|c| 0.5 * (jq[r][c] + je[r][c])));
1128                add_point(&mut load, self.m_rod_middle, &jm, std::array::from_fn(|k| 0.5 * (aq[k] + ae[k])), self.g);
1129            }
1130            if self.rod_spin > 0.0 {
1131                let ju = std::array::from_fn(|r| std::array::from_fn(|c| jq[r][c] - je[r][c]));
1132                let accel = std::array::from_fn(|k| aq[k] - ae[k]);
1133                let moved: V3 = std::array::from_fn(|k| elbow[k] + y[i] * axis[k]);
1134                self.add_spin(&mut load, axis, sub(self.legs.end(i, x), moved), &ju, &qv, accel);
1135            }
1136        }
1137        load
1138    }
1139
1140    /// The spin of a forearm pair's rods about their own axis into `load`, as the D3's: the parallelogram keeps the
1141    /// pair's plane through the elbow's axis a and the forearm u, so a rod turns about u as that plane does. With
1142    /// sigma = a . u, n = a . (u' x u) and L = |u|, the spin is s = -sigma n / (L (L^2 - sigma^2)) = g . q',
1143    /// g = -sigma / (L (L^2 - sigma^2)) J_u^T (u x a); it adds I g g^T to the mass matrix and
1144    /// I (s0' g + s J_u^T (u' x u) / L^3) to the velocity term (s0' the spin's rate at no acceleration of the
1145    /// coordinates, u'' = `accel`).
1146    fn add_spin<const N: usize>(&self, load: &mut LoadN<N>, a: V3, u: V3, ju: &[[f64; N]; 3], w: &[f64; N], accel: V3) {
1147        let l = self.legs.lb;
1148        let du: V3 = std::array::from_fn(|r| (0..N).map(|c| ju[r][c] * w[c]).sum());
1149        let (sigma, n) = (dot(a, u), dot(a, cross(du, u)));
1150        let d = l * l - sigma * sigma;
1151        let s = -sigma * n / (l * d);
1152        let axis = cross(u, a);
1153        let g: [f64; N] = std::array::from_fn(|c| -sigma / (l * d) * (0..3).map(|k| ju[k][c] * axis[k]).sum::<f64>());
1154        let (dsigma, dn) = (dot(a, du), dot(a, cross(accel, u)));
1155        let ds = -(dsigma * n + sigma * dn) / (l * d) - 2.0 * sigma * sigma * dsigma * n / (l * d * d);
1156        let turn = cross(du, u).map(|v| v / l.powi(3));
1157        for r in 0..N {
1158            for c in 0..N {
1159                load.0[r][c] += self.rod_spin * g[r] * g[c];
1160            }
1161            load.1[r] += self.rod_spin * (ds * g[r] + s * (0..3).map(|k| ju[k][r] * turn[k]).sum::<f64>());
1162        }
1163    }
1164
1165    /// The rigid model's load: the tool turning with the slide.
1166    fn rigid_load(&self, t: V4, w: V4) -> Load {
1167        self.load_at(t, w, self.carried(), self.tool_inertia())
1168    }
1169
1170    /// What the joints carry at state s: the rigid model's load, or with effects.amplifier_compliance the load without
1171    /// the tool's turn and the amplifier's torque through the slide, kappa J_h^T tau_a, in the velocity term. With
1172    /// bending arms only the tubes are on the joints, and the springs' torque stands in for the rest: its weight Q_d in
1173    /// the gravity, the remainder in the velocity term (so that the torque breakdown shows the weight as gravity).
1174    fn joint_load(&self, s: &[f64]) -> Load {
1175        let (t, w) = self.arms(s);
1176        if self.amplifier.is_none() && self.bending.is_none() {
1177            return self.rigid_load(t, w);
1178        }
1179        self.joint_load_at(s, &self.pose_at(s))
1180    }
1181
1182    /// `joint_load` with effects.amplifier_compliance or bending arms, the pose (`pose_at`) known.
1183    fn joint_load_at(&self, s: &[f64], pose: &Pose) -> Load {
1184        let (t, w) = self.arms(s);
1185        if let Some(b) = self.bending {
1186            let ((e, _), (bend, rate), (y, _)) = (self.elbows(s), self.bend(s), self.lateral(s));
1187            let (.., tip) = self.load_n::<8>(e, y, *pose, [0.0; 4], [0.0; 4], self.carried(), 0.0, false);
1188            let mut mass: M4 =
1189                std::array::from_fn(|r| std::array::from_fn(|c| if r == c { self.root_inertia } else { 0.0 }));
1190            let gravity = std::array::from_fn(|i| self.g * self.root_moment * t[i].cos() + tip[i]);
1191            let mut velocity: V4 = std::array::from_fn(|i| tip[i] - b.k * bend[i] - b.c * rate[i]);
1192            if self.tube_coupling > 0.0 {
1193                // The elbows' equation solved for them: (I_r - B^2 (M_d^-1)_ee) theta'' = f_r - B (M_d^-1 f_d)_e.
1194                let (m, f) = self.distal(s, pose, b);
1195                let inv = sim_components::chain::Lu::new(&m).and_then(|lu| lu.inverse()).unwrap_or([[f64::NAN; 8]; 8]);
1196                let bb = self.tube_coupling;
1197                for r in 0..4 {
1198                    for c in 0..4 {
1199                        mass[r][c] -= bb * bb * inv[r][c];
1200                    }
1201                    velocity[r] += bb * (0..8).map(|c| inv[r][c] * f[c]).sum::<f64>();
1202                }
1203            }
1204            return (mass, velocity, gravity);
1205        }
1206        let (x, j, _) = *pose;
1207        let mut load = self.load_with(t, x, j, w, self.carried(), 0.0);
1208        let torque = self.amplifier_torque_at(s, pose);
1209        for r in 0..4 {
1210            load.1[r] += self.kappa * j[3][r] * torque;
1211        }
1212        load
1213    }
1214
1215    /// With bending arms, the rates of the bend states into `out`, from the joints' acceleration `acc`: the elbows'
1216    /// accelerations, of their angles and their moves, from M_d q'' = Q_d - v_d - (k_b delta + c_b delta', k_l y +
1217    /// c_l y') - kappa P_h^T tau_a (`load_n` beyond the tubes; P_h the slide's row of the Jacobians, the tool's turn
1218    /// with the slide where it is not on the amplifier's spring).
1219    fn bend_rates(&self, s: &[f64], pose: &Pose, acc: V4, out: &mut [f64]) {
1220        let Some(b) = self.bending else { return };
1221        let ((_, rate), (_, yv)) = (self.bend(s), self.lateral(s));
1222        let (mass, mut rhs) = self.distal(s, pose, b);
1223        // The tube's coupling to the root (effects.arm_tube_inertia): B theta'' on the elbows' rows.
1224        for i in 0..4 {
1225            rhs[i] -= self.tube_coupling * acc[i];
1226        }
1227        let q = sim_components::chain::solve(mass.as_flattened(), &rhs).unwrap_or_else(|| vec![f64::NAN; 8]);
1228        let at = self.bend_at();
1229        out[at..at + 4].copy_from_slice(&rate);
1230        for i in 0..4 {
1231            out[at + 4 + i] = q[i] - acc[i];
1232        }
1233        out[at + 8..at + 12].copy_from_slice(&yv);
1234        out[at + 12..at + 16].copy_from_slice(&q[4..]);
1235    }
1236
1237    /// Beyond the tubes (bending arms): the mass matrix M_d in the elbows' angles and moves, and what drives them,
1238    /// f_d = Q_d - v_d - (k_b delta + c_b delta', k_l y + c_l y') - kappa P_h^T tau_a.
1239    fn distal(&self, s: &[f64], pose: &Pose, b: Bending) -> ([[f64; 8]; 8], [f64; 8]) {
1240        let ((e, speeds), (bend, rate), (y, yv)) = (self.elbows(s), self.bend(s), self.lateral(s));
1241        let spin = if self.amplifier.is_some() { 0.0 } else { self.tool_inertia() };
1242        let (mass, velocity, gravity) = self.load_n::<8>(e, y, *pose, speeds, yv, self.carried(), spin, false);
1243        let torque = self.amplifier_torque_at(s, pose);
1244        let (_, j, jy) = *pose;
1245        // The push at the tool on the elbows (its power per unit of their bend's rates, which move them) and their moves.
1246        let at = self.bend_at();
1247        let (on_elbows, on_moves): (V4, V4) = (self.pushed(s, at + 4), self.pushed(s, at + 12));
1248        let rhs = std::array::from_fn(|i| {
1249            let slide = if i < 4 { j[3][i] } else { jy[3][i - 4] };
1250            let spring =
1251                if i < 4 { b.k * bend[i] + b.c * rate[i] } else { b.k_lateral * y[i - 4] + b.c_lateral * yv[i - 4] };
1252            let push = if i < 4 { on_elbows[i] } else { on_moves[i - 4] };
1253            gravity[i] - velocity[i] - self.kappa * slide * torque - spring + push
1254        });
1255        (mass, rhs)
1256    }
1257
1258    /// At rest with the plate at x and the mass `carried` at the tool's point (bending arms): the joints' angles, the
1259    /// torque gravity puts on each joint (all of it: the tube's own and, through the spring, the rest), the arms'
1260    /// bend, Q_d / k_b, and the elbows' moves out of the arms' planes, Q_y / k_l (from none, three rounds: Q_y hardly
1261    /// changes with them).
1262    fn rest_at(&self, b: Bending, x: V4, carried: f64) -> (V4, V4, V4, V4) {
1263        let tip_at = |y: V4| {
1264            let e = self.legs.inverse_moved(x, y).unwrap_or([f64::NAN; 4]);
1265            let pose = match self.legs.jacobians(e, y, x) {
1266                Some((j, jy)) => (x, j, jy),
1267                None => ([f64::NAN; 4], [[f64::NAN; 4]; 4], [[f64::NAN; 4]; 4]),
1268            };
1269            (e, self.load_n::<8>(e, y, pose, [0.0; 4], [0.0; 4], carried, 0.0, false).2)
1270        };
1271        // Q_y hardly changes with y: each round takes some 1e-4 of what is left.
1272        let mut y = [0.0; 4];
1273        for _ in 0..20 {
1274            let (_, tip) = tip_at(y);
1275            let next: V4 = std::array::from_fn(|i| tip[4 + i] / b.k_lateral);
1276            let settled = (0..4).all(|i| (next[i] - y[i]).abs() <= 1e-15);
1277            y = next;
1278            if settled {
1279                break;
1280            }
1281        }
1282        let (e, tip) = tip_at(y);
1283        let bend: V4 = std::array::from_fn(|i| tip[i] / b.k);
1284        let t: V4 = std::array::from_fn(|i| e[i] - bend[i]);
1285        (t, std::array::from_fn(|i| self.g * self.root_moment * t[i].cos() + tip[i]), bend, y)
1286    }
1287
1288    /// Rigid model: the arms' acceleration, and per joint the torque into its gearbox (after the rotor's own
1289    /// acceleration) and out of it, at the arm.
1290    fn rigid_solve(&self, s: &[f64], torque: &[f64]) -> (V4, V4, V4) {
1291        let (t, w) = self.arms(s);
1292        let (rotor, rotor_speed) = self.rotors(s);
1293        let brakes = self.brakes(s);
1294        let (mass, velocity, gravity) = self.joint_load(s);
1295        let drive: V4 = std::array::from_fn(|k| {
1296            self.joints[k].rigid_drive(torque[k], rotor[k], rotor_speed[k], brakes[k], self.brake_engaged).0
1297        });
1298        let push = self.pushed_on_arms(s);
1299        let rest: V4 =
1300            std::array::from_fn(|k| gravity[k] - velocity[k] + self.joints[k].output_torque(t[k], w[k]) + push[k]);
1301        let solve = |loss: V4| -> V4 {
1302            let m: M4 = std::array::from_fn(|r| {
1303                std::array::from_fn(|c| {
1304                    mass[r][c] + if r == c { loss[r] * self.joints[r].reflected_inertia() } else { 0.0 }
1305                })
1306            });
1307            solve4(&m, std::array::from_fn(|k| loss[k] * drive[k] + rest[k])).unwrap_or([f64::NAN; 4])
1308        };
1309        // The loss factors of the torques going in, at their fixed point (`mech::settled_loss`).
1310        let loss = sim_components::mech::settled_loss([1.0; 4], |loss| {
1311            let acc = solve(*loss);
1312            std::array::from_fn(|k| {
1313                self.joints[k].gearbox.loss_factor(drive[k] - self.joints[k].reflected_inertia() * acc[k], w[k])
1314            })
1315        });
1316        let acc = solve(loss);
1317        let into: V4 = std::array::from_fn(|k| drive[k] - self.joints[k].reflected_inertia() * acc[k]);
1318        (acc, into, std::array::from_fn(|k| loss[k] * into[k]))
1319    }
1320
1321    /// The arms' acceleration in either model.
1322    fn arm_acceleration(&self, s: &[f64], torque: &[f64]) -> V4 {
1323        if self.elastic {
1324            let mut d = vec![0.0; self.state_len()];
1325            self.derivatives(s, torque, &mut d);
1326            [d[4], d[5], d[6], d[7]]
1327        } else {
1328            self.rigid_solve(s, torque).0
1329        }
1330    }
1331
1332    /// The torque each gearbox passes to its arm.
1333    fn gear_output(&self, s: &[f64], torque: &[f64]) -> V4 {
1334        if self.elastic {
1335            std::array::from_fn(|k| self.joints[k].gearbox.torque(s[8 + k], s[12 + k], s[k], s[4 + k]).output)
1336        } else {
1337            self.rigid_solve(s, torque).2
1338        }
1339    }
1340
1341    fn energy_parts(&self, s: &[f64]) -> [f64; 3] {
1342        let (t, w) = self.arms(s);
1343        let ((e, ew), (y, yv)) = (self.elbows(s), self.lateral(s));
1344        let pose = self.pose_at(s);
1345        let x = pose.0;
1346        let spin = if self.amplifier.is_some() { 0.0 } else { self.tool_inertia() };
1347        // Beyond the tubes at the elbows' speeds and moves, the tubes at the joints' (all of it at once with rigid
1348        // links).
1349        let mut kinetic = if self.bending.is_some() {
1350            let (mass, ..) = self.load_n::<8>(e, y, pose, ew, yv, self.carried(), spin, false);
1351            let q: [f64; 8] = std::array::from_fn(|i| if i < 4 { ew[i] } else { yv[i - 4] });
1352            let moving: f64 = (0..8).map(|r| q[r] * (0..8).map(|c| mass[r][c] * q[c]).sum::<f64>()).sum();
1353            0.5 * moving + 0.5 * self.root_inertia * dot4(w, w) + self.tube_coupling * dot4(w, ew)
1354        } else {
1355            let (mass, ..) = self.load_with(t, x, pose.1, w, self.carried(), spin);
1356            0.5 * dot4(w, mul4(&mass, w))
1357        };
1358        let middles: f64 = (0..4).map(|i| 0.5 * (self.legs.elbow(i, e[i])[0][2] + x[2])).sum();
1359        let sines = |a: V4| a.iter().map(|v| v.sin()).sum::<f64>();
1360        // The lumped forearms' weight at their middles (`weight_shift`): the split's excess from the elbows to the plate.
1361        let shifted = self.g * self.weight_shift * (4.0 * x[2] + self.legs.la * sines(e));
1362        let potential = shifted
1363            + if self.bending.is_some() {
1364                self.g
1365                    * ((2.0 * self.m_part + self.carried()) * x[2] + self.m_rod_middle * middles
1366                        - self.root_moment * sines(t)
1367                        - self.tip_moment * sines(e))
1368            } else {
1369                self.g
1370                    * ((2.0 * self.m_part + self.carried()) * x[2] + self.m_rod_middle * middles
1371                        - self.arm_moment * sines(t))
1372            };
1373        let mut elastic: f64 = (0..4).map(|k| self.joints[k].stop_energy(t[k])).sum();
1374        if let Some(b) = self.bending {
1375            let (bend, _) = self.bend(s);
1376            elastic += 0.5 * b.k * dot4(bend, bend) + 0.5 * b.k_lateral * dot4(y, y);
1377        }
1378        if self.elastic {
1379            for k in 0..4 {
1380                kinetic += 0.5 * self.joints[k].rotor_inertia * s[12 + k] * s[12 + k];
1381                elastic += self.joints[k].gearbox.energy(s[8 + k], s[k]);
1382            }
1383        } else {
1384            kinetic += 0.5 * (0..4).map(|k| self.joints[k].reflected_inertia() * w[k] * w[k]).sum::<f64>();
1385        }
1386        if let Some(a) = self.amplifier {
1387            let at = self.turn_at();
1388            kinetic += 0.5 * self.tool_inertia() * s[at + 1] * s[at + 1];
1389            elastic += a.energy(self.kappa * x[3] - s[at]);
1390        }
1391        [kinetic, potential, elastic]
1392    }
1393
1394    /// The loss powers that are signals into `out`: the amplifier's damping only with effects.amplifier_compliance, the
1395    /// arms' bending damping only with effects.arm_bending.
1396    fn loss_signals(&self, losses: &Losses, out: &mut Vec<f64>) {
1397        out.extend(&losses.powers[..14]);
1398        if self.amplifier.is_some() {
1399            out.push(losses.powers[14]);
1400        }
1401        if self.bending.is_some() {
1402            out.push(losses.powers[15]);
1403        }
1404    }
1405
1406    fn losses(&self, s: &[f64], torque: &[f64]) -> Losses {
1407        let (t, w) = self.arms(s);
1408        let (rotor, rotor_speed) = self.rotors(s);
1409        let brakes = self.brakes(s);
1410        let mut powers = [0.0; 16];
1411        let mut gear_at_rotor = [0.0; 4];
1412        let rigid = (!self.elastic).then(|| self.rigid_solve(s, torque));
1413        let (mut stops, mut other) = (0.0, 0.0);
1414        for k in 0..4 {
1415            let joint = &self.joints[k];
1416            let [friction, stop, shaft, drag] = joint.losses(t[k], w[k], rotor_speed[k], brakes[k], self.brake_engaged);
1417            let gear = match &rigid {
1418                Some((_, into, out)) => {
1419                    gear_at_rotor[k] = (into[k] - out[k]) / joint.ratio();
1420                    (into[k] - out[k]) * w[k]
1421                }
1422                None => {
1423                    let g = joint.gearbox.torque(s[8 + k], s[12 + k], s[k], s[4 + k]);
1424                    gear_at_rotor[k] = g.rotor - g.output / joint.ratio();
1425                    joint.gearbox.loss_power(s[8 + k], s[12 + k], s[k], s[4 + k])
1426                }
1427            };
1428            powers[3 * k..3 * k + 3].copy_from_slice(&[friction, shaft, gear + drag]);
1429            stops += stop;
1430            other += (torque[k] - joint.ripple.apply(torque[k], rotor[k])) * rotor_speed[k];
1431        }
1432        powers[12] = stops;
1433        powers[13] = other;
1434        if let Some(a) = self.amplifier {
1435            let (twist, rate) = self.twist(s);
1436            powers[14] = a.loss_power(twist, rate);
1437        }
1438        if let Some(b) = self.bending {
1439            let ((_, rate), (_, moving)) = (self.bend(s), self.lateral(s));
1440            powers[15] = b.c * dot4(rate, rate) + b.c_lateral * dot4(moving, moving);
1441        }
1442        Losses { powers, gear_at_rotor }
1443    }
1444
1445    /// Whether a position is within the working range (cylinder, top, spherical bottom), widened by `slack`.
1446    fn in_envelope(&self, p: &[f64], slack: f64) -> bool {
1447        let (centre, r) = self.sphere;
1448        let below = if centre.is_finite() {
1449            (p[0] * p[0] + p[1] * p[1] + (p[2] - centre).powi(2)).sqrt() <= r + slack
1450        } else {
1451            p[2] >= self.axes[2].min - slack
1452        };
1453        p[0].hypot(p[1]) <= self.radius + slack && p[2] <= self.top + slack && below
1454    }
1455
1456    /// How far the motors' pose can be from the tool's at rest anywhere in the working range, payload on or off, the
1457    /// tool's turn counted in rad as the settling check counts it: each gearbox twisted by the torque it holds against
1458    /// gravity over its stiffness, plus half its backlash either way (all sixteen combinations), through the forward
1459    /// kinematics. Over a grid of the range: 5 radii, 12 directions, 9 heights and the bottom, the turn at its ends and
1460    /// its middle; plus a tenth for what the grid steps over and the joints' friction. At least the default 0.1 mm;
1461    /// that alone in the rigid model, whose gearboxes do not twist. The amplifier's own play does not reach the motors.
1462    fn rest_sag(&self) -> f64 {
1463        if !self.elastic && self.bending.is_none() {
1464            return 1e-4;
1465        }
1466        let mut most = 0f64;
1467        let (bottom, top) = (self.axes[2].min, self.top);
1468        let turns = [self.axes[3].min, 0.5 * (self.axes[3].min + self.axes[3].max), self.axes[3].max];
1469        for ring in 0..=4 {
1470            let rho = self.radius * ring as f64 / 4.0;
1471            for turn in 0..12 {
1472                let (sin, cos) = (turn as f64 * std::f64::consts::TAU / 12.0).sin_cos();
1473                let (centre, r) = self.sphere;
1474                let lowest = if centre.is_finite() { centre - (r * r - rho * rho).max(0.0).sqrt() } else { bottom };
1475                for z in (0..=8).map(|k| lowest + (top - lowest) * k as f64 / 8.0) {
1476                    let p = [rho * cos, rho * sin, z];
1477                    if !self.in_envelope(&p, 1e-9) {
1478                        continue;
1479                    }
1480                    for c in turns {
1481                        let x = self.coordinates(&[p[0], p[1], p[2], c]);
1482                        let Some(t) = self.legs.inverse(x) else { continue };
1483                        let Some(j) = self.legs.jacobian(t, x) else { continue };
1484                        for m in [self.m_carriage, self.m_carriage + self.m_payload] {
1485                            // With bending arms the joints' angles at rest are short of the elbows' by the bend.
1486                            let (t, gravity) = match self.bending {
1487                                Some(b) => {
1488                                    let (t, gravity, ..) = self.rest_at(b, x, m);
1489                                    (t, gravity)
1490                                }
1491                                None => (t, self.load_with(t, x, j, [0.0; 4], m, 0.0).2),
1492                            };
1493                            // No twist and no backlash in the rigid joint model.
1494                            let twist: V4 = std::array::from_fn(|k| {
1495                                if !self.elastic {
1496                                    return 0.0;
1497                                }
1498                                (-gravity[k] - self.joints[k].output_torque(t[k], 0.0))
1499                                    / self.joints[k].gearbox.stiffness
1500                            });
1501                            for signs in 0..16 {
1502                                let half = |k: usize| {
1503                                    let sign = if signs >> k & 1 == 1 { 1.0 } else { -1.0 };
1504                                    if self.elastic { sign * self.joints[k].gearbox.half_backlash } else { 0.0 }
1505                                };
1506                                let moved = std::array::from_fn(|k| t[k] + twist[k] + half(k));
1507                                if let Some(q) = self.legs.forward_from(moved, x) {
1508                                    let off: V4 =
1509                                        std::array::from_fn(|k| (q[k] - x[k]) * if k == 3 { self.kappa } else { 1.0 });
1510                                    most = most.max(dot4(off, off).sqrt());
1511                                }
1512                            }
1513                        }
1514                    }
1515                }
1516            }
1517        }
1518        (1.1 * most).max(1e-4)
1519    }
1520
1521    /// The arms' modes with the motors held (by their position loops): the gearboxes' springs k (all alike) against
1522    /// the load's mass matrix M, the rotors still, so w^2 = k / mu over M's eigenvalues mu, the shape M's eigenvector
1523    /// v; the damping ratio c / (2 w mu) with the gearboxes' damping c. The tool counts with the slide unless it is on
1524    /// the amplifier's spring (`amplifier_mode`). Gravity's stiffness and the stops are left out. Frequency in Hz,
1525    /// damping ratio and shape in the arm angles, lowest first; none in the rigid model or out of reach. K1 for the moves
1526    /// that excite the modes; with hysteresis a small vibration (`small`) sees K1 + sigma, as the 3-axis delta's.
1527    ///
1528    /// With effects.arm_bending (`arm_modes`) the coordinates are the joints' turns, the elbows' turns and their moves
1529    /// out of the arms' planes (12 modes with the gearboxes' springs, 8 without them: the arms' bending alone), the
1530    /// shape in those 12 coordinates; each arm on its own gearbox and the bending's and the lateral dampers in the
1531    /// damping (v'Cv / (2 w v'Mv), the cross terms of a damping that is not proportional left out).
1532    fn modes_at(&self, tool: &[f64], small: bool) -> Vec<(f64, f64, Vec<f64>)> {
1533        if (!self.elastic && self.bending.is_none()) || tool.len() != 4 {
1534            return Vec::new();
1535        }
1536        let x = self.coordinates(tool);
1537        let Some(t) = self.legs.inverse(x) else { return Vec::new() };
1538        let spin = if self.amplifier.is_some() { 0.0 } else { self.tool_inertia() };
1539        let Some(b) = self.bending else {
1540            let (mass, ..) = self.load_at(t, [0.0; 4], self.carried(), spin);
1541            let (mu, v) = symmetric_eigen(mass.iter().map(|row| row.to_vec()).collect());
1542            let g = &self.joints[0].gearbox;
1543            let (k, c) = (g.stiffness + if small && g.hysteresis > 0.0 { g.dahl_stiffness } else { 0.0 }, g.damping);
1544            let mut out: Vec<(f64, f64, Vec<f64>)> = (0..4)
1545                .filter(|&i| mu[i] > 0.0)
1546                .map(|i| {
1547                    let w = (k / mu[i]).sqrt();
1548                    (w / std::f64::consts::TAU, c / (2.0 * w * mu[i]), (0..4).map(|r| v[r][i]).collect())
1549                })
1550                .collect();
1551            out.sort_by(|a, b| a.0.total_cmp(&b.0));
1552            return out;
1553        };
1554        let Some((j, jy)) = self.legs.jacobians(t, [0.0; 4], x) else { return Vec::new() };
1555        let distal: Vec<Vec<f64>> = self
1556            .load_n::<8>(t, [0.0; 4], (x, j, jy), [0.0; 4], [0.0; 4], self.carried(), spin, false)
1557            .0
1558            .map(Vec::from)
1559            .into();
1560        // K1, the stiffness of the moves that excite the mode; with hysteresis a small vibration sees K1 + sigma.
1561        let k_gear = self.elastic.then(|| {
1562            std::array::from_fn(|i| {
1563                let g = &self.joints[i].gearbox;
1564                g.stiffness + if small && g.hysteresis > 0.0 { g.dahl_stiffness } else { 0.0 }
1565            })
1566        });
1567        let c_gear: V4 = std::array::from_fn(|i| if self.elastic { self.joints[i].gearbox.damping } else { 0.0 });
1568        arm_modes((self.root_inertia, self.tube_coupling), &distal, k_gear, b.k, b.k_lateral)
1569            .into_iter()
1570            .map(|(w2, v)| {
1571                let distal_kinetic: f64 =
1572                    (0..8).map(|r| v[4 + r] * (0..8).map(|c| distal[r][c] * v[4 + c]).sum::<f64>()).sum();
1573                let kinetic = (0..4)
1574                    .map(|i| self.root_inertia * v[i] * v[i] + 2.0 * self.tube_coupling * v[i] * v[4 + i])
1575                    .sum::<f64>()
1576                    + distal_kinetic;
1577                let damped: f64 = (0..4)
1578                    .map(|i| {
1579                        c_gear[i] * v[i] * v[i] + b.c * (v[4 + i] - v[i]).powi(2) + b.c_lateral * v[8 + i] * v[8 + i]
1580                    })
1581                    .sum();
1582                let w = w2.sqrt();
1583                (w / std::f64::consts::TAU, damped / (2.0 * w * kinetic), v)
1584            })
1585            .collect()
1586    }
1587
1588    /// The arms' four modes (`modes_at`, `small` amplitude or not) and the amplifier's, lowest first.
1589    fn modes_with(&self, tool_pose: &[f64], small: bool) -> Vec<Mode> {
1590        let mut out: Vec<Mode> =
1591            self.modes_at(tool_pose, small).into_iter().map(|(hz, damping, _)| Mode { hz, damping }).collect();
1592        out.extend(self.amplifier_mode());
1593        out.sort_by(|a, b| a.hz.total_cmp(&b.hz));
1594        out
1595    }
1596
1597    /// The tool's turn on the amplifier's spring with the slide held, as the D4's tool: w^2 = k / I_t, damping ratio
1598    /// c / (2 sqrt(k I_t)). `None` without effects.amplifier_compliance.
1599    pub fn amplifier_mode(&self) -> Option<Mode> {
1600        let a = self.amplifier?;
1601        let j = self.tool_inertia();
1602        Some(Mode {
1603            hz: (a.stiffness / j).sqrt() / std::f64::consts::TAU,
1604            damping: a.damping / (2.0 * (a.stiffness * j).sqrt()),
1605        })
1606    }
1607
1608    /// The tool's bar under the carriage at p, 0.12 m long, turned by `c`: its two ends.
1609    fn tool_bar(&self, p: V3, c: f64) -> (V3, V3) {
1610        let half = [0.06 * c.cos(), 0.06 * c.sin(), 0.0];
1611        let under = [p[0], p[1], p[2] - 0.04];
1612        (std::array::from_fn(|k| under[k] - half[k]), std::array::from_fn(|k| under[k] + half[k]))
1613    }
1614
1615    /// The two plate parts as drawn at x: each a bar between its two forearm pairs' ends (at the plate radius from the
1616    /// part's centre, at least 30 mm so that a bar is drawn).
1617    fn plate_bars(&self, x: V4) -> [(V3, V3); 2] {
1618        let r = self.plate_radius.max(0.03);
1619        let end = |i: usize| {
1620            let (q, (c, s)) = (self.legs.end(i, x), self.legs.azimuth[i]);
1621            [q[0] + r * c, q[1] + r * s, q[2]]
1622        };
1623        [(end(0), end(1)), (end(2), end(3))]
1624    }
1625
1626    /// The carriage at the tool's point and the payload under it, as `scene` draws them.
1627    fn on_carriage(&self, p: V3) -> Vec<Part> {
1628        let mut parts = vec![Part::new("carriage", Shape::Box { size: [0.08, 0.08, 0.05] }, p, [0.55, 0.55, 0.6])];
1629        if self.payload_attached && self.m_payload > 0.0 {
1630            parts.push(Part::new(
1631                "payload",
1632                Shape::Box { size: [0.12, 0.12, 0.08] },
1633                [p[0], p[1], p[2] - 0.1],
1634                [0.2, 0.7, 0.3],
1635            ));
1636        }
1637        parts
1638    }
1639
1640    /// Upper arm k from its shoulder to its end, as `scene` draws it: the legs' elbow is at e, the arm's end at the base
1641    /// radius (the plate's radius added back), moved by y out of the arm's plane.
1642    fn arm(&self, k: usize, t: V4, y: V4) -> (V3, V3) {
1643        let (c, sn) = self.legs.azimuth[k];
1644        let elbow = self.legs.elbows_moved(t, y)[k];
1645        (
1646            [self.base_radius * c, self.base_radius * sn, 0.0],
1647            [elbow[0] + self.plate_radius * c, elbow[1] + self.plate_radius * sn, elbow[2]],
1648        )
1649    }
1650
1651    /// The tool's turn and its speed at state s.
1652    fn turn(&self, s: &[f64]) -> (f64, f64) {
1653        if self.amplifier.is_some() {
1654            let at = self.turn_at();
1655            return (s[at], s[at + 1]);
1656        }
1657        self.slide_of(s, &self.pose_at(s))
1658    }
1659
1660    /// The torque breakdown, loss powers, energies of the effect views.
1661    fn view_signals(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
1662        let (_, w) = self.arms(s);
1663        let (_, rotor_speed) = self.rotors(s);
1664        let brakes = self.brakes(s);
1665        let (mass, velocity, gravity) = self.joint_load(s);
1666        let acc = self.arm_acceleration(s, torque);
1667        let moving = mul4(&mass, acc);
1668        let losses = self.losses(s, torque);
1669        for k in 0..4 {
1670            let joint = &self.joints[k];
1671            let i = joint.ratio();
1672            let held = joint.brake.torque(self.brake_engaged, rotor_speed[k], brakes[k]).0;
1673            let parts = [
1674                (moving[k] + velocity[k] + joint.reflected_inertia() * acc[k]) / i,
1675                -gravity[k] / i,
1676                joint.shaft.torque(rotor_speed[k]) + held + losses.gear_at_rotor[k] + joint.friction.torque(w[k]) / i,
1677            ];
1678            out.extend(parts);
1679            out.push(torque[k] - parts.iter().sum::<f64>());
1680        }
1681        self.loss_signals(&losses, out);
1682        out.extend(self.energy_parts(s));
1683        for k in 0..4 {
1684            out.extend(self.joints[k].friction_signals(w[k]));
1685        }
1686    }
1687
1688    fn effect_infos(&self, out: &mut Vec<SignalInfo>) {
1689        for motor in &self.motors {
1690            out.extend(TORQUE_PARTS.map(|part| {
1691                SignalInfo::new(
1692                    format!("motor.{}.torque_{part}", motor.id),
1693                    motor.key,
1694                    &format!("quantity-torque-{part}"),
1695                    "N m",
1696                )
1697            }));
1698        }
1699        for (k, motor) in self.motors.iter().enumerate() {
1700            let gear = if self.joints[k].gearbox.is_coupling() {
1701                "quantity-coupling-loss-power"
1702            } else {
1703                "quantity-gearbox-loss-power"
1704            };
1705            out.push(SignalInfo::new(
1706                format!("{LOSS_PREFIX}joint_{}", motor.id),
1707                ARMS[k],
1708                "quantity-friction-power",
1709                "W",
1710            ));
1711            out.push(SignalInfo::new(
1712                format!("{LOSS_PREFIX}shaft_{}", motor.id),
1713                motor.key,
1714                "quantity-shaft-friction-power",
1715                "W",
1716            ));
1717            out.push(SignalInfo::new(format!("{LOSS_PREFIX}gearbox_{}", motor.id), motor.key, gear, "W"));
1718        }
1719        out.push(SignalInfo::new(format!("{LOSS_PREFIX}hard_stops"), "group-joint", "quantity-damping-power", "W"));
1720        out.push(SignalInfo::new(format!("{LOSS_PREFIX}other"), "loss-other", "quantity-power-given-off", "W"));
1721        if self.amplifier.is_some() {
1722            out.push(SignalInfo::new(format!("{LOSS_PREFIX}amplifier"), "group-plate", "quantity-damping-power", "W"));
1723        }
1724        if self.bending.is_some() {
1725            out.push(SignalInfo::new(
1726                format!("{LOSS_PREFIX}arm_bending"),
1727                "group-upper-arms",
1728                "quantity-damping-power",
1729                "W",
1730            ));
1731        }
1732        out.extend(ENERGY_PARTS.map(|part| {
1733            SignalInfo::new(format!("energy.{part}"), "group-energy", &format!("quantity-energy-{part}"), "J")
1734        }));
1735        for k in 0..4 {
1736            out.extend(sim_components::joint::RotaryJoint::friction_infos(JOINT_CONTACTS[k], ARMS[k]));
1737        }
1738    }
1739}
1740
1741/// The arms' translation keys, in the motors' order.
1742const ARMS: [&str; 4] = ["arm-1", "arm-2", "arm-3", "arm-4"];
1743/// The ids of the joints' friction contacts (`<id>.friction_<part>`), in the motors' order.
1744const JOINT_CONTACTS: [&str; 4] = ["joint.1", "joint.2", "joint.3", "joint.4"];
1745
1746impl Machine for H4 {
1747    /// In the tool's frame (z up): the plate's two parts at p -+ h d, the carriage with the payload at p, the rods'
1748    /// middles (effects.forearm_inertia) between elbow and plate as the dynamics has them; the arms turning about their
1749    /// joints at the base radius and their rotors about the elbows' axes; the tool's turn about z (its own angle with
1750    /// effects.amplifier_compliance). With effects.forearm_inertia each pair's rods spin about their own axis `u / L`
1751    /// at the rate `add_spin` of the dynamics derives, s = -sigma n / (L (L^2 - sigma^2)) (sigma = a . u,
1752    /// n = a . (u' x u), a the elbow's axis, u the forearm), and carry I s `u / L` of angular momentum: the plane of
1753    /// the pair's rods rotates rigidly with the spin, so that is its angular velocity's component along the rod.
1754    fn frame_momentum(&self, s: &[f64]) -> Option<sim_core::FrameMomentum> {
1755        use sim_components::base::{add_point, add_spin, add_turning};
1756        let mut f = sim_core::FrameMomentum { gravity: [0.0, 0.0, -self.g], ..Default::default() };
1757        let (t, w) = self.arms(s);
1758        let ((e, ew), (y, yv)) = (self.elbows(s), self.lateral(s));
1759        let (x, j, jy) = self.pose_at(s);
1760        let xv: V4 = std::array::from_fn(|r| dot4(j[r], ew) + dot4(jy[r], yv));
1761        let d = self.legs.slide;
1762        // A point at p + side h d, and its speed.
1763        let point = |side: f64| -> (V3, V3) {
1764            (std::array::from_fn(|k| x[k] + side * d[k] * x[3]), std::array::from_fn(|k| xv[k] + side * d[k] * xv[3]))
1765        };
1766        for side in [-1.0, 1.0] {
1767            let (r, v) = point(side);
1768            add_point(&mut f, self.m_part, r, v);
1769        }
1770        let (r, v) = point(0.0);
1771        add_point(&mut f, self.carried(), r, v);
1772        let rotor_speed = self.rotors(s).1;
1773        for i in 0..4 {
1774            let (sin, cos) = t[i].sin_cos();
1775            let (dir, ddir) = (self.legs.to_base(i, [cos, 0.0, -sin]), self.legs.to_base(i, [-sin, 0.0, -cos]));
1776            let joint = self.legs.to_base(i, [self.base_radius, 0.0, 0.0]);
1777            let tangent = self.legs.tangent(i);
1778            if self.bending.is_some() {
1779                // The tube turns with its joint and its bent share with the elbow (the bend added); the elbow is a
1780                // point at its moved place with its whole speed. Out of the plane the tube's sections move by
1781                // phi(s) y: momentum int(phi) m y' = 0.3915 m y' at 0.7265 L_a along the arm (int(xi phi) / int(phi)),
1782                // and the moved sections carry the in-plane momentum int(phi v0) = m L_a (0.2844 theta' +
1783                // 0.25 delta') along the turn, at y off the plane. The elbow block twists about the arm's normal.
1784                let la = self.legs.la;
1785                add_turning(&mut f, joint, dir, ddir, w[i], self.root_inertia, self.root_moment);
1786                let (sin, cos) = e[i].sin_cos();
1787                let (tip, dtip) = (self.legs.to_base(i, [cos, 0.0, -sin]), self.legs.to_base(i, [-sin, 0.0, -cos]));
1788                let point = la * la * self.m_elbow;
1789                add_turning(
1790                    &mut f,
1791                    joint,
1792                    tip,
1793                    dtip,
1794                    ew[i],
1795                    self.tip_inertia - point,
1796                    self.tip_moment - la * self.m_elbow,
1797                );
1798                // The coupling B theta' e' adds B (theta' + e') about the arm's axis.
1799                add_spin(&mut f, cross(dir, ddir), self.tube_coupling, w[i] + ew[i]);
1800                let elbow: V3 = std::array::from_fn(|k| joint[k] + la * tip[k] + y[i] * tangent[k]);
1801                let elbow_v: V3 = std::array::from_fn(|k| la * ew[i] * dtip[k] + yv[i] * tangent[k]);
1802                add_point(&mut f, self.m_elbow, elbow, elbow_v);
1803                if self.tube_mass > 0.0 {
1804                    use sim_components::beam::{STATIC_SHAPE_MASS, STATIC_SHAPE_PARTICIPATION, STATIC_SHAPE_TIP_SLOPE};
1805                    let m = STATIC_SHAPE_PARTICIPATION * self.tube_mass;
1806                    let at: V3 = std::array::from_fn(|k| joint[k] + TUBE_CENTROID * la * tip[k]);
1807                    add_point(
1808                        &mut f,
1809                        m,
1810                        std::array::from_fn(|k| at[k] + y[i] * tangent[k]),
1811                        tangent.map(|v| v * yv[i]),
1812                    );
1813                    add_point(&mut f, -m, at, [0.0; 3]);
1814                    let along = self.tube_mass * la * (TUBE_MOMENT * w[i] + STATIC_SHAPE_MASS * (ew[i] - w[i]));
1815                    let off = cross(tangent.map(|v| v * y[i]), dtip.map(|v| v * along));
1816                    (0..3).for_each(|k| f.angular[k] += off[k]);
1817                    add_spin(&mut f, cross(tip, tangent), self.twist_inertia, STATIC_SHAPE_TIP_SLOPE * yv[i] / la);
1818                }
1819            } else {
1820                add_turning(&mut f, joint, dir, ddir, w[i], self.arm_inertia, self.arm_moment);
1821            }
1822            add_spin(&mut f, tangent, self.joints[i].rotor_inertia, rotor_speed[i]);
1823            if self.m_forearms > 0.0 || self.rod_spin > 0.0 {
1824                let (elbow, d1) = (self.legs.elbows_moved(e, y)[i], self.legs.elbow(i, e[i])[1]);
1825                let (end, end_v) = point(SIDE[i]);
1826                let elbow_v: V3 = std::array::from_fn(|k| d1[k] * ew[i] + tangent[k] * yv[i]);
1827                // The legs fold the plate radius into the elbow (e = base less plate radius): the rod's ends lie that
1828                // much further out along the arm's azimuth.
1829                let (c, sn) = self.legs.azimuth[i];
1830                let out = [self.plate_radius * c, self.plate_radius * sn, 0.0];
1831                let middle = std::array::from_fn(|k| 0.5 * (elbow[k] + end[k]) + out[k]);
1832                // The forearms as the rods they are, whatever share of their inertia the lumped dynamics put at the
1833                // elbow: a sixth at each end, two thirds at the middle, so that their weight sits where the potential
1834                // has it. What the split puts at the elbow and at the plate part beyond those sixths comes off there.
1835                let m_fb = self.m_forearms;
1836                let at_elbow = (self.forearm_share - 1.0 / 6.0) * m_fb;
1837                let at_plate = (5.0 / 6.0 - self.forearm_share) * m_fb - self.m_rod_middle;
1838                add_point(&mut f, -at_elbow, std::array::from_fn(|k| elbow[k] + out[k]), elbow_v);
1839                add_point(&mut f, -at_plate, end, end_v);
1840                add_point(&mut f, 2.0 / 3.0 * m_fb, middle, std::array::from_fn(|k| 0.5 * (elbow_v[k] + end_v[k])));
1841                if self.rod_spin > 0.0 {
1842                    let (u, du) = (sub(end, elbow), std::array::from_fn(|k| end_v[k] - elbow_v[k]));
1843                    let (l, a) = (self.legs.lb, self.legs.tangent(i));
1844                    let sigma = dot(a, u);
1845                    let spin = -sigma * dot(a, cross(du, u)) / (l * (l * l - sigma * sigma));
1846                    add_spin(&mut f, u.map(|v| v / l), self.rod_spin, spin);
1847                }
1848            }
1849        }
1850        let turn = match self.amplifier {
1851            Some(_) => s[self.turn_at() + 1],
1852            None => self.kappa * xv[3],
1853        };
1854        add_spin(&mut f, [0.0, 0.0, 1.0], self.tool_inertia(), turn);
1855        Some(f)
1856    }
1857    fn axes(&self) -> &[AxisInfo] {
1858        &self.axes
1859    }
1860    fn motors(&self) -> &[MotorInfo] {
1861        &self.motors
1862    }
1863
1864    /// NaN where the pose is out of reach: the controller never asks for one (see `unreachable`).
1865    fn inverse(&self, tool: &[f64], motors: &mut [f64]) {
1866        let t = self.legs.inverse(self.coordinates(tool)).unwrap_or([f64::NAN; 4]);
1867        for k in 0..4 {
1868            motors[k] = self.ratio() * t[k];
1869        }
1870    }
1871    fn forward(&self, motors: &[f64], tool: &mut [f64]) {
1872        let i = self.ratio();
1873        let x = self.legs.forward(std::array::from_fn(|k| motors[k] / i)).unwrap_or([f64::NAN; 4]);
1874        tool[..3].copy_from_slice(&x[..3]);
1875        tool[3] = self.kappa * x[3];
1876    }
1877
1878    fn state_len(&self) -> usize {
1879        self.bend_at() + if self.bending.is_some() { 16 } else { 0 }
1880    }
1881
1882    fn equilibrium(&self, tool: &[f64], state: &mut Vec<f64>, torque: &mut [f64]) {
1883        // With bending arms the elbows are at the pose, the joints short of them by the arms' bend under the weight.
1884        let (t, gravity, bend, lateral) = match self.bending {
1885            Some(b) => self.rest_at(b, self.coordinates(tool), self.carried()),
1886            None => {
1887                let t = self.legs.inverse(self.coordinates(tool)).unwrap_or([f64::NAN; 4]);
1888                (t, self.rigid_load(t, [0.0; 4]).2, [0.0; 4], [0.0; 4])
1889            }
1890        };
1891        state.clear();
1892        state.extend(t);
1893        state.extend([0.0; 4]);
1894        for k in 0..4 {
1895            let joint = &self.joints[k];
1896            // At rest the gearbox holds the arm against gravity and the stops.
1897            let out = -gravity[k] - joint.output_torque(t[k], 0.0);
1898            let rotor = joint.ratio() * (t[k] + if self.elastic { joint.gearbox.static_twist(out) } else { 0.0 });
1899            if self.elastic {
1900                state.push(rotor);
1901            }
1902            torque[k] = joint.ripple.invert(out / joint.ratio(), rotor);
1903        }
1904        // Rotor speeds and brakes at rest; the tool at its turn, its spring unloaded (nothing turns it at rest).
1905        state.resize(self.turn_at(), 0.0);
1906        if self.amplifier.is_some() {
1907            state.extend([tool[3], 0.0]);
1908        }
1909        // The bend still, and the elbows' moves out of the planes.
1910        if self.bending.is_some() {
1911            state.extend(bend);
1912            state.extend([0.0; 4]);
1913            state.extend(lateral);
1914            state.extend([0.0; 4]);
1915        }
1916    }
1917
1918    fn derivatives(&self, s: &[f64], torque: &[f64], out: &mut [f64]) {
1919        // The pose of the elbows, worked out once for the amplifier, the bend and the load (forward kinematics by
1920        // Newton).
1921        let pose = (self.amplifier.is_some() || self.bending.is_some()).then(|| self.pose_at(s));
1922        if let (Some(pose), true) = (&pose, self.amplifier.is_some()) {
1923            let at = self.turn_at();
1924            out[at] = s[at + 1];
1925            out[at + 1] = (self.amplifier_torque_at(s, pose) + self.pushed::<1>(s, at + 1)[0]) / self.tool_inertia();
1926        }
1927        if !self.elastic {
1928            let (acc, ..) = self.rigid_solve(s, torque);
1929            let (_, rotor_speed) = self.rotors(s);
1930            let brakes = self.brakes(s);
1931            out[..4].copy_from_slice(&s[4..8]);
1932            out[4..8].copy_from_slice(&acc);
1933            for k in 0..4 {
1934                out[8 + k] = self.joints[k].brake.torque(self.brake_engaged, rotor_speed[k], brakes[k]).1;
1935            }
1936            if let Some(pose) = &pose {
1937                self.bend_rates(s, pose, acc, out);
1938            }
1939            return;
1940        }
1941        let (t, w) = self.arms(s);
1942        let (mass, velocity, gravity) = match &pose {
1943            Some(pose) => self.joint_load_at(s, pose),
1944            None => self.joint_load(s),
1945        };
1946        let (mut rhs, push) = ([0.0; 4], self.pushed_on_arms(s));
1947        for k in 0..4 {
1948            let joint = &self.joints[k];
1949            let (gear, rotor_acc, brake_rate) =
1950                joint.rotor(torque[k], s[8 + k], s[12 + k], t[k], w[k], s[16 + k], self.brake_engaged);
1951            rhs[k] = gear.output + gravity[k] - velocity[k] + joint.output_torque(t[k], w[k]) + push[k];
1952            out[8 + k] = s[12 + k];
1953            out[12 + k] = rotor_acc;
1954            out[16 + k] = brake_rate;
1955        }
1956        let acc = solve4(&mass, rhs).unwrap_or([f64::NAN; 4]);
1957        out[..4].copy_from_slice(&s[4..8]);
1958        out[4..8].copy_from_slice(&acc);
1959        if let Some(pose) = &pose {
1960            self.bend_rates(s, pose, acc, out);
1961        }
1962    }
1963
1964    fn tool_state(&self, s: &[f64], pos: &mut [f64], vel: &mut [f64]) {
1965        let ((_, ew), (_, yv)) = (self.elbows(s), self.lateral(s));
1966        let (x, j, jy) = self.pose_at(s);
1967        let v: V4 = std::array::from_fn(|r| dot4(j[r], ew) + dot4(jy[r], yv));
1968        pos[..3].copy_from_slice(&x[..3]);
1969        vel[..3].copy_from_slice(&v[..3]);
1970        (pos[3], vel[3]) = self.turn(s);
1971    }
1972    /// The arms turn at the speed, the tool on the amplifier's spring with them, the bend (in and out of the arms'
1973    /// planes) standing still.
1974    fn set_tool_velocity(&self, s: &mut [f64], vel: &[f64]) {
1975        let (_, j, _) = self.pose_at(s);
1976        let w = solve4(&j, self.coordinates(vel)).unwrap_or([f64::NAN; 4]);
1977        s[4..8].copy_from_slice(&w);
1978        if self.bending.is_some() {
1979            let at = self.bend_at();
1980            s[at + 4..at + 8].fill(0.0);
1981            s[at + 12..at + 16].fill(0.0);
1982        }
1983        if self.elastic {
1984            for k in 0..4 {
1985                s[12 + k] = self.joints[k].ratio() * w[k];
1986            }
1987        }
1988        if self.amplifier.is_some() {
1989            let at = self.turn_at();
1990            s[at + 1] = vel[3];
1991        }
1992    }
1993    fn motor_state(&self, s: &[f64], pos: &mut [f64], vel: &mut [f64]) {
1994        let (rotor, speed) = self.rotors(s);
1995        pos[..4].copy_from_slice(&rotor);
1996        vel[..4].copy_from_slice(&speed);
1997    }
1998
1999    /// Rigid, loss-free, at rest: M theta'' - Q_g at the arm over the ratio, plus the rotor's own J_rotor i theta'',
2000    /// theta'' = J^-1 (p'', c'' / kappa).
2001    fn feedforward_torque(&self, pos: &[f64], acc: &[f64], out: &mut [f64]) {
2002        let x = self.coordinates(pos);
2003        let t = self.legs.inverse(x).unwrap_or([f64::NAN; 4]);
2004        let j = self.legs.jacobian(t, x).unwrap_or([[f64::NAN; 4]; 4]);
2005        let (mass, _, gravity) = self.load_with(t, x, j, [0.0; 4], self.carried(), self.tool_inertia());
2006        let arm_acc = solve4(&j, self.coordinates(acc)).unwrap_or([f64::NAN; 4]);
2007        let at_arm = mul4(&mass, arm_acc);
2008        for k in 0..4 {
2009            let joint = &self.joints[k];
2010            out[k] = (at_arm[k] - gravity[k]) / joint.ratio() + joint.rotor_inertia * joint.ratio() * arm_acc[k];
2011        }
2012    }
2013
2014    /// With the speed: theta' = J^-1 x', theta'' = J^-1 (x'' - J_x^-1 w), and at the arm M theta'' + v - Q_g, over the
2015    /// ratio, plus the rotor's own J_rotor i theta''. The tool turns with the slide.
2016    fn feedforward_torque_moving(&self, pos: &[f64], vel: &[f64], acc: &[f64], out: &mut [f64]) {
2017        let x = self.coordinates(pos);
2018        let t = self.legs.inverse(x).unwrap_or([f64::NAN; 4]);
2019        let j = self.legs.jacobian(t, x).unwrap_or([[f64::NAN; 4]; 4]);
2020        let (xv, xa) = (self.coordinates(vel), self.coordinates(acc));
2021        let w = solve4(&j, xv).unwrap_or([f64::NAN; 4]);
2022        let bend = self.legs.velocity_term(t, x, w, xv).unwrap_or([f64::NAN; 4]);
2023        let arm_acc = solve4(&j, std::array::from_fn(|i| xa[i] - bend[i])).unwrap_or([f64::NAN; 4]);
2024        let (mass, velocity, gravity) = self.load_with(t, x, j, w, self.carried(), self.tool_inertia());
2025        let at_arm = mul4(&mass, arm_acc);
2026        for k in 0..4 {
2027            let joint = &self.joints[k];
2028            out[k] = (at_arm[k] + velocity[k] - gravity[k]) / joint.ratio()
2029                + joint.rotor_inertia * joint.ratio() * arm_acc[k];
2030        }
2031    }
2032
2033    /// The rigid model at a steady speed, theta' = J^-1 (p', c' / kappa): per arm the joint's friction f(theta')
2034    /// through the gearbox as `rigid_solve` takes it, f / (i loss), plus the motor shaft's friction (with the gearbox's
2035    /// drag) at i theta'. The loss factor is the one of what the gearbox passes at rest, f - Q_g, as in `rigid_solve`;
2036    /// the weight itself is the rigid feedforward's. The amplifier's damping does not work at a steady speed; the brake
2037    /// is released and the stops are not touched in a move.
2038    fn steady_friction(&self, pos: &[f64], vel: &[f64], out: &mut [f64]) {
2039        let x = self.coordinates(pos);
2040        let t = self.legs.inverse(x).unwrap_or([f64::NAN; 4]);
2041        let j = self.legs.jacobian(t, x).unwrap_or([[f64::NAN; 4]; 4]);
2042        let w = solve4(&j, self.coordinates(vel)).unwrap_or([f64::NAN; 4]);
2043        let gravity = self.load_with(t, x, j, [0.0; 4], self.carried(), self.tool_inertia()).2;
2044        for k in 0..4 {
2045            let joint = &self.joints[k];
2046            let at_arm = joint.friction.torque(w[k]);
2047            let loss = joint.gearbox.loss_factor(at_arm - gravity[k], w[k]);
2048            out[k] = joint.shaft.torque(joint.ratio() * w[k]) + at_arm / (joint.ratio() * loss);
2049        }
2050    }
2051
2052    fn energy(&self, s: &[f64]) -> f64 {
2053        self.energy_parts(s).iter().sum()
2054    }
2055
2056    /// As `Machine::adopt_state`, the same pose and speed with the gears as at rest there; but from a model to one with
2057    /// the same states (`Sim::reconfigure` keeps the entry), as on the other machines with gears on their arms, each gearbox keeps the twist it
2058    /// had at its motor, and with effects.amplifier_compliance the tool keeps its angle and speed on the amplifier's
2059    /// spring, the slide where the arms had it. Rebuilt at rest, the slide was put under the tool and the spring
2060    /// unloaded, and the gears put back in the middle of their play: after a 1 % change of the ratio during a move the
2061    /// tool's turn jumped by 0.19 mrad in the first 10 ms (0.02 now).
2062    fn adopt_state(&self, old: &dyn Machine, old_state: &[f64]) -> Vec<f64> {
2063        let (mut pos, mut vel, mut before, mut after) = ([0.0; 4], [0.0; 4], [0.0; 4], [0.0; 4]);
2064        old.tool_state(old_state, &mut pos, &mut vel);
2065        old.inverse(&pos, &mut before);
2066        self.inverse(&pos, &mut after);
2067        let same = old_state.len() == self.state_len();
2068        if same && before == after {
2069            return old_state.to_vec();
2070        }
2071        // The slide's turn, from the old arms in this machine's geometry: the tool's own where it is not on a spring.
2072        let (mut slide, mut slide_vel) = (pos, vel);
2073        if same && self.amplifier.is_some() {
2074            (slide[3], slide_vel[3]) = self.slide_of(old_state, &self.pose_at(old_state));
2075            old.inverse(&slide, &mut before);
2076            self.inverse(&slide, &mut after);
2077        }
2078        let mut state = Vec::new();
2079        self.equilibrium(&slide, &mut state, &mut [0.0; 4]);
2080        self.set_tool_velocity(&mut state, &slide_vel);
2081        if same && self.amplifier.is_some() {
2082            let at = self.turn_at();
2083            (state[at], state[at + 1]) = (pos[3], vel[3]);
2084        }
2085        if same && self.elastic {
2086            let (mut rotor, mut speed) = ([0.0; 4], [0.0; 4]);
2087            old.motor_state(old_state, &mut rotor, &mut speed);
2088            for k in 0..4 {
2089                state[8 + k] = after[k] + rotor[k] - before[k];
2090            }
2091        }
2092        state
2093    }
2094
2095    fn set_payload_attached(&mut self, attached: bool) {
2096        self.payload_attached = attached;
2097    }
2098    fn set_brake_engaged(&mut self, engaged: bool) {
2099        self.brake_engaged = engaged;
2100    }
2101    /// A stop met within the step (`HardStop::substeps`, `RotaryJoint::stop_substeps`).
2102    fn substeps_wanted(&self, s: &[f64], _torque: &[f64], dt: f64, _substeps: u32) -> u32 {
2103        let (t, w) = self.arms(s);
2104        (0..t.len()).map(|k| self.joints[k].stop_substeps(t[k], w[k], dt)).max().unwrap_or(1)
2105    }
2106    /// The push acts on the plate and the tool, beyond the gearboxes, in either model: on the arms, or with bending
2107    /// arms on the elbows and their moves out of the arms' planes, and with the amplifier's compliance its turn on the
2108    /// tool's (`pushed`); its power is the budget's crash row.
2109    fn set_tool_force(&mut self, force: &[f64]) -> bool {
2110        self.push = [force[0], force[1], force[2], force[3]];
2111        true
2112    }
2113
2114    /// The gearboxes' hysteresis states move on to where the step ended (`Gearbox::commit`).
2115    fn after_step(&mut self, s: &mut [f64], _dt: f64) {
2116        if self.elastic {
2117            for k in 0..4 {
2118                self.joints[k].gearbox.commit(s[8 + k], s[k]);
2119            }
2120        }
2121    }
2122
2123    /// The gearboxes, in the order of `thermal_parts`.
2124    fn set_part_temperatures(&mut self, rises: &[f64]) {
2125        let Some(law) = &self.thermal else { return };
2126        if self.joints[0].gearbox.is_coupling() {
2127            return;
2128        }
2129        for (joint, rise) in self.joints.iter_mut().zip(rises) {
2130            joint.gearbox.efficiency = law.gearbox_efficiency(*rise);
2131        }
2132    }
2133
2134    /// What the gearboxes can sag at rest anywhere in the working range (`rest_sag`).
2135    fn setpoint_slack(&self) -> f64 {
2136        self.rest_slack
2137    }
2138
2139    fn unreachable(&self, tool: &[f64], slack: f64) -> Option<&'static str> {
2140        if tool.len() != 4 {
2141            return Some("error-target-out-of-range");
2142        }
2143        if !self.in_envelope(tool, slack) {
2144            return Some("error-delta-outside-envelope");
2145        }
2146        let x = self.coordinates(tool);
2147        let Some(t) = self.legs.inverse(x) else { return Some("error-delta-out-of-reach") };
2148        let (min, max) = self.joints[0].range;
2149        if t.iter().any(|a| *a < min || *a > max) {
2150            return Some("error-delta-joint-stop");
2151        }
2152        match self.legs.jacobian(t, x) {
2153            Some(j) if condition_number(&j) <= self.max_condition => None,
2154            _ => Some("error-delta-singularity"),
2155        }
2156    }
2157
2158    /// Of the Jacobian in (x, y, z, h), elbows out (`condition_number`), as the signal `kinematics.condition` and the
2159    /// check against `workspace.max_condition_number`.
2160    fn condition(&self, tool: &[f64]) -> Option<f64> {
2161        let x = self.coordinates(tool);
2162        let j = self.legs.inverse(x).and_then(|t| self.legs.jacobian(t, x));
2163        Some(j.map_or(f64::INFINITY, |j| condition_number(&j)))
2164    }
2165
2166    fn signal_infos(&self) -> Vec<SignalInfo> {
2167        let mut out = Vec::new();
2168        for (k, motor) in self.motors.iter().enumerate() {
2169            out.push(SignalInfo::new(format!("arm.{}.angle", motor.id), ARMS[k], "quantity-arm-angle", "rad"));
2170            out.push(SignalInfo::new(
2171                format!("gearbox.{}.output_torque", motor.id),
2172                motor.key,
2173                "quantity-gearbox-torque",
2174                "N m",
2175            ));
2176        }
2177        out.push(SignalInfo::new("kinematics.condition", "group-kinematics", "quantity-condition-number", ""));
2178        out.push(SignalInfo::new("plate.slide", "group-plate", "quantity-plate-slide", "m"));
2179        if self.amplifier.is_some() {
2180            out.push(SignalInfo::new("plate.amplifier_twist", "group-plate", "quantity-amplifier-twist", "rad"));
2181        }
2182        self.effect_infos(&mut out);
2183        out
2184    }
2185
2186    /// Per arm its angle and gearbox torque, the condition number, the parts' slide against each other (2 h) and with
2187    /// effects.amplifier_compliance the amplifier's twist.
2188    fn base_signals(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
2189        let (t, _) = self.arms(s);
2190        let gear = self.gear_output(s, torque);
2191        for k in 0..4 {
2192            out.extend([t[k], gear[k]]);
2193        }
2194        let (x, j, _) = self.pose_at(s);
2195        out.push(condition_number(&j));
2196        out.push(2.0 * x[3]);
2197        if self.amplifier.is_some() {
2198            out.push(self.twist(s).0);
2199        }
2200    }
2201    fn effect_signals(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
2202        self.view_signals(s, torque, out);
2203    }
2204    fn loss_powers(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
2205        self.loss_signals(&self.losses(s, torque), out);
2206    }
2207
2208    /// The four joints' bearing friction, rotary contacts (N m over rad/s at the arm).
2209    fn friction_contacts(&self) -> Vec<sim_core::FrictionContact> {
2210        (0..4).map(|k| sim_core::FrictionContact { id: JOINT_CONTACTS[k], owner_key: ARMS[k] }).collect()
2211    }
2212    fn friction_rotary(&self, _i: usize) -> bool {
2213        true
2214    }
2215    fn friction_curve(&self, i: usize, speed: f64, _load_scale: f64) -> [f64; 3] {
2216        self.joints.get(i).map_or([0.0; 3], |j| j.friction_split(speed))
2217    }
2218    /// The arm turns at its motor's highest speed over the gearbox's ratio.
2219    fn friction_speed_limit(&self, i: usize, motor_speed: &[f64]) -> Option<f64> {
2220        Some(motor_speed.get(i)? / self.joints.get(i)?.ratio())
2221    }
2222
2223    /// The four gearboxes, where there are gearboxes (not on a direct drive).
2224    fn thermal_parts(&self) -> Vec<ThermalPart> {
2225        if self.joints[0].gearbox.is_coupling() {
2226            return Vec::new();
2227        }
2228        [
2229            ("gearbox_1", "motor-arm-1"),
2230            ("gearbox_2", "motor-arm-2"),
2231            ("gearbox_3", "motor-arm-3"),
2232            ("gearbox_4", "motor-arm-4"),
2233        ]
2234        .into_iter()
2235        .enumerate()
2236        .map(|(k, (id, owner_key))| ThermalPart {
2237            id,
2238            kind: "gearbox",
2239            owner_key,
2240            scene_part: "gearbox",
2241            scene_index: k,
2242        })
2243        .collect()
2244    }
2245
2246    fn scene(&self, s: &[f64], out: &mut Scene) {
2247        // The arms drawn straight to their elbows, bent or not.
2248        let ((t, _), (y, _)) = (self.elbows(s), self.lateral(s));
2249        let (rotor, rotor_speed) = self.rotors(s);
2250        let (x, ..) = self.pose_moved(t, y);
2251        let (c, _) = self.turn(s);
2252        let p = [x[0], x[1], x[2]];
2253        out.parts.clear();
2254        out.labels.clear();
2255        let grey = [0.62, 0.64, 0.68];
2256        out.parts.push(Part::new(
2257            "base",
2258            Shape::Box { size: [2.4 * self.base_radius, 2.4 * self.base_radius, 0.04] },
2259            [0.0, 0.0, 0.1],
2260            grey,
2261        ));
2262        for k in 0..4 {
2263            let (cos, sin) = self.legs.azimuth[k];
2264            let (shoulder, arm_end) = self.arm(k, t, y);
2265            let at = |r: f64, z: f64| [r * cos, r * sin, z];
2266            out.parts.push(Part::new(
2267                sim_core::scene::MOTOR_PART,
2268                Shape::Box { size: [0.1, 0.1, 0.14] },
2269                at(self.base_radius, 0.17),
2270                [0.9, 0.45, 0.1],
2271            ));
2272            out.parts.push(Part::new(
2273                "gearbox",
2274                Shape::Box { size: [0.1, 0.1, 0.07] },
2275                at(self.base_radius, 0.055),
2276                [0.25, 0.25, 0.28],
2277            ));
2278            out.parts.push(
2279                Part::new(
2280                    "rotor-bar",
2281                    Shape::Box { size: [0.08, 0.004, 0.012] },
2282                    at(self.base_radius, 0.245),
2283                    [0.1, 0.1, 0.1],
2284                )
2285                .turned(rotor[k]),
2286            );
2287            out.parts.push(Part::new(
2288                "arm",
2289                Shape::Segment { to: arm_end, width: ARM_WIDTH },
2290                shoulder,
2291                [0.2, 0.22, 0.26],
2292            ));
2293            // The two rods of the forearm pair, apart along the elbow's axis (tangential to the base).
2294            for (from, to) in self.legs.rods_moved(k, t[k], y[k], x, self.plate_radius, self.rod_spacing) {
2295                out.parts.push(Part::new("forearm", Shape::Segment { to, width: ROD_WIDTH }, from, [0.15, 0.15, 0.15]));
2296            }
2297            out.labels.push(Label {
2298                pos: at(self.base_radius, 0.32),
2299                owner_key: self.motors[k].key,
2300                value: rotor_speed[k] * 60.0 / std::f64::consts::TAU,
2301                unit_key: "unit-rpm",
2302                decimals: 0,
2303            });
2304        }
2305        for (from, to) in self.plate_bars(x) {
2306            out.parts.push(Part::new("plate-part", Shape::Segment { to, width: PLATE_WIDTH }, from, [0.55, 0.55, 0.6]));
2307        }
2308        out.parts.extend(self.on_carriage(p));
2309        // A bar under the carriage, turned with the tool.
2310        let (from, to) = self.tool_bar(p, c);
2311        out.parts.push(Part::new("tool", Shape::Segment { to, width: TOOL_BAR_WIDTH }, from, [0.85, 0.75, 0.2]));
2312        out.labels.push(Label {
2313            pos: [p[0], p[1], p[2] - 0.2],
2314            owner_key: "axis-z",
2315            value: p[2],
2316            unit_key: "unit-m",
2317            decimals: 3,
2318        });
2319    }
2320
2321    /// The carriage's centre, the tool's point: the machine's frame is the scene's.
2322    fn scene_point(&self, tool_pose: &[f64]) -> Option<[f64; 3]> {
2323        Some([tool_pose[0], tool_pose[1], tool_pose[2]])
2324    }
2325
2326    /// The carriage and the payload under it as boxes, where `scene` draws them.
2327    fn collision_bodies(&self, s: &[f64]) -> Vec<sim_core::Aabb> {
2328        let (x, ..) = self.pose_at(s);
2329        sim_core::scene::scene_boxes(&self.on_carriage([x[0], x[1], x[2]]), &["carriage", "payload"])
2330    }
2331
2332    /// The two plate parts, the eight forearm rods, the four upper arms and the tool's bar under the carriage, each
2333    /// the capsule along the segment `scene` draws, of half its width: exact for a round piece of that width, and no
2334    /// wider than the drawn strip anywhere along it.
2335    fn collision_capsules(&self, s: &[f64]) -> Vec<sim_core::Capsule> {
2336        let ((t, _), (y, _)) = (self.elbows(s), self.lateral(s));
2337        let (x, ..) = self.pose_moved(t, y);
2338        let capsule = |(from, to): (V3, V3), width: f64| sim_core::Capsule { from, to, radius: width / 2.0 };
2339        let mut out: Vec<_> = self.plate_bars(x).into_iter().map(|bar| capsule(bar, PLATE_WIDTH)).collect();
2340        for k in 0..4 {
2341            out.extend(
2342                self.legs
2343                    .rods_moved(k, t[k], y[k], x, self.plate_radius, self.rod_spacing)
2344                    .map(|rod| capsule(rod, ROD_WIDTH)),
2345            );
2346            out.push(capsule(self.arm(k, t, y), ARM_WIDTH));
2347        }
2348        out.push(capsule(self.tool_bar([x[0], x[1], x[2]], self.turn(s).0), TOOL_BAR_WIDTH));
2349        out
2350    }
2351
2352    /// With effects.joint_elasticity: per arm its gearbox's spring (K1) between the rotor and the rest of the motor's
2353    /// rigid inertia at the pose, over the ratio squared; the arms' bending and the amplifier are left out.
2354    fn trains(&self, tool_pose: &[f64]) -> Vec<Option<sim_core::Train>> {
2355        if !self.elastic {
2356            return Vec::new();
2357        }
2358        let whole = sim_components::control::rigid_inertias(self, tool_pose);
2359        self.joints.iter().zip(whole).map(|(j, whole)| j.train(whole)).collect()
2360    }
2361
2362    /// The lowest of the arms' modes (`modes_at`), with the gearboxes' springs (effects.joint_elasticity): what an input
2363    /// shaper on the path is for. The tool's turn on the amplifier is in `modes`.
2364    fn resonance_hz(&self, tool_pose: &[f64]) -> Option<f64> {
2365        self.modes_at(tool_pose, false).first().map(|mode| mode.0)
2366    }
2367
2368    /// The mode of `resonance_hz`: the joints' turns in the arm angles, rotors and tool still; scaled so that the tool
2369    /// point's largest travel along an axis is 1 m.
2370    fn mode_shape(&self, tool_pose: &[f64]) -> Option<(f64, Vec<f64>)> {
2371        let (hz, _, v) = self.modes_at(tool_pose, false).into_iter().next()?;
2372        let x = self.coordinates(tool_pose);
2373        let (j, jy) = self.legs.jacobians(self.legs.inverse(x)?, [0.0; 4], x)?;
2374        // The joints' turns, the elbows' turns and moves (with bending arms; else the arm angles alone).
2375        let block = |at: usize| -> V4 { std::array::from_fn(|k| v.get(at + k).copied().unwrap_or(0.0)) };
2376        let (root, tip, moves) =
2377            if self.bending.is_some() { (block(0), block(4), block(8)) } else { (block(0), block(0), [0.0; 4]) };
2378        let (a, b) = (mul4(&j, tip), mul4(&jy, moves));
2379        let largest = (0..3).fold(0f64, |m, k| m.max((a[k] + b[k]).abs()));
2380        let mut shape = vec![0.0; self.state_len()];
2381        for k in 0..4 {
2382            shape[k] = root[k] / largest;
2383        }
2384        if self.bending.is_some() {
2385            let at = self.bend_at();
2386            for k in 0..4 {
2387                shape[at + k] = (tip[k] - root[k]) / largest;
2388                shape[at + 8 + k] = moves[k] / largest;
2389            }
2390        }
2391        Some((hz, shape))
2392    }
2393
2394    /// The arms' four modes (with effects.joint_elasticity) and the tool's turn on the amplifier (with
2395    /// effects.amplifier_compliance), lowest first.
2396    fn modes(&self, tool_pose: &[f64]) -> Vec<Mode> {
2397        self.modes_with(tool_pose, false)
2398    }
2399
2400    /// `modes` with the gearboxes' hysteresis stiffness added (K1 + sigma): the frequencies of a small ringing. The
2401    /// amplifier's spring has no hysteresis: its mode stays.
2402    fn modes_small_amplitude(&self, tool_pose: &[f64]) -> Vec<Mode> {
2403        self.modes_with(tool_pose, true)
2404    }
2405}
2406
2407/// The forearm rods', upper arms', plate parts' and tool bar's width as drawn and as collision capsules (twice their
2408/// radius), m.
2409const ROD_WIDTH: f64 = 0.014;
2410/// The tube's mode, the static shape psi = (3 xi^2 - xi^3) / 2 along the arm (xi = s / L_a, consistent with
2411/// k_b = 3 E I / L_a, `beam::STATIC_SHAPE_MASS`): int(xi psi) = 11/40 over int(psi) = 3/8, 11/15, where its momentum
2412/// out of the plane acts; int(xi psi) itself, the tube's in-plane momentum that moves with its turn.
2413const TUBE_CENTROID: f64 = sim_components::beam::STATIC_SHAPE_MOMENT / sim_components::beam::STATIC_SHAPE_PARTICIPATION;
2414const TUBE_MOMENT: f64 = sim_components::beam::STATIC_SHAPE_MOMENT;
2415const ARM_WIDTH: f64 = 0.05;
2416const PLATE_WIDTH: f64 = 0.03;
2417const TOOL_BAR_WIDTH: f64 = 0.015;
2418
2419#[cfg(test)]
2420mod tests;