Skip to main content

machine_crank_cam/
indexer.rs

1//! A rotary indexing table: a driver turned by the motor through its gearbox steps a table of n stations on by a
2//! station per turn of the driver, and holds it still in between (the dwell) while the stations work. Two drives:
3//!
4//! - `geneva-drive`: a Geneva (Maltese cross) wheel of n radial slots, a pin on a crank of radius a entering a slot
5//!   radially at a centre distance C = a / sin(pi / n), and the locking disc on the crank holding the wheel while the
6//!   pin is out.
7//! - `cam-indexer`: a cam index drive (a globoid or roller-gear cam turning the turret's rollers), whose cam moves the
8//!   turret by its motion law, here the modified sine, over `indexer.index_angle_deg` of the cam's turn and holds it by
9//!   the cam's dwell ridge over the rest.
10//!
11//! The joint is the driver's angle theta (rad), 0 where the index is half done (the Geneva's pin deepest in its slot).
12//! The index runs over |theta - 2 pi k| < h: the Geneva's half angle h = pi / 2 - pi / n, so it moves over (n - 2) /
13//! (2 n) of the driver's turn and dwells over (n + 2) / (2 n); the cam's h is half its index angle.
14//!
15//! Geneva, with lambda = a / C = sin(pi / n) and x = theta - 2 pi k (Hartenberg & Denavit 1964, VDI 2727):
16//!
17//!   tan(phi) = lambda sin(x) / (1 - lambda cos(x))
18//!   phi'  = lambda (cos(x) - lambda) / (1 - 2 lambda cos(x) + lambda^2)          (d phi / d theta)
19//!   phi'' = -lambda (1 - lambda^2) sin(x) / (1 - 2 lambda cos(x) + lambda^2)^2
20//!
21//! The wheel starts and stops at rest (phi' = 0 at x = -+h), but with phi'' = tan(pi / n) at once: the acceleration
22//! jumps, the jerk is infinite. The torque on the wheel steps there by J tan(pi / n) theta'^2, and so does the pin's
23//! force on the slot's flank. The driver does not feel the step: its torque is J phi' phi'' theta'^2, and phi' is 0
24//! there. The pin is r = C sqrt(1 - 2 lambda cos(x) + lambda^2) from the wheel's centre and pushes across the radial slot
25//! with F = T / r.
26//!
27//! Cam index drive, u = (x + h) / (2 h) over the index: phi = (2 pi / n) s(u) with the modified sine s (`modified_sine`),
28//! its peak acceleration 5.528 and speed 1.760 (times the step over (2 h)^2 and 2 h), no acceleration step at either
29//! end. The cam's rollers on the turret's pitch radius r_p take F = T / r_p along the turret's tangent. With the cam's
30//! own radius R_c where the rollers touch (`indexer.cam_radius_m`) the contact is inclined by the cam's pressure
31//! angle: the roller's path along the cam's axis is z = r_p phi, the rib's slope against the cam's turn dz / d theta =
32//! r_p phi', so tan(alpha) = r_p phi' / R_c, the normal force N = F / cos(alpha) (its axial part is F, its
33//! circumferential part N sin(alpha) = F tan(alpha) at R_c gives the cam the torque F r_p phi' = T phi', as the
34//! lossless J phi' phi'' theta'^2 term has it). Absent: along the tangent, alpha = 0 (signal `indexer.pressure_angle`
35//! only with the key).
36//!
37//! The wheel (or turret), the table and the parts on it (`mass.payload_kg` at `table.station_radius_m`,
38//! `effects.payload`) turn with phi: J(theta) = J_driver + J_t phi'^2, J_t = J_wheel + J_table + m r_s^2, and the speed
39//! term J_t phi' phi'' theta'^2. Lossless and rigid: the table is horizontal and nothing but the driver's bearings
40//! (`[joint]`) takes energy.
41//!
42//! In the dwell the locking disc (the cam's dwell ridge) holds the wheel within its play (`indexer.locking_play_rad`):
43//! the table's index accuracy is half that play at the station radius, whatever the motor does. The table rings on
44//! its shaft (`table.stiffness_nm_rad` k, `table.damping_ratio`) after each index: the twist x of the table side (the
45//! table and its parts, J_s; the wheel is held by the cam) against the wheel follows x'' + 2 zeta w_n x' + w_n^2 x =
46//! -phi'' theta'^2, w_n^2 = k / J_s, through the index at the driver's speed, and what is
47//! left at its end, A, dies as exp(-zeta w_n t): the table settles to `ratings.index_settling_tolerance_m` at the station
48//! radius ln(A / tol) / (zeta w_n) after the index. The Geneva's step in acceleration at the end leaves A = tan(pi / n)
49//! theta'^2 / w_n^2; the modified sine's smooth end far less. That settling signal is worked out beside the dynamics at
50//! the driver's speed at each moment of the index, as if it ran the whole index at that speed (exact under `cam.run`, an
51//! estimate on a servo cycle that speeds up through the index), and the ring does not act back on the driver.
52//!
53//! `effects.table_twist` (off as shipped) makes the twist a joint of its own, passive, after the driver
54//! (`Mechanism::passive_joints`): the wheel (J_w, locked to the driver by the cam, angle phi(theta)) and the table side
55//! (J_s = J_table + m r_s^2) turn with v = phi' theta' + x'. T = J_d theta'^2 / 2 + J_w (phi' theta')^2 / 2 + J_s v^2 / 2
56//! gives, with Lagrange's equations,
57//!
58//!   (J_d + J_t phi'^2) theta'' + J_s phi' x'' + J_t phi' phi'' theta'^2 = torque,
59//!   J_s phi' theta'' + J_s x'' + J_s phi'' theta'^2 = -k x - c x',
60//!
61//! J_t = J_w + J_s, k = `table.stiffness_nm_rad`, c = 2 zeta sqrt(k J_s). The ring acts back on the driver through the
62//! mass coupling J_s phi', the drive's loop sees it, and the twist is a state (signal `table.twist`; its spring's energy
63//! is elastic energy, its damper's power the loss row `power.table_twist`). The cam's torque on the wheel is then J_w
64//! (phi'' theta'^2 + phi' theta'') less the shaft's k x + c x' on it (= J_w a_w + J_s (a_w + x''), J_t a_w as the twist
65//! stiffens), the contact force that over the lever; the index error in the
66//! dwell adds |x| at the station radius. The feedforward knows the rigid table only (the twist held at zero), as a
67//! drive does.
68
69use crate::{axis, machine, master, payload};
70use sim_components::cam::{Cam, Law, Segment};
71use sim_components::chain::Mechanism;
72use sim_components::joint::RotaryJoint;
73use sim_core::{CamMaster, Config, ConfigError, Label, Machine, Part, RatingCheck, Scene, Shape, SignalInfo};
74use std::f64::consts::{PI, TAU};
75
76/// The modified sine over u in [0, 1]: its lift s, ds/du and d2s/du2 (VDI 2143; peak d2s/du2 4 pi^2 / (4 + pi) =
77/// 5.528 at u = 1/8 and 7/8, peak ds/du 4 pi / (4 + pi) = 1.760 at u = 1/2): a quarter sine of acceleration over the
78/// first and last eighth, a half sine of a third of its frequency between.
79pub fn modified_sine(u: f64) -> [f64; 3] {
80    let k = 1.0 / (4.0 + PI);
81    let ends = |base: f64| {
82        let a = 4.0 * PI * u;
83        [k * (base + PI * u - 0.25 * a.sin()), k * (PI - PI * a.cos()), k * 4.0 * PI * PI * a.sin()]
84    };
85    if u <= 0.125 {
86        ends(0.0)
87    } else if u >= 0.875 {
88        ends(4.0)
89    } else {
90        let a = PI / 3.0 + 4.0 * PI * u / 3.0;
91        [k * (2.0 + PI * u - 2.25 * a.sin()), k * (PI - 3.0 * PI * a.cos()), k * 4.0 * PI * PI * a.sin()]
92    }
93}
94
95/// How the driver moves the wheel.
96#[derive(Debug, Clone, Copy, PartialEq)]
97pub enum Drive {
98    /// A Geneva wheel: lambda = a / C = sin(pi / n), and the crank's radius a.
99    Geneva { lambda: f64, crank_radius: f64 },
100    /// A cam index drive with the modified sine, its rollers on `pitch_radius`.
101    Cam { pitch_radius: f64, cam_radius: Option<f64> },
102}
103
104pub struct Indexer {
105    pub drive: Drive,
106    pub stations: usize,
107    /// Half the driver's angle over which the index runs, rad.
108    pub half: f64,
109    pub j_driver: f64,
110    /// The wheel's (turret's) and the table's own inertia, the parts apart.
111    pub j_wheel_table: f64,
112    pub payload: f64,
113    pub station_radius: f64,
114    pub attached: bool,
115    pub play: f64,
116    /// The table's mode on its shaft against the locked wheel: w_n (rad/s) and zeta.
117    pub mode: (f64, f64),
118    /// The wheel's (turret's) own inertia, which turns with phi alone.
119    pub j_wheel: f64,
120    /// With effects.table_twist: the table's shaft stiffness (N m/rad) and damping (N m s/rad) of the twist joint.
121    pub twist: Option<(f64, f64)>,
122    /// The tolerance the table settles to, rad.
123    pub tolerance: f64,
124    pub cam: Cam,
125    pub master: Option<CamMaster>,
126    limits: [f64; 3],
127}
128
129pub fn build_geneva(cfg: &Config) -> Result<Box<dyn Machine>, ConfigError> {
130    build(cfg, false)
131}
132
133pub fn build_cam(cfg: &Config) -> Result<Box<dyn Machine>, ConfigError> {
134    build(cfg, true)
135}
136
137fn build(cfg: &Config, cam: bool) -> Result<Box<dyn Machine>, ConfigError> {
138    let joint = RotaryJoint::from_config(cfg)?;
139    let indexer = Indexer::from_config(cfg, cam)?;
140    let theta = axis(cfg, "driver", "axis-driver", "rad", joint.range)?;
141    machine(cfg, indexer, (joint, None, "rad"), theta, true)
142}
143
144impl Indexer {
145    pub fn from_config(cfg: &Config, cam: bool) -> Result<Self, ConfigError> {
146        let stations = cfg.positive("indexer.stations")?;
147        let least = if cam { 2.0 } else { 3.0 };
148        if stations.fract() != 0.0 || stations < least {
149            return Err(ConfigError::Invalid("indexer.stations".into()));
150        }
151        let n = stations as usize;
152        let (drive, half) = if cam {
153            let angle = cfg.positive("indexer.index_angle_deg")?;
154            if angle >= 360.0 {
155                return Err(ConfigError::Invalid("indexer.index_angle_deg".into()));
156            }
157            let cam_radius = if cfg.get("indexer.cam_radius_m").is_ok() {
158                Some(cfg.positive("indexer.cam_radius_m")?)
159            } else {
160                None
161            };
162            let pitch_radius = cfg.positive("indexer.roller_pitch_radius_m")?;
163            (Drive::Cam { pitch_radius, cam_radius }, 0.5 * angle.to_radians())
164        } else {
165            let lambda = (PI / n as f64).sin();
166            (Drive::Geneva { lambda, crank_radius: cfg.positive("indexer.crank_radius_m")? }, 0.5 * PI - PI / n as f64)
167        };
168        let station_radius = cfg.positive("table.station_radius_m")?;
169        let j_wheel = cfg.positive("indexer.wheel_inertia_kgm2")?;
170        let j_wheel_table = j_wheel + cfg.positive("table.inertia_kgm2")?;
171        let payload = payload(cfg)?;
172        let j_all = j_wheel_table + payload * station_radius * station_radius;
173        let stiffness = cfg.positive("table.stiffness_nm_rad")?;
174        // The table side twists against the wheel, which the cam (or the locking disc) holds: the wheel is not in the mode.
175        let j_side = j_all - j_wheel;
176        let w_n = (stiffness / j_side).sqrt();
177        let zeta = cfg.positive("table.damping_ratio")?;
178        let twist = cfg.bool("effects.table_twist")?.then(|| (stiffness, 2.0 * zeta * (stiffness * j_side).sqrt()));
179        let one_turn = Cam::from_segments(&[Segment { master: TAU, slave: TAU, law: Law::Linear }])
180            .expect("one turn at constant speed");
181        let master = master(cfg, TAU * cfg.positive("indexer.turns_per_min")? / 60.0, one_turn.period)?;
182        Ok(Indexer {
183            drive,
184            stations: n,
185            half,
186            j_driver: cfg.positive("indexer.driver_inertia_kgm2")?,
187            j_wheel_table,
188            payload,
189            station_radius,
190            attached: true,
191            play: cfg.non_negative("indexer.locking_play_rad")?,
192            mode: (w_n, zeta),
193            j_wheel,
194            twist,
195            tolerance: cfg.positive("ratings.index_settling_tolerance_m")? / station_radius,
196            cam: one_turn,
197            master,
198            limits: [
199                cfg.f64("ratings.indexer_max_contact_force_n").unwrap_or(f64::INFINITY),
200                cfg.f64("ratings.index_max_error_m").unwrap_or(f64::INFINITY),
201                cfg.f64("ratings.index_max_settling_s").unwrap_or(f64::INFINITY),
202            ],
203        })
204    }
205
206    /// The table's inertia with the parts as they are.
207    pub fn j_table(&self) -> f64 {
208        let r = self.station_radius;
209        self.j_wheel_table + if self.attached { self.payload * r * r } else { 0.0 }
210    }
211
212    /// The table side's inertia (table and parts, the wheel apart), kg m^2.
213    fn j_side(&self) -> f64 {
214        self.j_table() - self.j_wheel
215    }
216
217    /// The cam's pressure angle at the driver's angle, rad: atan(r_p phi' / R_c); 0 for the Geneva, in the dwell and
218    /// without `indexer.cam_radius_m`.
219    pub fn pressure_angle(&self, theta: f64) -> f64 {
220        match self.drive {
221            Drive::Cam { pitch_radius, cam_radius: Some(r) } => (pitch_radius * self.motion(theta)[1] / r).atan(),
222            _ => 0.0,
223        }
224    }
225
226    /// The angle of one station, rad.
227    fn step(&self) -> f64 {
228        TAU / self.stations as f64
229    }
230
231    /// The driver's angle from the middle of the index, x in [-h, h), or `None` in the dwell; and the index count k.
232    fn phase(&self, theta: f64) -> (Option<f64>, f64) {
233        let h = self.half;
234        let k = ((theta + h) / TAU).floor();
235        let w = theta + h - TAU * k;
236        ((w < 2.0 * h).then_some(w - h), k)
237    }
238
239    /// The wheel's angle phi and its derivatives d phi / d theta, d2 phi / d theta2 at the driver's angle.
240    pub fn motion(&self, theta: f64) -> [f64; 3] {
241        let (x, k) = self.phase(theta);
242        let step = self.step();
243        let Some(x) = x else { return [(k + 1.0) * step, 0.0, 0.0] };
244        match self.drive {
245            Drive::Geneva { lambda: l, .. } => {
246                let d = 1.0 - 2.0 * l * x.cos() + l * l;
247                let local = (l * x.sin()).atan2(1.0 - l * x.cos());
248                [k * step + 0.5 * step + local, l * (x.cos() - l) / d, -l * (1.0 - l * l) * x.sin() / (d * d)]
249            }
250            Drive::Cam { .. } => {
251                let span = 2.0 * self.half;
252                let [s, s1, s2] = modified_sine((x + self.half) / span);
253                [k * step + step * s, step * s1 / span, step * s2 / (span * span)]
254            }
255        }
256    }
257
258    /// The lever of the contact from the wheel's centre, m: the Geneva's pin, the cam's rollers. `None` in the dwell.
259    pub fn lever(&self, theta: f64) -> Option<f64> {
260        let x = self.phase(theta).0?;
261        Some(match self.drive {
262            Drive::Geneva { lambda: l, crank_radius } => crank_radius / l * (1.0 - 2.0 * l * x.cos() + l * l).sqrt(),
263            Drive::Cam { pitch_radius, .. } => pitch_radius,
264        })
265    }
266
267    /// The torque the drive puts on the wheel (table and parts) and the contact force, at the driver's angle, speed and
268    /// acceleration.
269    pub fn loads(&self, theta: f64, speed: f64, acc: f64) -> [f64; 2] {
270        self.loads_twisted(theta, speed, acc, None)
271    }
272
273    /// `loads`, with the twist joint's shaft torque `held` (k x + c x', N m) where it is a state: the cam then turns the
274    /// wheel alone and the shaft's torque on it. The contact force along the normal (1 / cos of the cam's pressure angle
275    /// on the force along the turret's tangent).
276    fn loads_twisted(&self, theta: f64, speed: f64, acc: f64, held: Option<f64>) -> [f64; 2] {
277        let [_, p1, p2] = self.motion(theta);
278        let a_w = p2 * speed * speed + p1 * acc;
279        let torque = match held {
280            Some(held) => self.j_wheel * a_w - held,
281            None => self.j_table() * a_w,
282        };
283        [torque, self.lever(theta).map_or(0.0, |r| torque / r / self.pressure_angle(theta).cos())]
284    }
285
286    /// The table's twist ring left at the end of an index run at the driver's speed `speed` throughout, rad: its
287    /// amplitude sqrt(x^2 + ((x' + zeta w_n x) / w_d)^2) from rest at the index's start. Over 2000 steps, each with the
288    /// base acceleration at its middle held and the oscillator's own solution (exact for that held force).
289    pub fn residual(&self, speed: f64) -> f64 {
290        let (w, zeta) = self.mode;
291        if speed.abs() < 1e-9 {
292            return 0.0;
293        }
294        const STEPS: usize = 2000;
295        let (sigma, wd) = (zeta * w, w * (1.0 - zeta * zeta).sqrt());
296        let dt = 2.0 * self.half / speed.abs() / STEPS as f64;
297        let (c, s, e) = ((wd * dt).cos(), (wd * dt).sin(), (-sigma * dt).exp());
298        let phi = [[e * (c + sigma / wd * s), e * s / wd], [-e * w * w / wd * s, e * (c - sigma / wd * s)]];
299        let (mut x, mut v) = (0.0, 0.0);
300        for i in 0..STEPS {
301            let theta = -self.half + (i as f64 + 0.5) * 2.0 * self.half / STEPS as f64;
302            let rest = -self.motion(theta)[2] * speed * speed / (w * w);
303            let y = x - rest;
304            (x, v) = (rest + phi[0][0] * y + phi[0][1] * v, phi[1][0] * y + phi[1][1] * v);
305        }
306        x.hypot((v + sigma * x) / wd)
307    }
308
309    /// How long the table rings beyond the tolerance after an index at the driver's speed, s.
310    pub fn settling_time(&self, speed: f64) -> f64 {
311        let a = self.residual(speed);
312        if a <= self.tolerance { 0.0 } else { (a / self.tolerance).ln() / (self.mode.0 * self.mode.1) }
313    }
314}
315
316impl Mechanism for Indexer {
317    /// In the scene's frame: the wheel and the table turning about +y with phi' theta' (the table side with the twist's
318    /// rate on top), the parts a point each at the station radius on it, the driver and the rotor on its shaft: the
319    /// Geneva's crank about -y beside the wheel (it turns the wheel against itself), the cam's shaft square to the
320    /// turret's, along z, the turret's tangent where the cam meets it. Their centres stay put: the parts' first moment, n
321    /// of them evenly round the table, stays at its centre.
322    fn frame_momentum(&self, q: &[f64], qd: &[f64], rotor_spin: &[f64]) -> Option<sim_core::FrameMomentum> {
323        use sim_components::base::{add_point, add_spin};
324        let [phi, p1, _] = self.motion(q[0]);
325        let (x, xd) = (q.get(1).copied().unwrap_or(0.0), qd.get(1).copied().unwrap_or(0.0));
326        let (wheel, table) = (p1 * qd[0], p1 * qd[0] + xd);
327        let mut f = sim_core::FrameMomentum::default();
328        add_spin(&mut f, [0.0, 1.0, 0.0], self.j_wheel, wheel);
329        add_spin(&mut f, [0.0, 1.0, 0.0], self.j_wheel_table - self.j_wheel, table);
330        let (parts, r) = (if self.attached { self.payload } else { 0.0 }, self.station_radius);
331        for i in 0..self.stations {
332            // The scene's angle from +x towards +z: the table turns it back by phi.
333            let a = self.step() * i as f64 - phi - x;
334            let (s, c) = a.sin_cos();
335            add_point(&mut f, parts / self.stations as f64, [r * c, 0.0, r * s], [r * s * table, 0.0, -r * c * table]);
336        }
337        let shaft = match self.drive {
338            Drive::Geneva { .. } => [0.0, -1.0, 0.0],
339            Drive::Cam { .. } => [0.0, 0.0, 1.0],
340        };
341        add_spin(&mut f, shaft, self.j_driver, qd[0]);
342        add_spin(&mut f, shaft, 1.0, rotor_spin[0]);
343        Some(f)
344    }
345    fn dynamics(&self, q: &[f64], qd: &[f64], mass: &mut [f64], bias: &mut [f64]) {
346        let [_, p1, p2] = self.motion(q[0]);
347        mass[0] = self.j_driver + self.j_table() * p1 * p1;
348        bias[0] = self.j_table() * p1 * p2 * qd[0] * qd[0];
349        if self.twist.is_some() {
350            // With the twist: the matrix of the doc comment (all joints, driver first).
351            let js = self.j_side();
352            (mass[1], mass[2], mass[3]) = (js * p1, js * p1, js);
353            bias[1] = js * p2 * qd[0] * qd[0];
354        }
355    }
356    fn passive_joints(&self) -> Vec<(f64, f64)> {
357        self.twist.into_iter().collect()
358    }
359    fn passive_signals(&self) -> Vec<SignalInfo> {
360        self.twist
361            .map(|_| SignalInfo::new("table.twist", "group-table", "quantity-table-twist", "rad"))
362            .into_iter()
363            .collect()
364    }
365    fn passive_loss_row(&self) -> Option<(&'static str, &'static str)> {
366        Some(("table_twist", "group-table"))
367    }
368    fn forward(&self, q: &[f64], tool: &mut [f64]) {
369        tool[0] = q[0];
370    }
371    fn potential(&self, _q: &[f64]) -> f64 {
372        0.0
373    }
374    fn set_payload_attached(&mut self, attached: bool) {
375        self.attached = attached;
376    }
377    /// The speed term of J(theta) needs the feedforward's speed terms.
378    fn tool_is_joints(&self) -> bool {
379        false
380    }
381    fn cam(&self) -> Option<CamMaster> {
382        self.master
383    }
384    fn cam_at(&self, master: f64, out: &mut [[f64; 4]]) {
385        out[0] = self.cam.at(master);
386    }
387    fn cam_curve(&self) -> Option<sim_core::CamCurve> {
388        let cam = self.cam.clone();
389        Some(std::sync::Arc::new(move |master, out: &mut [[f64; 4]]| out[0] = cam.at(master)))
390    }
391
392    fn signal_infos(&self) -> Vec<SignalInfo> {
393        [
394            ("table.angle", "group-table", "quantity-position", "rad"),
395            ("table.speed", "group-table", "quantity-speed", "rad/s"),
396            ("table.acceleration", "group-table", "quantity-acceleration", "rad/s²"),
397            ("table.drive_torque", "group-table", "quantity-table-torque", "N m"),
398            ("indexer.contact_force", "group-indexer", "quantity-contact-force", "N"),
399            ("table.index_error", "group-table", "quantity-index-error", "m"),
400            ("table.settling_time", "group-table", "quantity-settling-time", "s"),
401            ("indexer.inertia", "group-indexer", "quantity-driver-inertia", "kg m²"),
402        ]
403        .into_iter()
404        .chain(matches!(self.drive, Drive::Cam { cam_radius: Some(_), .. }).then_some((
405            "indexer.pressure_angle",
406            "group-indexer",
407            "quantity-pressure-angle",
408            "rad",
409        )))
410        .map(|(id, owner, quantity, unit)| SignalInfo::new(id, owner, quantity, unit))
411        .collect()
412    }
413    fn signals(&self, q: &[f64], qd: &[f64], qdd: &[f64], _force: &[f64], out: &mut Vec<f64>) {
414        let [phi, p1, p2] = self.motion(q[0]);
415        // The twist joint's angle and speed, where the state has it (the rigid feedforward's checks hold it at rest).
416        let at = |v: &[f64]| v.get(1).copied().unwrap_or(0.0);
417        let (x, xd, xdd) = (at(q), at(qd), at(qdd));
418        let held = self.twist.filter(|_| q.len() > 1).map(|(k, c)| k * x + c * xd);
419        let [torque, contact] = self.loads_twisted(q[0], qd[0], qdd[0], held);
420        let moving = self.phase(q[0]).0.is_some();
421        // The table turns with the wheel and its twist.
422        out.extend([
423            phi + x,
424            p1 * qd[0] + xd,
425            p2 * qd[0] * qd[0] + p1 * qdd[0] + xdd,
426            torque,
427            contact,
428            // Held by the locking disc: half its play either way, at the stations.
429            if moving { 0.0 } else { (0.5 * self.play + x.abs()) * self.station_radius },
430            if moving { self.settling_time(qd[0]) } else { 0.0 },
431            self.j_driver + self.j_table() * p1 * p1,
432        ]);
433        if matches!(self.drive, Drive::Cam { cam_radius: Some(_), .. }) {
434            out.push(self.pressure_angle(q[0]));
435        }
436    }
437    fn rating_checks(&self) -> Vec<RatingCheck> {
438        [
439            ("indexer-contact-force", "indexer.contact_force"),
440            ("index-accuracy", "table.index_error"),
441            ("index-settling", "table.settling_time"),
442        ]
443        .into_iter()
444        .zip(self.limits)
445        .filter(|(_, limit)| limit.is_finite())
446        .map(|((check, signal), limit)| RatingCheck { check, signal: signal.into(), motor: None, limit, life: false })
447        .collect()
448    }
449
450    /// The stations' fixtures and the parts on them: what turns with the table and can hit an obstacle (the table
451    /// itself is a cylinder, which no collision box stands for).
452    fn collision_parts(&self) -> &'static [&'static str] {
453        &["station", "payload"]
454    }
455
456    /// Seen from the front: the table at the origin with a mark and a fixture (with its part) per station turning with
457    /// it, the driver beside it with its crank (or cam) mark; the gearbox and the motor behind the driver.
458    fn scene(&self, q: &[f64], rotors: &[f64], rotor_speeds: &[f64], out: &mut Scene) {
459        let r = self.station_radius;
460        // The table turns the twist beyond the wheel.
461        let phi = self.motion(q[0])[0] + q.get(1).copied().unwrap_or(0.0);
462        let driver = [-(r + 0.12), 0.0, 0.0];
463        out.parts.push(Part::new("table", Shape::Cylinder { radius: r, length: 0.03 }, [0.0; 3], [0.45, 0.47, 0.5]));
464        for i in 0..self.stations {
465            out.parts.push(
466                Part::new("table-mark", Shape::Box { size: [r, 0.004, 0.02] }, [0.0, -0.017, 0.0], [0.1, 0.1, 0.1])
467                    .turned(-phi + self.step() * i as f64),
468            );
469            let a = -phi + self.step() * i as f64;
470            let at = |y: f64| [0.85 * r * a.cos(), y, 0.85 * r * a.sin()];
471            let fixture = Part::new("station", Shape::Box { size: [0.05, 0.01, 0.05] }, at(-0.02), [0.6, 0.62, 0.66]);
472            out.parts.push(fixture.turned(a));
473            if self.attached && self.payload > 0.0 {
474                let part = Part::new("payload", Shape::Box { size: [0.04, 0.03, 0.04] }, at(-0.04), [0.2, 0.7, 0.3]);
475                out.parts.push(part.turned(a));
476            }
477        }
478        out.parts.push(Part::new("driver", Shape::Cylinder { radius: 0.08, length: 0.03 }, driver, [0.3, 0.32, 0.36]));
479        out.parts.push(
480            Part::new("driver-mark", Shape::Box { size: [0.08, 0.004, 0.015] }, driver, [0.9, 0.8, 0.2]).turned(q[0]),
481        );
482        let motor = [driver[0], 0.12, 0.0];
483        out.parts.push(Part::new(
484            sim_core::scene::MOTOR_PART,
485            Shape::Cylinder { radius: 0.05, length: 0.12 },
486            motor,
487            [0.9, 0.45, 0.1],
488        ));
489        // The gearbox between motor and driver: the part that warms (`JointMachine::thermal_parts`).
490        out.parts.push(Part::new(
491            "gearbox",
492            Shape::Box { size: [0.1, 0.06, 0.1] },
493            [driver[0], 0.06, 0.0],
494            [0.25, 0.25, 0.28],
495        ));
496        out.parts.push(
497            Part::new("rotor-bar", Shape::Box { size: [0.07, 0.004, 0.012] }, [motor[0], 0.19, 0.0], [0.1, 0.1, 0.1])
498                .turned(rotors[0]),
499        );
500        out.labels.push(Label {
501            pos: [driver[0], 0.0, 0.16],
502            owner_key: "motor-joint-1",
503            value: rotor_speeds[0] * 60.0 / TAU,
504            unit_key: "unit-rpm",
505            decimals: 0,
506        });
507        out.labels.push(Label {
508            pos: [0.0, 0.0, r + 0.05],
509            owner_key: "group-table",
510            value: phi.to_degrees(),
511            unit_key: "unit-deg",
512            decimals: 1,
513        });
514    }
515}