Skip to main content

machine_crank_cam/
toggle.rs

1//! A toggle press (knuckle-joint press): two links in line between the frame's top pivot O and the ram, the upper one of
2//! length a, the lower one of length b, their joint the knee K; a crank of radius r, turned by the motor through its
3//! gearbox, pushes the knee across through a connecting rod of length c. Where the links stand stretched (the dead
4//! centre) the ram is at its bottom, and near there it moves very little for the knee's travel: the force at the ram is
5//! the crank's torque over a ratio dx/dq that falls to zero at the dead centre, the force amplification the machine is
6//! built for.
7//!
8//! Why a crank and not a ball screw: the crank-driven knuckle joint is the classic form and keeps the crate's turning
9//! drive, cam and axis in rad; its ratio near the dead centre falls with both the links' and the four-bar's geometry,
10//! which `crank.angle_at_dead_centre_deg` sets (90: the crank across the rod there, the ratio falls linearly; towards
11//! 180 the crank comes into line with the rod and the dwell grows flat). The screw-driven toggle (the knee on the nut)
12//! is the same links with the knee's travel a linear joint; not built.
13//!
14//! Frame (scene's x across, z up), O at the origin, the ram on a vertical guide through O. The knee K = (a sin(phi),
15//! -a cos(phi)), phi the upper link's angle from straight down; the ram x = a cos(phi) + sqrt(b^2 - a^2 sin^2(phi)) below
16//! O (the slider-crank's formula, `crank::slider_motion`, the upper link its crank), x = a + b at the dead centre phi = 0.
17//! The joint q is the crank angle from the dead centre: the crank pin P = C + r (cos(t), sin(t)), t = t0 + q,
18//! t0 = `crank.angle_at_dead_centre_deg`; the crank's centre C lies where, at q = 0, the rod lies level from P to the
19//! stretched knee (0, -a): C = (c, -a) - r (cos(t0), sin(t0)). The knee closes the four-bar O-K-P-C: K on the circle of
20//! radius a about O and the one of radius c about P, the branch below the line O-P:
21//!
22//!   phi = atan2(P_z, P_x) - acos((a^2 + |P|^2 - c^2) / (2 a |P|)) + pi / 2,
23//!   phi' = (D . P_q) / (D . K_phi),   D = K - P,
24//!   phi'' = -(E . E + D . (K_phiphi phi'^2 - P_qq)) / (D . K_phi),   E = K_phi phi' - P_q,
25//!   x' = x_phi phi',   x'' = x_phiphi phi'^2 + x_phi phi''.
26//!
27//! x' (m/rad) is the transmission ratio, zero at the dead centre; the ram force a crank torque tau gives is tau / x'.
28//! The joint works through the dead centre (the ram then rises again) where its stops let it: `joint.max_angle_deg`
29//! above 0; on one side of it where they end there. The inverse from the ram's distance to the dead centre has two
30//! branches, before (phi > 0) and after it (`TogglePress::crank_angle`).
31//!
32//! Masses: the crank and the rod's crank end (`rod.crank_end_share`) at the pin; the upper link a uniform bar about O
33//! (J = m a^2 / 3, its centre at a / 2); at the knee the rod's other end and the lower link's share
34//! (`toggle.lower_link_knee_share`); at the ram the ram, the die (payload) and the rest of the lower link. So
35//! J(q) = J_crank + m_pin r^2 + (m_up a^2 / 3 + m_knee a^2) phi'^2 + m_x x'^2, its speed term
36//! ((m_up a^2 / 3 + m_knee a^2) phi' phi'' + m_x x' x'') q'^2, and V = g (m_pin z_P - (m_knee a + m_up a / 2) cos(phi)
37//! - m_x x).
38//!
39//! The process force (effects.process_force) is a table over the ram's distance from the bottom dead centre
40//! (`process.distance_m`, `process.force_n`), pushing the ram up while it moves down or stands, and fading out over
41//! `process.smoothing_m_s` as it rises (the part springs back at once): a forming force that holds through a dwell at
42//! the dead centre. The frame stretches under it as a spring in series (effects.frame_stretch,
43//! `frame.stretch_stiffness_n_m` = k): the ram stands F / k short of where the links put it, so the force is the root
44//! of F = table(d + F / k), d the links' distance from the dead centre; on a segment of the table from (d_i, F_i) of
45//! slope s_i, F = (F_i + s_i (d - d_i)) / (1 - s_i / k). Its torque at the crank is -F x'.
46//!
47//! Signals: the ram's height above the bottom dead centre (with the frame's stretch), its speed and acceleration, the
48//! ratio x', the press force, the force capacity at the pose and its use, the frame's stretch, the forces of the upper
49//! and lower link (compression positive; the links and their pins are two-force members, so the pins carry them) and
50//! of the rod, and the inertia J(q) at the crank. Verdicts: "press-capacity" (the press force within the capacity,
51//! min(`ratings.rated_press_force_n`, tau_max / |x'|), tau_max the drive's peak torque through the gearbox's ratio and
52//! efficiency, at most `ratings.gearbox_max_torque_nm`), "upper-link-force", "lower-link-force"
53//! (`ratings.link_max_force_n`), "rod-force" (`ratings.rod_max_force_n`), "frame-deflection"
54//! (`ratings.frame_max_deflection_m`).
55
56use crate::crank::slider_motion;
57use crate::{Table, axis, gravity, machine, master, payload};
58use sim_components::cam::Cam;
59use sim_components::chain::Mechanism;
60use sim_components::joint::RotaryJoint;
61use sim_core::{CamMaster, Config, ConfigError, Label, Machine, Part, RatingCheck, Scene, Shape, SignalInfo};
62use std::f64::consts::{FRAC_PI_2, PI, TAU};
63
64pub struct TogglePress {
65    /// Upper and lower link, crank radius, rod length, m.
66    pub a: f64,
67    pub b: f64,
68    pub r: f64,
69    pub c: f64,
70    /// The crank's angle (from the scene's x towards z) at the dead centre, rad.
71    pub t0: f64,
72    /// The crank's centre (x, z), m, the top pivot at the origin.
73    pub centre: [f64; 2],
74    pub j_crank: f64,
75    /// The rod's crank end, at the pin.
76    pub m_pin: f64,
77    /// The upper link, a uniform bar.
78    pub m_upper: f64,
79    /// At the knee: the rod's other end and the lower link's share.
80    pub m_knee: f64,
81    /// The ram and the lower link's rest, the die (payload) apart.
82    pub m_ram: f64,
83    pub payload: f64,
84    pub attached: bool,
85    pub g: f64,
86    pub(crate) process: Option<Table>,
87    /// The process force fades out over this ram speed upwards, m/s.
88    pub smoothing: f64,
89    /// The frame's stiffness under the press force, N/m; `None` with effects.frame_stretch off (a rigid frame).
90    pub frame: Option<f64>,
91    /// The torque the drive can put on the crank, N m: its peak torque through the gearbox.
92    pub crank_torque: f64,
93    /// What the frame and the links are rated for, N.
94    pub rated_force: f64,
95    pub cam: Option<(Cam, CamMaster)>,
96    /// The crank's assembly for the inverse: the sign of the angle from C-K to C-P.
97    branch: f64,
98    /// Limits of the link, rod and frame checks (infinite: no check).
99    limits: [f64; 3],
100}
101
102/// The linkage at a crank angle: the pin and the knee (x, z), the upper link's angle and its two rates over q, and the
103/// ram x, x', x''.
104#[derive(Debug, Clone, Copy)]
105pub struct Pose {
106    pub pin: [f64; 2],
107    pub knee: [f64; 2],
108    pub phi: [f64; 3],
109    pub x: [f64; 3],
110}
111
112pub fn build(cfg: &Config) -> Result<Box<dyn Machine>, ConfigError> {
113    let joint = RotaryJoint::from_config(cfg)?;
114    let press = TogglePress::from_config(cfg)?;
115    // The four-bar must close over the whole of the joint's range, and keep away from its own dead points (rod and upper
116    // link in line), where phi' would have no bound.
117    for k in 0..=400 {
118        let q = joint.range.0 + (joint.range.1 - joint.range.0) * k as f64 / 400.0;
119        let p = press.pose(q);
120        if !(p.phi[1].is_finite() && p.x[0].is_finite() && p.phi[1].abs() < 50.0) {
121            return Err(ConfigError::Invalid("crank.radius_m".into()));
122        }
123    }
124    let q = axis(cfg, "crank", "axis-crank", "rad", joint.range)?;
125    machine(cfg, press, (joint, None, "rad"), q, false)
126}
127
128fn dot(u: [f64; 2], v: [f64; 2]) -> f64 {
129    u[0] * v[0] + u[1] * v[1]
130}
131
132impl TogglePress {
133    pub fn from_config(cfg: &Config) -> Result<Self, ConfigError> {
134        let (a, b) = (cfg.positive("toggle.upper_link_m")?, cfg.positive("toggle.lower_link_m")?);
135        let (r, c) = (cfg.positive("crank.radius_m")?, cfg.positive("rod.length_m")?);
136        if b < a {
137            return Err(ConfigError::Invalid("toggle.lower_link_m".into()));
138        }
139        let share = |key: &str| -> Result<f64, ConfigError> {
140            let s = cfg.non_negative(key)?;
141            if s > 1.0 { Err(ConfigError::Invalid(key.into())) } else { Ok(s) }
142        };
143        let (rod_share, knee_share) = (share("rod.crank_end_share")?, share("toggle.lower_link_knee_share")?);
144        let (rod, lower) = (cfg.non_negative("rod.mass_kg")?, cfg.non_negative("toggle.lower_link_mass_kg")?);
145        let t0 = cfg.f64("crank.angle_at_dead_centre_deg")?.to_radians();
146        if !(0.0..PI).contains(&t0) || t0 == 0.0 {
147            return Err(ConfigError::Invalid("crank.angle_at_dead_centre_deg".into()));
148        }
149        let cam = Cam::from_config(cfg, "cam")?;
150        let master = master(cfg, cam.period * cfg.positive("crank.strokes_per_min")? / 60.0, cam.period)?;
151        let crank_torque = (cfg.positive("drive.peak_torque_nm")?
152            * cfg.positive("gearbox.ratio")?
153            * cfg.positive("gearbox.efficiency")?)
154        .min(match cfg.get("ratings.gearbox_max_torque_nm") {
155            Ok(_) => cfg.positive("ratings.gearbox_max_torque_nm")?,
156            Err(_) => f64::INFINITY,
157        });
158        let centre = [c - r * t0.cos(), -a - r * t0.sin()];
159        let mut press = TogglePress {
160            a,
161            b,
162            r,
163            c,
164            t0,
165            centre,
166            j_crank: cfg.positive("crank.inertia_kgm2")?,
167            m_pin: rod_share * rod,
168            m_upper: cfg.non_negative("toggle.upper_link_mass_kg")?,
169            m_knee: (1.0 - rod_share) * rod + knee_share * lower,
170            m_ram: cfg.positive("ram.mass_kg")? + (1.0 - knee_share) * lower,
171            payload: payload(cfg)?,
172            attached: true,
173            g: gravity(cfg)?,
174            process: if cfg.bool("effects.process_force")? {
175                Some(Table::from_config(cfg, "process.distance_m", "process.force_n")?)
176            } else {
177                None
178            },
179            smoothing: cfg.positive("process.smoothing_m_s")?,
180            frame: if cfg.bool("effects.frame_stretch")? {
181                Some(cfg.positive("frame.stretch_stiffness_n_m")?)
182            } else {
183                None
184            },
185            crank_torque,
186            rated_force: cfg.positive("ratings.rated_press_force_n")?,
187            cam: master.map(|m| (cam, m)),
188            branch: 1.0,
189            limits: ["link_max_force_n", "rod_max_force_n", "frame_max_deflection_m"]
190                .map(|k| cfg.f64(&format!("ratings.{k}")).unwrap_or(f64::INFINITY)),
191        };
192        // The crank's assembly: the side of C-K that puts the crank at t0 with the links stretched.
193        let to_knee = [-centre[0], -a - centre[1]];
194        let (gamma, delta) = (to_knee[1].atan2(to_knee[0]), press.crank_delta(to_knee));
195        let wrap = |x: f64| (x + PI).rem_euclid(TAU) - PI;
196        press.branch = if wrap(gamma + delta - t0).abs() < wrap(gamma - delta - t0).abs() { 1.0 } else { -1.0 };
197        Ok(press)
198    }
199
200    /// The angle between C-K and C-P where the rod of length c reaches K from the crank's circle.
201    fn crank_delta(&self, to_knee: [f64; 2]) -> f64 {
202        let e = to_knee[0].hypot(to_knee[1]);
203        ((self.r * self.r + e * e - self.c * self.c) / (2.0 * self.r * e)).acos()
204    }
205
206    /// The linkage at the crank angle q (the module's formulas); NaN where the four-bar does not close.
207    pub fn pose(&self, q: f64) -> Pose {
208        let (a, r, c) = (self.a, self.r, self.c);
209        let (s, co) = (self.t0 + q).sin_cos();
210        let pin = [self.centre[0] + r * co, self.centre[1] + r * s];
211        let (pq, pqq) = ([-r * s, r * co], [-r * co, -r * s]);
212        let d = pin[0].hypot(pin[1]);
213        let phi = pin[1].atan2(pin[0]) - ((a * a + d * d - c * c) / (2.0 * a * d)).acos() + FRAC_PI_2;
214        let (sp, cp) = phi.sin_cos();
215        let knee = [a * sp, -a * cp];
216        let (kp, kpp) = ([a * cp, a * sp], [-a * sp, a * cp]);
217        let dk = [knee[0] - pin[0], knee[1] - pin[1]];
218        let den = dot(dk, kp);
219        let phi1 = dot(dk, pq) / den;
220        let e = [kp[0] * phi1 - pq[0], kp[1] * phi1 - pq[1]];
221        let phi2 = -(dot(e, e) + dot(dk, [kpp[0] * phi1 * phi1 - pqq[0], kpp[1] * phi1 * phi1 - pqq[1]])) / den;
222        let [x, xp, xpp] = slider_motion(a, self.b, phi);
223        Pose { pin, knee, phi: [phi, phi1, phi2], x: [x, xp * phi1, xpp * phi1 * phi1 + xp * phi2] }
224    }
225
226    /// The inverse: the crank angle that puts the ram (the links, without the frame's stretch) `distance` above the
227    /// bottom dead centre, before the dead centre (`before`, phi > 0) or after it; `None` beyond the links' reach or the
228    /// crank's.
229    pub fn crank_angle(&self, distance: f64, before: bool) -> Option<f64> {
230        let (a, b) = (self.a, self.b);
231        let x = a + b - distance;
232        let cos = (a * a + x * x - b * b) / (2.0 * a * x);
233        if !(distance >= 0.0 && x > b - a && cos.abs() <= 1.0 + 1e-12) {
234            return None;
235        }
236        let cos = cos.clamp(-1.0, 1.0);
237        let phi = if before { cos.acos() } else { -cos.acos() };
238        let knee = [a * phi.sin(), -a * phi.cos()];
239        let to_knee = [knee[0] - self.centre[0], knee[1] - self.centre[1]];
240        let delta = self.crank_delta(to_knee);
241        let t = to_knee[1].atan2(to_knee[0]) + self.branch * delta;
242        delta.is_finite().then(|| (t - self.t0 + PI).rem_euclid(TAU) - PI)
243    }
244
245    fn m_x(&self) -> f64 {
246        self.m_ram + if self.attached { self.payload } else { 0.0 }
247    }
248
249    /// What the knee and the upper link put in J: m_up a^2 / 3 + m_knee a^2.
250    fn j_knee(&self) -> f64 {
251        (self.m_upper / 3.0 + self.m_knee) * self.a * self.a
252    }
253
254    /// J(q): what the crank feels of crank, pin, links, knee and ram.
255    pub fn inertia(&self, q: f64) -> f64 {
256        let p = self.pose(q);
257        self.j_crank + self.m_pin * self.r * self.r + self.j_knee() * p.phi[1] * p.phi[1] + self.m_x() * p.x[1] * p.x[1]
258    }
259
260    /// The torque the crank needs to hold the ram force `force` at q against nothing else: F x'.
261    pub fn holding_torque(&self, q: f64, force: f64) -> f64 {
262        force * self.pose(q).x[1]
263    }
264
265    /// The force the press can give at q: the rated force, or less where the drive's torque through the ratio gives less.
266    pub fn capacity(&self, q: f64) -> f64 {
267        let ratio = self.pose(q).x[1].abs();
268        if ratio * self.rated_force <= self.crank_torque { self.rated_force } else { self.crank_torque / ratio }
269    }
270
271    /// The press force at the links' distance `d` from the bottom dead centre, before the motion's share: the root of
272    /// F = table(d + F / k), segment by segment of the table (linear there: F = (v_i + s_i (d - d_i)) / (1 - s_i / k)).
273    pub fn press_force_at(&self, d: f64) -> f64 {
274        let Some(table) = &self.process else { return 0.0 };
275        let Some(k) = self.frame else { return table.at(d) };
276        if table.at.len() < 2 {
277            return table.at(d + table.value[0] / k).min(table.value[0]);
278        }
279        for i in 0..table.at.len() - 1 {
280            let (a0, a1, v0, v1) = (table.at[i], table.at[i + 1], table.value[i], table.value[i + 1]);
281            let slope = (v1 - v0) / (a1 - a0);
282            let f = (v0 + slope * (d - a0)) / (1.0 - slope / k);
283            let u = d + f / k;
284            if f >= 0.0 && u >= a0 && u <= a1 {
285                return f;
286            }
287        }
288        0.0
289    }
290
291    /// The press force on the ram (pushing it up) and the frame's stretch at q and the crank's speed: the table's force
292    /// while the ram moves down or stands, fading out as it rises.
293    pub fn press_force(&self, q: f64, speed: f64) -> (f64, f64) {
294        if self.process.is_none() {
295            return (0.0, 0.0);
296        }
297        let p = self.pose(q);
298        let share = (1.0 + p.x[1] * speed / self.smoothing).clamp(0.0, 1.0);
299        let force = self.press_force_at(self.a + self.b - p.x[0]) * share;
300        (force, self.frame.map_or(0.0, |k| force / k))
301    }
302
303    /// The forces of the upper link, the lower link and the rod (compression positive), N, at the crank's angle, speed
304    /// and acceleration. The ram along z: C_b w / b = m_x x'' + F - m_x g (w = x - a cos(phi)). The upper link about O:
305    /// across the link at the knee it pushes T = (-m_up g a sin(phi) / 2 - J_up phi'') / a; the knee:
306    /// m_knee K'' = C_a u_a + T n_a - C_b u_b + C_rod u_rod + m_knee g, solved for C_a and C_rod.
307    pub fn link_forces(&self, q: f64, speed: f64, acc: f64) -> [f64; 3] {
308        let (a, b) = (self.a, self.b);
309        let p = self.pose(q);
310        let (force, _) = self.press_force(q, speed);
311        let ram_acc = p.x[2] * speed * speed + p.x[1] * acc;
312        let (sp, cp) = p.phi[0].sin_cos();
313        let w = p.x[0] - a * cp;
314        let lower = (self.m_x() * (ram_acc - self.g) + force) * b / w;
315        let (phi_v, phi_a) = (p.phi[1] * speed, p.phi[2] * speed * speed + p.phi[1] * acc);
316        let across = (-self.m_upper * self.g * a * sp / 2.0 - self.m_upper * a * a / 3.0 * phi_a) / a;
317        let knee_acc = [a * cp * phi_a - a * sp * phi_v * phi_v, a * sp * phi_a + a * cp * phi_v * phi_v];
318        let (ua, na) = ([sp, -cp], [cp, sp]);
319        let ub = [-a * sp / b, -w / b];
320        let ur = [(p.knee[0] - p.pin[0]) / self.c, (p.knee[1] - p.pin[1]) / self.c];
321        let rhs: Vec<f64> = (0..2)
322            .map(|k| self.m_knee * (knee_acc[k] + if k == 1 { self.g } else { 0.0 }) - across * na[k] + lower * ub[k])
323            .collect();
324        let det = ua[0] * ur[1] - ua[1] * ur[0];
325        let upper = (rhs[0] * ur[1] - rhs[1] * ur[0]) / det;
326        let rod = (ua[0] * rhs[1] - ua[1] * rhs[0]) / det;
327        [upper, lower, rod]
328    }
329}
330
331impl Mechanism for TogglePress {
332    /// In the scene's frame: the crank turning about -y with the rod's crank end at the pin, the upper link a bar turning
333    /// about the top pivot (about -y as phi grows), the knee's and the ram's masses, the rotor about the crank's axis; the
334    /// press force pushing the ram up.
335    fn frame_momentum(&self, q: &[f64], qd: &[f64], rotor_spin: &[f64]) -> Option<sim_core::FrameMomentum> {
336        use sim_components::base::{add_point, add_spin};
337        let (p, w) = (self.pose(q[0]), qd[0]);
338        let at = |v: [f64; 2]| [v[0], 0.0, v[1]];
339        let (force, _) = self.press_force(q[0], w);
340        let ram = -p.x[0];
341        let mut f = sim_core::FrameMomentum {
342            gravity: [0.0, 0.0, -self.g],
343            external: [0.0, 0.0, force],
344            external_at: [0.0, 0.0, ram],
345            ..Default::default()
346        };
347        let (s, c) = (self.t0 + q[0]).sin_cos();
348        add_point(&mut f, self.m_pin, at(p.pin), [-self.r * s * w, 0.0, self.r * c * w]);
349        let phi_v = p.phi[1] * w;
350        let knee_v = [self.a * p.phi[0].cos() * phi_v, 0.0, self.a * p.phi[0].sin() * phi_v];
351        add_point(&mut f, self.m_knee, at(p.knee), knee_v);
352        add_point(&mut f, self.m_upper, at([p.knee[0] / 2.0, p.knee[1] / 2.0]), knee_v.map(|v| v / 2.0));
353        add_spin(&mut f, [0.0, -1.0, 0.0], self.m_upper * self.a * self.a / 12.0, phi_v);
354        add_point(&mut f, self.m_x(), [0.0, 0.0, ram], [0.0, 0.0, -p.x[1] * w]);
355        add_spin(&mut f, [0.0, -1.0, 0.0], self.j_crank, w);
356        f.angular[1] -= rotor_spin[0];
357        Some(f)
358    }
359    fn dynamics(&self, q: &[f64], qd: &[f64], mass: &mut [f64], bias: &mut [f64]) {
360        let p = self.pose(q[0]);
361        mass[0] = self.inertia(q[0]);
362        let gravity = self.g
363            * (-self.m_x() * p.x[1]
364                + (self.m_knee + self.m_upper / 2.0) * self.a * p.phi[0].sin() * p.phi[1]
365                + self.m_pin * self.r * (self.t0 + q[0]).cos());
366        bias[0] = (self.j_knee() * p.phi[1] * p.phi[2] + self.m_x() * p.x[1] * p.x[2]) * qd[0] * qd[0] + gravity;
367    }
368    fn potential(&self, q: &[f64]) -> f64 {
369        let p = self.pose(q[0]);
370        self.g
371            * (self.m_pin * p.pin[1]
372                - (self.m_knee + self.m_upper / 2.0) * self.a * p.phi[0].cos()
373                - self.m_x() * p.x[0])
374    }
375    fn set_payload_attached(&mut self, attached: bool) {
376        self.attached = attached;
377    }
378    /// The speed term of J(q) needs the feedforward's speed terms.
379    fn tool_is_joints(&self) -> bool {
380        false
381    }
382    fn has_process(&self) -> bool {
383        self.process.is_some()
384    }
385    fn process_torque(&self, q: &[f64], qd: &[f64], out: &mut [f64]) {
386        out[0] -= self.press_force(q[0], qd[0]).0 * self.pose(q[0]).x[1];
387    }
388    fn cam(&self) -> Option<CamMaster> {
389        self.cam.as_ref().map(|(_, m)| *m)
390    }
391    fn cam_at(&self, master: f64, out: &mut [[f64; 4]]) {
392        if let Some((cam, _)) = &self.cam {
393            out[0] = cam.at(master);
394        }
395    }
396    fn cam_curve(&self) -> Option<sim_core::CamCurve> {
397        let cam = self.cam.as_ref()?.0.clone();
398        Some(std::sync::Arc::new(move |master, out: &mut [[f64; 4]]| out[0] = cam.at(master)))
399    }
400
401    fn signal_infos(&self) -> Vec<SignalInfo> {
402        [
403            ("ram.height", "group-ram", "quantity-height-above-bdc", "m"),
404            ("ram.speed", "group-ram", "quantity-speed", "m/s"),
405            ("ram.acceleration", "group-ram", "quantity-acceleration", "m/s²"),
406            ("toggle.ratio", "group-toggle", "quantity-transmission-ratio", "m/rad"),
407            ("press.force", "group-process", "quantity-process-force", "N"),
408            ("press.capacity", "group-process", "quantity-force-capacity", "N"),
409            ("press.capacity_use", "group-process", "quantity-capacity-use", ""),
410            ("frame.deflection", "group-frame", "quantity-frame-deflection", "m"),
411            ("toggle.upper_link_force", "group-upper-link", "quantity-link-force", "N"),
412            ("toggle.lower_link_force", "group-lower-link", "quantity-link-force", "N"),
413            ("rod.force", "group-rod", "quantity-rod-force", "N"),
414            ("crank.inertia", "group-crank", "quantity-reflected-inertia", "kg m²"),
415        ]
416        .into_iter()
417        .map(|(id, owner, quantity, unit)| SignalInfo::new(id, owner, quantity, unit))
418        .collect()
419    }
420    /// The signals along a crank motion without jerk.
421    fn signals(&self, q: &[f64], qd: &[f64], qdd: &[f64], force: &[f64], out: &mut Vec<f64>) {
422        self.signals_with_jerk(q, qd, qdd, &[0.0], force, out);
423    }
424    /// Where the press force fades as the ram rises, the frame's stretch follows the crank's speed, so the ram's
425    /// acceleration follows the crank's jerk.
426    fn reads_jerk(&self) -> bool {
427        self.process.is_some() && self.frame.is_some()
428    }
429    fn signals_with_jerk(&self, q: &[f64], qd: &[f64], qdd: &[f64], qddd: &[f64], _force: &[f64], out: &mut Vec<f64>) {
430        let p = self.pose(q[0]);
431        let (force, stretch) = self.press_force(q[0], qd[0]);
432        let capacity = self.capacity(q[0]);
433        let [upper, lower, rod] = self.link_forces(q[0], qd[0], qdd[0]);
434        // The frame's stretch changes with the angle and (where the force fades as the ram rises) with the speed.
435        let (h, at) = (1e-7, |q: f64, w: f64| self.press_force(q, w).1);
436        let (q, w, a) = (q[0], qd[0], qdd[0]);
437        let stretch_rate =
438            (at(q + h, w) - at(q - h, w)) / (2.0 * h) * w + (at(q, w + h) - at(q, w - h)) / (2.0 * h) * a;
439        // Its second derivative s_qq w^2 + 2 s_qw w a + s_ww a^2 + s_q a + s_w j (a wider step for the second
440        // derivatives: these divide by its square); s_w is not zero where the force fades as the ram rises.
441        let (k, s) = (1e-5, at(q, w));
442        let stretch_acc = (at(q + k, w) - 2.0 * s + at(q - k, w)) / (k * k) * w * w
443            + (at(q + k, w + k) - at(q + k, w - k) - at(q - k, w + k) + at(q - k, w - k)) / (2.0 * k * k) * w * a
444            + (at(q, w + k) - 2.0 * s + at(q, w - k)) / (k * k) * a * a
445            + (at(q + h, w) - at(q - h, w)) / (2.0 * h) * a
446            + (at(q, w + h) - at(q, w - h)) / (2.0 * h) * qddd[0];
447        out.extend([
448            self.a + self.b - p.x[0] + stretch,
449            // The height is a + b - x + stretch, so its derivatives carry the minus sign of x (x is positive down).
450            -p.x[1] * w + stretch_rate,
451            -(p.x[2] * w * w + p.x[1] * a) + stretch_acc,
452            p.x[1],
453            force,
454            capacity,
455            force / capacity,
456            stretch,
457            upper,
458            lower,
459            rod,
460            self.inertia(q),
461        ]);
462    }
463    fn rating_checks(&self) -> Vec<RatingCheck> {
464        let [link, rod, frame] = self.limits;
465        [
466            ("press-capacity", "press.capacity_use", 1.0),
467            ("upper-link-force", "toggle.upper_link_force", link),
468            ("lower-link-force", "toggle.lower_link_force", link),
469            ("rod-force", "rod.force", rod),
470            ("frame-deflection", "frame.deflection", frame),
471        ]
472        .into_iter()
473        .filter(|(_, _, limit)| limit.is_finite())
474        .map(|(check, signal, limit)| RatingCheck { check, signal: signal.into(), motor: None, limit, life: false })
475        .collect()
476    }
477
478    fn collision_parts(&self) -> &'static [&'static str] {
479        &["ram", "payload"]
480    }
481
482    /// Seen from the front: the crown with the top pivot, the two links to the ram on its guide, the rod from the crank's
483    /// pin to the knee, the crank disc with the motor behind it; the bed below the ram's bottom dead centre.
484    fn scene(&self, q: &[f64], rotors: &[f64], rotor_speeds: &[f64], out: &mut Scene) {
485        let (a, b, r) = (self.a, self.b, self.r);
486        let p = self.pose(q[0]);
487        let (_, stretch) = self.press_force(q[0], 0.0);
488        let at = |v: [f64; 2]| [v[0], 0.0, v[1]];
489        let ram = -(p.x[0] - stretch);
490        let grey = [0.62, 0.64, 0.68];
491        let bottom = -(a + b) - 0.12;
492        out.parts.push(Part::new("crown", Shape::Box { size: [0.3, 0.12, 0.05] }, [0.0, 0.0, 0.04], grey));
493        out.parts.push(Part::new("bed", Shape::Box { size: [0.3, 0.12, 0.05] }, [0.0, 0.0, bottom], grey));
494        out.parts.push(Part::new(
495            "column",
496            Shape::Segment { to: [-0.17, 0.0, bottom], width: 0.04 },
497            [-0.17, 0.0, 0.04],
498            grey,
499        ));
500        out.parts.push(Part::new(
501            "upper-link",
502            Shape::Segment { to: at(p.knee), width: 0.03 },
503            [0.0; 3],
504            [0.75, 0.75, 0.78],
505        ));
506        out.parts.push(Part::new(
507            "lower-link",
508            Shape::Segment { to: [0.0, 0.0, ram], width: 0.03 },
509            at(p.knee),
510            [0.75, 0.75, 0.78],
511        ));
512        out.parts.push(Part::new("rod", Shape::Segment { to: at(p.knee), width: 0.025 }, at(p.pin), [0.6, 0.6, 0.64]));
513        let centre = at(self.centre);
514        out.parts.push(Part::new(
515            "crank",
516            Shape::Cylinder { radius: 1.25 * r, length: 0.03 },
517            centre,
518            [0.45, 0.47, 0.5],
519        ));
520        out.parts.push(
521            Part::new(
522                "crank-arm",
523                Shape::Box { size: [r, 0.004, 0.2 * r] },
524                [(centre[0] + p.pin[0]) / 2.0, -0.02, (centre[2] + p.pin[1]) / 2.0],
525                [0.1, 0.1, 0.1],
526            )
527            .turned(self.t0 + q[0]),
528        );
529        out.parts.push(Part::new(
530            "ram",
531            Shape::Box { size: [0.12, 0.1, 0.06] },
532            [0.0, 0.0, ram - 0.03],
533            [0.2, 0.22, 0.26],
534        ));
535        if self.attached && self.payload > 0.0 {
536            out.parts.push(Part::new(
537                "payload",
538                Shape::Box { size: [0.08, 0.08, 0.04] },
539                [0.0, 0.0, ram - 0.08],
540                [0.2, 0.7, 0.3],
541            ));
542        }
543        out.parts.push(Part::new(
544            sim_core::scene::MOTOR_PART,
545            Shape::Cylinder { radius: 0.05, length: 0.12 },
546            [centre[0], 0.12, centre[2]],
547            [0.9, 0.45, 0.1],
548        ));
549        out.parts.push(Part::new(
550            "gearbox",
551            Shape::Box { size: [0.1, 0.06, 0.1] },
552            [centre[0], 0.06, centre[2]],
553            [0.25, 0.25, 0.28],
554        ));
555        out.parts.push(
556            Part::new(
557                "rotor-bar",
558                Shape::Box { size: [0.07, 0.004, 0.012] },
559                [centre[0], 0.19, centre[2]],
560                [0.1, 0.1, 0.1],
561            )
562            .turned(rotors[0]),
563        );
564        out.labels.push(Label {
565            pos: [centre[0], 0.0, centre[2] + 1.25 * r + 0.08],
566            owner_key: "motor-joint-1",
567            value: rotor_speeds[0] * 60.0 / TAU,
568            unit_key: "unit-rpm",
569            decimals: 0,
570        });
571        out.labels.push(Label {
572            pos: [0.15, 0.0, ram],
573            owner_key: "group-ram",
574            value: a + b + ram,
575            unit_key: "unit-m",
576            decimals: 5,
577        });
578    }
579    fn scene_point(&self, tool: &[f64]) -> Option<[f64; 3]> {
580        Some([0.0, 0.0, -self.pose(tool[0]).x[0]])
581    }
582}