Skip to main content

machine_delta_linear/
lib.rs

1//! Linear delta: three toothed-belt axes on the columns of a frame at 120 degrees, each carriage carrying a
2//! parallelogram of two rods down to a plate that stays level (Festo EXPT, the Kossel printers). The columns
3//! stand upright or lean by an angle alpha (`geometry.column_incline_deg`, positive with their tops towards the
4//! machine's axis). The tool is the plate's centre, x, y, z.
5//!
6//! Kinematics per leg i at azimuth phi_i, with e = column radius - plate radius (the plate's offset folded into the
7//! columns, as the plate never turns; both measured at z = 0), the carriage's travel h_i along its column from z = 0
8//! and the rod length L:
9//!
10//! ```text
11//! column     d_i = (-sin alpha cos phi_i, -sin alpha sin phi_i, cos alpha)
12//! joint      c_i = (e cos phi_i, e sin phi_i, 0) + h_i d_i
13//! constraint |p - c_i|^2 = L^2
14//! inverse    h_i = q_i . d_i + sqrt(L^2 - rho_i^2),  q_i = p - c_i(0), rho_i = |q_i - (q_i . d_i) d_i|
15//!            (rho_i the plate's distance from the joint line; the carriage above the plate)
16//! forward    p = the lower of the two points at L from all three joints (trilateration)
17//! Jacobian   J_x p' = J_q h', J_x rows u_i = p - c_i, J_q = diag(u_i . d_i); p' = J h', J = J_x^-1 J_q
18//!            J_x p'' = J_q h'' + w, w_i = -|p' - d_i h_i'|^2
19//! ```
20//!
21//! Upright (alpha 0) d_i = e_z, h_i is the joint's height and these are the vertical delta's formulas, to the bit.
22//!
23//! Dynamics at the D3's level (Codourey 1998, Olsson 2009): the rods' rotational inertia is left out and each rod pair's
24//! mass m_rod split, a share r at its carriage and 1 - r at the plate. The machine is three carriages plus a point mass
25//! at the plate, m_nt = plate + payload + 3 (1 - r) m_rod, and by virtual work
26//!
27//! ```text
28//! M(h) h'' = F_belt + Q_g - m_nt J^T J_x^-1 w - F_guide + F_stop,   M = m_c 1 + m_nt J^T J,
29//! Q_g,i = -g m_c cos alpha - m_nt g J_zi,   m_c = carriage + r m_rod
30//! ```
31//!
32//! The carriage's weight acts on its belt with m_c g cos alpha; the rest, m_c g sin alpha, and what the rods' pull has
33//! across the column, the guide takes (`guide_loads`).
34//!
35//! Each column is a belt axis as on the one-axis machine, turned upright with its motor at the top: the motor pulley
36//! at the top and an idler at the bottom cut the belt into section 1, from the motor pulley straight down to the carriage
37//! (length span + stroke - x), and section 2, from the motor pulley down round the idler and up to the carriage
38//! (3 span + stroke + x), x = h - h_min the carriage's place in its stroke. The belt pulls the carriage up with T1 - T2
39//! and the pulley with r (T2 - T1). Elastic (effects.belt_stretch) the sections are springs and pulley and rotor states of
40//! their own behind the coupling or gearbox; rigid, carriage, pulley and rotor turn together, x = r a, rotor = i a.
41//! The guides are LuGre contacts (`Lugre`), loaded across the rail by the rods' pull.
42
43use sim_components::mech::{
44    Belt, Gearbox, HardStop, HoldingBrake, Lugre, Ripple, SectionForce, ShaftFriction, ThermalFeedback,
45};
46use sim_core::{
47    AxisInfo, BeltSection, Config, ConfigError, ENERGY_PARTS, FRICTION_SIGNALS, FrictionContact, LOSS_PREFIX, Label,
48    Machine, MachineEntry, MotorInfo, Part, RatingCheck, Scene, Shape, SignalInfo, TORQUE_PARTS, ThermalPart,
49};
50
51pub static ENTRY: MachineEntry = MachineEntry {
52    id: "delta-linear",
53    key: "machine-delta-linear",
54    default_config: include_str!("../default.toml"),
55    i18n: &[("en", include_str!("../i18n/en.ftl")), ("de", include_str!("../i18n/de.ftl"))],
56    build,
57    suite_configs,
58};
59
60const G: f64 = 9.80665;
61
62/// Effects that take energy out or put it in; the standard suite runs with them off.
63pub const LOSSY_EFFECTS: [&str; 10] = [
64    "belt_damping",
65    "guide_friction",
66    "load_dependent_friction",
67    "motor_friction",
68    "gearbox_drag",
69    "gearbox_lost_motion",
70    "gearbox_efficiency",
71    "torque_ripple",
72    "temperature",
73    "holding_brake",
74];
75
76fn build(cfg: &Config) -> Result<Box<dyn Machine>, ConfigError> {
77    sim_components::base::mount(cfg, Box::new(LinearDelta::new(cfg)?))
78}
79
80/// The default config with every loss switched off.
81pub fn lossless_config() -> Config {
82    let mut cfg = ENTRY.config();
83    for effect in LOSSY_EFFECTS {
84        cfg.set_text(&format!("effects.{effect} = false")).unwrap();
85    }
86    cfg.set_text("gearbox.damping_nm_s_rad = 0.0").unwrap();
87    cfg.set_text("hard_stop.damping_n_s_m = 0.0").unwrap();
88    cfg
89}
90
91/// Loss-free rigid and elastic models, with and without the payload; the elastic ones with the belt's tooth stiffness
92/// once with and once without.
93fn suite_configs() -> Vec<Config> {
94    let mut out = Vec::new();
95    for (elastic, payload) in [(false, true), (false, false), (true, true), (true, false)] {
96        let mut cfg = lossless_config();
97        cfg.set_text(&format!("effects.belt_stretch = {elastic}")).unwrap();
98        cfg.set_text(&format!("effects.payload = {payload}")).unwrap();
99        cfg.set_text(&format!("effects.belt_tooth_stiffness = {}", elastic && payload)).unwrap();
100        out.push(cfg);
101    }
102    out
103}
104
105type V3 = [f64; 3];
106type M3 = [[f64; 3]; 3];
107
108fn dot(a: V3, b: V3) -> f64 {
109    a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
110}
111
112fn sub(a: V3, b: V3) -> V3 {
113    [a[0] - b[0], a[1] - b[1], a[2] - b[2]]
114}
115
116fn cross(a: V3, b: V3) -> V3 {
117    [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
118}
119
120fn norm(a: V3) -> f64 {
121    dot(a, a).sqrt()
122}
123
124fn mul(m: &M3, v: V3) -> V3 {
125    [dot(m[0], v), dot(m[1], v), dot(m[2], v)]
126}
127
128fn transpose(m: &M3) -> M3 {
129    std::array::from_fn(|i| std::array::from_fn(|j| m[j][i]))
130}
131
132/// The inverse of a 3 x 3 matrix by its adjugate; `None` where it is singular.
133fn inverse(m: &M3) -> Option<M3> {
134    let det = dot(m[0], cross(m[1], m[2]));
135    if !(det.abs() > 1e-300) || !det.is_finite() {
136        return None;
137    }
138    let (c0, c1, c2) = (cross(m[1], m[2]), cross(m[2], m[0]), cross(m[0], m[1]));
139    Some(std::array::from_fn(|i| [c0[i] / det, c1[i] / det, c2[i] / det]))
140}
141
142/// The 2-norm condition number of a 3 x 3 matrix, as the spatial delta picker's (copied so that
143/// the machine crates stay apart): the square root of the largest over the smallest eigenvalue of J^T J.
144pub fn condition_number(j: &M3) -> f64 {
145    let jt = transpose(j);
146    let a: M3 = std::array::from_fn(|r| std::array::from_fn(|c| dot(jt[r], jt[c])));
147    let q = (a[0][0] + a[1][1] + a[2][2]) / 3.0;
148    let p1 = a[0][1] * a[0][1] + a[0][2] * a[0][2] + a[1][2] * a[1][2];
149    let p2 = (0..3).map(|i| (a[i][i] - q).powi(2)).sum::<f64>() + 2.0 * p1;
150    let p = (p2 / 6.0).sqrt();
151    if p < 1e-15 * q.abs() {
152        return 1.0;
153    }
154    let b: M3 = std::array::from_fn(|r| std::array::from_fn(|c| (a[r][c] - if r == c { q } else { 0.0 }) / p));
155    let half_det = (dot(b[0], cross(b[1], b[2])) / 2.0).clamp(-1.0, 1.0);
156    let phi = half_det.acos() / 3.0;
157    let (largest, smallest) = (q + 2.0 * p * phi.cos(), q + 2.0 * p * (phi + 2.0 * std::f64::consts::PI / 3.0).cos());
158    if smallest <= 0.0 { f64::INFINITY } else { (largest / smallest).sqrt() }
159}
160
161/// The leg geometry and the kinematics, apart from masses and drives.
162#[derive(Debug, Clone)]
163pub struct Legs {
164    /// Column radius less plate radius (at z = 0), rod length.
165    pub e: f64,
166    pub l: f64,
167    /// cos and sin of the columns' azimuths, 0, 120 and 240 degrees.
168    pub azimuth: [(f64, f64); 3],
169    /// Each column's unit direction d_i, up along it: e_z upright, its top towards the axis for a positive incline.
170    pub dir: [V3; 3],
171}
172
173impl Legs {
174    /// `incline`: the columns' lean from the vertical, rad, positive with their tops towards the axis.
175    pub fn new(e: f64, l: f64, incline: f64) -> Self {
176        let azimuth = [0.0f64, 120.0, 240.0].map(|deg| (deg.to_radians().cos(), deg.to_radians().sin()));
177        let (sin, cos) = incline.sin_cos();
178        let dir = azimuth.map(|(c, s)| [-sin * c, -sin * s, cos]);
179        Self { e, l, azimuth, dir }
180    }
181
182    /// Where column i's joint line passes z = 0, x and y.
183    fn column(&self, i: usize) -> [f64; 2] {
184        let (c, s) = self.azimuth[i];
185        [self.e * c, self.e * s]
186    }
187
188    /// The plate position's offset from column i's joint line at right angles to it (upright: horizontal, its z exactly
189    /// 0), and the travel along the column to its foot, q . d.
190    fn across(&self, i: usize, p: V3) -> (V3, f64) {
191        let ([cx, cy], d) = (self.column(i), self.dir[i]);
192        let q = [p[0] - cx, p[1] - cy, p[2]];
193        let along = dot(q, d);
194        ([q[0] - along * d[0], q[1] - along * d[1], q[2] - along * d[2]], along)
195    }
196
197    /// The distance of a plate position from column i's joint line (upright: horizontal).
198    pub fn reach(&self, i: usize, p: V3) -> f64 {
199        let (q, _) = self.across(i, p);
200        q[0].hypot(q[1]).hypot(q[2])
201    }
202
203    fn joint(&self, i: usize, h: f64) -> V3 {
204        let ([cx, cy], d) = (self.column(i), self.dir[i]);
205        [cx + h * d[0], cy + h * d[1], h * d[2]]
206    }
207
208    /// The carriages' travel along their columns for a plate position; `None` out of the rods' reach.
209    pub fn inverse(&self, p: V3) -> Option<V3> {
210        let mut out = [0.0; 3];
211        for (i, h) in out.iter_mut().enumerate() {
212            let d = self.l * self.l - self.reach(i, p).powi(2);
213            if !(d >= 0.0) {
214                return None;
215            }
216            *h = self.across(i, p).1 + d.sqrt();
217        }
218        Some(out)
219    }
220
221    /// The plate position for the carriages' travel: the lower point at a rod's length from all three joints. `None`
222    /// where the legs cannot be assembled.
223    pub fn forward(&self, h: V3) -> Option<V3> {
224        let c = [0, 1, 2].map(|i| self.joint(i, h[i]));
225        let ex = sub(c[1], c[0]);
226        let d = norm(ex);
227        let ex = ex.map(|v| v / d);
228        let to3 = sub(c[2], c[0]);
229        let i = dot(ex, to3);
230        let ey = sub(to3, ex.map(|v| v * i));
231        let ey_len = norm(ey);
232        if !(d > 1e-12 && ey_len > 1e-12) {
233            return None;
234        }
235        let ey = ey.map(|v| v / ey_len);
236        let ez = cross(ex, ey);
237        let j = dot(ey, to3);
238        let x = d / 2.0;
239        let y = (i * i + j * j - 2.0 * i * x) / (2.0 * j);
240        let z2 = self.l * self.l - x * x - y * y;
241        if !(z2 >= 0.0) {
242            return None;
243        }
244        let base: V3 = std::array::from_fn(|k| c[0][k] + x * ex[k] + y * ey[k]);
245        let (up, down): (V3, V3) = (
246            std::array::from_fn(|k| base[k] + z2.sqrt() * ez[k]),
247            std::array::from_fn(|k| base[k] - z2.sqrt() * ez[k]),
248        );
249        Some(if up[2] < down[2] { up } else { down })
250    }
251
252    /// J_x (rows: the rod vectors u_i = p - c_i) and the diagonal of J_q (u_i . d_i).
253    fn constraint(&self, h: V3, p: V3) -> (M3, V3) {
254        let jx = [0, 1, 2].map(|i| sub(p, self.joint(i, h[i])));
255        (jx, [0, 1, 2].map(|i| dot(jx[i], self.dir[i])))
256    }
257
258    /// The Jacobian J[i][j] = dp_i / dh_j at carriage heights h and plate position p; `None` at a direct singularity.
259    pub fn jacobian(&self, h: V3, p: V3) -> Option<M3> {
260        let (jx, jq) = self.constraint(h, p);
261        let inv = inverse(&jx)?;
262        Some(std::array::from_fn(|i| std::array::from_fn(|j| inv[i][j] * jq[j])))
263    }
264
265    /// J' h' = J_x^-1 w: the plate's acceleration at carriage speeds `hv` and no carriage acceleration.
266    pub fn velocity_term(&self, h: V3, p: V3, hv: V3, pv: V3) -> Option<V3> {
267        let (jx, _) = self.constraint(h, p);
268        let inv = inverse(&jx)?;
269        let w: V3 = std::array::from_fn(|i| {
270            let d = self.dir[i];
271            let rel = [pv[0] - hv[i] * d[0], pv[1] - hv[i] * d[1], pv[2] - hv[i] * d[2]];
272            -dot(rel, rel)
273        });
274        Some(mul(&inv, w))
275    }
276
277    /// The pull of each rod pair on its carriage that holds a plate of `m` kg against gravity `g` while it accelerates
278    /// at `acc`, as the multiplier lambda_i of the rod vector u_i (force on carriage i: lambda_i u_i): the plate's
279    /// m acc = -m g e_z - J_x^T lambda.
280    pub fn rod_pull(&self, h: V3, p: V3, m: f64, g: f64, acc: V3) -> Option<V3> {
281        self.rod_force(h, p, [-m * acc[0], -m * acc[1], -m * (acc[2] + g)])
282    }
283
284    /// The rods' pull that takes the force `force` on the plate: `rod_pull` for any force, such as the plate's weight
285    /// and what accelerating it takes, m (g - a).
286    pub fn rod_force(&self, h: V3, p: V3, force: V3) -> Option<V3> {
287        let (jx, _) = self.constraint(h, p);
288        Some(mul(&transpose(&inverse(&jx)?), force))
289    }
290}
291
292#[derive(Clone)]
293pub struct LinearDelta {
294    legs: Legs,
295    /// The geometry as configured, for the scene: the columns' incline (rad), column and plate radius, the rods' spacing.
296    incline: f64,
297    column_radius: f64,
298    plate_radius: f64,
299    rod_spacing: f64,
300    /// The carriage joints' upper stop height and the stroke below it.
301    top_stop: f64,
302    stroke: f64,
303    elastic: bool,
304    g: f64,
305    /// Carriage with its share of the rods; plate with the rest of them; payload.
306    m_c: f64,
307    m_plate: f64,
308    m_payload: f64,
309    payload_attached: bool,
310    brake_engaged: bool,
311    /// An obstacle's push on the tool (`Machine::set_tool_force`), held until changed.
312    push: V3,
313    /// The belt axis on each column, all alike.
314    r: f64,
315    /// Unstretched belt fed per radian of pulley (the radius holds at pretension, as on the one-axis machine).
316    r_mat: f64,
317    span_min: f64,
318    belt: Belt,
319    /// Each column's belt as a thermal part: its resistance to the air, K/W, and its time constant, s (`thermal_values`).
320    belt_thermal: (f64, f64),
321    /// Unstretched belt per section at x = 0 with the pulley at angle 0.
322    mat0: [f64; 2],
323    /// Each carriage's guide; alike but for their temperatures (effects.thermal_feedback).
324    friction: [Lugre; 3],
325    shaft: ShaftFriction,
326    ripple: Ripple,
327    /// The coupling or gearbox as configured (ratio, stiffness, backlash), and each column's own, whose efficiency
328    /// follows its temperature.
329    gearbox: Gearbox,
330    gears: [Gearbox; 3],
331    /// With effects.thermal_feedback: the law, and the guides' viscous coefficient at the reference temperature.
332    thermal: Option<(ThermalFeedback, f64)>,
333    /// ratings.guide_max_load_n, guide_dynamic_load_rating_n and required_life_h, where the config has them.
334    guide_max_load: Option<f64>,
335    guide_rating: Option<f64>,
336    /// geometry.rod_joint_*_m: where the rod pairs' joints stand from the guide's centre, along the column, outward
337    /// (away from the axis, in the vertical plane through it) and tangentially. All zero: the force passes the centre.
338    joint_offset: V3,
339    /// ratings.guide_moment_x_nm, _y_, _z_: the guide's moment ratings about the column, the tangential and the outward
340    /// axis (Festo's Mx, My, Mz); an absent one leaves that moment out of the equivalent load.
341    guide_moment_max: [Option<f64>; 3],
342    required_life: Option<f64>,
343    /// Each axis's gearbox hysteresis state (`Gearbox::anchor`); `gearbox` holds the values all three share.
344    anchors: [[f64; 2]; 3],
345    stops: HardStop,
346    brake: HoldingBrake,
347    /// Rotor with the gearbox's input; pulley with the belt's mass.
348    j_rotor: f64,
349    j_pulley: f64,
350    /// The working range: a cylinder of `radius` from `bottom` to `top`; the rods' tilt and the condition number refused
351    /// above.
352    radius: f64,
353    top: f64,
354    max_tilt: f64,
355    max_condition: f64,
356    axes: [AxisInfo; 3],
357    motors: [MotorInfo; 3],
358    /// `Machine::setpoint_slack`, worked out once (`rest_sag`) when first asked for: its 600 equilibria take 8 ms, 50
359    /// times what the rest of a build takes, and a run that plans no path (a loop measurement, a sweep) never asks.
360    rest_slack: std::sync::OnceLock<f64>,
361}
362
363// Elastic state: [h 1..3, pulley angle 1..3, rotor angle 1..3, h' 1..3, pulley speed 1..3, rotor speed 1..3,
364// friction 1..3, brake 1..3, slack]; slack: seconds a belt section has spent without tension, as on the other belt machines.
365const N_ELASTIC: usize = 25;
366// Rigid state: [h 1..3, h' 1..3, friction 1..3, brake 1..3].
367const N_RIGID: usize = 12;
368/// Loss powers per column: guide, motor shaft and brake, gearbox, belt; then the stops, and what the ripple gives off.
369const N_LOSSES: usize = 14;
370
371const SECTIONS: [&str; 6] = ["belt.1", "belt.2", "belt.3", "belt.4", "belt.5", "belt.6"];
372const SECTION_KEYS: [&str; 6] = [
373    "belt-section-1-1",
374    "belt-section-1-2",
375    "belt-section-2-1",
376    "belt-section-2-2",
377    "belt-section-3-1",
378    "belt-section-3-2",
379];
380const CARRIAGES: [&str; 3] = ["carriage-1", "carriage-2", "carriage-3"];
381const CONTACTS: [&str; 3] = ["carriage.1", "carriage.2", "carriage.3"];
382
383/// What one moment of the rigid model gives per column: carriage acceleration, the torque into the gearbox (after the
384/// rotor's own acceleration) and out of it at the pulley.
385struct Rigid {
386    acc: V3,
387    into: V3,
388    out: V3,
389}
390
391impl LinearDelta {
392    pub fn new(cfg: &Config) -> Result<Self, ConfigError> {
393        let column_radius = cfg.positive("geometry.column_radius_m")?;
394        let plate_radius = cfg.non_negative("geometry.plate_radius_m")?;
395        if plate_radius >= column_radius {
396            return Err(ConfigError::Invalid("geometry.plate_radius_m".into()));
397        }
398        let l = cfg.positive("geometry.rod_m")?;
399        let share = cfg.non_negative("mass.rod_carriage_share")?;
400        if share > 1.0 {
401            return Err(ConfigError::Invalid("mass.rod_carriage_share".into()));
402        }
403        let m_rod = cfg.non_negative("mass.rod_pair_kg")?;
404        let (radius, top, bottom) =
405            (cfg.positive("workspace.radius_m")?, cfg.f64("workspace.top_z_m")?, cfg.f64("workspace.bottom_z_m")?);
406        if bottom >= top {
407            return Err(ConfigError::Invalid("workspace.bottom_z_m".into()));
408        }
409        let max_tilt = cfg.positive("workspace.max_rod_angle_deg")?.to_radians();
410        let r = cfg.positive("geometry.pulley_radius_m")?;
411        let belt = Belt::from_config(cfg)?;
412        let j_rotor = cfg.positive("motor.rotor_inertia_kgm2")? + cfg.non_negative("gearbox.inertia_at_input_kgm2")?;
413        let axis = |id: &'static str, key: &'static str, min: f64, max: f64| -> Result<AxisInfo, ConfigError> {
414            Ok(AxisInfo {
415                id,
416                key,
417                unit: "m",
418                min,
419                max,
420                max_vel: cfg.positive(&format!("axis.{id}.max_velocity_m_s"))?,
421                max_acc: cfg.positive(&format!("axis.{id}.max_acceleration_m_s2"))?,
422                max_jerk: cfg.positive(&format!("axis.{id}.max_jerk_m_s3"))?,
423            })
424        };
425        let incline = cfg.f64("geometry.column_incline_deg")?;
426        if !(incline.abs() < 60.0) {
427            return Err(ConfigError::Invalid("geometry.column_incline_deg".into()));
428        }
429        let incline = incline.to_radians();
430        let rating = |key: &str| cfg.positive(&format!("ratings.{key}")).ok();
431        let mut m = Self {
432            legs: Legs::new(column_radius - plate_radius, l, incline),
433            incline,
434            column_radius,
435            plate_radius,
436            rod_spacing: cfg.non_negative("geometry.rod_spacing_m")?,
437            top_stop: cfg.f64("geometry.carriage_top_m")?,
438            stroke: cfg.positive("geometry.stroke_m")?,
439            elastic: cfg.bool("effects.belt_stretch")?,
440            g: if cfg.bool("effects.gravity")? { G } else { 0.0 },
441            m_c: cfg.positive("mass.carriage_kg")? + share * m_rod,
442            m_plate: cfg.positive("mass.plate_kg")? + 3.0 * (1.0 - share) * m_rod,
443            m_payload: if cfg.bool("effects.payload")? { cfg.non_negative("mass.payload_kg")? } else { 0.0 },
444            payload_attached: true,
445            brake_engaged: false,
446            push: [0.0; 3],
447            r,
448            r_mat: belt.rest_length(r),
449            span_min: cfg.positive("geometry.span_min_m")?,
450            mat0: [0.0; 2],
451            belt_thermal: (0.0, 0.0),
452            friction: [
453                Lugre::from_config(cfg, "friction")?,
454                Lugre::from_config(cfg, "friction")?,
455                Lugre::from_config(cfg, "friction")?,
456            ],
457            shaft: ShaftFriction::from_config(cfg)?,
458            ripple: Ripple::from_config(cfg)?,
459            gearbox: Gearbox::from_config(cfg)?,
460            gears: [Gearbox::from_config(cfg)?, Gearbox::from_config(cfg)?, Gearbox::from_config(cfg)?],
461            thermal: match ThermalFeedback::from_config(cfg)? {
462                Some(law) => Some((law, cfg.non_negative("friction.viscous_n_s_m")?)),
463                None => None,
464            },
465            guide_max_load: rating("guide_max_load_n"),
466            guide_rating: rating("guide_dynamic_load_rating_n"),
467            joint_offset: [
468                cfg.f64("geometry.rod_joint_along_m")?,
469                cfg.f64("geometry.rod_joint_outward_m")?,
470                cfg.f64("geometry.rod_joint_tangent_m")?,
471            ],
472            guide_moment_max: ["x", "y", "z"].map(|k| rating(&format!("guide_moment_{k}_nm"))),
473            required_life: rating("required_life_h"),
474            anchors: [[f64::NAN, 0.0]; 3],
475            stops: HardStop::from_config(cfg)?,
476            brake: HoldingBrake::from_config(cfg, j_rotor)?,
477            j_rotor,
478            j_pulley: cfg.positive("pulley.inertia_kgm2")?,
479            belt,
480            radius,
481            top,
482            max_tilt,
483            max_condition: cfg.positive("workspace.max_condition_number")?,
484            axes: [
485                axis("x", "axis-x", -radius, radius)?,
486                axis("y", "axis-y", -radius, radius)?,
487                axis("z", "axis-z", bottom, top)?,
488            ],
489            motors: [
490                MotorInfo { id: "1", key: "motor-column-1" },
491                MotorInfo { id: "2", key: "motor-column-2" },
492                MotorInfo { id: "3", key: "motor-column-3" },
493            ],
494            rest_slack: std::sync::OnceLock::new(),
495        };
496        let geo = m.geo(0.0);
497        m.mat0 = geo.map(|g| m.belt.rest_length(g));
498        // The whole belt runs at carriage speed, so all of its mass sits on the pulley.
499        m.j_pulley += m.belt.mass_per_m * (geo[0] + geo[1] - 2.0 * m.belt.tooth_length) * r * r;
500        // Each belt as a thermal part: a loop of length L (the sections' geometric length, as the mass above), width w,
501        // heated by its damping loss. Resistance to the air R = 1 / (h A) over both sides, A = 2 w L, h = belt.convection_w_m2_k;
502        // capacity C = (mass per metre) L cp, cp = belt.specific_heat_j_kg_k; time constant C R. A thin belt (3 mm,
503        // polyurethane 0.2 W/(m K)) is at one temperature through its thickness: Biot h t / 2 k = 0.1.
504        let length = geo[0] + geo[1] - 2.0 * m.belt.tooth_length;
505        let width = cfg.positive("ratings.belt_width_mm")? * 1e-3;
506        let mut conductance = cfg.positive("belt.convection_w_m2_k")? * 2.0 * width * length;
507        // effects.belt_pulley_conduction: the belt also gives heat to its two pulleys through the half wrap (pi r) it lies
508        // on each, from its middle through half its thickness, G = 2 pi r w k / (t / 2), in parallel with the air. The
509        // pulleys sit in the axis's end housings and stay at the air's temperature; the contact's own resistance is left
510        // out (a PU belt pressed on aluminium, some kW/(m^2 K) against k / (t / 2) = 133 W/(m^2 K)).
511        if cfg.get("effects.belt_pulley_conduction").is_ok() && cfg.bool("effects.belt_pulley_conduction")? {
512            let (thickness, k) = (cfg.positive("belt.thickness_m")?, cfg.positive("belt.thermal_conductivity_w_m_k")?);
513            conductance += std::f64::consts::TAU * r * width * k / (0.5 * thickness);
514        }
515        let resistance = 1.0 / conductance;
516        let capacity = cfg.positive("belt.mass_kg_m")? * length * cfg.positive("belt.specific_heat_j_kg_k")?;
517        m.belt_thermal = (resistance, capacity * resistance);
518        Ok(m)
519    }
520
521    /// How far the tool can be from where the motors' angles put it at rest anywhere in the working range, payload on or
522    /// off: the belt stretched by the weight it holds and the coupling or gearbox twisted (with half its backlash), as
523    /// `equilibrium` sets them up, through the forward kinematics; over 5 radii, 12 directions and 5 heights. Plus a
524    /// tenth for what the grid steps over; at least the default 0.1 mm.
525    fn rest_sag(&mut self) -> f64 {
526        let mut most = 0f64;
527        let (bottom, top) = (self.axes[2].min, self.top);
528        for attached in [true, false] {
529            self.payload_attached = attached;
530            for ring in 0..=4 {
531                let rho = self.radius * ring as f64 / 4.0;
532                for turn in 0..12 {
533                    let (sin, cos) = (turn as f64 * std::f64::consts::TAU / 12.0).sin_cos();
534                    for k in 0..=4 {
535                        let p = [rho * cos, rho * sin, bottom + (top - bottom) * k as f64 / 4.0];
536                        if self.unreachable(&p, 0.0).is_some() {
537                            continue;
538                        }
539                        let (mut state, mut torque, mut motors, mut speed, mut tool) =
540                            (Vec::new(), [0.0; 3], [0.0; 3], [0.0; 3], [0.0; 3]);
541                        self.equilibrium(&p, &mut state, &mut torque);
542                        self.motor_state(&state, &mut motors, &mut speed);
543                        self.forward(&motors, &mut tool);
544                        most = most.max(norm(sub(tool, p)));
545                    }
546                }
547            }
548        }
549        self.payload_attached = true;
550        (1.1 * most).max(1e-4)
551    }
552
553    pub fn legs(&self) -> &Legs {
554        &self.legs
555    }
556
557    /// The point mass at the plate.
558    pub fn m_nt(&self) -> f64 {
559        self.m_plate + if self.payload_attached { self.m_payload } else { 0.0 }
560    }
561
562    /// A carriage with its share of the rods.
563    pub fn m_carriage(&self) -> f64 {
564        self.m_c
565    }
566
567    fn h_min(&self) -> f64 {
568        self.top_stop - self.stroke
569    }
570
571    /// Geometric length of a column's two belt sections at x. Each ends at the motor pulley once, where the teeth in mesh
572    /// count as more belt (`Belt::tooth_length`).
573    fn geo(&self, x: f64) -> [f64; 2] {
574        let (s, teeth) = (self.span_min, self.belt.tooth_length);
575        [s + self.stroke - x + teeth, 3.0 * s + self.stroke + x + teeth]
576    }
577
578    /// Column k's two sections in the elastic state `s`.
579    fn sections(&self, s: &[f64], k: usize) -> [SectionForce; 2] {
580        let (geo, fed) = (self.geo(s[k] - self.h_min()), self.r_mat * s[3 + k]);
581        let rate = self.r_mat * s[12 + k];
582        [
583            self.belt.section(geo[0], self.mat0[0] - fed, -s[9 + k], -rate),
584            self.belt.section(geo[1], self.mat0[1] + fed, s[9 + k], rate),
585        ]
586    }
587
588    fn heights(&self, s: &[f64]) -> (V3, V3) {
589        let at = if self.elastic { 9 } else { 3 };
590        ([s[0], s[1], s[2]], [s[at], s[at + 1], s[at + 2]])
591    }
592
593    fn frictions(&self, s: &[f64]) -> V3 {
594        let at = if self.elastic { 18 } else { 6 };
595        [s[at], s[at + 1], s[at + 2]]
596    }
597
598    fn brakes(&self, s: &[f64]) -> V3 {
599        let at = if self.elastic { 21 } else { 9 };
600        [s[at], s[at + 1], s[at + 2]]
601    }
602
603    /// Rotor angles and speeds of a state.
604    fn rotors(&self, s: &[f64]) -> (V3, V3) {
605        if self.elastic {
606            ([s[6], s[7], s[8]], [s[15], s[16], s[17]])
607        } else {
608            let k = self.gearbox.ratio / self.r;
609            (std::array::from_fn(|i| k * (s[i] - self.h_min())), std::array::from_fn(|i| k * s[3 + i]))
610        }
611    }
612
613    /// Where the plate is and the Jacobian there, for carriage heights; NaN where the legs cannot be assembled.
614    fn pose(&self, h: V3) -> (V3, M3) {
615        self.legs
616            .forward(h)
617            .and_then(|p| Some((p, self.legs.jacobian(h, p)?)))
618            .unwrap_or(([f64::NAN; 3], [[f64::NAN; 3]; 3]))
619    }
620
621    /// The load's mass matrix M (carriages and plate), the velocity term m_nt J^T J_x^-1 w and the generalised gravity
622    /// Q_g at carriage heights h and speeds v.
623    fn load(&self, h: V3, v: V3) -> (M3, V3, V3) {
624        let (p, j) = self.pose(h);
625        let jt = transpose(&j);
626        let m = self.m_nt();
627        let mass: M3 = std::array::from_fn(|r| {
628            std::array::from_fn(|c| m * dot(jt[r], jt[c]) + if r == c { self.m_c } else { 0.0 })
629        });
630        let velocity =
631            self.legs.velocity_term(h, p, v, mul(&j, v)).map_or([f64::NAN; 3], |a| mul(&jt, a.map(|x| m * x)));
632        // The carriage's weight along its column (cos alpha); the guide takes the rest.
633        let gravity: V3 = std::array::from_fn(|k| -self.g * self.m_c * self.legs.dir[k][2] - m * self.g * j[2][k]);
634        (mass, velocity, gravity)
635    }
636
637    /// Each guide's equivalent load while the plate accelerates at `acc`: what the rods' pull (`Legs::rod_pull`) and the
638    /// carriage's weight have at right angles to the column, F, plus the moments of the pull about the guide's centre.
639    /// The carriage moves along its column only, so its own acceleration loads the belt, not the guide; the plate's
640    /// reaches the guide through the rods.
641    /// The joints stand at `joint_offset` = (a, b, c) along the column d, outward e_r and tangentially e_t from the
642    /// centre, so the pull f = pull u gives M = o x f, with Mx = M.d, My = M.e_t, Mz = M.e_r (Festo's axes). The
643    /// catalogue's rows state the combination F / F_max + Mx / Mx_max + My / My_max + Mz / Mz_max <= 1 (F_max
644    /// `ratings.guide_max_load_n`), so the equivalent load is P = F + F_max sum |M_i| / M_i,max over the moments with a
645    /// rating, which is also the friction's load. The weight acts at the centre and gives no moment.
646    fn guide_loads(&self, h: V3, acc: V3) -> V3 {
647        self.guide_loads_at(h, self.pose(h).0, acc).map(|(load, _)| load)
648    }
649
650    /// Each guide's equivalent load (`guide_loads`) and its moments Mx, My, Mz in N m, with the plate at p (the pose of
651    /// h).
652    fn guide_loads_at(&self, h: V3, p: V3, acc: V3) -> [(f64, V3); 3] {
653        let pull = self.legs.rod_pull(h, p, self.m_nt(), self.g, acc).unwrap_or([f64::NAN; 3]);
654        std::array::from_fn(|k| {
655            let (u, d) = (sub(p, self.legs.joint(k, h[k])), self.legs.dir[k]);
656            let f = [pull[k] * u[0], pull[k] * u[1], pull[k] * u[2] - self.m_c * self.g];
657            let along = dot(f, d);
658            let across = norm([f[0] - along * d[0], f[1] - along * d[1], f[2] - along * d[2]]);
659            let (extra, moments) = self.joint_moments(k, u, pull[k]);
660            (across + extra, moments)
661        })
662    }
663
664    /// The moments Mx, My, Mz of the pull `pull` of column k's rod pair (the pair's joint at `u` from the plate) about
665    /// the guide's centre, and the load they add to the equivalent load (`guide_loads`).
666    fn joint_moments(&self, k: usize, u: V3, pull: f64) -> (f64, V3) {
667        if self.joint_offset == [0.0; 3] {
668            return (0.0, [0.0; 3]);
669        }
670        let d = self.legs.dir[k];
671        let (c, s) = self.legs.azimuth[k];
672        let e_t = [-s, c, 0.0];
673        let e_r = cross(e_t, d);
674        let [a, b, t] = self.joint_offset;
675        let o = std::array::from_fn(|i| a * d[i] + b * e_r[i] + t * e_t[i]);
676        let m = cross(o, u.map(|x| pull * x));
677        let moments = [dot(m, d), dot(m, e_t), dot(m, e_r)];
678        let reference = self.guide_max_load.unwrap_or(0.0);
679        let extra: f64 = (0..3).filter_map(|i| self.guide_moment_max[i].map(|r| moments[i].abs() / r)).sum();
680        (reference * extra, moments)
681    }
682
683    /// The plate's acceleration p'' = J h'' + J_x^-1 w for the carriages' acceleration.
684    fn plate_acceleration(&self, s: &[f64], carriage_acc: V3) -> V3 {
685        let (h, v) = self.heights(s);
686        let (p, j) = self.pose(h);
687        let bend = self.legs.velocity_term(h, p, v, mul(&j, v)).unwrap_or([f64::NAN; 3]);
688        let along = mul(&j, carriage_acc);
689        std::array::from_fn(|i| along[i] + bend[i])
690    }
691
692    /// The friction levels' factor per guide at rest: they are given for a guide under its preload alone.
693    fn load_scales(&self, h: V3) -> V3 {
694        let loads = self.guide_loads(h, [0.0; 3]);
695        std::array::from_fn(|k| self.friction[k].load_scale(loads[k], 0.0))
696    }
697
698    /// The friction's load factors under the load the guides carry while moving. That load holds the plate's
699    /// acceleration, which the friction itself changes, so the factors x are taken at their fixed point x = G(x)
700    /// (`mech::settled_loss`): G takes the factors to the friction (`guide_friction`), the acceleration, the guides' load
701    /// of that acceleration and the factors of that load, from the factors at rest. The friction is linear in the factor
702    /// with its bristles' force, so G' is that force over the preload and the load's share of it: 0.012 to 0.015 at
703    /// 0.2 m/s (`the_frictions_load_factor_is_the_fixed_point_with_the_acceleration`), and the rounds settle in about
704    /// eight. Elastic, only the friction in the carriages' balance changes from round to round (`elastic_balance`);
705    /// rigid, the gearboxes' losses with it, so each round solves the rigid model anew. Without load-dependent friction
706    /// (or friction) the factors at rest.
707    fn scales_at(&self, s: &[f64], torque: &[f64]) -> V3 {
708        let (h, v) = self.heights(s);
709        let rest = self.load_scales(h);
710        if self.friction.iter().all(|f| !(f.on && f.load_dependent)) {
711            return rest;
712        }
713        let (p, j) = self.pose(h);
714        let bend = self.legs.velocity_term(h, p, v, mul(&j, v)).unwrap_or([f64::NAN; 3]);
715        let (balance, frictions) = (self.elastic.then(|| self.elastic_balance(s)), self.frictions(s));
716        sim_components::mech::settled_loss(rest, |scales| {
717            let acc = match &balance {
718                Some((inv, base, _)) => {
719                    mul(inv, std::array::from_fn(|k| base[k] - self.guide_friction(k, v[k], frictions[k], scales[k]).0))
720                }
721                None => self.rigid_solve_with(s, torque, *scales).acc,
722            };
723            let along = mul(&j, acc);
724            let loads = self.guide_loads_at(h, p, std::array::from_fn(|i| along[i] + bend[i]));
725            std::array::from_fn(|k| self.friction[k].load_scale(loads[k].0, 0.0))
726        })
727    }
728
729    /// Guide k's friction force (opposing a positive speed) and its bristles' rate at speed v, bristle deflection s and
730    /// load factor `scale`: LuGre with the load scaling the bristles' stiffness and damping together with the levels,
731    /// F = scale (sigma_0 s + sigma_1 s') + b v, s' = v - sigma_0 |v| s / g(v) of the levels without load (`Lugre::eval`
732    /// at factor 1). Steady it slides at scale g(v) + b v, as with the load in the levels alone; but the deflection no
733    /// longer grows with the load, so a load that changes faster than the bristles settle does not reach the force
734    /// through sigma_1 s'. With the load in the levels alone a change of the factor gave sigma_1 |v| s' at once,
735    /// 1500 N s/m x 0.65 m/s = 975 N per unit of factor against the 15.7 N level, and the factor's fixed point with the
736    /// acceleration (`scales_at`) had a loop gain of +0.95 on the default cycle (pulley torque 8.4 N m of 5).
737    fn guide_friction(&self, k: usize, v: f64, s: f64, scale: f64) -> (f64, f64) {
738        let f = &self.friction[k];
739        if !f.on {
740            return (0.0, 0.0);
741        }
742        let (force, rate) = f.eval(v, s, 1.0);
743        (scale * (force - f.viscous * v) + f.viscous * v, rate)
744    }
745
746    /// The elastic model's carriage balance but for the guides' friction: the inverse of the mass matrix and per carriage
747    /// what acts on it besides the friction (the belt's two sections, gravity, the speed term, the stops), M h'' = base
748    /// - friction; and the sections.
749    fn elastic_balance(&self, s: &[f64]) -> (M3, V3, [[SectionForce; 2]; 3]) {
750        let (h, v) = self.heights(s);
751        let (mass, velocity, gravity) = self.load(h, v);
752        let sections: [[SectionForce; 2]; 3] = std::array::from_fn(|k| self.sections(s, k));
753        let push = self.pushed(s);
754        let base = std::array::from_fn(|k| {
755            sections[k][0].tension - sections[k][1].tension + gravity[k] - velocity[k]
756                + self.stop_force(h[k], v[k])
757                + push[k]
758        });
759        (inverse(&mass).unwrap_or([[f64::NAN; 3]; 3]), base, sections)
760    }
761
762    /// The push at the tool on each carriage: its virtual power per unit of each carriage's speed, through the
763    /// platform's Jacobian (`sim_core::tool_force_on_rates`); zero without a push.
764    fn pushed(&self, s: &[f64]) -> V3 {
765        let rates = if self.elastic { 9..12 } else { 3..6 };
766        sim_core::tool_force_on_rates(self, s, &self.push, rates).map_or([0.0; 3], |q| [q[0], q[1], q[2]])
767    }
768
769    /// Force of the stops on carriage k.
770    fn stop_force(&self, h: f64, v: f64) -> f64 {
771        self.stops.force(h - self.h_min(), v, self.stroke)
772    }
773
774    /// The rigid model's moment. The gearbox loses torque only on what it transmits (the motor's less what accelerates
775    /// the rotor itself); the second pass takes the acceleration of the first for that, as on the one-axis machine.
776    fn rigid_solve(&self, s: &[f64], torque: &[f64]) -> Rigid {
777        self.rigid_solve_with(s, torque, self.scales_at(s, torque))
778    }
779
780    /// `rigid_solve` with the friction's load factors given (`scales_at` solves them with it).
781    fn rigid_solve_with(&self, s: &[f64], torque: &[f64], scales: V3) -> Rigid {
782        let (r, ratio) = (self.r, self.gearbox.ratio);
783        let (h, v) = self.heights(s);
784        let (rotor, speed) = self.rotors(s);
785        let (brakes, frictions) = (self.brakes(s), self.frictions(s));
786        let (mass, velocity, gravity) = self.load(h, v);
787        // Belt force the motor would give with a loss-free gearbox and a massless rotor; a brake holds the rotor.
788        let drive: V3 = std::array::from_fn(|k| {
789            ratio
790                * (self.ripple.apply(torque[k], rotor[k])
791                    - self.shaft.torque(speed[k])
792                    - self.brake.torque(self.brake_engaged, speed[k], brakes[k]).0)
793                / r
794        });
795        let push = self.pushed(s);
796        let rest: V3 = std::array::from_fn(|k| {
797            gravity[k] - velocity[k] - self.guide_friction(k, v[k], frictions[k], scales[k]).0
798                + self.stop_force(h[k], v[k])
799                + push[k]
800        });
801        let rotor_mass = ratio * ratio * self.j_rotor / (r * r);
802        let solve = |loss: V3| -> V3 {
803            let m: M3 = std::array::from_fn(|i| {
804                std::array::from_fn(|c| {
805                    mass[i][c] + if i == c { self.j_pulley / (r * r) + loss[i] * rotor_mass } else { 0.0 }
806                })
807            });
808            inverse(&m).map_or([f64::NAN; 3], |inv| mul(&inv, std::array::from_fn(|k| loss[k] * drive[k] + rest[k])))
809        };
810        // The loss factors of the torques going in, at their fixed point (`mech::settled_loss`).
811        let loss = sim_components::mech::settled_loss([1.0; 3], |loss| {
812            let acc = solve(*loss);
813            std::array::from_fn(|k| self.gears[k].loss_factor((drive[k] - rotor_mass * acc[k]) * r, v[k] / r))
814        });
815        let acc = solve(loss);
816        let into: V3 = std::array::from_fn(|k| (drive[k] - rotor_mass * acc[k]) * r);
817        Rigid { acc, into, out: std::array::from_fn(|k| loss[k] * into[k]) }
818    }
819
820    /// The carriages' acceleration in either model.
821    fn carriage_acceleration(&self, s: &[f64], torque: &[f64]) -> V3 {
822        self.carriage_acceleration_with(s, torque, self.scales_at(s, torque))
823    }
824
825    /// `derivatives` with the friction's load factors given (`scales_at`).
826    fn derivatives_with(&self, s: &[f64], torque: &[f64], scales: V3, out: &mut [f64]) {
827        let v = self.heights(s).1;
828        let (_, speed) = self.rotors(s);
829        let (brakes, frictions) = (self.brakes(s), self.frictions(s));
830        if !self.elastic {
831            let acc = self.rigid_solve_with(s, torque, scales).acc;
832            out[..3].copy_from_slice(&v);
833            out[3..6].copy_from_slice(&acc);
834            for k in 0..3 {
835                out[6 + k] = self.guide_friction(k, v[k], frictions[k], scales[k]).1;
836                out[9 + k] = self.brake.torque(self.brake_engaged, speed[k], brakes[k]).1;
837            }
838            return;
839        }
840        let (inv, base, sections) = self.elastic_balance(s);
841        let mut rhs = [0.0; 3];
842        out[24] = 0.0;
843        for (k, sec) in sections.iter().enumerate() {
844            if sec.iter().any(|f| f.tension <= 0.0) {
845                out[24] = 1.0;
846            }
847            let (ff, ds) = self.guide_friction(k, v[k], frictions[k], scales[k]);
848            rhs[k] = base[k] - ff;
849            let gear = self.gear(k).torque(s[6 + k], s[15 + k], s[3 + k], s[12 + k]);
850            let (brake, brake_rate) = self.brake.torque(self.brake_engaged, s[15 + k], brakes[k]);
851            out[3 + k] = s[12 + k];
852            out[6 + k] = s[15 + k];
853            out[12 + k] = (gear.output + self.r_mat * (sec[1].material - sec[0].material)) / self.j_pulley;
854            out[15 + k] = (self.ripple.apply(torque[k], s[6 + k]) - gear.rotor - self.shaft.torque(s[15 + k]) - brake)
855                / self.j_rotor;
856            out[18 + k] = ds;
857            out[21 + k] = brake_rate;
858        }
859        out[..3].copy_from_slice(&v);
860        out[9..12].copy_from_slice(&mul(&inv, rhs));
861    }
862
863    /// The carriages' acceleration at the given friction load factors.
864    fn carriage_acceleration_with(&self, s: &[f64], torque: &[f64], scales: V3) -> V3 {
865        if self.elastic {
866            let mut d = [0.0; N_ELASTIC];
867            self.derivatives_with(s, torque, scales, &mut d);
868            [d[9], d[10], d[11]]
869        } else {
870            self.rigid_solve_with(s, torque, scales).acc
871        }
872    }
873
874    /// Axis k's gearbox (its own, warmed by its own temperature) with its own hysteresis state.
875    fn gear(&self, k: usize) -> Gearbox {
876        Gearbox { anchor: self.anchors[k], ..self.gears[k].clone() }
877    }
878
879    /// The torque each coupling or gearbox passes to its pulley.
880    fn gear_output(&self, s: &[f64], torque: &[f64]) -> V3 {
881        if self.elastic {
882            std::array::from_fn(|k| self.gear(k).torque(s[6 + k], s[15 + k], s[3 + k], s[12 + k]).output)
883        } else {
884            self.rigid_solve(s, torque).out
885        }
886    }
887
888    /// Each section's tension; in the rigid model the pretension.
889    fn tensions(&self, s: &[f64]) -> [f64; 6] {
890        std::array::from_fn(
891            |i| if self.elastic { self.sections(s, i / 2)[i % 2].tension } else { self.belt.pretension },
892        )
893    }
894
895    fn energy_parts(&self, s: &[f64]) -> [f64; 3] {
896        let (h, v) = self.heights(s);
897        let (mass, ..) = self.load(h, v);
898        let mut kinetic = 0.5 * dot(v, mul(&mass, v));
899        let (p, _) = self.pose(h);
900        // The joints stand at h cos alpha.
901        let potential = self.g * (self.m_nt() * p[2] + self.m_c * dot(h, self.legs.dir.map(|d| d[2])));
902        let mut elastic: f64 = (0..3).map(|k| self.stops.energy(h[k] - self.h_min(), self.stroke)).sum();
903        if self.elastic {
904            for k in 0..3 {
905                kinetic += 0.5 * (self.j_pulley * s[12 + k] * s[12 + k] + self.j_rotor * s[15 + k] * s[15 + k]);
906                let (geo, fed) = (self.geo(h[k] - self.h_min()), self.r_mat * s[3 + k]);
907                elastic += self.belt.energy(geo[0], self.mat0[0] - fed)
908                    + self.belt.energy(geo[1], self.mat0[1] + fed)
909                    + self.gear(k).energy(s[6 + k], s[3 + k]);
910            }
911        } else {
912            let (r, ratio) = (self.r, self.gearbox.ratio);
913            kinetic += 0.5 * (self.j_pulley + ratio * ratio * self.j_rotor) / (r * r) * dot(v, v);
914        }
915        [kinetic, potential, elastic]
916    }
917
918    /// The loss powers in the order of `effect_infos`, and per column the gearbox loss as a torque at the rotor and the
919    /// brake torque.
920    fn losses(&self, s: &[f64], torque: &[f64]) -> ([f64; N_LOSSES], V3, V3) {
921        let (h, v) = self.heights(s);
922        let (rotor, speed) = self.rotors(s);
923        let (brakes, frictions, scales) = (self.brakes(s), self.frictions(s), self.scales_at(s, torque));
924        let rigid = (!self.elastic).then(|| self.rigid_solve(s, torque));
925        let (mut powers, mut gear_at_rotor, mut held) = ([0.0; N_LOSSES], [0.0; 3], [0.0; 3]);
926        let ratio = self.gearbox.ratio;
927        for k in 0..3 {
928            held[k] = self.brake.torque(self.brake_engaged, speed[k], brakes[k]).0;
929            let guide = self.guide_friction(k, v[k], frictions[k], scales[k]).0 * v[k];
930            let (gear, belt) = match &rigid {
931                Some(m) => {
932                    gear_at_rotor[k] = (m.into[k] - m.out[k]) / ratio;
933                    (gear_at_rotor[k] * speed[k], 0.0)
934                }
935                None => {
936                    let g = self.gear(k).torque(s[6 + k], s[15 + k], s[3 + k], s[12 + k]);
937                    gear_at_rotor[k] = g.rotor - g.output / ratio;
938                    let (geo, fed, rate) =
939                        (self.geo(h[k] - self.h_min()), self.r_mat * s[3 + k], self.r_mat * s[12 + k]);
940                    let belt = self.belt.loss_power(geo[0], self.mat0[0] - fed, -v[k], -rate)
941                        + self.belt.loss_power(geo[1], self.mat0[1] + fed, v[k], rate);
942                    (self.gear(k).loss_power(s[6 + k], s[15 + k], s[3 + k], s[12 + k]), belt)
943                }
944            };
945            powers[4 * k..4 * k + 4].copy_from_slice(&[
946                guide,
947                // The gearbox's drag acts on the rotor but is the gearbox's loss.
948                (self.shaft.torque(speed[k]) + held[k]) * speed[k] - self.shaft.drag_power(speed[k]),
949                gear + self.shaft.drag_power(speed[k]),
950                belt,
951            ]);
952            powers[12] += self.stops.loss_power(h[k] - self.h_min(), v[k], self.stroke);
953            powers[13] += (torque[k] - self.ripple.apply(torque[k], rotor[k])) * speed[k];
954        }
955        (powers, gear_at_rotor, held)
956    }
957
958    /// Whether a pose is within the working range (cylinder from bottom to top), widened by `slack`.
959    fn in_envelope(&self, p: &[f64], slack: f64) -> bool {
960        p[0].hypot(p[1]) <= self.radius + slack && p[2] <= self.top + slack && p[2] >= self.axes[2].min - slack
961    }
962
963    /// The torque breakdown, loss powers, energies, friction signals and belt stretch of the effect views.
964    fn view_signals(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
965        let (r, ratio) = (self.r, self.gearbox.ratio);
966        let (h, v) = self.heights(s);
967        let (_, speed) = self.rotors(s);
968        let (mass, velocity, gravity) = self.load(h, v);
969        let acc = self.carriage_acceleration(s, torque);
970        let moving = mul(&mass, acc);
971        let (powers, gear_at_rotor, held) = self.losses(s, torque);
972        let (frictions, scales) = (self.frictions(s), self.scales_at(s, torque));
973        // The transpose r / i takes a force at the carriage to the motor; pulley and rotor counted as a rigid machine
974        // would turn them.
975        let inertia = (self.j_pulley + ratio * ratio * self.j_rotor) / (r * r);
976        for k in 0..3 {
977            let parts = [
978                r / ratio * (moving[k] + velocity[k] + inertia * acc[k]),
979                -r / ratio * gravity[k],
980                self.shaft.torque(speed[k])
981                    + held[k]
982                    + gear_at_rotor[k]
983                    + r / ratio * self.guide_friction(k, v[k], frictions[k], scales[k]).0,
984            ];
985            out.extend(parts);
986            out.push(torque[k] - parts.iter().sum::<f64>());
987        }
988        out.extend(powers);
989        out.extend(self.energy_parts(s));
990        for k in 0..3 {
991            out.push(v[k]);
992            // `guide_friction`'s parts: the bristles' at no load times the factor, the viscous as it is.
993            let [coulomb, viscous, stiction] = self.friction[k].split(v[k], frictions[k], 1.0);
994            out.extend([scales[k] * coulomb, viscous, scales[k] * stiction]);
995            out.push(scales[k]);
996        }
997        // Stretch per section: its length less its unstretched belt; in the rigid model that of pretension.
998        for i in 0..6 {
999            let (k, side) = (i / 2, i % 2);
1000            let geo = self.geo(h[k] - self.h_min())[side];
1001            let mat = if self.elastic {
1002                self.mat0[side] + if side == 0 { -1.0 } else { 1.0 } * self.r_mat * s[3 + k]
1003            } else {
1004                self.belt.rest_length(geo)
1005            };
1006            out.push(geo - mat);
1007        }
1008    }
1009
1010    fn effect_infos(&self, out: &mut Vec<SignalInfo>) {
1011        for motor in &self.motors {
1012            out.extend(TORQUE_PARTS.map(|part| {
1013                SignalInfo::new(
1014                    format!("motor.{}.torque_{part}", motor.id),
1015                    motor.key,
1016                    &format!("quantity-torque-{part}"),
1017                    "N m",
1018                )
1019            }));
1020        }
1021        for (k, motor) in self.motors.iter().enumerate() {
1022            let gear =
1023                if self.gearbox.is_coupling() { "quantity-coupling-loss-power" } else { "quantity-gearbox-loss-power" };
1024            out.push(SignalInfo::new(
1025                format!("{LOSS_PREFIX}guide_{}", motor.id),
1026                CARRIAGES[k],
1027                "quantity-friction-power",
1028                "W",
1029            ));
1030            out.push(SignalInfo::new(
1031                format!("{LOSS_PREFIX}shaft_{}", motor.id),
1032                motor.key,
1033                "quantity-shaft-friction-power",
1034                "W",
1035            ));
1036            out.push(SignalInfo::new(format!("{LOSS_PREFIX}gearbox_{}", motor.id), motor.key, gear, "W"));
1037            out.push(SignalInfo::new(
1038                format!("{LOSS_PREFIX}belt_{}", motor.id),
1039                CARRIAGES[k],
1040                "quantity-damping-power",
1041                "W",
1042            ));
1043        }
1044        out.push(SignalInfo::new(format!("{LOSS_PREFIX}hard_stops"), "group-hard_stop", "quantity-damping-power", "W"));
1045        out.push(SignalInfo::new(format!("{LOSS_PREFIX}other"), "loss-other", "quantity-power-given-off", "W"));
1046        out.extend(ENERGY_PARTS.map(|part| {
1047            SignalInfo::new(format!("energy.{part}"), "group-energy", &format!("quantity-energy-{part}"), "J")
1048        }));
1049        for (k, contact) in CONTACTS.iter().enumerate() {
1050            for part in FRICTION_SIGNALS {
1051                let unit = match part {
1052                    "speed" => "m/s",
1053                    "load_scale" => "",
1054                    _ => "N",
1055                };
1056                out.push(SignalInfo::new(
1057                    format!("{contact}.friction_{part}"),
1058                    CARRIAGES[k],
1059                    &format!("quantity-friction-{}", part.replace('_', "-")),
1060                    unit,
1061                ));
1062            }
1063        }
1064        out.extend(
1065            SECTIONS
1066                .iter()
1067                .zip(SECTION_KEYS)
1068                .map(|(id, key)| SignalInfo::new(format!("{id}.stretch"), key, "quantity-section-stretch", "m")),
1069        );
1070    }
1071
1072    /// The plate at `p` and the payload under it, as `scene` draws them.
1073    fn on_plate(&self, p: V3) -> Vec<Part> {
1074        let size = 2.4 * self.plate_radius.max(0.03);
1075        let mut parts = vec![Part::new("plate", Shape::Box { size: [size, size, 0.03] }, p, [0.55, 0.55, 0.6])];
1076        if self.payload_attached && self.m_payload > 0.0 {
1077            parts.push(Part::new(
1078                "payload",
1079                Shape::Box { size: [0.1, 0.1, 0.08] },
1080                [p[0], p[1], p[2] - 0.06],
1081                [0.2, 0.7, 0.3],
1082            ));
1083        }
1084        parts
1085    }
1086}
1087
1088impl Machine for LinearDelta {
1089    /// The plate (with the payload and the rods' share) at the tool, the carriages (with theirs) on their columns, moving
1090    /// along them, and each column's pulley and rotor at its top spinning about the horizontal across the column,
1091    /// positive as the carriage rises. What does not move is left out (see `FrameMomentum`).
1092    fn frame_momentum(&self, s: &[f64]) -> Option<sim_core::FrameMomentum> {
1093        use sim_components::base::{add_point, add_spin};
1094        let mut f = sim_core::FrameMomentum { gravity: [0.0, 0.0, -self.g], ..Default::default() };
1095        let (h, v) = self.heights(s);
1096        let (p, j) = self.pose(h);
1097        add_point(&mut f, self.m_nt(), p, mul(&j, v));
1098        let rotor_speed = self.rotors(s).1;
1099        for i in 0..3 {
1100            let (c, sin) = self.legs.azimuth[i];
1101            add_point(&mut f, self.m_c, self.legs.joint(i, h[i]), self.legs.dir[i].map(|x| x * v[i]));
1102            let pulley = if self.elastic { s[12 + i] } else { v[i] / self.r };
1103            let across = [-sin, c, 0.0];
1104            add_spin(&mut f, across, self.j_pulley, pulley);
1105            add_spin(&mut f, across, self.j_rotor, rotor_speed[i]);
1106        }
1107        Some(f)
1108    }
1109    fn axes(&self) -> &[AxisInfo] {
1110        &self.axes
1111    }
1112    fn motors(&self) -> &[MotorInfo] {
1113        &self.motors
1114    }
1115
1116    /// NaN where the pose is out of reach: the controller never asks for one (see `unreachable`).
1117    fn inverse(&self, tool: &[f64], motors: &mut [f64]) {
1118        let h = self.legs.inverse([tool[0], tool[1], tool[2]]).unwrap_or([f64::NAN; 3]);
1119        for k in 0..3 {
1120            motors[k] = self.gearbox.ratio * (h[k] - self.h_min()) / self.r;
1121        }
1122    }
1123    fn forward(&self, motors: &[f64], tool: &mut [f64]) {
1124        let h = std::array::from_fn(|k| self.h_min() + motors[k] * self.r / self.gearbox.ratio);
1125        tool[..3].copy_from_slice(&self.legs.forward(h).unwrap_or([f64::NAN; 3]));
1126    }
1127
1128    fn state_len(&self) -> usize {
1129        if self.elastic { N_ELASTIC } else { N_RIGID }
1130    }
1131
1132    /// Each carriage held by its belt against its weight and the rods' share of the plate's, Q_g; elastic, each column's
1133    /// sections share their belt so that T1 - T2 is that force, as on the one-axis machine.
1134    fn equilibrium(&self, tool: &[f64], state: &mut Vec<f64>, torque: &mut [f64]) {
1135        let h = self.legs.inverse([tool[0], tool[1], tool[2]]).unwrap_or([f64::NAN; 3]);
1136        let (_, _, gravity) = self.load(h, [0.0; 3]);
1137        let (r, ratio) = (self.r, self.gearbox.ratio);
1138        state.clear();
1139        state.extend(h);
1140        if !self.elastic {
1141            state.resize(N_RIGID, 0.0);
1142            for k in 0..3 {
1143                let angle = ratio * (h[k] - self.h_min()) / r;
1144                torque[k] = self.ripple.invert(-(gravity[k] + self.stop_force(h[k], 0.0)) * r / ratio, angle);
1145            }
1146            return;
1147        }
1148        let (mut pulleys, mut rotors) = ([0.0; 3], [0.0; 3]);
1149        for k in 0..3 {
1150            let force = -(gravity[k] + self.stop_force(h[k], 0.0));
1151            let geo = self.geo(h[k] - self.h_min());
1152            let mat = self.belt.static_material(&geo, &[force, 0.0], self.mat0.iter().sum());
1153            pulleys[k] = (self.mat0[0] - mat[0]) / self.r_mat;
1154            let m: [f64; 2] = std::array::from_fn(|i| self.belt.section(geo[i], mat[i], 0.0, 0.0).material);
1155            // The pulley at rest: what the coupling passes on balances the belt, r (m2 - m1).
1156            let gear = -self.r_mat * (m[1] - m[0]);
1157            rotors[k] = ratio * (pulleys[k] + self.gearbox.static_twist(gear));
1158            torque[k] = self.ripple.invert(gear / ratio, rotors[k]);
1159        }
1160        state.extend(pulleys);
1161        state.extend(rotors);
1162        state.resize(N_ELASTIC, 0.0);
1163    }
1164
1165    fn derivatives(&self, s: &[f64], torque: &[f64], out: &mut [f64]) {
1166        self.derivatives_with(s, torque, self.scales_at(s, torque), out);
1167    }
1168
1169    fn tool_state(&self, s: &[f64], pos: &mut [f64], vel: &mut [f64]) {
1170        let (h, v) = self.heights(s);
1171        let (p, j) = self.pose(h);
1172        pos[..3].copy_from_slice(&p);
1173        vel[..3].copy_from_slice(&mul(&j, v));
1174    }
1175    fn set_tool_velocity(&self, s: &mut [f64], vel: &[f64]) {
1176        let (h, _) = self.heights(s);
1177        let (_, j) = self.pose(h);
1178        let v = inverse(&j).map_or([f64::NAN; 3], |inv| mul(&inv, [vel[0], vel[1], vel[2]]));
1179        if self.elastic {
1180            for k in 0..3 {
1181                (s[9 + k], s[12 + k], s[15 + k]) = (v[k], v[k] / self.r, self.gearbox.ratio * v[k] / self.r);
1182            }
1183        } else {
1184            s[3..6].copy_from_slice(&v);
1185        }
1186    }
1187    fn motor_state(&self, s: &[f64], pos: &mut [f64], vel: &mut [f64]) {
1188        let (rotor, speed) = self.rotors(s);
1189        pos[..3].copy_from_slice(&rotor);
1190        vel[..3].copy_from_slice(&speed);
1191    }
1192
1193    /// Rigid, loss-free, at rest: (M h'' - Q_g + J_pulley / r^2 h'') r / i at the motor, plus the rotor's own
1194    /// J_rotor i h'' / r.
1195    fn feedforward_torque(&self, pos: &[f64], acc: &[f64], out: &mut [f64]) {
1196        self.feedforward_torque_moving(pos, &[0.0; 3], acc, out);
1197    }
1198
1199    /// With the speed: h' = J^-1 p', h'' = J^-1 (p'' - J_x^-1 w), and at the carriage m_c h'' + m_nt J^T p'' - Q_g (which
1200    /// is M h'' + m_nt J^T J_x^-1 w - Q_g), plus pulley and rotor.
1201    fn feedforward_torque_moving(&self, pos: &[f64], vel: &[f64], acc: &[f64], out: &mut [f64]) {
1202        let p = [pos[0], pos[1], pos[2]];
1203        let h = self.legs.inverse(p).unwrap_or([f64::NAN; 3]);
1204        let (_, _, gravity) = self.load(h, [0.0; 3]);
1205        let (_, j) = self.pose(h);
1206        let inv = inverse(&j).unwrap_or([[f64::NAN; 3]; 3]);
1207        let (pv, pa) = ([vel[0], vel[1], vel[2]], [acc[0], acc[1], acc[2]]);
1208        let v = mul(&inv, pv);
1209        let bend = self.legs.velocity_term(h, p, v, pv).unwrap_or([f64::NAN; 3]);
1210        let carriage_acc = mul(&inv, std::array::from_fn(|i| pa[i] - bend[i]));
1211        let force = transpose(&j).map(|column| self.m_nt() * dot(column, pa));
1212        let (r, ratio) = (self.r, self.gearbox.ratio);
1213        for k in 0..3 {
1214            let at_carriage = (self.m_c + self.j_pulley / (r * r)) * carriage_acc[k] + force[k] - gravity[k];
1215            out[k] = at_carriage * r / ratio + self.j_rotor * ratio * carriage_acc[k] / r;
1216        }
1217    }
1218
1219    /// The rigid model at a steady speed, h' = J^-1 p': per column its guide at the steady level under the load at rest
1220    /// (`load_scales`: at a steady speed the plate does not accelerate) through its gearbox, r / (i loss), plus the motor shaft's friction (with
1221    /// the gearbox's drag) at i h' / r. The loss factor is the one of what the gearbox passes at rest, F - Q_g, as in
1222    /// `rigid_solve`; the weight itself is the rigid feedforward's. The brake is released and the stops are not touched
1223    /// in a move.
1224    fn steady_friction(&self, pos: &[f64], vel: &[f64], out: &mut [f64]) {
1225        let h = self.legs.inverse([pos[0], pos[1], pos[2]]).unwrap_or([f64::NAN; 3]);
1226        let (_, j) = self.pose(h);
1227        let v = inverse(&j).map_or([f64::NAN; 3], |inv| mul(&inv, [vel[0], vel[1], vel[2]]));
1228        let (r, ratio, scales, gravity) = (self.r, self.gearbox.ratio, self.load_scales(h), self.load(h, [0.0; 3]).2);
1229        for k in 0..3 {
1230            let force = self.friction[k].feedforward(v[k], scales[k]);
1231            let loss = self.gears[k].loss_factor((force - gravity[k]) * r, v[k] / r);
1232            out[k] = self.shaft.torque(ratio * v[k] / r) + r / (ratio * loss) * force;
1233        }
1234    }
1235
1236    /// Per column, F = m_c h'' + m_nt (J^T p'')_k - Q_g,k on the carriage (without pulley and rotor), T1 - T2 = F, and the
1237    /// belt keeps its length: (T1 - P) L1 + (T2 - P) L2 = 0. So T1 = P + F L2 / (L1 + L2), T2 = P - F L1 / (L1 + L2).
1238    fn rigid_tensions(&self, pos: &[f64], acc: &[f64], out: &mut Vec<f64>) {
1239        self.rigid_tensions_moving(pos, &[0.0; 3], acc, out);
1240    }
1241
1242    /// With the speed: the carriage's acceleration is h'' = J^-1 (p'' - J_x^-1 w), as in `feedforward_torque_moving`.
1243    fn rigid_tensions_moving(&self, pos: &[f64], vel: &[f64], acc: &[f64], out: &mut Vec<f64>) {
1244        let p = [pos[0], pos[1], pos[2]];
1245        let h = self.legs.inverse(p).unwrap_or([f64::NAN; 3]);
1246        let (_, _, gravity) = self.load(h, [0.0; 3]);
1247        let (_, j) = self.pose(h);
1248        let inv = inverse(&j).unwrap_or([[f64::NAN; 3]; 3]);
1249        let (pv, pa) = ([vel[0], vel[1], vel[2]], [acc[0], acc[1], acc[2]]);
1250        let bend = self.legs.velocity_term(h, p, mul(&inv, pv), pv).unwrap_or([f64::NAN; 3]);
1251        let carriage_acc = mul(&inv, std::array::from_fn(|i| pa[i] - bend[i]));
1252        let force = transpose(&j).map(|column| self.m_nt() * dot(column, pa));
1253        let pre = self.belt.pretension;
1254        for k in 0..3 {
1255            let f = self.m_c * carriage_acc[k] + force[k] - gravity[k];
1256            let [l1, l2] = self.geo(h[k] - self.h_min());
1257            out.extend([pre + f * l2 / (l1 + l2), pre - f * l1 / (l1 + l2)]);
1258        }
1259    }
1260
1261    /// Each carriage guide's load across its rail (`guide_loads`) at a tool pose and acceleration: the rods' pull and the
1262    /// carriage's weight at right angles to the column, at rest under the plate's weight and moving with what accelerating the plate (and payload) takes on
1263    /// top, m a, through the same rods; the size of the sum is at most the rest's plus the moving part's.
1264    fn rigid_guide_loads(&self, pos: &[f64], acc: &[f64], out: &mut Vec<[f64; 2]>) {
1265        let p = [pos[0], pos[1], pos[2]];
1266        let h = self.legs.inverse(p).unwrap_or([f64::NAN; 3]);
1267        let m = self.m_nt();
1268        let pull = |a: V3| {
1269            let force = [-m * a[0], -m * a[1], -m * (self.g + a[2])];
1270            self.legs.rod_force(h, p, force).unwrap_or([f64::NAN; 3])
1271        };
1272        let (rest, moving) = (pull([0.0; 3]), pull([acc[0], acc[1], acc[2]]));
1273        for k in 0..3 {
1274            // As `guide_loads`: the part of the rod pull and the carriage's weight at right angles to the column.
1275            let (u, d) = (sub(p, self.legs.joint(k, h[k])), self.legs.dir[k]);
1276            let across = |f: V3| {
1277                let along = dot(f, d);
1278                std::array::from_fn::<f64, 3, _>(|i| f[i] - along * d[i])
1279            };
1280            let at_rest = across([rest[k] * u[0], rest[k] * u[1], rest[k] * u[2] - self.m_c * self.g]);
1281            let extra = across(u.map(|x| (moving[k] - rest[k]) * x));
1282            // The moments of the pull are linear in it, as are the force's parts: they add to both in the same way.
1283            let (moment_rest, moment_extra) =
1284                (self.joint_moments(k, u, rest[k]).0, self.joint_moments(k, u, moving[k] - rest[k]).0);
1285            let size = norm(extra) + moment_extra;
1286            out.push([norm(at_rest) + moment_rest, if dot(extra, at_rest) < 0.0 { -size } else { size }]);
1287        }
1288    }
1289
1290    fn energy(&self, s: &[f64]) -> f64 {
1291        self.energy_parts(s).iter().sum()
1292    }
1293
1294    /// As `Machine::adopt_state`, the same tool pose and speed, but what the belts, couplings, guides and brakes were
1295    /// doing is kept: rebuilt at rest, the belts dropped what they carried beyond the weight (the guides' friction and
1296    /// the plate's pull, 34 N of tension at 3 m/s) and the guides' bristles their deflection. Each column's section 1
1297    /// keeps its stretch (section 2 then its own, as the belt keeps its length) and its coupling the torque it passed.
1298    fn adopt_state(&self, old: &dyn Machine, old_state: &[f64]) -> Vec<f64> {
1299        let (mut pos, mut vel, mut before, mut after) = ([0.0; 3], [0.0; 3], [0.0; 3], [0.0; 3]);
1300        old.tool_state(old_state, &mut pos, &mut vel);
1301        old.inverse(&pos, &mut before);
1302        self.inverse(&pos, &mut after);
1303        if old_state.len() == self.state_len() && before == after {
1304            return old_state.to_vec();
1305        }
1306        let mut state = Vec::new();
1307        self.equilibrium(&pos, &mut state, &mut [0.0; 3]);
1308        self.set_tool_velocity(&mut state, &vel);
1309        // The old machine is a linear delta too (`Sim::reconfigure` keeps the entry), elastic or rigid: its friction and
1310        // brake states.
1311        let was_elastic = old_state.len() == N_ELASTIC;
1312        let (from, to) = (if was_elastic { 18 } else { 6 }, if self.elastic { 18 } else { 6 });
1313        state[to..to + 6].copy_from_slice(&old_state[from..from + 6]);
1314        if self.elastic && was_elastic {
1315            state[24] = old_state[24];
1316            let (infos, mut row) = (old.signal_infos(), Vec::new());
1317            old.signals(old_state, &[0.0; 3], &mut row);
1318            let signal = |id: String| row[infos.iter().position(|s| s.id == id).unwrap()];
1319            for k in 0..3 {
1320                let geo = self.geo(state[k] - self.h_min())[0];
1321                state[3 + k] = (self.mat0[0] - geo + signal(format!("{}.stretch", SECTIONS[2 * k]))) / self.r_mat;
1322                state[6 + k] = self.gearbox.ratio
1323                    * (state[3 + k] + self.gearbox.static_twist(signal(format!("gearbox.{}.output_torque", k + 1))));
1324            }
1325        }
1326        state
1327    }
1328
1329    fn set_payload_attached(&mut self, attached: bool) {
1330        self.payload_attached = attached;
1331    }
1332    /// The gearboxes' hysteresis states move on to where the step ended (`Gearbox::commit`).
1333    fn after_step(&mut self, s: &mut [f64], _dt: f64) {
1334        if self.elastic {
1335            for k in 0..3 {
1336                let mut g = self.gear(k);
1337                g.commit(s[6 + k], s[3 + k]);
1338                self.anchors[k] = g.anchor;
1339            }
1340        }
1341    }
1342    fn memory(&self) -> Vec<f64> {
1343        self.anchors.concat()
1344    }
1345    fn set_memory(&mut self, memory: &[f64]) {
1346        for (anchor, a) in self.anchors.iter_mut().zip(memory.as_chunks::<2>().0) {
1347            *anchor = *a;
1348        }
1349    }
1350
1351    fn set_brake_engaged(&mut self, engaged: bool) {
1352        self.brake_engaged = engaged;
1353    }
1354    /// A carriage meeting its stop within the step (`HardStop::substeps`).
1355    fn substeps_wanted(&self, s: &[f64], _torque: &[f64], dt: f64, _substeps: u32) -> u32 {
1356        let (h, v) = self.heights(s);
1357        (0..3).map(|k| self.stops.substeps(h[k] - self.h_min(), v[k], self.stroke, dt)).max().unwrap_or(1)
1358    }
1359    /// The push acts on the platform, beyond the belts, in either model (`pushed`); its power is the budget's crash row.
1360    fn set_tool_force(&mut self, force: &[f64]) -> bool {
1361        self.push = [force[0], force[1], force[2]];
1362        true
1363    }
1364
1365    /// What the belts stretch and the couplings twist at rest anywhere in the working range (`rest_sag`).
1366    fn setpoint_slack(&self) -> f64 {
1367        // On a copy: `rest_sag` switches the payload, and nothing else it reads changes after `new`.
1368        *self.rest_slack.get_or_init(|| self.clone().rest_sag())
1369    }
1370
1371    fn unreachable(&self, tool: &[f64], slack: f64) -> Option<&'static str> {
1372        if tool.len() != 3 {
1373            return Some("error-target-out-of-range");
1374        }
1375        let p = [tool[0], tool[1], tool[2]];
1376        if !self.in_envelope(&p, slack) {
1377            return Some("error-delta-outside-envelope");
1378        }
1379        let Some(h) = self.legs.inverse(p) else { return Some("error-delta-out-of-reach") };
1380        if (0..3).any(|k| self.legs.reach(k, p) > self.legs.l * self.max_tilt.sin()) {
1381            return Some("error-delta-linear-rod-angle");
1382        }
1383        if h.iter().any(|h| *h < self.h_min() || *h > self.top_stop) {
1384            return Some("error-delta-linear-carriage-stop");
1385        }
1386        match self.legs.jacobian(h, p) {
1387            Some(j) if condition_number(&j) <= self.max_condition => None,
1388            _ => Some("error-delta-singularity"),
1389        }
1390    }
1391
1392    /// The condition number of the legs' Jacobian at the plate position, for the workspace map; infinite out of the
1393    /// rods' reach or at a direct singularity.
1394    fn condition(&self, tool: &[f64]) -> Option<f64> {
1395        let p = [tool[0], tool[1], tool[2]];
1396        Some(
1397            self.legs.inverse(p).and_then(|h| self.legs.jacobian(h, p)).map_or(f64::INFINITY, |j| condition_number(&j)),
1398        )
1399    }
1400
1401    fn signal_infos(&self) -> Vec<SignalInfo> {
1402        let mut out = Vec::new();
1403        for (k, motor) in self.motors.iter().enumerate() {
1404            out.push(SignalInfo::new(
1405                format!("carriage.{}.height", motor.id),
1406                CARRIAGES[k],
1407                "quantity-carriage-height",
1408                "m",
1409            ));
1410            out.push(SignalInfo::new(
1411                format!("{}.tension", SECTIONS[2 * k]),
1412                SECTION_KEYS[2 * k],
1413                "quantity-tension",
1414                "N",
1415            ));
1416            out.push(SignalInfo::new(
1417                format!("{}.tension", SECTIONS[2 * k + 1]),
1418                SECTION_KEYS[2 * k + 1],
1419                "quantity-tension",
1420                "N",
1421            ));
1422            out.push(SignalInfo::new(
1423                format!("pulley.{}.radial_load", motor.id),
1424                motor.key,
1425                "quantity-radial-load",
1426                "N",
1427            ));
1428            out.push(SignalInfo::new(
1429                format!("carriage.{}.guide_load", motor.id),
1430                CARRIAGES[k],
1431                "quantity-guide-load",
1432                "N",
1433            ));
1434            out.push(SignalInfo::new(
1435                format!("gearbox.{}.output_torque", motor.id),
1436                motor.key,
1437                "quantity-gearbox-torque",
1438                "N m",
1439            ));
1440        }
1441        out.push(SignalInfo::new("kinematics.condition", "group-kinematics", "quantity-condition-number", ""));
1442        out.push(SignalInfo::new("belt.slack_time", "group-belt", "quantity-slack-time", "s"));
1443        if self.guide_rating.is_some() {
1444            for (k, motor) in self.motors.iter().enumerate() {
1445                out.push(SignalInfo::new(
1446                    format!("carriage.{}.guide_damage_rate", motor.id),
1447                    CARRIAGES[k],
1448                    "quantity-damage-rate",
1449                    "1/h",
1450                ));
1451            }
1452        }
1453        if self.joint_offset != [0.0; 3] {
1454            for (k, motor) in self.motors.iter().enumerate() {
1455                for axis in ["x", "y", "z"] {
1456                    out.push(SignalInfo::new(
1457                        format!("carriage.{}.guide_moment_{axis}", motor.id),
1458                        CARRIAGES[k],
1459                        "quantity-guide-moment",
1460                        "N m",
1461                    ));
1462                }
1463            }
1464        }
1465        self.effect_infos(&mut out);
1466        out
1467    }
1468
1469    /// Each guide's highest load against ratings.guide_max_load_n and its life against ratings.required_life_h, from
1470    /// its damage rate: the catalogue's L10 = (C / P)^3 50 km of travel (C ratings.guide_dynamic_load_rating_n), used up
1471    /// at the carriage's speed |h'|, 3600 |h'| (P / C)^3 / 50 km per hour. The generic guide checks follow a tool axis
1472    /// (`axis.<id>.guide_load`), which a carriage is not.
1473    fn rating_checks(&self) -> Vec<RatingCheck> {
1474        let mut out = Vec::new();
1475        for (k, motor) in self.motors.iter().enumerate() {
1476            if let Some(limit) = self.guide_max_load {
1477                let signal = format!("carriage.{}.guide_load", motor.id);
1478                out.push(RatingCheck { check: "guide-load", signal, motor: Some(k), limit, life: false });
1479            }
1480            if let (Some(_), Some(limit)) = (self.guide_rating, self.required_life) {
1481                let signal = format!("carriage.{}.guide_damage_rate", motor.id);
1482                out.push(RatingCheck { check: "guide-life", signal, motor: Some(k), limit, life: true });
1483            }
1484        }
1485        out
1486    }
1487
1488    /// The motor pulley takes half a turn of belt: both sections pull its shaft the same way, so the radial load is
1489    /// the sum of their tensions.
1490    fn base_signals(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
1491        let (h, v) = self.heights(s);
1492        let plate = self.plate_acceleration(s, self.carriage_acceleration(s, torque));
1493        let parts = self.guide_loads_at(h, self.pose(h).0, plate);
1494        let (tensions, gear, guides) = (self.tensions(s), self.gear_output(s, torque), parts.map(|(load, _)| load));
1495        for k in 0..3 {
1496            out.extend([
1497                h[k],
1498                tensions[2 * k],
1499                tensions[2 * k + 1],
1500                tensions[2 * k] + tensions[2 * k + 1],
1501                guides[k],
1502                gear[k],
1503            ]);
1504        }
1505        let (_, j) = self.pose(h);
1506        out.push(condition_number(&j));
1507        out.push(if self.elastic { s[24] } else { 0.0 });
1508        if let Some(c) = self.guide_rating {
1509            out.extend((0..3).map(|k| 3600.0 * v[k].abs() * (guides[k] / c).powi(3) / 50e3));
1510        }
1511        if self.joint_offset != [0.0; 3] {
1512            out.extend(parts.iter().flat_map(|(_, moments)| *moments));
1513        }
1514    }
1515    fn effect_signals(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
1516        self.view_signals(s, torque, out);
1517    }
1518    fn loss_powers(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
1519        out.extend(self.losses(s, torque).0);
1520    }
1521
1522    fn friction_contacts(&self) -> Vec<FrictionContact> {
1523        (0..3).map(|k| FrictionContact { id: CONTACTS[k], owner_key: CARRIAGES[k] }).collect()
1524    }
1525    fn friction_curve(&self, i: usize, speed: f64, load_scale: f64) -> [f64; 3] {
1526        if i < 3 { self.friction[i].steady(speed, load_scale) } else { [0.0; 3] }
1527    }
1528    /// A carriage runs at most at its motor's highest speed through the gearbox and the pulley (on no axis of its own).
1529    fn friction_speed_limit(&self, i: usize, motor_speed: &[f64]) -> Option<f64> {
1530        (i < 3).then(|| Some(motor_speed.get(i)? * self.r / self.gearbox.ratio)).flatten()
1531    }
1532
1533    /// Two sections per column, in the order of the signals `belt.<i>.tension`: column 1's to the carriage from above and
1534    /// round the idler, then column 2's and 3's.
1535    fn belt_sections(&self) -> Vec<BeltSection> {
1536        SECTIONS
1537            .iter()
1538            .zip(SECTION_KEYS)
1539            .map(|(id, owner_key)| BeltSection { id, owner_key, pretension: self.belt.pretension })
1540            .collect()
1541    }
1542
1543    /// The gearboxes (not the shipped couplings, which lose nothing), the three guides and the three belts, each warming
1544    /// with its loss (power.gearbox_<k>, power.guide_<k>, power.belt_<k>, the belt's damping); shown on the gearbox and the
1545    /// carriage of its column, the belt on the first segment drawn of its loop (seven to a column, never of zero length).
1546    /// A belt's resistance and time constant follow from its size (`thermal_values`), its rated rise is `thermal.belt_max_rise_k`.
1547    fn thermal_parts(&self) -> Vec<ThermalPart> {
1548        let part =
1549            |id, kind, owner_key, scene_part, scene_index| ThermalPart { id, kind, owner_key, scene_part, scene_index };
1550        let mut out = Vec::new();
1551        if !self.gearbox.is_coupling() {
1552            out.extend([
1553                part("gearbox_1", "gearbox", self.motors[0].key, "gearbox", 0),
1554                part("gearbox_2", "gearbox", self.motors[1].key, "gearbox", 1),
1555                part("gearbox_3", "gearbox", self.motors[2].key, "gearbox", 2),
1556            ]);
1557        }
1558        out.extend([
1559            part("guide_1", "guide", CARRIAGES[0], "carriage", 0),
1560            part("guide_2", "guide", CARRIAGES[1], "carriage", 1),
1561            part("guide_3", "guide", CARRIAGES[2], "carriage", 2),
1562            part("belt_1", "belt", CARRIAGES[0], "belt", 0),
1563            part("belt_2", "belt", CARRIAGES[1], "belt", 7),
1564            part("belt_3", "belt", CARRIAGES[2], "belt", 14),
1565        ]);
1566        out
1567    }
1568
1569    fn thermal_values(&self, id: &str) -> Option<(f64, f64)> {
1570        id.starts_with("belt_").then_some(self.belt_thermal)
1571    }
1572
1573    /// With effects.thermal_feedback, in the order of `thermal_parts`: each gearbox's efficiency and each guide's viscous
1574    /// friction follow its temperature.
1575    fn set_part_temperatures(&mut self, rises: &[f64]) {
1576        let Some((law, viscous)) = &self.thermal else { return };
1577        let gearboxes = if self.gearbox.is_coupling() { 0 } else { 3 };
1578        for k in 0..gearboxes {
1579            self.gears[k].efficiency = law.gearbox_efficiency(rises[k]);
1580        }
1581        for k in 0..3 {
1582            self.friction[k].viscous = viscous * law.viscosity_factor(rises[gearboxes + k]);
1583        }
1584    }
1585
1586    /// Each column's belt loop in the vertical plane through the column, seen from outside: the motor at the top, an
1587    /// idler at the bottom, the carriage on the front run. The scene helpers draw in an x-z plane at a depth y, so each
1588    /// loop is drawn in the plane parallel to x-z through its column, a little in front of it. An inclined column's loop
1589    /// is drawn upright, its z the travel along the column, and then sheared onto the column: (x, y, z) to
1590    /// (x, y, 0) + z d, the pulleys' axes kept along y.
1591    fn scene(&self, s: &[f64], out: &mut Scene) {
1592        use sim_core::scene::{belt, drive_unit, idler};
1593        let (h, _) = self.heights(s);
1594        let (rotor, rotor_speed) = self.rotors(s);
1595        let (p, _) = self.pose(h);
1596        let r = self.r;
1597        let tensions = self.tensions(s);
1598        out.parts.clear();
1599        out.labels.clear();
1600        let grey = [0.62, 0.64, 0.68];
1601        let (top, bottom) = (self.top_stop + self.span_min, self.h_min() - self.span_min);
1602        let rim = self.column_radius + 0.08;
1603        out.parts.push(Part::new(
1604            "frame",
1605            Shape::Box { size: [2.0 * rim, 2.0 * rim, 0.04] },
1606            [0.0, 0.0, (top + 0.12) * self.legs.dir[0][2]],
1607            grey,
1608        ));
1609        for k in 0..3 {
1610            let (c, sn) = self.legs.azimuth[k];
1611            let (cx, cy) = (self.column_radius * c, self.column_radius * sn);
1612            let d = self.legs.dir[k];
1613            let onto = |q: [f64; 3]| [q[0] + q[2] * d[0], q[1] + q[2] * d[1], q[2] * d[2]];
1614            let first = out.parts.len();
1615            let (cx_rim, cy_rim) = (cx * rim / self.column_radius, cy * rim / self.column_radius);
1616            out.parts.push(if self.incline == 0.0 {
1617                Part::new(
1618                    "column",
1619                    Shape::Box { size: [0.08, 0.08, top - bottom + 0.2] },
1620                    [cx_rim, cy_rim, 0.5 * (top + bottom)],
1621                    grey,
1622                )
1623            } else {
1624                // Sheared below with the loop: from the foot to the head of the column.
1625                let to = [cx_rim, cy_rim, top + 0.1];
1626                Part::new("column", Shape::Segment { to, width: 0.08 }, [cx_rim, cy_rim, bottom - 0.1], grey)
1627            });
1628            let pulley = if self.elastic { s[3 + k] } else { rotor[k] / self.gearbox.ratio };
1629            // The belt's plane, in front of the column's centre; x across it, z up.
1630            let y = cy - 0.05;
1631            let shade = [0, 1].map(|i| {
1632                ((tensions[2 * k + i] - self.belt.pretension) / self.belt.pretension.max(1.0)).clamp(-1.0, 1.0) as f32
1633            });
1634            // A positive pulley angle lifts the carriage on the run at x = cx + r: the pulley turns anticlockwise seen
1635            // from the front.
1636            drive_unit(&mut out.parts, [cx, top], y, r, pulley, rotor[k], [0.9, 0.45, 0.1]);
1637            idler(&mut out.parts, [cx, bottom], y, r, pulley);
1638            let path = [
1639                [cx + r, h[k]],
1640                [cx + r, top],
1641                [cx, top + r],
1642                [cx - r, top],
1643                [cx - r, bottom],
1644                [cx, bottom - r],
1645                [cx + r, bottom],
1646                [cx + r, h[k]],
1647            ];
1648            belt(&mut out.parts, &path, y, 0.025, 0.003 * 8.0, |i| shade[if i < 2 { 0 } else { 1 }]);
1649            out.parts.push(Part::new(
1650                "carriage",
1651                Shape::Box { size: [0.12, 0.06, 0.1] },
1652                [cx + r, cy - 0.02, h[k]],
1653                [0.2, 0.22, 0.26],
1654            ));
1655            for part in &mut out.parts[first..] {
1656                part.pos = onto(part.pos);
1657                if let Shape::Segment { to, .. } = &mut part.shape {
1658                    *to = onto(*to);
1659                }
1660            }
1661            let joint = onto([cx, cy, h[k]]);
1662            // The two rods of the pair, apart along the carriage's width (tangential to the frame).
1663            let half = [-0.5 * self.rod_spacing * sn, 0.5 * self.rod_spacing * c, 0.0];
1664            let plate_end = [p[0] + self.plate_radius * c, p[1] + self.plate_radius * sn, p[2]];
1665            for side in [-1.0, 1.0] {
1666                let from = std::array::from_fn(|i| joint[i] + side * half[i]);
1667                let to = std::array::from_fn(|i| plate_end[i] + side * half[i]);
1668                out.parts.push(Part::new("rod", Shape::Segment { to, width: 0.012 }, from, [0.15, 0.15, 0.15]));
1669            }
1670            out.labels.push(Label {
1671                pos: onto([cx, cy, top + 0.25]),
1672                owner_key: self.motors[k].key,
1673                value: rotor_speed[k] * 60.0 / std::f64::consts::TAU,
1674                unit_key: "unit-rpm",
1675                decimals: 0,
1676            });
1677        }
1678        out.parts.extend(self.on_plate(p));
1679        out.labels.push(Label {
1680            pos: [p[0], p[1], p[2] - 0.15],
1681            owner_key: "axis-z",
1682            value: p[2],
1683            unit_key: "unit-m",
1684            decimals: 3,
1685        });
1686    }
1687
1688    /// The plate's centre: the machine's frame is the scene's.
1689    fn scene_point(&self, tool_pose: &[f64]) -> Option<[f64; 3]> {
1690        Some([tool_pose[0], tool_pose[1], tool_pose[2]])
1691    }
1692
1693    /// The plate and the payload under it, where `scene` draws them; the rods are left out.
1694    fn collision_bodies(&self, s: &[f64]) -> Vec<sim_core::Aabb> {
1695        let (h, _) = self.heights(s);
1696        sim_core::scene::scene_boxes(&self.on_plate(self.pose(h).0), &["plate", "payload"])
1697    }
1698}
1699
1700#[cfg(test)]
1701mod tests;