Skip to main content

machine_crank_cam/
crank.rs

1//! A slider-crank: a crank of radius r turned by the motor through its gearbox, a connecting rod of length l, a slider
2//! on a straight guide through the crank's centre, as in mechanical and servo presses, pushers and pick-and-place by
3//! crank. The joint is the crank angle theta (rad), 0 where the slider is furthest out (the outer dead centre, a press's
4//! bottom dead centre). The slider's distance from the crank's centre:
5//!
6//!   x(theta) = r cos(theta) + sqrt(l^2 - r^2 sin^2(theta)),
7//!   x' = -r sin(theta) - r^2 sin(theta) cos(theta) / w,    w = sqrt(l^2 - r^2 sin^2(theta)),
8//!   x'' = -r cos(theta) - r^2 cos(2 theta) / w - r^4 sin^2(theta) cos^2(theta) / w^3.
9//!
10//! The rod's mass is split into a share at the crank pin (`rod.crank_end_share`) and the rest at the slider. The load's
11//! inertia at the crank depends on the angle: J(theta) = J_crank + m_pin r^2 + m_x x'^2, m_x slider, die (payload) and the
12//! rod's slider end; its speed term is m_x x' x'' theta'^2 (dJ/dtheta theta'^2 / 2). Gravity, the guide inclined by
13//! `slider.incline_deg` (from the crank towards the slider, -90 for a ram below the crank): V = g (m_x x sin(beta) +
14//! m_pin r sin(theta + beta)).
15//!
16//! The process force (effects.process_force) is a table over the slider's distance from the outer dead centre
17//! (`process.distance_m`, `process.force_n`): it pushes back on the slider while it moves outwards, as forming does, and
18//! not on the way back (springback and stripping left out). At the crank it is the torque -F x'(theta).
19//!
20//! Signals: the slider's position, speed and acceleration, the process force, the rod force, the guide's load across
21//! (the rod's side push and the weight across), the crank bearing's load and the inertia J(theta) at the crank; the
22//! rod force, the guide's and the bearing's load are judged against `ratings.rod_max_force_n`,
23//! `ratings.slider_guide_max_load_n` and `ratings.crank_bearing_max_load_n`.
24
25use crate::{Table, axis, forwards, gravity, machine, master, payload};
26use sim_components::cam::Cam;
27use sim_components::chain::Mechanism;
28use sim_components::joint::RotaryJoint;
29use sim_core::{CamMaster, Config, ConfigError, Label, Machine, Part, RatingCheck, Scene, Shape, SignalInfo};
30use std::f64::consts::TAU;
31
32pub struct SliderCrank {
33    pub r: f64,
34    pub l: f64,
35    /// The crank's own inertia about its axis, kg m^2.
36    pub j_crank: f64,
37    /// The slider and the rod's slider end, the die on it (payload) apart.
38    pub m_slider: f64,
39    pub payload: f64,
40    pub attached: bool,
41    /// The rod's crank end, at the crank pin.
42    pub m_pin: f64,
43    pub g: f64,
44    /// The guide's incline from the crank towards the slider, rad.
45    pub beta: f64,
46    pub(crate) process: Option<Table>,
47    /// The process force fades in from rest to this slider speed, m/s.
48    pub smoothing: f64,
49    pub cam: Option<(Cam, CamMaster)>,
50    limits: [f64; 3],
51}
52
53pub fn build(cfg: &Config) -> Result<Box<dyn Machine>, ConfigError> {
54    let joint = RotaryJoint::from_config(cfg)?;
55    let crank = SliderCrank::from_config(cfg)?;
56    let theta = axis(cfg, "crank", "axis-crank", "rad", joint.range)?;
57    machine(cfg, crank, (joint, None, "rad"), theta, true)
58}
59
60impl SliderCrank {
61    pub fn from_config(cfg: &Config) -> Result<Self, ConfigError> {
62        let (r, l) = (cfg.positive("crank.radius_m")?, cfg.positive("rod.length_m")?);
63        if l <= r {
64            return Err(ConfigError::Invalid("rod.length_m".into()));
65        }
66        let share = cfg.non_negative("rod.crank_end_share")?;
67        if share > 1.0 {
68            return Err(ConfigError::Invalid("rod.crank_end_share".into()));
69        }
70        let rod = cfg.non_negative("rod.mass_kg")?;
71        let incline = cfg.f64("slider.incline_deg")?;
72        if !(-90.0..=90.0).contains(&incline) {
73            return Err(ConfigError::Invalid("slider.incline_deg".into()));
74        }
75        let cam = crank_cam(cfg)?;
76        let master = master(cfg, cam.period * cfg.positive("crank.strokes_per_min")? / 60.0, cam.period)?;
77        Ok(SliderCrank {
78            r,
79            l,
80            j_crank: cfg.positive("crank.inertia_kgm2")?,
81            m_slider: cfg.positive("slider.mass_kg")? + (1.0 - share) * rod,
82            payload: payload(cfg)?,
83            attached: true,
84            m_pin: share * rod,
85            g: gravity(cfg)?,
86            beta: incline.to_radians(),
87            process: if cfg.bool("effects.process_force")? {
88                Some(Table::from_config(cfg, "process.distance_m", "process.force_n")?)
89            } else {
90                None
91            },
92            smoothing: cfg.positive("process.smoothing_m_s")?,
93            limits: ["rod_max_force_n", "slider_guide_max_load_n", "crank_bearing_max_load_n"]
94                .map(|k| cfg.f64(&format!("ratings.{k}")).unwrap_or(f64::INFINITY)),
95            cam: master.map(|m| (cam, m)),
96        })
97    }
98}
99
100/// The crank's cam: one linear segment over a turn (constant speed, `crank.motion = "constant"`), or `[cam]`'s.
101fn crank_cam(cfg: &Config) -> Result<Cam, ConfigError> {
102    match cfg.get("crank.motion")?.as_str() {
103        Some("constant") => Ok(Cam::from_segments(&[sim_components::cam::Segment {
104            master: TAU,
105            slave: TAU,
106            law: sim_components::cam::Law::Linear,
107        }])
108        .expect("one turn at constant speed")),
109        Some("cam") => Cam::from_config(cfg, "cam"),
110        _ => Err(ConfigError::Invalid("crank.motion".into())),
111    }
112}
113
114/// x, x' and x'' of a slider-crank of crank r and rod l at the crank angle theta (the module's formulas): also the toggle
115/// press's two links in line, the upper one the crank.
116pub fn slider_motion(r: f64, l: f64, theta: f64) -> [f64; 3] {
117    let (s, c) = theta.sin_cos();
118    let w = (l * l - r * r * s * s).sqrt();
119    [
120        r * c + w,
121        -r * s - r * r * s * c / w,
122        -r * c - r * r * (c * c - s * s) / w - r.powi(4) * s * s * c * c / w.powi(3),
123    ]
124}
125
126impl SliderCrank {
127    /// x, x' and x'' at the crank angle theta (the module's formulas).
128    pub fn slider(&self, theta: f64) -> [f64; 3] {
129        slider_motion(self.r, self.l, theta)
130    }
131
132    fn m_x(&self) -> f64 {
133        self.m_slider + if self.attached { self.payload } else { 0.0 }
134    }
135
136    /// J(theta): what the crank feels of crank, pin and slider.
137    pub fn inertia(&self, theta: f64) -> f64 {
138        let x1 = self.slider(theta)[1];
139        self.j_crank + self.m_pin * self.r * self.r + self.m_x() * x1 * x1
140    }
141
142    /// The process force on the slider at the angle and speed, N, pushing it back towards the crank.
143    pub fn process_force(&self, theta: f64, speed: f64) -> f64 {
144        let Some(table) = &self.process else { return 0.0 };
145        let [x, x1, _] = self.slider(theta);
146        table.at(self.r + self.l - x) * forwards(x1 * speed, self.smoothing)
147    }
148
149    /// The rod's force (tension positive), the guide's load across and the crank bearing's load, N, at the crank's
150    /// angle, speed and acceleration. Slider along x: -T cos(phi) + F_x = m_x x'', F_x the process force and the weight
151    /// along; across: N + T sin(phi) - m_x g cos(beta) = 0, sin(phi) = r sin(theta) / l. The bearing holds the pin's
152    /// mass on its circle against gravity and the rod's pull T (x - r cos, -r sin) / l.
153    pub fn loads(&self, theta: f64, speed: f64, acc: f64) -> [f64; 3] {
154        let (r, l, m) = (self.r, self.l, self.m_x());
155        let [x, x1, x2] = self.slider(theta);
156        let (s, c) = theta.sin_cos();
157        let (sb, cb) = self.beta.sin_cos();
158        let slider_acc = x2 * speed * speed + x1 * acc;
159        let along = -self.process_force(theta, speed) - m * self.g * sb;
160        let w = x - r * c;
161        let tension = (along - m * slider_acc) * l / w;
162        let guide = (m * self.g * cb - tension * r * s / l).abs();
163        let pin_acc = [r * (-acc * s - speed * speed * c), r * (acc * c - speed * speed * s)];
164        let rod = [tension * w / l, -tension * r * s / l];
165        let gravity = [-self.g * sb, -self.g * cb];
166        let bearing: Vec<f64> = (0..2).map(|k| self.m_pin * (pin_acc[k] - gravity[k]) - rod[k]).collect();
167        [tension, guide, bearing[0].hypot(bearing[1])]
168    }
169}
170
171impl Mechanism for SliderCrank {
172    /// In the scene's frame (x, z in the crank's plane, z up): the crank turning about -y, the rod's crank end at the
173    /// pin, the slider with the rod's other end and the die on the guide, the rotor about the crank's axis; the process
174    /// force pushing the slider back along the guide.
175    fn frame_momentum(&self, q: &[f64], qd: &[f64], rotor_spin: &[f64]) -> Option<sim_core::FrameMomentum> {
176        use sim_components::base::{add_point, add_spin};
177        let (sb, cb) = self.beta.sin_cos();
178        let at = |a: f64, b: f64| [a * cb - b * sb, 0.0, a * sb + b * cb];
179        let ((s, c), [x, x1, _], w) = (q[0].sin_cos(), self.slider(q[0]), qd[0]);
180        let process = self.process_force(q[0], w);
181        let mut f = sim_core::FrameMomentum {
182            gravity: [0.0, 0.0, -self.g],
183            external: at(-process, 0.0),
184            external_at: at(x, 0.0),
185            ..Default::default()
186        };
187        add_point(&mut f, self.m_pin, at(self.r * c, self.r * s), at(-self.r * s * w, self.r * c * w));
188        add_point(&mut f, self.m_x(), at(x, 0.0), at(x1 * w, 0.0));
189        add_spin(&mut f, [0.0, -1.0, 0.0], self.j_crank, w);
190        f.angular[1] -= rotor_spin[0];
191        Some(f)
192    }
193    fn dynamics(&self, q: &[f64], qd: &[f64], mass: &mut [f64], bias: &mut [f64]) {
194        let [_, x1, x2] = self.slider(q[0]);
195        mass[0] = self.inertia(q[0]);
196        bias[0] = self.m_x() * x1 * x2 * qd[0] * qd[0]
197            + self.g * (self.m_x() * x1 * self.beta.sin() + self.m_pin * self.r * (q[0] + self.beta).cos());
198    }
199    fn potential(&self, q: &[f64]) -> f64 {
200        self.g * (self.m_x() * self.slider(q[0])[0] * self.beta.sin() + self.m_pin * self.r * (q[0] + self.beta).sin())
201    }
202    fn set_payload_attached(&mut self, attached: bool) {
203        self.attached = attached;
204    }
205    /// The speed term of J(theta) needs the feedforward's speed terms.
206    fn tool_is_joints(&self) -> bool {
207        false
208    }
209    fn has_process(&self) -> bool {
210        self.process.is_some()
211    }
212    fn process_torque(&self, q: &[f64], qd: &[f64], out: &mut [f64]) {
213        out[0] -= self.process_force(q[0], qd[0]) * self.slider(q[0])[1];
214    }
215    fn cam(&self) -> Option<CamMaster> {
216        self.cam.as_ref().map(|(_, m)| *m)
217    }
218    fn cam_at(&self, master: f64, out: &mut [[f64; 4]]) {
219        if let Some((cam, _)) = &self.cam {
220            out[0] = cam.at(master);
221        }
222    }
223    fn cam_curve(&self) -> Option<sim_core::CamCurve> {
224        let cam = self.cam.as_ref()?.0.clone();
225        Some(std::sync::Arc::new(move |master, out: &mut [[f64; 4]]| out[0] = cam.at(master)))
226    }
227
228    fn signal_infos(&self) -> Vec<SignalInfo> {
229        [
230            ("slider.position", "group-slider", "quantity-position", "m"),
231            ("slider.speed", "group-slider", "quantity-speed", "m/s"),
232            ("slider.acceleration", "group-slider", "quantity-acceleration", "m/s²"),
233            ("slider.process_force", "group-process", "quantity-process-force", "N"),
234            ("rod.force", "group-rod", "quantity-rod-force", "N"),
235            ("slider.guide_load", "group-slider", "quantity-guide-load", "N"),
236            ("crank.bearing_load", "group-crank", "quantity-bearing-load", "N"),
237            ("crank.inertia", "group-crank", "quantity-reflected-inertia", "kg m²"),
238        ]
239        .into_iter()
240        .map(|(id, owner, quantity, unit)| SignalInfo::new(id, owner, quantity, unit))
241        .collect()
242    }
243    fn signals(&self, q: &[f64], qd: &[f64], qdd: &[f64], _force: &[f64], out: &mut Vec<f64>) {
244        let [x, x1, x2] = self.slider(q[0]);
245        let [rod, guide, bearing] = self.loads(q[0], qd[0], qdd[0]);
246        out.extend([
247            x,
248            x1 * qd[0],
249            x2 * qd[0] * qd[0] + x1 * qdd[0],
250            self.process_force(q[0], qd[0]),
251            rod,
252            guide,
253            bearing,
254            self.inertia(q[0]),
255        ]);
256    }
257    fn rating_checks(&self) -> Vec<RatingCheck> {
258        [
259            ("rod-force", "rod.force"),
260            ("slider-guide-load", "slider.guide_load"),
261            ("crank-bearing-load", "crank.bearing_load"),
262        ]
263        .into_iter()
264        .zip(self.limits)
265        .filter(|(_, limit)| limit.is_finite())
266        .map(|((check, signal), limit)| RatingCheck { check, signal: signal.into(), motor: None, limit, life: false })
267        .collect()
268    }
269
270    fn collision_parts(&self) -> &'static [&'static str] {
271        &["slider", "payload"]
272    }
273
274    /// Seen from the front: the crank disc at the origin with its pin, the rod to the slider on its guide, inclined as
275    /// configured; the motor behind the crank.
276    fn scene(&self, q: &[f64], rotors: &[f64], rotor_speeds: &[f64], out: &mut Scene) {
277        let (sb, cb) = self.beta.sin_cos();
278        // Guide coordinates (along, across) to the scene's x and z.
279        let at = |a: f64, b: f64| [a * cb - b * sb, 0.0, a * sb + b * cb];
280        let (r, l, theta) = (self.r, self.l, q[0]);
281        let x = self.slider(theta)[0];
282        let pin = at(r * theta.cos(), r * theta.sin());
283        let grey = [0.62, 0.64, 0.68];
284        out.parts.push(Part::new(
285            "frame",
286            Shape::Segment { to: at(r + l + 0.1, -0.06), width: 0.06 },
287            at(l - r - 0.1, -0.06),
288            grey,
289        ));
290        out.parts.push(Part::new(
291            "crank",
292            Shape::Cylinder { radius: 1.25 * r, length: 0.03 },
293            [0.0; 3],
294            [0.45, 0.47, 0.5],
295        ));
296        out.parts.push(
297            Part::new(
298                "crank-arm",
299                Shape::Box { size: [r, 0.004, 0.2 * r] },
300                [0.5 * pin[0], -0.02, 0.5 * pin[2]],
301                [0.1, 0.1, 0.1],
302            )
303            .turned(theta + self.beta),
304        );
305        out.parts.push(Part::new("rod", Shape::Segment { to: at(x, 0.0), width: 0.03 }, pin, [0.75, 0.75, 0.78]));
306        out.parts.push(Part::new("slider", Shape::Box { size: [0.12, 0.1, 0.12] }, at(x, 0.0), [0.2, 0.22, 0.26]));
307        if self.attached && self.payload > 0.0 {
308            out.parts.push(Part::new(
309                "payload",
310                Shape::Box { size: [0.06, 0.08, 0.1] },
311                at(x + 0.09, 0.0),
312                [0.2, 0.7, 0.3],
313            ));
314        }
315        out.parts.push(Part::new(
316            sim_core::scene::MOTOR_PART,
317            Shape::Cylinder { radius: 0.05, length: 0.12 },
318            [0.0, 0.12, 0.0],
319            [0.9, 0.45, 0.1],
320        ));
321        out.parts.push(Part::new(
322            "gearbox",
323            Shape::Box { size: [0.1, 0.06, 0.1] },
324            [0.0, 0.06, 0.0],
325            [0.25, 0.25, 0.28],
326        ));
327        out.parts.push(
328            Part::new("rotor-bar", Shape::Box { size: [0.07, 0.004, 0.012] }, [0.0, 0.19, 0.0], [0.1, 0.1, 0.1])
329                .turned(rotors[0]),
330        );
331        out.labels.push(Label {
332            pos: [0.0, 0.0, 1.25 * r + 0.08],
333            owner_key: "motor-joint-1",
334            value: rotor_speeds[0] * 60.0 / TAU,
335            unit_key: "unit-rpm",
336            decimals: 0,
337        });
338        out.labels.push(Label {
339            pos: at(x, 0.15),
340            owner_key: "group-slider",
341            value: self.r + self.l - x,
342            unit_key: "unit-m",
343            decimals: 4,
344        });
345    }
346    fn scene_point(&self, tool: &[f64]) -> Option<[f64; 3]> {
347        let (sb, cb) = self.beta.sin_cos();
348        let x = self.slider(tool[0])[0];
349        Some([x * cb, 0.0, x * sb])
350    }
351}